diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/AssemblyInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/AssemblyInfo.cs index edd96e49d..f5f7aebca 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/AssemblyInfo.cs @@ -1,9 +1,9 @@ using System.Reflection; using System.Resources; -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersionAttribute("3.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index 97fdbc978..4ee258575 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -8,7 +8,6 @@ using System.Reflection; namespace Microsoft.PowerShell.Commands.Diagnostics.Common { - internal static class CommonUtilities { #if !CORECLR @@ -16,27 +15,27 @@ namespace Microsoft.PowerShell.Commands.Diagnostics.Common // StringArrayToString helper converts a string array into a comma-separated string. // Note this has only limited use, individual strings cannot have commas. // - public static string StringArrayToString (IEnumerable input) + public static string StringArrayToString(IEnumerable input) { string ret = ""; foreach (string element in input) - { - ret += element + ", "; + { + ret += element + ", "; } ret = ret.TrimEnd(); - ret = ret.TrimEnd(','); + ret = ret.TrimEnd(','); return ret; } - - const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; - const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; - const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; - + + private const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; + private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; + private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; + private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002; + private const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, @@ -58,15 +57,15 @@ namespace Microsoft.PowerShell.Commands.Diagnostics.Common [DllImport("kernel32.dll", EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] private static extern ushort GetUserDefaultLangID(); - + public static uint FormatMessageFromModule(uint lastError, string moduleName, out String msg) { - Debug.Assert (!string.IsNullOrEmpty(moduleName)); + Debug.Assert(!string.IsNullOrEmpty(moduleName)); uint formatError = 0; msg = String.Empty; IntPtr moduleHandle = IntPtr.Zero; - + moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); if (moduleHandle == IntPtr.Zero) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs index c487309f3..f7f1a0aa1 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs @@ -6,55 +6,50 @@ using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; -using System.Diagnostics; +using System.Diagnostics; using System.ComponentModel; - + namespace Microsoft.PowerShell.Commands.GetCounter { - - - public class CounterFileInfo - { - internal CounterFileInfo(DateTime oldestRecord, - DateTime newestRecord, - UInt32 sampleCount) + public class CounterFileInfo { - - _oldestRecord = oldestRecord; - _newestRecord = newestRecord; - _sampleCount = sampleCount; - } - - internal CounterFileInfo(){} - - public DateTime OldestRecord - { - get + internal CounterFileInfo(DateTime oldestRecord, + DateTime newestRecord, + UInt32 sampleCount) { - return _oldestRecord; - } - } - private DateTime _oldestRecord = DateTime.MinValue; - - public DateTime NewestRecord - { - get - { - return _newestRecord; + _oldestRecord = oldestRecord; + _newestRecord = newestRecord; + _sampleCount = sampleCount; } - } - private DateTime _newestRecord = DateTime.MaxValue; - - public UInt32 SampleCount - { - get + + internal CounterFileInfo() { } + + public DateTime OldestRecord { - return _sampleCount; + 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; } - private UInt32 _sampleCount = 0; - - } - } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs index a7cdd86d1..4897c33e7 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs @@ -6,23 +6,22 @@ using System; using System.Reflection; using System.Collections.Generic; -using System.Diagnostics; +using System.Diagnostics; using System.ComponentModel; using System.Resources; using Microsoft.Powershell.Commands.GetCounter.PdhNative; using System.Globalization; using System.Diagnostics.CodeAnalysis; - + namespace Microsoft.PowerShell.Commands.GetCounter { - public class PerformanceCounterSample { internal PerformanceCounterSample() { } - + internal PerformanceCounterSample(string path, string instanceName, double cookedValue, @@ -36,109 +35,106 @@ namespace Microsoft.PowerShell.Commands.GetCounter UInt64 timeStamp100nSec, UInt32 status) { - _path = path; - _instanceName = instanceName; - _cookedValue = cookedValue; - _rawValue = rawValue; - _secondValue = secondValue; - _multiCount = multiCount; - _counterType = counterType; - _defaultScale = defaultScale; - _timeBase = timeBase; - _timeStamp = timeStamp; - _timeStamp100nSec = timeStamp100nSec; - _status = status; + _path = path; + _instanceName = instanceName; + _cookedValue = cookedValue; + _rawValue = rawValue; + _secondValue = secondValue; + _multiCount = multiCount; + _counterType = counterType; + _defaultScale = defaultScale; + _timeBase = timeBase; + _timeStamp = timeStamp; + _timeStamp100nSec = timeStamp100nSec; + _status = status; } - + public string Path { - get {return _path;} - set {_path = value;} + get { return _path; } + set { _path = value; } } private string _path = ""; public string InstanceName { - get {return _instanceName;} - set {_instanceName = value;} + get { return _instanceName; } + set { _instanceName = value; } } private string _instanceName = ""; public double CookedValue { - get {return _cookedValue;} - set {_cookedValue = value;} + get { return _cookedValue; } + set { _cookedValue = value; } } private double _cookedValue = 0; public UInt64 RawValue { - get {return _rawValue;} - set {_rawValue = value;} + get { return _rawValue; } + set { _rawValue = value; } } private UInt64 _rawValue = 0; public UInt64 SecondValue { - get {return _secondValue;} - set {_secondValue = value;} + get { return _secondValue; } + set { _secondValue = value; } } private UInt64 _secondValue = 0; - + public uint MultipleCount { - get {return _multiCount;} - set {_multiCount = value;} + get { return _multiCount; } + set { _multiCount = value; } } private uint _multiCount = 0; public PerformanceCounterType CounterType { - get {return _counterType;} - set {_counterType = value;} + get { return _counterType; } + set { _counterType = value; } } private PerformanceCounterType _counterType = 0; public DateTime Timestamp { - get {return _timeStamp;} - set {_timeStamp = value;} + get { return _timeStamp; } + set { _timeStamp = value; } } private DateTime _timeStamp = DateTime.MinValue; - + public UInt64 Timestamp100NSec { - get {return _timeStamp100nSec;} - set {_timeStamp100nSec = value;} + get { return _timeStamp100nSec; } + set { _timeStamp100nSec = value; } } private UInt64 _timeStamp100nSec = 0; public UInt32 Status { - get {return _status;} - set {_status = value;} + get { return _status; } + set { _status = value; } } private UInt32 _status = 0; public UInt32 DefaultScale { - get {return _defaultScale;} - set {_defaultScale = value;} + get { return _defaultScale; } + set { _defaultScale = value; } } private UInt32 _defaultScale = 0; public UInt64 TimeBase { - get {return _timeBase;} - set {_timeBase = value;} + get { return _timeBase; } + set { _timeBase = value; } } private UInt64 _timeBase = 0; - - - } public class PerformanceCounterSampleSet @@ -148,33 +144,32 @@ namespace Microsoft.PowerShell.Commands.GetCounter _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); } - internal PerformanceCounterSampleSet (DateTime timeStamp, + internal PerformanceCounterSampleSet(DateTime timeStamp, PerformanceCounterSample[] counterSamples, bool firstSet) : this() { _timeStamp = timeStamp; - _counterSamples = counterSamples; + _counterSamples = counterSamples; } public DateTime Timestamp { - get {return _timeStamp;} - set {_timeStamp = value;} + get { return _timeStamp; } + set { _timeStamp = value; } } private DateTime _timeStamp = DateTime.MinValue; [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample.CounterSamples", - Justification="A string[] is required here because that is the type Powershell supports")] + Justification = "A string[] is required here because that is the type Powershell supports")] public PerformanceCounterSample[] CounterSamples { - get {return _counterSamples;} - set {_counterSamples = value;} + get { return _counterSamples; } + set { _counterSamples = value; } } private PerformanceCounterSample[] _counterSamples = null; private ResourceManager _resourceMgr = null; - } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs index 76b1c397f..f0d1e5ea1 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -6,130 +6,127 @@ using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; -using System.Diagnostics; +using System.Diagnostics; using System.ComponentModel; - + namespace Microsoft.PowerShell.Commands.GetCounter { - - public class CounterSet - { - internal CounterSet(string setName, - string machineName, - PerformanceCounterCategoryType categoryType, - string setHelp, - ref Dictionary counterInstanceMapping) + public class CounterSet { - _counterSetName = setName; - if (machineName == null || machineName.Length == 0) + internal CounterSet(string setName, + string machineName, + PerformanceCounterCategoryType categoryType, + string setHelp, + ref Dictionary counterInstanceMapping) { - machineName = "."; - } - else - { - _machineName = machineName; - if (!_machineName.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) + _counterSetName = setName; + if (machineName == null || machineName.Length == 0) { - _machineName = @"\\" + _machineName; + machineName = "."; + } + else + { + _machineName = machineName; + if (!_machineName.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) + { + _machineName = @"\\" + _machineName; + } + } + _counterSetType = categoryType; + _description = setHelp; + _counterInstanceMapping = counterInstanceMapping; + } + + public string CounterSetName + { + get + { + return _counterSetName; } } - _counterSetType = categoryType; - _description = setHelp; - _counterInstanceMapping = counterInstanceMapping; - } - - public string CounterSetName - { - get - { - return _counterSetName; - } - } - private string _counterSetName = ""; + private string _counterSetName = ""; - public string MachineName - { - get + public string MachineName { - return _machineName; - } - } - private string _machineName = "."; - - public PerformanceCounterCategoryType CounterSetType - { - get - { - return _counterSetType; - } - } - private PerformanceCounterCategoryType _counterSetType; - - - public string Description - { - get - { - return _description; - } - } - private string _description = ""; - - internal Dictionary CounterInstanceMapping - { - get - { - return _counterInstanceMapping; - } - } - private Dictionary _counterInstanceMapping; - - public StringCollection Paths - { - get - { - StringCollection retColl = new StringCollection(); - foreach (string counterName in this.CounterInstanceMapping.Keys) + get { - string path; - if (CounterInstanceMapping[counterName].Length != 0) - { - path = (_machineName == ".") ? - ("\\" + _counterSetName + "(*)\\" + counterName) : - (_machineName + "\\" + _counterSetName + "(*)\\" + counterName); - } - else - { - path = (_machineName == ".") ? - ("\\" + _counterSetName + "\\" + counterName) : - (_machineName + "\\" + _counterSetName + "\\" + counterName); - } - retColl.Add(path); + return _machineName; } - - return retColl; } - } + private string _machineName = "."; - public StringCollection PathsWithInstances - { - get + public PerformanceCounterCategoryType CounterSetType { - StringCollection retColl = new StringCollection(); - foreach (string counterName in CounterInstanceMapping.Keys) + get { - foreach (string instanceName in CounterInstanceMapping[counterName]) + return _counterSetType; + } + } + private PerformanceCounterCategoryType _counterSetType; + + + public string Description + { + get + { + return _description; + } + } + private string _description = ""; + + internal Dictionary CounterInstanceMapping + { + get + { + return _counterInstanceMapping; + } + } + private Dictionary _counterInstanceMapping; + + public StringCollection Paths + { + get + { + StringCollection retColl = new StringCollection(); + foreach (string counterName in this.CounterInstanceMapping.Keys) { - string path = (_machineName == ".") ? - ("\\" + _counterSetName + "(" + instanceName + ")\\" + counterName) : - (_machineName + "\\" + _counterSetName + "(" + instanceName + ")\\" + counterName); + string path; + if (CounterInstanceMapping[counterName].Length != 0) + { + path = (_machineName == ".") ? + ("\\" + _counterSetName + "(*)\\" + counterName) : + (_machineName + "\\" + _counterSetName + "(*)\\" + counterName); + } + else + { + path = (_machineName == ".") ? + ("\\" + _counterSetName + "\\" + counterName) : + (_machineName + "\\" + _counterSetName + "\\" + counterName); + } retColl.Add(path); } + + return retColl; + } + } + + public StringCollection PathsWithInstances + { + get + { + StringCollection retColl = new StringCollection(); + foreach (string counterName in CounterInstanceMapping.Keys) + { + foreach (string instanceName in CounterInstanceMapping[counterName]) + { + string path = (_machineName == ".") ? + ("\\" + _counterSetName + "(" + instanceName + ")\\" + counterName) : + (_machineName + "\\" + _counterSetName + "(" + instanceName + ")\\" + counterName); + retColl.Add(path); + } + } + return retColl; } - return retColl; } } - - } - } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs index 49246e66f..49de2321b 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs @@ -8,7 +8,7 @@ using System.Text; using System.IO; using System.Xml; using System.Net; -using System.Management.Automation; +using System.Management.Automation; using System.ComponentModel; using System.Reflection; using System.Globalization; @@ -30,347 +30,342 @@ using Microsoft.PowerShell.Commands.Diagnostics.Common; namespace Microsoft.PowerShell.Commands { - - /// - /// Class that implements the Get-Counter cmdlet. - /// - [Cmdlet("Export", "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "http://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] - 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() - { - - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - - // - // Determine the OS version: this cmdlet requires Windows 7 - // because it uses new Pdh functionality. - // - if (System.Environment.OSVersion.Version.Major < 6 || - (System.Environment.OSVersion.Version.Major == 6 && System.Environment.OSVersion.Version.Minor < 1)) - { - string msg = _resourceMgr.GetString("ExportCtrWin7Required"); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); - } - - _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); - - // - // Validate the Format and CounterSamples arguments - // - ValidateFormat(); - - 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 + /// Class that implements the Get-Counter cmdlet. /// - protected override void StopProcessing() + [Cmdlet("Export", "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138337")] + public sealed class ExportCounterCommand : PSCmdlet { - _stopping = true; - _pdhHelper.Dispose(); - } + // + // Path parameter + // + [Parameter( + Mandatory = true, + Position = 0, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + [Alias("PSPath")] - // - // 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) + public string Path { - if (_format.ToLower(CultureInfo.InvariantCulture).Equals("blg")) + 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] + 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() + { + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + + // + // Determine the OS version: this cmdlet requires Windows 7 + // because it uses new Pdh functionality. + // + if (System.Environment.OSVersion.Version.Major < 6 || + (System.Environment.OSVersion.Version.Major == 6 && System.Environment.OSVersion.Version.Minor < 1)) { - res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]); + string msg = _resourceMgr.GetString("ExportCtrWin7Required"); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); } - else + + _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); + + // + // Validate the Format and CounterSamples arguments + // + ValidateFormat(); + + if (Circular.IsPresent && _maxSize == 0) { - res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[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.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) + res = _pdhHelper.OpenQuery(); + if (res != 0) { ReportPdhError(res, true); } + } - _queryInitialized = true; + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() + { + _pdhHelper.Dispose(); } - foreach (PerformanceCounterSampleSet set in _counterSampleSets) + /// + /// Handle Control-C + /// + protected override void StopProcessing() { - _pdhHelper.ResetRelogValues(); - - foreach (PerformanceCounterSample sample in set.CounterSamples) + _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) { - bool bUnknownKey = false; - res = _pdhHelper.SetCounterValue(sample, out bUnknownKey); - if (bUnknownKey) + if (_format.ToLower(CultureInfo.InvariantCulture).Equals("blg")) { - 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)); + 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); } - } - res = _pdhHelper.WriteRelogSample(set.Timestamp); - if (res != 0) - { - ReportPdhError(res, true); + _queryInitialized = true; } - if (_stopping) - { - break; - } - } - } - - // ValidateFormat() helper. - // Validates Format argument: only "BLG", "TSV" and "CSV" are valid strings (case-insensitive) - // - private void ValidateFormat() - { - switch (_format.ToLower(CultureInfo.InvariantCulture)) - { - case "blg": - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; - break; - case "csv": - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; - break; - case "tsv": - _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; - break; - default: - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidFormat"), _format); - Exception exc = new Exception (msg); - ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidFormat", ErrorCategory.InvalidArgument, null)); - break; - } - } - private void ResolvePath() - { - try - { - Collection result = null; - result = SessionState.Path.GetResolvedPSPathFromPSPath(_path); - if (result.Count > 1) + foreach (PerformanceCounterSampleSet set in _counterSampleSets) { - 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; + _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; + } } } - 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) + // ValidateFormat() helper. + // Validates Format argument: only "BLG", "TSV" and "CSV" are valid strings (case-insensitive) + // + private void ValidateFormat() { - msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); + switch (_format.ToLower(CultureInfo.InvariantCulture)) + { + case "blg": + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; + break; + case "csv": + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; + break; + case "tsv": + _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; + break; + default: + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterInvalidFormat"), _format); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterInvalidFormat", ErrorCategory.InvalidArgument, null)); + break; + } } - Exception exc = new Exception (msg); - if (bTerminate) + + private void ResolvePath() { - ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + 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; + } } - else + + private void ReportPdhError(uint res, bool bTerminate) { - WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + 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/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 815f10705..dd52a22aa 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -8,7 +8,7 @@ using System.Text; using System.IO; using System.Xml; using System.Net; -using System.Management.Automation; +using System.Management.Automation; using System.ComponentModel; using System.Reflection; using System.Globalization; @@ -30,161 +30,163 @@ using Microsoft.PowerShell.Commands.Diagnostics.Common; namespace Microsoft.PowerShell.Commands { - - /// - /// Class that implements the Get-Counter cmdlet. - /// - [Cmdlet(VerbsCommon.Get, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138335")] - public sealed class GetCounterCommand : PSCmdlet - { - // - // ListSet parameter - // - [Parameter( - Position = 0, - Mandatory = true, - ParameterSetName="ListSetSet", - ValueFromPipeline = true, - 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 + /// + /// Class that implements the Get-Counter cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138335")] + public sealed class GetCounterCommand : PSCmdlet { - get {return _listSet;} - set {_listSet = value;} - } - private string[] _listSet = {"*"}; + // + // ListSet parameter + // + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListSetSet", + ValueFromPipeline = true, + 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")] - - // - // Counter parameter - // - [Parameter( - Position = 0, - ParameterSetName="GetCounterSet", - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - 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; - _defaultCounters = false;} - } - private string[] _counter = {@"\network interface(*)\bytes total/sec", - @"\processor(_total)\% processor time", - @"\memory\% committed bytes in use", - @"\memory\cache faults/sec", - @"\physicaldisk(_total)\% disk time", - @"\physicaldisk(_total)\current disk queue length"}; - private bool _defaultCounters = true; - - private List _accumulatedCounters = new List(); - - - // - // SampleInterval parameter. - // Defaults to 1 second. - // - [Parameter( - ParameterSetName="GetCounterSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [ValidateRange((int)1, int.MaxValue)] - public int SampleInterval - { - get {return _sampleInterval;} - set {_sampleInterval = value;} - } - private int _sampleInterval = 1; - - - // - // 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 + public string[] ListSet { - _maxSamples = value; - _maxSamplesSpecified = true; + get { return _listSet; } + set { _listSet = value; } } - } - private Int64 _maxSamples = 1; - private bool _maxSamplesSpecified = false; + private string[] _listSet = { "*" }; - // - // Continuous switch - // - [Parameter(ParameterSetName="GetCounterSet")] - public SwitchParameter Continuous - { - get {return _continuous;} - set{_continuous = value;} - } - private bool _continuous = false; - + // + // Counter parameter + // + [Parameter( + Position = 0, + ParameterSetName = "GetCounterSet", + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + 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; + _defaultCounters = false; + } + } + private string[] _counter = {@"\network interface(*)\bytes total/sec", + @"\processor(_total)\% processor time", + @"\memory\% committed bytes in use", + @"\memory\cache faults/sec", + @"\physicaldisk(_total)\% disk time", + @"\physicaldisk(_total)\current disk queue length"}; + private bool _defaultCounters = true; - // - // ComputerName parameter - // - [Parameter( - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [ValidateNotNull] - [AllowEmptyCollection] - [Alias("Cn")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ComputerName", - Justification="A string[] is required here because that is the type Powershell supports")] - public string[] ComputerName - { - get {return _computerName;} - set {_computerName = value;} - } - private string[] _computerName = new string[0]; + private List _accumulatedCounters = new List(); - private ResourceManager _resourceMgr = null; - private PdhHelper _pdhHelper = null; + // + // SampleInterval parameter. + // Defaults to 1 second. + // + [Parameter( + ParameterSetName = "GetCounterSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateRange((int)1, int.MaxValue)] + public int SampleInterval + { + get { return _sampleInterval; } + set { _sampleInterval = value; } + } + private int _sampleInterval = 1; - private EventWaitHandle _cancelEventArrived = new EventWaitHandle(false, EventResetMode.ManualReset); - // Culture identifier(s) - private const int FrenchCultureId = 0x040C; - // The localized Pdh resource strings might use Unicode characters that are different from - // what the user can type with the keyboard to represent a special character. - // - // e.g. the apostrophe in Frence UI culture: it's [char]39 from keyboard, but it's [char]8217 - // in the resource strings. - // - // With this dictionary, we can add special mapping if we find other special cases in the future. - private readonly Dictionary>> _cultureAndSpecialCharacterMap = - new Dictionary>>() - { + // + // 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; + _maxSamplesSpecified = true; + } + } + private Int64 _maxSamples = 1; + private bool _maxSamplesSpecified = false; + + + // + // Continuous switch + // + [Parameter(ParameterSetName = "GetCounterSet")] + public SwitchParameter Continuous + { + get { return _continuous; } + set { _continuous = value; } + } + private bool _continuous = false; + + + // + // ComputerName parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [ValidateNotNull] + [AllowEmptyCollection] + [Alias("Cn")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetCounterCommand.ComputerName", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] ComputerName + { + get { return _computerName; } + set { _computerName = value; } + } + private string[] _computerName = new string[0]; + + private ResourceManager _resourceMgr = null; + + private PdhHelper _pdhHelper = null; + + private EventWaitHandle _cancelEventArrived = new EventWaitHandle(false, EventResetMode.ManualReset); + + // Culture identifier(s) + private const int FrenchCultureId = 0x040C; + // The localized Pdh resource strings might use Unicode characters that are different from + // what the user can type with the keyboard to represent a special character. + // + // e.g. the apostrophe in Frence UI culture: it's [char]39 from keyboard, but it's [char]8217 + // in the resource strings. + // + // With this dictionary, we can add special mapping if we find other special cases in the future. + private readonly Dictionary>> _cultureAndSpecialCharacterMap = + new Dictionary>>() + { { FrenchCultureId, new List>() { @@ -196,450 +198,447 @@ namespace Microsoft.PowerShell.Commands new Tuple((char) 0x275C, (char) 0x2019), } } - }; + }; - // - // BeginProcessing() is invoked once per pipeline - // - protected override void BeginProcessing() - { - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - - _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); - uint res = _pdhHelper.ConnectToDataSource(); - if (res != 0) + // + // BeginProcessing() is invoked once per pipeline + // + protected override void BeginProcessing() { - ReportPdhError(res, true); - return; - } + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - - if (Continuous.IsPresent && _maxSamplesSpecified) - { - Exception exc = new Exception(string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterContinuousOrMaxSamples"))); - ThrowTerminatingError (new ErrorRecord(exc, "CounterContinuousOrMaxSamples", ErrorCategory.InvalidArgument, null)); - } - } - - // - // EndProcessing() is invoked once per pipeline - // - protected override void EndProcessing() - { - if (ParameterSetName == "GetCounterSet") - { - ProcessGetCounter(); - } - - _pdhHelper.Dispose(); - } - - - // - // Handle Control-C - // - protected override void StopProcessing() - { - _cancelEventArrived.Set(); - _pdhHelper.Dispose(); - } - - // - // ProcessRecord() override. - // This is the main entry point for the cmdlet. - // - protected override void ProcessRecord() - { - try - { - switch (ParameterSetName) + _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); + uint res = _pdhHelper.ConnectToDataSource(); + if (res != 0) { - case "ListSetSet": - ProcessListSet(); - break; - - case "GetCounterSet": - AccumulatePipelineCounters(); - break; - - default: - Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); - break; - } - } - catch (Exception exc) - { - ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - } - } - - // - // AccumulatePipelineCounters() accumulates counter paths in the pipeline scenario: - // we do not want to start sampling until all the counters are supplied. - // - private void AccumulatePipelineCounters() - { - _accumulatedCounters.AddRange(_counter); - } - - // - // ProcessListSet() does the work to process ListSet parameter set. - // - private void ProcessListSet() - { - if (_computerName.Length == 0) - { - ProcessListSetPerMachine(null); - } - else foreach (string machine in _computerName) - { - ProcessListSetPerMachine(machine); - } - } - - // - // ProcessListSetPerMachine() helper lists counter sets on a machine. - // NOTE: machine argument should be NULL for the local machine - // - private void ProcessListSetPerMachine(string machine) - { - StringCollection counterSets = new StringCollection(); - uint res = _pdhHelper.EnumObjects(machine, ref counterSets); - if (res != 0) - { - //add an error message - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine)); - return; - } - - CultureInfo culture = Thread.CurrentThread.CurrentUICulture; - List> characterReplacementList = null; - StringCollection validPaths = new StringCollection(); - - _cultureAndSpecialCharacterMap.TryGetValue(culture.LCID, out characterReplacementList); - - foreach (string pattern in _listSet) - { - bool bMatched = false; - string normalizedPattern = pattern; - - if (characterReplacementList != null) - { - foreach (Tuple pair in characterReplacementList) - { - normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2); - } + ReportPdhError(res, true); + return; } - WildcardPattern wildLogPattern = new WildcardPattern(normalizedPattern, WildcardOptions.IgnoreCase); - foreach (string counterSet in counterSets) - { - if (!wildLogPattern.IsMatch(counterSet)) - { - continue; - } - - StringCollection counterSetCounters = new StringCollection(); - StringCollection counterSetInstances = new StringCollection(); + if (Continuous.IsPresent && _maxSamplesSpecified) + { + Exception exc = new Exception(string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterContinuousOrMaxSamples"))); + ThrowTerminatingError(new ErrorRecord(exc, "CounterContinuousOrMaxSamples", ErrorCategory.InvalidArgument, null)); + } + } - res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); - if (res == PdhResults.PDH_ACCESS_DENIED) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null)); - continue; - } - else if (res != 0) + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() + { + if (ParameterSetName == "GetCounterSet") + { + ProcessGetCounter(); + } + + _pdhHelper.Dispose(); + } + + + // + // Handle Control-C + // + protected override void StopProcessing() + { + _cancelEventArrived.Set(); + _pdhHelper.Dispose(); + } + + // + // ProcessRecord() override. + // This is the main entry point for the cmdlet. + // + protected override void ProcessRecord() + { + try + { + switch (ParameterSetName) { + case "ListSetSet": + ProcessListSet(); + break; + + case "GetCounterSet": + AccumulatePipelineCounters(); + break; + + default: + Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + break; + } + } + catch (Exception exc) + { + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + + // + // AccumulatePipelineCounters() accumulates counter paths in the pipeline scenario: + // we do not want to start sampling until all the counters are supplied. + // + private void AccumulatePipelineCounters() + { + _accumulatedCounters.AddRange(_counter); + } + + // + // ProcessListSet() does the work to process ListSet parameter set. + // + private void ProcessListSet() + { + if (_computerName.Length == 0) + { + ProcessListSetPerMachine(null); + } + else + foreach (string machine in _computerName) + { + ProcessListSetPerMachine(machine); + } + } + + // + // ProcessListSetPerMachine() helper lists counter sets on a machine. + // NOTE: machine argument should be NULL for the local machine + // + private void ProcessListSetPerMachine(string machine) + { + StringCollection counterSets = new StringCollection(); + uint res = _pdhHelper.EnumObjects(machine, ref counterSets); + if (res != 0) + { + //add an error message + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine)); + return; + } + + CultureInfo culture = Thread.CurrentThread.CurrentUICulture; + List> characterReplacementList = null; + StringCollection validPaths = new StringCollection(); + + _cultureAndSpecialCharacterMap.TryGetValue(culture.LCID, out characterReplacementList); + + foreach (string pattern in _listSet) + { + bool bMatched = false; + string normalizedPattern = pattern; + + if (characterReplacementList != null) + { + foreach (Tuple pair in characterReplacementList) + { + normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2); + } + } + + WildcardPattern wildLogPattern = new WildcardPattern(normalizedPattern, 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 == PdhResults.PDH_ACCESS_DENIED) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null)); + continue; + } + else if (res != 0) + { + ReportPdhError(res, false); + continue; + } + + string[] instanceArray = new string[counterSetInstances.Count]; + int i = 0; + foreach (string instance in counterSetInstances) + { + instanceArray[i++] = instance; + } + + // + // Special case: no instances present: change to * to create a valid paths + // + if (instanceArray.Length == 1 && + instanceArray[0].Length == 0) + { + instanceArray[0] = "*"; + } + + Dictionary counterInstanceMapping = new Dictionary(); + foreach (string counter in counterSetCounters) + { + if (!counterInstanceMapping.ContainsKey(counter)) + { + 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("NoMatchingCounterSetsFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, + machine ?? "localhost", normalizedPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + + // + // ProcessGetCounter() + // Does the work to process GetCounterSet parameter set. + // + private void ProcessGetCounter() + { + // 1. Combine machine names with paths, if needed, to construct full paths + // 2. Translate default paths into current locale + // 3. Expand wildcards and validate the paths and write errors for any invalid paths + // 4. OpenQuery/ AddCounters + // 5. Skip the first reading + + CultureInfo culture = Thread.CurrentThread.CurrentUICulture; + List> characterReplacementList = null; + List paths = CombineMachinesAndCounterPaths(); + uint res = 0; + + if (!_defaultCounters) + { + _cultureAndSpecialCharacterMap.TryGetValue(culture.LCID, out characterReplacementList); + } + + + StringCollection allExpandedPaths = new StringCollection(); + foreach (string path in paths) + { + string localizedPath = path; + if (_defaultCounters) + { + res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath); + if (res != 0) + { + string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterPathTranslationFailed", ErrorCategory.InvalidResult, null)); + + localizedPath = path; + } + } + else if (characterReplacementList != null) + { + foreach (Tuple pair in characterReplacementList) + { + localizedPath = localizedPath.Replace(pair.Item1, pair.Item2); + } + } + + StringCollection expandedPaths; + res = _pdhHelper.ExpandWildCardPath(localizedPath, out expandedPaths); + if (res != 0) + { + WriteDebug("Could not expand path " + localizedPath); ReportPdhError(res, false); continue; } - string[] instanceArray = new string[counterSetInstances.Count]; - int i = 0; - foreach (string instance in counterSetInstances) + foreach (string expandedPath in expandedPaths) { - instanceArray[i++] = instance; - } + if (!_pdhHelper.IsPathValid(expandedPath)) + { + string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathIsInvalid"), localizedPath); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); - // - // Special case: no instances present: change to * to create a valid paths - // - if (instanceArray.Length == 1 && - instanceArray[0].Length == 0) - { - instanceArray[0] = "*"; + continue; + } + allExpandedPaths.Add(expandedPath); } - - Dictionary counterInstanceMapping = new Dictionary(); - foreach (string counter in counterSetCounters) - { - if (!counterInstanceMapping.ContainsKey(counter)) - { - 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) + if (allExpandedPaths.Count == 0) { - string msg = _resourceMgr.GetString("NoMatchingCounterSetsFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, - machine ?? "localhost", normalizedPattern)); - WriteError (new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null)); - } - } - - } - - // - // ProcessGetCounter() - // Does the work to process GetCounterSet parameter set. - // - private void ProcessGetCounter() - { - // 1. Combine machine names with paths, if needed, to construct full paths - // 2. Translate default paths into current locale - // 3. Expand wildcards and validate the paths and write errors for any invalid paths - // 4. OpenQuery/ AddCounters - // 5. Skip the first reading - - CultureInfo culture = Thread.CurrentThread.CurrentUICulture; - List> characterReplacementList = null; - List paths = CombineMachinesAndCounterPaths(); - uint res = 0; - - if (!_defaultCounters) - { - _cultureAndSpecialCharacterMap.TryGetValue(culture.LCID, out characterReplacementList); - } - - - StringCollection allExpandedPaths = new StringCollection(); - foreach (string path in paths) - { - string localizedPath = path; - if (_defaultCounters) - { - res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath); - if (res != 0) - { - string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord(exc, "CounterPathTranslationFailed", ErrorCategory.InvalidResult, null)); - - localizedPath = path; - } - } - else if (characterReplacementList != null) - { - foreach (Tuple pair in characterReplacementList) - { - localizedPath = localizedPath.Replace(pair.Item1, pair.Item2); - } + return; } - StringCollection expandedPaths; - res = _pdhHelper.ExpandWildCardPath(localizedPath, out expandedPaths); + res = _pdhHelper.OpenQuery(); if (res != 0) { - WriteDebug("Could not expand path " + localizedPath); ReportPdhError(res, false); - continue; } - - foreach (string expandedPath in expandedPaths) + res = _pdhHelper.AddCounters(ref allExpandedPaths, true); + if (res != 0) { - if (!_pdhHelper.IsPathValid(expandedPath)) + ReportPdhError(res, true); + + return; + } + + PerformanceCounterSampleSet nextSet; + + bool bSkip = true; + uint sampleReads = 0; + + if (Continuous.IsPresent) + { + _maxSamples = KEEP_ON_SAMPLING; + } + + while (true) + { + // read the first set just to get the initial values + res = _pdhHelper.ReadNextSet(out nextSet, bSkip); + + if (res == 0) { - string msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathIsInvalid"), localizedPath); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null)); - - continue; + //Display valid data + if (!bSkip) + { + WriteSampleSetObject(nextSet); + sampleReads++; + } + + //Don't need to skip anymore + bSkip = false; } - allExpandedPaths.Add(expandedPath); - } - } - if (allExpandedPaths.Count == 0) - { - return; - } - - res = _pdhHelper.OpenQuery(); - if (res != 0) - { - ReportPdhError(res, false); - } - res = _pdhHelper.AddCounters(ref allExpandedPaths, true); - if (res != 0) - { - ReportPdhError(res, true); - - return; - } - - PerformanceCounterSampleSet nextSet; - - bool bSkip = true; - uint sampleReads = 0; - - if (Continuous.IsPresent) - { - _maxSamples = KEEP_ON_SAMPLING; - } - - while (true) - { - // read the first set just to get the initial values - res = _pdhHelper.ReadNextSet (out nextSet, bSkip); - - if (res == 0) - { - //Display valid data - if (!bSkip) + else if (res == PdhResults.PDH_NO_DATA || res == PdhResults.PDH_INVALID_DATA) { - WriteSampleSetObject (nextSet); + // The provider may not be running. + // We should keep on trying - but skip the next valid reading. + + ReportPdhError(res, false); + + bSkip = true; + + // Count this failed attempt as a sample: sampleReads++; } + else + { + // Unexpected error, return + ReportPdhError(res, true); + return; + } - //Don't need to skip anymore - bSkip = false; + if (_maxSamples != KEEP_ON_SAMPLING && sampleReads >= _maxSamples) + { + break; + } + bool cancelled = _cancelEventArrived.WaitOne((int)_sampleInterval * 1000, true); + if (cancelled) + { + break; + } } - else if (res == PdhResults.PDH_NO_DATA || res == PdhResults.PDH_INVALID_DATA) + } + + private void ReportPdhError(uint res, bool bTerminate) + { + string msg; + uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); + if (formatRes != 0) { - // The provider may not be running. - // We should keep on trying - but skip the next valid reading. - - ReportPdhError(res, false); - - bSkip = true; - - // Count this failed attempt as a sample: - sampleReads++; + msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } - else + Exception exc = new Exception(msg); + if (bTerminate) { - // Unexpected error, return - ReportPdhError(res, true); - return; - } - - if (_maxSamples != KEEP_ON_SAMPLING && sampleReads >= _maxSamples) - { - break; - } - - bool cancelled = _cancelEventArrived.WaitOne((int)_sampleInterval * 1000, true); - if (cancelled) - { - break; - } - - } - } - - 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)); - } - } - - - // - // CombineMachinesAndCounterPaths() helper. - // For paths that do not contain machine names, creates a path for each machine in machineNames. - // Paths already containing a machine name will be preserved. - // - private List CombineMachinesAndCounterPaths () - { - List retColl = new List(); - - if (_computerName.Length == 0) - { - retColl.AddRange(_accumulatedCounters); - return retColl; - } - - foreach (string path in _accumulatedCounters) - { - if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) //NOTE: can we do anything smarter here? - { - retColl.Add (path); + ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } else { - foreach (string machine in _computerName) + WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); + } + } + + + // + // CombineMachinesAndCounterPaths() helper. + // For paths that do not contain machine names, creates a path for each machine in machineNames. + // Paths already containing a machine name will be preserved. + // + private List CombineMachinesAndCounterPaths() + { + List retColl = new List(); + + if (_computerName.Length == 0) + { + retColl.AddRange(_accumulatedCounters); + return retColl; + } + + foreach (string path in _accumulatedCounters) + { + if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) //NOTE: can we do anything smarter here? { - if (machine.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) + retColl.Add(path); + } + else + { + foreach (string machine in _computerName) { - retColl.Add (machine + "\\" + path); - } - else - { - retColl.Add ("\\\\" + machine + "\\" + path); + if (machine.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) + { + retColl.Add(machine + "\\" + path); + } + else + { + retColl.Add("\\\\" + machine + "\\" + path); + } } } } + + return retColl; } - return retColl; - } - - // - // 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. - // - private void WriteSampleSetObject(PerformanceCounterSampleSet set) - { - foreach (PerformanceCounterSample sample in set.CounterSamples) + // + // 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. + // + private void WriteSampleSetObject(PerformanceCounterSampleSet set) { - if (sample.Status != 0) + foreach (PerformanceCounterSample sample in set.CounterSamples) { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSampleDataInvalid")); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); - break; + 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); } - WriteObject (set); } - - } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index e6e2ad81d..9b6111684 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -19,2083 +19,2061 @@ using System.Diagnostics.CodeAnalysis; [assembly: CLSCompliant(false)] -namespace Microsoft.PowerShell.Commands +namespace Microsoft.PowerShell.Commands { - /// - /// Class that implements the Get-WinEvent cmdlet. - /// - [Cmdlet(VerbsCommon.Get, "WinEvent" , DefaultParameterSetName = "GetLogSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138336")] - public sealed class GetWinEventCommand : PSCmdlet - { - /// - /// ListLog parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ParameterSetName="ListLogSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ListLogParamHelp")] - [AllowEmptyCollection] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.ListLog", - Justification="A string[] is required here because that is the type Powershell supports")] - - public string[] ListLog + /// + /// Class that implements the Get-WinEvent cmdlet. + /// + [Cmdlet(VerbsCommon.Get, "WinEvent", DefaultParameterSetName = "GetLogSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138336")] + public sealed class GetWinEventCommand : PSCmdlet { - get {return _listLog;} - set {_listLog = value;} - } - private string[] _listLog = {"*"}; + /// + /// ListLog parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ListLogParamHelp")] + [AllowEmptyCollection] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ListLog", + Justification = "A string[] is required here because that is the type Powershell supports")] - /// - /// GetLog parameter - /// - [Parameter( - Position = 0, - ParameterSetName="GetLogSet", - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "GetLogParamHelp")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.LogName", - Justification="A string[] is required here because that is the type Powershell supports")] - public string[] LogName - { - get {return _logName;} - set {_logName = value;} - } - private string[] _logName = {"*"}; - - - /// - /// ListProvider parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ParameterSetName="ListProviderSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ListProviderParamHelp")] - [AllowEmptyCollection] - - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.ListProvider", - Justification="A string[] is required here because that is the type Powershell supports")] - - public string[] ListProvider - { - get {return _listProvider;} - set {_listProvider = value;} - } - private string[] _listProvider = {"*"}; - - - /// - /// ProviderName parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ParameterSetName="GetProviderSet", - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "GetProviderParamHelp")] - - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.ProviderName", - Justification="A string[] is required here because that is the type Powershell supports")] - - public string[] ProviderName - { - get {return _providerName;} - set {_providerName = value;} - } - private string[] _providerName; - - - /// - /// Path parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ParameterSetName="FileSet", - ValueFromPipelineByPropertyName = true, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "PathParamHelp")] - - [Alias("PSPath")] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.Path", - 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; - - - /// - /// MaxEvents parameter - /// - [Parameter( - ParameterSetName="FileSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "MaxEventsParamHelp")] - [Parameter( - ParameterSetName="GetProviderSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "MaxEventsParamHelp")] - [Parameter( - ParameterSetName="GetLogSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "MaxEventsParamHelp")] - [Parameter( - ParameterSetName="HashQuerySet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "MaxEventsParamHelp")] - [Parameter( - ParameterSetName="XmlQuerySet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "MaxEventsParamHelp")] - [ValidateRange((Int64)1, Int64.MaxValue)] - public Int64 MaxEvents - { - get {return _maxEvents;} - set {_maxEvents = value;} - } - private Int64 _maxEvents = -1; - - /// - /// ComputerName parameter - /// - [Parameter( - ParameterSetName="ListProviderSet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [Parameter( - ParameterSetName="GetProviderSet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [Parameter( - ParameterSetName="ListLogSet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [Parameter( - ParameterSetName="GetLogSet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [Parameter( - ParameterSetName="HashQuerySet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - [Parameter( - ParameterSetName="XmlQuerySet", - HelpMessageBaseName = "GetEventResources", - HelpMessageResourceId = "ComputerNameParamHelp")] - - [ValidateNotNull] - [Alias("Cn")] - public string ComputerName - { - get {return _computerName;} - set {_computerName = value;} - } - private string _computerName = string.Empty; - - /// - /// Credential parameter - /// - [Parameter(ParameterSetName="ListProviderSet")] - [Parameter(ParameterSetName="GetProviderSet")] - [Parameter(ParameterSetName="ListLogSet")] - [Parameter(ParameterSetName="GetLogSet")] - [Parameter(ParameterSetName="HashQuerySet")] - [Parameter(ParameterSetName="XmlQuerySet")] - [Parameter(ParameterSetName="FileSet")] - [Credential] - public PSCredential Credential - { - get {return _credential;} - set {_credential = value;} - } - private PSCredential _credential = PSCredential.Empty; - - - /// - /// FilterXPath parameter - /// - [Parameter( - ParameterSetName="FileSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [Parameter( - ParameterSetName="GetProviderSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [Parameter( - ParameterSetName="GetLogSet", - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - HelpMessageBaseName = "GetEventResources")] - [ValidateNotNull] - public string FilterXPath - { - get {return _filter;} - set {_filter = value;} - } - private string _filter = "*"; - - /// - /// FilterXml parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - ParameterSetName = "XmlQuerySet", - HelpMessageBaseName = "GetEventResources")] - - [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.FilterXml", - Justification="An XmlDocument is required here because that is the type Powershell supports")] - - public XmlDocument FilterXml - { - get {return _xmlQuery;} - set {_xmlQuery = value;} - } - private XmlDocument _xmlQuery = null; - - - /// - /// FilterHashtable parameter - /// - [Parameter( - Position = 0, - Mandatory = true, - ValueFromPipeline = false, - ValueFromPipelineByPropertyName = false, - ParameterSetName = "HashQuerySet", - HelpMessageBaseName = "GetEventResources")] - - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.FilterHashtable", - Justification="A string[] is required here because that is the type Powershell supports")] - - public Hashtable[] FilterHashtable - { - get {return _selector;} - set {_selector = value;} - } - private Hashtable[] _selector; - - /// - /// Force switch - /// - [Parameter(ParameterSetName="ListLogSet")] - [Parameter(ParameterSetName="GetProviderSet")] - [Parameter(ParameterSetName="GetLogSet")] - - [Parameter(ParameterSetName="HashQuerySet")] - public SwitchParameter Force - { - get {return _force;} - set{_force = value;} - } - private SwitchParameter _force; - - /// - /// Oldest switch - /// - [Parameter(ParameterSetName="FileSet")] - [Parameter(ParameterSetName="GetProviderSet")] - [Parameter(ParameterSetName="GetLogSet")] - - [Parameter(ParameterSetName="HashQuerySet")] - [Parameter(ParameterSetName="XmlQuerySet")] - public SwitchParameter Oldest - { - get {return _oldest;} - set{_oldest = value;} - } - private bool _oldest = false; - - - // - // Query builder constant strings - // - private const string queryListOpen= ""; - private const string queryListClose= ""; - private const string queryTemplate = ""; - private const string queryOpenerTemplate = ""; - private const string propOpen = "["; - private const string propClose = "]"; - private const string filePrefix = "file://"; - - // - // Other private members and constants - // - private ResourceManager _resourceMgr = null; - private Dictionary _providersByLogMap = new Dictionary(); - - private StringCollection _logNamesMatchingWildcard = null; - private StringCollection _resolvedPaths = new StringCollection(); - - private List _accumulatedLogNames = new List(); - private List _accumulatedProviderNames = new List(); - private List _accumulatedFileNames = new List(); - - private const uint MAX_EVENT_BATCH=100; - - // - // Hashtable query key names - // - private const string hashkey_logname_lc="logname"; - private const string hashkey_providername_lc="providername"; - private const string hashkey_path_lc="path"; - private const string hashkey_keywords_lc="keywords"; - private const string hashkey_id_lc="id"; - private const string hashkey_level_lc="level"; - private const string hashkey_starttime_lc="starttime"; - private const string hashkey_endtime_lc="endtime"; - private const string hashkey_userid_lc="userid"; - private const string hashkey_data_lc="data"; - - - /// - /// BeginProcessing() is invoked once per pipeline: we will load System.Core.dll here - /// - protected override void BeginProcessing() - { - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - } - - - /// - /// EndProcessing() is invoked once per pipeline - /// - protected override void EndProcessing() - { - - switch (ParameterSetName) + public string[] ListLog { - case "GetLogSet": - ProcessGetLog(); - break; - - case "FileSet": - ProcessFile(); - break; - - case "GetProviderSet": - ProcessGetProvider(); - break; - - default: - break; - } - } - - - /// - /// ProcessRecord() override. - /// This is the main entry point for the cmdlet. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case "ListLogSet": - ProcessListLog(); - break; - - case "ListProviderSet": - ProcessListProvider(); - break; - - case "GetLogSet": - AccumulatePipelineLogNames(); - break; - - case "FileSet": - AccumulatePipelineFileNames(); - break; - - case "HashQuerySet": - ProcessHashQuery(); - break; - - case "GetProviderSet": - AccumulatePipelineProviderNames(); - break; - - case "XmlQuerySet": - ProcessFilterXml(); - break; - - default: - WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); - break; - } - - } - - - // - // AccumulatePipelineCounters() accumulates log names in the pipeline scenario: - // we do not want to construct a query until all the log names are supplied. - // - private void AccumulatePipelineLogNames() - { - _accumulatedLogNames.AddRange(_logName); - } - - // - // AccumulatePipelineProviderNames() accumulates provider names in the pipeline scenario: - // we do not want to construct a query until all the provider names are supplied. - // - private void AccumulatePipelineProviderNames() - { - _accumulatedProviderNames.AddRange(_logName); - } - - // - // AccumulatePipelineFileNames() accumulates log file paths in the pipeline scenario: - // we do not want to construct a query until all the file names are supplied. - // - private void AccumulatePipelineFileNames() - { - _accumulatedFileNames.AddRange(_logName); - } - - // - // Process GetLog parameter set - // - private void ProcessGetLog() - { - EventLogSession eventLogSession = CreateSession(); - - FindLogNamesMatchingWildcards (eventLogSession, _accumulatedLogNames); - if (_logNamesMatchingWildcard.Count == 0) - { - return; - } - - EventLogQuery logQuery; - if (_logNamesMatchingWildcard.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.LogName, query); - logQuery.TolerateQueryErrors = true; + get { return _listLog; } + set { _listLog = value; } } - else + private string[] _listLog = { "*" }; + + /// + /// GetLog parameter + /// + [Parameter( + Position = 0, + ParameterSetName = "GetLogSet", + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "GetLogParamHelp")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.LogName", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] LogName { - logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, _filter); + get { return _logName; } + set { _logName = value; } } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; - - EventLogReader readerObj = new EventLogReader(logQuery); - - if (readerObj != null) + private string[] _logName = { "*" }; + + + /// + /// ListProvider parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "ListProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ListProviderParamHelp")] + [AllowEmptyCollection] + + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ListProvider", + Justification = "A string[] is required here because that is the type Powershell supports")] + + public string[] ListProvider { - ReadEvents (readerObj); + get { return _listProvider; } + set { _listProvider = value; } } - } + private string[] _listProvider = { "*" }; - // - // Process GetProviderSet parameter set - // - private void ProcessGetProvider() - { - EventLogSession eventLogSession = CreateSession(); + /// + /// ProviderName parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "GetProviderSet", + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "GetProviderParamHelp")] - FindProvidersByLogForWildcardPatterns (eventLogSession, _providerName); - - if (_providersByLogMap.Count == 0) + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.ProviderName", + Justification = "A string[] is required here because that is the type Powershell supports")] + + public string[] ProviderName { - // - // Just return: errors already written above for each unmatched provider name pattern. - // - return; - } - - - EventLogQuery logQuery = null; - if (_providersByLogMap.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.LogName, query); - logQuery.TolerateQueryErrors = true; + get { return _providerName; } + set { _providerName = value; } } - else + private string[] _providerName; + + + /// + /// Path parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ParameterSetName = "FileSet", + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "PathParamHelp")] + + [Alias("PSPath")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.Path", + Justification = "A string[] is required here because that is the type Powershell supports")] + public string[] Path { - // - // There's only one key at this point, but we need an enumerator to get to it. - // - foreach (string log in _providersByLogMap.Keys) - { - logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); - WriteVerbose (string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); - } + get { return _path; } + set { _path = value; } } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest;; + private string[] _path; - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) + + /// + /// MaxEvents parameter + /// + [Parameter( + ParameterSetName = "FileSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "GetProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "GetLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "HashQuerySet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [Parameter( + ParameterSetName = "XmlQuerySet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "MaxEventsParamHelp")] + [ValidateRange((Int64)1, Int64.MaxValue)] + public Int64 MaxEvents { - ReadEvents (readerObj); + get { return _maxEvents; } + set { _maxEvents = value; } } - } + private Int64 _maxEvents = -1; - - // - // Process ListLog parameter set - // - private void ProcessListLog() - { + /// + /// ComputerName parameter + /// + [Parameter( + ParameterSetName = "ListProviderSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "GetProviderSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "ListLogSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "GetLogSet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "HashQuerySet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] + [Parameter( + ParameterSetName = "XmlQuerySet", + HelpMessageBaseName = "GetEventResources", + HelpMessageResourceId = "ComputerNameParamHelp")] - EventLogSession eventLogSession = CreateSession(); - - foreach (string logPattern in _listLog) - { - bool bMatchFound = false; - - foreach (string logName in eventLogSession.GetLogNames()) - { - WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); - - if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) - && string.Equals(logPattern, logName, StringComparison.CurrentCultureIgnoreCase)) - || - (wildLogPattern.IsMatch(logName))) - { - try - { - EventLogConfiguration logObj = new EventLogConfiguration(logName, eventLogSession); - - // - // Skip direct channels matching the wildcard unless -Force is present. - // - if (!Force.IsPresent && - WildcardPattern.ContainsWildcardCharacters(logPattern) && - (logObj.LogType == EventLogType.Debug || - logObj.LogType == EventLogType.Analytical)) - { - continue; - } - - EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); - - PSObject outputObj = new PSObject(logObj ); - - outputObj.Properties.Add(new PSNoteProperty( "FileSize", logInfoObj.FileSize)); - outputObj.Properties.Add(new PSNoteProperty( "IsLogFull", logInfoObj.IsLogFull)); - outputObj.Properties.Add(new PSNoteProperty( "LastAccessTime", logInfoObj.LastAccessTime)); - outputObj.Properties.Add(new PSNoteProperty( "LastWriteTime", logInfoObj.LastWriteTime)); - outputObj.Properties.Add(new PSNoteProperty( "OldestRecordNumber", logInfoObj.OldestRecordNumber)); - outputObj.Properties.Add(new PSNoteProperty( "RecordCount", logInfoObj.RecordCount)); - - WriteObject (outputObj); - bMatchFound = true; - } - catch (Exception exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("LogInfoUnavailable"), - logName, exc.Message); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord( outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); - continue; - } - } - } - if (!bMatchFound) - { - string msg = _resourceMgr.GetString("NoMatchingLogsFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, this._computerName, logPattern)); - WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, null)); - } - } - - } - - // - // Process ListProvider parameter set - // - private void ProcessListProvider() - { - EventLogSession eventLogSession = CreateSession(); - - foreach (string provPattern in _listProvider) + [ValidateNotNull] + [Alias("Cn")] + public string ComputerName { - bool bMatchFound = false; - - foreach (string provName in eventLogSession.GetProviderNames()) - { - - WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); - - if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) - && string.Equals(provPattern, provName, StringComparison.CurrentCultureIgnoreCase)) - || - (wildProvPattern.IsMatch(provName))) - { - try - { - ProviderMetadata provObj = new ProviderMetadata(provName, eventLogSession, CultureInfo.CurrentCulture); - WriteObject (provObj); - bMatchFound = true; - } - catch (System.Diagnostics.Eventing.Reader.EventLogException exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("ProviderMetadataUnavailable"), - provName, exc.Message); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord( outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); - continue; - } - } - } - - if (!bMatchFound) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoMatchingProvidersFound"), - this._computerName, provPattern); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord( exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, null)); - } + get { return _computerName; } + set { _computerName = value; } } - - } - - // - // Process FilterXml parameter set - // - private void ProcessFilterXml() - { - EventLogSession eventLogSession = CreateSession(); + private string _computerName = string.Empty; - if (!Oldest.IsPresent) + /// + /// Credential parameter + /// + [Parameter(ParameterSetName = "ListProviderSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "ListLogSet")] + [Parameter(ParameterSetName = "GetLogSet")] + [Parameter(ParameterSetName = "HashQuerySet")] + [Parameter(ParameterSetName = "XmlQuerySet")] + [Parameter(ParameterSetName = "FileSet")] + [Credential] + public PSCredential Credential { - // - // Do minimal parsing of xmlQuery to determine if any direct channels or ETL files are in it. - // - XmlElement root = _xmlQuery.DocumentElement; - XmlNodeList queryNodes = root.SelectNodes("//Query//Select"); - foreach (XmlNode queryNode in queryNodes) - { - XmlAttributeCollection attribs = queryNode.Attributes; - foreach (XmlAttribute attrib in attribs) - { - if (attrib.Name.Equals("Path", StringComparison.OrdinalIgnoreCase)) - { - string logName = attrib.Value; - - if (logName.StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase)) - { - TerminateForNonEvtxFileWithoutOldest(logName); - } - - ValidateLogName(logName, eventLogSession); - } - } - } + get { return _credential; } + set { _credential = value; } } - - EventLogQuery logQuery = new EventLogQuery(null, PathType.LogName, _xmlQuery.InnerXml); - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; + private PSCredential _credential = PSCredential.Empty; - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) + + /// + /// FilterXPath parameter + /// + [Parameter( + ParameterSetName = "FileSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [Parameter( + ParameterSetName = "GetProviderSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [Parameter( + ParameterSetName = "GetLogSet", + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + HelpMessageBaseName = "GetEventResources")] + [ValidateNotNull] + public string FilterXPath { - ReadEvents (readerObj); + get { return _filter; } + set { _filter = value; } } - } + private string _filter = "*"; + + /// + /// FilterXml parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "XmlQuerySet", + HelpMessageBaseName = "GetEventResources")] + + [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.FilterXml", + Justification = "An XmlDocument is required here because that is the type Powershell supports")] + + public XmlDocument FilterXml + { + get { return _xmlQuery; } + set { _xmlQuery = value; } + } + private XmlDocument _xmlQuery = null; - // - // Process FileSet parameter set - // - private void ProcessFile() - { + /// + /// FilterHashtable parameter + /// + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "HashQuerySet", + HelpMessageBaseName = "GetEventResources")] + + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", + Scope = "member", + Target = "Microsoft.PowerShell.Commands.GetEvent.FilterHashtable", + Justification = "A string[] is required here because that is the type Powershell supports")] + + public Hashtable[] FilterHashtable + { + get { return _selector; } + set { _selector = value; } + } + private Hashtable[] _selector; + + /// + /// Force switch + /// + [Parameter(ParameterSetName = "ListLogSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "GetLogSet")] + + [Parameter(ParameterSetName = "HashQuerySet")] + public SwitchParameter Force + { + get { return _force; } + set { _force = value; } + } + private SwitchParameter _force; + + /// + /// Oldest switch + /// + [Parameter(ParameterSetName = "FileSet")] + [Parameter(ParameterSetName = "GetProviderSet")] + [Parameter(ParameterSetName = "GetLogSet")] + + [Parameter(ParameterSetName = "HashQuerySet")] + [Parameter(ParameterSetName = "XmlQuerySet")] + public SwitchParameter Oldest + { + get { return _oldest; } + set { _oldest = value; } + } + private bool _oldest = false; - EventLogSession eventLogSession = CreateSession(); // - // At this point, _path array contains paths that might have wildcards, - // environment variables or PS drives. Let's resolve those. + // Query builder constant strings // - for (int i = 0; i < _path.Length; i++) - { - StringCollection resolvedPaths = ValidateAndResolveFilePath (_path[i]); - foreach (string resolvedPath in resolvedPaths) - { - _resolvedPaths.Add (resolvedPath); - WriteVerbose (string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); - } - } + private const string queryListOpen = ""; + private const string queryListClose = ""; + private const string queryTemplate = ""; + private const string queryOpenerTemplate = ""; + private const string propOpen = "["; + private const string propClose = "]"; + private const string filePrefix = "file://"; - EventLogQuery logQuery = null; - if (_resolvedPaths.Count == 0) - { - return; - } - else if (_resolvedPaths.Count > 1) - { - string query = BuildStructuredQuery(eventLogSession); - logQuery = new EventLogQuery(null, PathType.FilePath, query); - logQuery.TolerateQueryErrors = true; - } - else - { - logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, _filter); - } - logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; - - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents (readerObj); - } - } - - // - // Process HashQuerySet parameter set - // - private void ProcessHashQuery() - { - CheckHashTablesForNullValues(); - - EventLogSession eventLogSession = CreateSession(); - - string query = BuildStructuredQuery(eventLogSession); - if (query.Length == 0) - { - return; - } - - EventLogQuery logQuery = new EventLogQuery(null, PathType.FilePath, query); - logQuery.Session = eventLogSession; - logQuery.TolerateQueryErrors = true; - logQuery.ReverseDirection = !_oldest; - - EventLogReader readerObj = new EventLogReader(logQuery); - if (readerObj != null) - { - ReadEvents (readerObj); - } - } - - // - // CreateSession creates an EventLogSession connected to a target machine or localhost. - // If _credential argment is PSCredential.Empty, the session will be created for the current context. - // - private EventLogSession CreateSession () - { - - EventLogSession eventLogSession = null; - - if (_computerName == string.Empty) - { - // Set _computerName to "localhost" for future error messages, - // but do not use it for the connection to avoid RPC overhead. - _computerName = "localhost"; - - if (_credential == PSCredential.Empty) - { - return new EventLogSession(); - } - } - else if (_credential == PSCredential.Empty) - { - return new EventLogSession(_computerName); - } - - // If we are here, either both computer name and credential were passed initially, - // or credential only - we will use it with "localhost" - - NetworkCredential netCred = (NetworkCredential) _credential; - eventLogSession = new EventLogSession(_computerName, - netCred.Domain, - netCred.UserName, - _credential.Password, - SessionAuthentication.Default - ); // - // Force the destruction of cached password + // Other private members and constants // - netCred.Password = ""; + private ResourceManager _resourceMgr = null; + private Dictionary _providersByLogMap = new Dictionary(); - return eventLogSession; - } + private StringCollection _logNamesMatchingWildcard = null; + private StringCollection _resolvedPaths = new StringCollection(); + + private List _accumulatedLogNames = new List(); + private List _accumulatedProviderNames = new List(); + private List _accumulatedFileNames = new List(); + + private const uint MAX_EVENT_BATCH = 100; + + // + // Hashtable query key names + // + private const string hashkey_logname_lc = "logname"; + private const string hashkey_providername_lc = "providername"; + private const string hashkey_path_lc = "path"; + private const string hashkey_keywords_lc = "keywords"; + private const string hashkey_id_lc = "id"; + private const string hashkey_level_lc = "level"; + private const string hashkey_starttime_lc = "starttime"; + private const string hashkey_endtime_lc = "endtime"; + private const string hashkey_userid_lc = "userid"; + private const string hashkey_data_lc = "data"; - // - // ReadEvents helper. - // - private void ReadEvents(EventLogReader readerObj) - { - Int64 numEvents = 0; - EventRecord evtObj = null; - - while (true) - { - try - { - evtObj = readerObj.ReadEvent(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - continue; - } - if (evtObj == null) - { - break; - } - if (_maxEvents != -1 && numEvents >= _maxEvents) - { - break; - } - - PSObject outputObj = new PSObject(evtObj); - - string evtMessage = _resourceMgr.GetString("NoEventMessage"); - try - { - evtMessage = evtObj.FormatDescription(); - } - catch (Exception exc) - { - WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); - } - outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); - - - // - // Enumerate the object one level to get to event payload - // - WriteObject (outputObj, true); - numEvents++; - } - - if (numEvents == 0) + /// + /// BeginProcessing() is invoked once per pipeline: we will load System.Core.dll here + /// + protected override void BeginProcessing() { - string msg = _resourceMgr.GetString("NoMatchingEventsFound"); - Exception exc = new Exception(msg); - WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); } - } + /// + /// EndProcessing() is invoked once per pipeline + /// + protected override void EndProcessing() + { + switch (ParameterSetName) + { + case "GetLogSet": + ProcessGetLog(); + break; - // - // BuildStructuredQuery() builds a structured query from cmdlet arguments. - // - private string BuildStructuredQuery(EventLogSession eventLogSession) - { - string result = ""; + case "FileSet": + ProcessFile(); + break; - switch (ParameterSetName) - { - case "ListLogSet": - break; + case "GetProviderSet": + ProcessGetProvider(); + break; - case "ListProviderSet": - break; + default: + break; + } + } - case "GetProviderSet": - { - result = queryListOpen; - uint queryId = 0; + /// + /// ProcessRecord() override. + /// This is the main entry point for the cmdlet. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case "ListLogSet": + ProcessListLog(); + break; + + case "ListProviderSet": + ProcessListProvider(); + break; + + case "GetLogSet": + AccumulatePipelineLogNames(); + break; + + case "FileSet": + AccumulatePipelineFileNames(); + break; + + case "HashQuerySet": + ProcessHashQuery(); + break; + + case "GetProviderSet": + AccumulatePipelineProviderNames(); + break; + + case "XmlQuerySet": + ProcessFilterXml(); + break; + + default: + WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + break; + } + } + + + // + // AccumulatePipelineCounters() accumulates log names in the pipeline scenario: + // we do not want to construct a query until all the log names are supplied. + // + private void AccumulatePipelineLogNames() + { + _accumulatedLogNames.AddRange(_logName); + } + + // + // AccumulatePipelineProviderNames() accumulates provider names in the pipeline scenario: + // we do not want to construct a query until all the provider names are supplied. + // + private void AccumulatePipelineProviderNames() + { + _accumulatedProviderNames.AddRange(_logName); + } + + // + // AccumulatePipelineFileNames() accumulates log file paths in the pipeline scenario: + // we do not want to construct a query until all the file names are supplied. + // + private void AccumulatePipelineFileNames() + { + _accumulatedFileNames.AddRange(_logName); + } + + // + // Process GetLog parameter set + // + private void ProcessGetLog() + { + EventLogSession eventLogSession = CreateSession(); + + FindLogNamesMatchingWildcards(eventLogSession, _accumulatedLogNames); + if (_logNamesMatchingWildcard.Count == 0) + { + return; + } + + EventLogQuery logQuery; + if (_logNamesMatchingWildcard.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_logNamesMatchingWildcard[0], PathType.LogName, _filter); + } + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + EventLogReader readerObj = new EventLogReader(logQuery); + + if (readerObj != null) + { + ReadEvents(readerObj); + } + } + + + // + // Process GetProviderSet parameter set + // + private void ProcessGetProvider() + { + EventLogSession eventLogSession = CreateSession(); + + FindProvidersByLogForWildcardPatterns(eventLogSession, _providerName); + + if (_providersByLogMap.Count == 0) + { + // + // Just return: errors already written above for each unmatched provider name pattern. + // + return; + } + + + EventLogQuery logQuery = null; + if (_providersByLogMap.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.LogName, query); + logQuery.TolerateQueryErrors = true; + } + else + { + // + // There's only one key at this point, but we need an enumerator to get to it. + // foreach (string log in _providersByLogMap.Keys) { - string providerFilter = AddProviderPredicatesToFilter(_providersByLogMap[log]); - string addedQuery; - addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[]{queryId++, log, providerFilter}); - result += addedQuery; - } - result += queryListClose; + logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); + WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); + } } - break; + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; ; - case "GetLogSet": + EventLogReader readerObj = new EventLogReader(logQuery); + if (readerObj != null) { - result = queryListOpen; - uint queryId = 0; - foreach (string log in _logNamesMatchingWildcard) - { - string addedQuery; - addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[]{queryId++, log, _filter}); - result += addedQuery; - } - result += queryListClose; + ReadEvents(readerObj); } - break; + } - case "FileSet": - { - result = queryListOpen; - uint queryId = 0; - foreach (string filePath in _resolvedPaths) - { - string properFilePath = filePrefix + filePath; - string addedQuery; - addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[]{queryId++, properFilePath, _filter}); - result += addedQuery; - } - result += queryListClose; - } - break; - case "HashQuerySet": - result = BuildStructuredQueryFromHashTable(eventLogSession); - break; - - default: - WriteDebug (string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); - break; - } - - WriteVerbose (string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("QueryTrace"), result)); - - return result; - } - - // - // BuildStructuredQueryFromHashTable() helper. - // Builds a structured query from the hashtable (Selector) argument. - // - private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession) - { - string result = ""; - - result = queryListOpen; - - uint queryId = 0; - - foreach (Hashtable hash in _selector) + // + // Process ListLog parameter set + // + private void ProcessListLog() { - string xpathString = ""; + EventLogSession eventLogSession = CreateSession(); - CheckHashTableForQueryPathPresence(hash); - - // - // Local queriedLogsQueryMap will hold names of logs or files to be queried - // mapped to the actual query strings being built up. - // - Dictionary queriedLogsQueryMap = new Dictionary(); - - // - // Process log, _path, or provider parameters first - // to create initial partially-filled query templates. - // Error out for direct channels unless -oldest is present. - // - // Order is important! Process "providername" key after "logname" and "file". - // - if (hash.ContainsKey(hashkey_logname_lc)) + foreach (string logPattern in _listLog) { - List logPatterns = new List(); - if (hash[hashkey_logname_lc] is Array) + bool bMatchFound = false; + + foreach (string logName in eventLogSession.GetLogNames()) { - foreach (Object elt in (Array)hash[hashkey_logname_lc]) + WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); + + if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) + && string.Equals(logPattern, logName, StringComparison.CurrentCultureIgnoreCase)) + || + (wildLogPattern.IsMatch(logName))) { - logPatterns.Add(elt.ToString()); - } + try + { + EventLogConfiguration logObj = new EventLogConfiguration(logName, eventLogSession); + + // + // Skip direct channels matching the wildcard unless -Force is present. + // + if (!Force.IsPresent && + WildcardPattern.ContainsWildcardCharacters(logPattern) && + (logObj.LogType == EventLogType.Debug || + logObj.LogType == EventLogType.Analytical)) + { + continue; + } + + EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); + + PSObject outputObj = new PSObject(logObj); + + outputObj.Properties.Add(new PSNoteProperty("FileSize", logInfoObj.FileSize)); + outputObj.Properties.Add(new PSNoteProperty("IsLogFull", logInfoObj.IsLogFull)); + outputObj.Properties.Add(new PSNoteProperty("LastAccessTime", logInfoObj.LastAccessTime)); + outputObj.Properties.Add(new PSNoteProperty("LastWriteTime", logInfoObj.LastWriteTime)); + outputObj.Properties.Add(new PSNoteProperty("OldestRecordNumber", logInfoObj.OldestRecordNumber)); + outputObj.Properties.Add(new PSNoteProperty("RecordCount", logInfoObj.RecordCount)); + + WriteObject(outputObj); + bMatchFound = true; + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + logName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } + } } - else + if (!bMatchFound) { - logPatterns.Add(hash[hashkey_logname_lc].ToString()); - } - - FindLogNamesMatchingWildcards(eventLogSession, logPatterns); - - foreach (string logName in _logNamesMatchingWildcard) - { - queriedLogsQueryMap.Add(logName.ToLowerInvariant(), - string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, logName)); + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, null)); } } - if (hash.ContainsKey(hashkey_path_lc)) + } + + // + // Process ListProvider parameter set + // + private void ProcessListProvider() + { + EventLogSession eventLogSession = CreateSession(); + + foreach (string provPattern in _listProvider) { - if (hash[hashkey_path_lc] is Array) + bool bMatchFound = false; + + foreach (string provName in eventLogSession.GetProviderNames()) { - foreach (Object elt in (Array)hash[hashkey_path_lc]) + WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); + + if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) + && string.Equals(provPattern, provName, StringComparison.CurrentCultureIgnoreCase)) + || + (wildProvPattern.IsMatch(provName))) { - StringCollection resolvedPaths = ValidateAndResolveFilePath (elt.ToString()); + try + { + ProviderMetadata provObj = new ProviderMetadata(provName, eventLogSession, CultureInfo.CurrentCulture); + WriteObject(provObj); + bMatchFound = true; + } + catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("ProviderMetadataUnavailable"), + provName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); + continue; + } + } + } + + if (!bMatchFound) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoMatchingProvidersFound"), + _computerName, provPattern); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, null)); + } + } + } + + // + // Process FilterXml parameter set + // + private void ProcessFilterXml() + { + EventLogSession eventLogSession = CreateSession(); + + if (!Oldest.IsPresent) + { + // + // Do minimal parsing of xmlQuery to determine if any direct channels or ETL files are in it. + // + XmlElement root = _xmlQuery.DocumentElement; + XmlNodeList queryNodes = root.SelectNodes("//Query//Select"); + foreach (XmlNode queryNode in queryNodes) + { + XmlAttributeCollection attribs = queryNode.Attributes; + foreach (XmlAttribute attrib in attribs) + { + if (attrib.Name.Equals("Path", StringComparison.OrdinalIgnoreCase)) + { + string logName = attrib.Value; + + if (logName.StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase)) + { + TerminateForNonEvtxFileWithoutOldest(logName); + } + + ValidateLogName(logName, eventLogSession); + } + } + } + } + + EventLogQuery logQuery = new EventLogQuery(null, PathType.LogName, _xmlQuery.InnerXml); + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + EventLogReader readerObj = new EventLogReader(logQuery); + if (readerObj != null) + { + ReadEvents(readerObj); + } + } + + + // + // Process FileSet parameter set + // + private void ProcessFile() + { + EventLogSession eventLogSession = CreateSession(); + + // + // At this point, _path array contains paths that might have wildcards, + // environment variables or PS drives. Let's resolve those. + // + for (int i = 0; i < _path.Length; i++) + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(_path[i]); + foreach (string resolvedPath in resolvedPaths) + { + _resolvedPaths.Add(resolvedPath); + WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); + } + } + + EventLogQuery logQuery = null; + if (_resolvedPaths.Count == 0) + { + return; + } + else if (_resolvedPaths.Count > 1) + { + string query = BuildStructuredQuery(eventLogSession); + logQuery = new EventLogQuery(null, PathType.FilePath, query); + logQuery.TolerateQueryErrors = true; + } + else + { + logQuery = new EventLogQuery(_resolvedPaths[0], PathType.FilePath, _filter); + } + logQuery.Session = eventLogSession; + logQuery.ReverseDirection = !_oldest; + + EventLogReader readerObj = new EventLogReader(logQuery); + if (readerObj != null) + { + ReadEvents(readerObj); + } + } + + // + // Process HashQuerySet parameter set + // + private void ProcessHashQuery() + { + CheckHashTablesForNullValues(); + + EventLogSession eventLogSession = CreateSession(); + + string query = BuildStructuredQuery(eventLogSession); + if (query.Length == 0) + { + return; + } + + EventLogQuery logQuery = new EventLogQuery(null, PathType.FilePath, query); + logQuery.Session = eventLogSession; + logQuery.TolerateQueryErrors = true; + logQuery.ReverseDirection = !_oldest; + + EventLogReader readerObj = new EventLogReader(logQuery); + if (readerObj != null) + { + ReadEvents(readerObj); + } + } + + // + // CreateSession creates an EventLogSession connected to a target machine or localhost. + // If _credential argment is PSCredential.Empty, the session will be created for the current context. + // + private EventLogSession CreateSession() + { + EventLogSession eventLogSession = null; + + if (_computerName == string.Empty) + { + // Set _computerName to "localhost" for future error messages, + // but do not use it for the connection to avoid RPC overhead. + _computerName = "localhost"; + + if (_credential == PSCredential.Empty) + { + return new EventLogSession(); + } + } + else if (_credential == PSCredential.Empty) + { + return new EventLogSession(_computerName); + } + + // If we are here, either both computer name and credential were passed initially, + // or credential only - we will use it with "localhost" + + NetworkCredential netCred = (NetworkCredential)_credential; + eventLogSession = new EventLogSession(_computerName, + netCred.Domain, + netCred.UserName, + _credential.Password, + SessionAuthentication.Default + ); + // + // Force the destruction of cached password + // + netCred.Password = ""; + + return eventLogSession; + } + + + // + // ReadEvents helper. + // + private void ReadEvents(EventLogReader readerObj) + { + Int64 numEvents = 0; + EventRecord evtObj = null; + + while (true) + { + try + { + evtObj = readerObj.ReadEvent(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + continue; + } + if (evtObj == null) + { + break; + } + if (_maxEvents != -1 && numEvents >= _maxEvents) + { + break; + } + + PSObject outputObj = new PSObject(evtObj); + + string evtMessage = _resourceMgr.GetString("NoEventMessage"); + try + { + evtMessage = evtObj.FormatDescription(); + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, exc.Message, ErrorCategory.NotSpecified, null)); + } + outputObj.Properties.Add(new PSNoteProperty("Message", evtMessage)); + + + // + // Enumerate the object one level to get to event payload + // + WriteObject(outputObj, true); + numEvents++; + } + + if (numEvents == 0) + { + string msg = _resourceMgr.GetString("NoMatchingEventsFound"); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "NoMatchingEventsFound", ErrorCategory.ObjectNotFound, null)); + } + } + + + + // + // BuildStructuredQuery() builds a structured query from cmdlet arguments. + // + private string BuildStructuredQuery(EventLogSession eventLogSession) + { + string result = ""; + + switch (ParameterSetName) + { + case "ListLogSet": + break; + + case "ListProviderSet": + break; + + case "GetProviderSet": + { + result = queryListOpen; + uint queryId = 0; + + foreach (string log in _providersByLogMap.Keys) + { + string providerFilter = AddProviderPredicatesToFilter(_providersByLogMap[log]); + string addedQuery; + addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, providerFilter }); + result += addedQuery; + } + result += queryListClose; + } + break; + + case "GetLogSet": + { + result = queryListOpen; + uint queryId = 0; + foreach (string log in _logNamesMatchingWildcard) + { + string addedQuery; + addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, log, _filter }); + result += addedQuery; + } + result += queryListClose; + } + break; + + case "FileSet": + { + result = queryListOpen; + uint queryId = 0; + foreach (string filePath in _resolvedPaths) + { + string properFilePath = filePrefix + filePath; + string addedQuery; + addedQuery = string.Format(CultureInfo.InvariantCulture, queryTemplate, new object[] { queryId++, properFilePath, _filter }); + result += addedQuery; + } + result += queryListClose; + } + break; + + case "HashQuerySet": + result = BuildStructuredQueryFromHashTable(eventLogSession); + break; + + default: + WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + break; + } + + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("QueryTrace"), result)); + + return result; + } + + // + // BuildStructuredQueryFromHashTable() helper. + // Builds a structured query from the hashtable (Selector) argument. + // + private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession) + { + string result = ""; + + result = queryListOpen; + + uint queryId = 0; + + foreach (Hashtable hash in _selector) + { + string xpathString = ""; + + CheckHashTableForQueryPathPresence(hash); + + // + // Local queriedLogsQueryMap will hold names of logs or files to be queried + // mapped to the actual query strings being built up. + // + Dictionary queriedLogsQueryMap = new Dictionary(); + + // + // Process log, _path, or provider parameters first + // to create initial partially-filled query templates. + // Error out for direct channels unless -oldest is present. + // + // Order is important! Process "providername" key after "logname" and "file". + // + if (hash.ContainsKey(hashkey_logname_lc)) + { + List logPatterns = new List(); + if (hash[hashkey_logname_lc] is Array) + { + foreach (Object elt in (Array)hash[hashkey_logname_lc]) + { + logPatterns.Add(elt.ToString()); + } + } + else + { + logPatterns.Add(hash[hashkey_logname_lc].ToString()); + } + + FindLogNamesMatchingWildcards(eventLogSession, logPatterns); + + foreach (string logName in _logNamesMatchingWildcard) + { + queriedLogsQueryMap.Add(logName.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, logName)); + } + } + if (hash.ContainsKey(hashkey_path_lc)) + { + if (hash[hashkey_path_lc] is Array) + { + foreach (Object elt in (Array)hash[hashkey_path_lc]) + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(elt.ToString()); + foreach (string resolvedPath in resolvedPaths) + { + queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), + string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath)); + } + } + } + else + { + StringCollection resolvedPaths = ValidateAndResolveFilePath(hash[hashkey_path_lc].ToString()); foreach (string resolvedPath in resolvedPaths) { - queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), + queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath)); } - } - } - else - { - StringCollection resolvedPaths = ValidateAndResolveFilePath (hash[hashkey_path_lc].ToString()); - foreach (string resolvedPath in resolvedPaths) - { - queriedLogsQueryMap.Add(filePrefix + resolvedPath.ToLowerInvariant(), - string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, filePrefix + resolvedPath)); } } - } - if (hash.ContainsKey(hashkey_providername_lc)) - { - - List provPatterns = new List(); - if (hash[hashkey_providername_lc] is Array) + if (hash.ContainsKey(hashkey_providername_lc)) { - foreach (Object elt in (Array)hash[hashkey_providername_lc]) + List provPatterns = new List(); + if (hash[hashkey_providername_lc] is Array) { - provPatterns.Add(elt.ToString()); - } - } - else - { - provPatterns.Add(hash[hashkey_providername_lc].ToString()); - } - - FindProvidersByLogForWildcardPatterns(eventLogSession, provPatterns); - - // - // If "providername" key is used alone, we will construct a query across all of the providers' logs. - // Otherwise, we will use the provider names to add predicates to "logname" and "path" queries. - // - if (!hash.ContainsKey(hashkey_path_lc) && !hash.ContainsKey(hashkey_logname_lc)) - { - foreach (string keyLogName in _providersByLogMap.Keys) - { - string providersPredicate = BuildProvidersPredicate(_providersByLogMap[keyLogName]); - string query = string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, keyLogName); - queriedLogsQueryMap.Add (keyLogName.ToLowerInvariant(), - query + "[" + providersPredicate); - } - } - else - { - List keysList = new List(queriedLogsQueryMap.Keys); - bool bRemovedIrrelevantLogs = false; - foreach (string queriedLog in keysList) - { - if (queriedLog.StartsWith(filePrefix, StringComparison.Ordinal)) + foreach (Object elt in (Array)hash[hashkey_providername_lc]) { - queriedLogsQueryMap[queriedLog] += "[" + BuildAllProvidersPredicate(); + provPatterns.Add(elt.ToString()); } - else + } + else + { + provPatterns.Add(hash[hashkey_providername_lc].ToString()); + } + + FindProvidersByLogForWildcardPatterns(eventLogSession, provPatterns); + + // + // If "providername" key is used alone, we will construct a query across all of the providers' logs. + // Otherwise, we will use the provider names to add predicates to "logname" and "path" queries. + // + if (!hash.ContainsKey(hashkey_path_lc) && !hash.ContainsKey(hashkey_logname_lc)) + { + foreach (string keyLogName in _providersByLogMap.Keys) { - if (_providersByLogMap.ContainsKey(queriedLog)) + string providersPredicate = BuildProvidersPredicate(_providersByLogMap[keyLogName]); + string query = string.Format(CultureInfo.InvariantCulture, queryOpenerTemplate, queryId++, keyLogName); + queriedLogsQueryMap.Add(keyLogName.ToLowerInvariant(), + query + "[" + providersPredicate); + } + } + else + { + List keysList = new List(queriedLogsQueryMap.Keys); + bool bRemovedIrrelevantLogs = false; + foreach (string queriedLog in keysList) + { + if (queriedLog.StartsWith(filePrefix, StringComparison.Ordinal)) { - string providersPredicate = BuildProvidersPredicate(_providersByLogMap[queriedLog]); - queriedLogsQueryMap[queriedLog] += "[" + providersPredicate; + queriedLogsQueryMap[queriedLog] += "[" + BuildAllProvidersPredicate(); } else { - WriteVerbose (string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("SpecifiedProvidersDontWriteToLog"), queriedLog)); - queriedLogsQueryMap.Remove(queriedLog); - bRemovedIrrelevantLogs = true; + if (_providersByLogMap.ContainsKey(queriedLog)) + { + string providersPredicate = BuildProvidersPredicate(_providersByLogMap[queriedLog]); + queriedLogsQueryMap[queriedLog] += "[" + providersPredicate; + } + else + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("SpecifiedProvidersDontWriteToLog"), queriedLog)); + queriedLogsQueryMap.Remove(queriedLog); + bRemovedIrrelevantLogs = true; + } } } - } - // - // Write an error if we have removed all the logs as irrelevant - // - if (bRemovedIrrelevantLogs && (queriedLogsQueryMap.Count == 0)) - { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("LogsAndProvidersDontOverlap")); - Exception exc = new Exception (msg); - WriteError(new ErrorRecord(exc, "LogsAndProvidersDontOverlap", ErrorCategory.InvalidArgument, null)); - continue; + // + // Write an error if we have removed all the logs as irrelevant + // + if (bRemovedIrrelevantLogs && (queriedLogsQueryMap.Count == 0)) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("LogsAndProvidersDontOverlap")); + Exception exc = new Exception(msg); + WriteError(new ErrorRecord(exc, "LogsAndProvidersDontOverlap", ErrorCategory.InvalidArgument, null)); + continue; + } } } - } - // - // If none of the logs/paths/providers were valid, queriedLogsQueryMap is empty. - // Simply conitnue to the next hashtable since all the errors have been written already. - // - if (queriedLogsQueryMap.Count == 0) - { - continue; - } + // + // If none of the logs/paths/providers were valid, queriedLogsQueryMap is empty. + // Simply conitnue to the next hashtable since all the errors have been written already. + // + if (queriedLogsQueryMap.Count == 0) + { + continue; + } - // - // At this point queriedLogsQueryMap contains all the query openings: missing the actual XPaths - // Let's build xpathString to attach to each query opening. - // - bool bDateTimeHandled = false; - foreach (string key in hash.Keys) - { - string added = ""; + // + // At this point queriedLogsQueryMap contains all the query openings: missing the actual XPaths + // Let's build xpathString to attach to each query opening. + // + bool bDateTimeHandled = false; + foreach (string key in hash.Keys) + { + string added = ""; - switch (key.ToLowerInvariant()) - { - case hashkey_logname_lc: - case hashkey_path_lc: - case hashkey_providername_lc: - break; - case hashkey_id_lc: - added = HandleEventIdHashValue(hash[key]); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - break; - - case hashkey_level_lc: - added = HandleLevelHashValue(hash[key]); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - break; - - case hashkey_keywords_lc: - added = HandleKeywordHashValue(hash[key]); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - break; - - case hashkey_starttime_lc: - if (bDateTimeHandled) - { + switch (key.ToLowerInvariant()) + { + case hashkey_logname_lc: + case hashkey_path_lc: + case hashkey_providername_lc: break; - } - added = HandleStartTimeHashValue(hash[key], hash); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - - bDateTimeHandled = true; - break; - - case hashkey_endtime_lc: - if (bDateTimeHandled) - { + case hashkey_id_lc: + added = HandleEventIdHashValue(hash[key]); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } break; - } - added = HandleEndTimeHashValue(hash[key], hash); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } + case hashkey_level_lc: + added = HandleLevelHashValue(hash[key]); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + break; - bDateTimeHandled = true; - break; - - case hashkey_data_lc: - added = HandleDataHashValue(hash[key]); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - break; - - case hashkey_userid_lc: - added = HandleContextHashValue(hash[key]); - if (added.Length > 0) - { - ExtendPredicate(ref xpathString); - xpathString += added; - } - break; - - default: - { - // - // None of the recognized values: this must be a named payload field - // - ExtendPredicate(ref xpathString); - xpathString += string.Format(CultureInfo.InvariantCulture, - "([EventData[Data[@Name='{0}']='{1}']] or [UserData/*/{0}='{1}'])", - key, hash[key]); - } - break; - } - } + case hashkey_keywords_lc: + added = HandleKeywordHashValue(hash[key]); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + break; - // - // Complete each query with the XPath. - // Handle the case where the query opener already has provider predicate(s). - // Add the queries from queriedLogsQueryMap into the resulting string. - // - foreach (string query in queriedLogsQueryMap.Values) - { - result += query; - - if (query.EndsWith("*", StringComparison.OrdinalIgnoreCase)) - { - // - // No provider predicate: just add the XPath string - // - if (xpathString.Length != 0) - { - result += propOpen + xpathString + propClose; + case hashkey_starttime_lc: + if (bDateTimeHandled) + { + break; + } + added = HandleStartTimeHashValue(hash[key], hash); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + + bDateTimeHandled = true; + break; + + case hashkey_endtime_lc: + if (bDateTimeHandled) + { + break; + } + + added = HandleEndTimeHashValue(hash[key], hash); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + + bDateTimeHandled = true; + break; + + case hashkey_data_lc: + added = HandleDataHashValue(hash[key]); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + break; + + case hashkey_userid_lc: + added = HandleContextHashValue(hash[key]); + if (added.Length > 0) + { + ExtendPredicate(ref xpathString); + xpathString += added; + } + break; + + default: + { + // + // None of the recognized values: this must be a named payload field + // + ExtendPredicate(ref xpathString); + xpathString += string.Format(CultureInfo.InvariantCulture, + "([EventData[Data[@Name='{0}']='{1}']] or [UserData/*/{0}='{1}'])", + key, hash[key]); + } + break; } } - else + + // + // Complete each query with the XPath. + // Handle the case where the query opener already has provider predicate(s). + // Add the queries from queriedLogsQueryMap into the resulting string. + // + foreach (string query in queriedLogsQueryMap.Values) { - // - // Add xpathString to provider predicates. - // - if (xpathString.Length != 0) + result += query; + + if (query.EndsWith("*", StringComparison.OrdinalIgnoreCase)) { - result += " and " + xpathString; + // + // No provider predicate: just add the XPath string + // + if (xpathString.Length != 0) + { + result += propOpen + xpathString + propClose; + } + } + else + { + // + // Add xpathString to provider predicates. + // + if (xpathString.Length != 0) + { + result += " and " + xpathString; + } + result += propClose; } - result += propClose; - } - - result += queryCloser; + result += queryCloser; + } + } //end foreach hashtable + + + result += queryListClose; + + return result; + } + + // + // HandleEventIdHashValue helper for hashtable structured query builder. + // Constructs and returns EventId XPath portion as a string. + // + private string HandleEventIdHashValue(Object value) + { + string ret = ""; + if (value is Array) + { + Array idsArray = (Array)(value); + ret += "("; + for (int i = 0; i < idsArray.Length; i++) + { + ret += "(System/EventID=" + idsArray.GetValue(i).ToString() + ")"; + if (i < (idsArray.Length - 1)) + { + ret += " or "; + } + } + ret += ")"; } - } //end foreach hashtable - - - result += queryListClose; - - return result; - } - - // - // HandleEventIdHashValue helper for hashtable structured query builder. - // Constructs and returns EventId XPath portion as a string. - // - private string HandleEventIdHashValue (Object value) - { - string ret = ""; - if (value is Array) - { - Array idsArray = (Array)(value); - ret += "("; - for (int i = 0; i < idsArray.Length; i++) + else { - ret += "(System/EventID=" + idsArray.GetValue(i).ToString() + ")"; - if ( i < (idsArray.Length - 1)) + ret += "(System/EventID=" + value + ")"; + } + + return ret; + } + + // + // HandleLevelHashValue helper for hashtable structured query builder. + // Constructs and returns Level XPath portion as a string. + // + private string HandleLevelHashValue(Object value) + { + string ret = ""; + + if (value is Array) + { + Array levelsArray = (Array)(value); + ret += "("; + for (int i = 0; i < levelsArray.Length; i++) { - ret += " or "; + ret += "(System/Level=" + levelsArray.GetValue(i).ToString() + ")"; + if (i < (levelsArray.Length - 1)) + { + ret += " or "; + } } - } - ret += ")"; - } - else - { - ret += "(System/EventID=" + value + ")"; - } - - return ret; - } - - // - // HandleLevelHashValue helper for hashtable structured query builder. - // Constructs and returns Level XPath portion as a string. - // - private string HandleLevelHashValue(Object value) - { - string ret = ""; - - if (value is Array) - { - Array levelsArray = (Array)(value); - ret += "("; - for (int i = 0; i < levelsArray.Length; i++) + ret += ")"; + } + else { - ret += "(System/Level=" + levelsArray.GetValue(i).ToString() + ")"; - if ( i < (levelsArray.Length - 1)) + ret += "(System/Level=" + value + ")"; + } + + return ret; + } + + // + // HandleKeywordHashValue helper for hashtable structured query builder. + // Constructs and returns Keyword XPath portion as a string. + // + private string HandleKeywordHashValue(Object value) + { + Int64 keywordsMask = 0; + Int64 keywordLong = 0; + + if (value is Array) + { + foreach (Object keyword in (Array)value) { - ret += " or "; + if (KeywordStringToInt64(keyword.ToString(), ref keywordLong)) + { + keywordsMask |= keywordLong; + } } - } - ret += ")"; - } - else - { - ret += "(System/Level=" + value + ")"; - } - - return ret; - } - - // - // HandleKeywordHashValue helper for hashtable structured query builder. - // Constructs and returns Keyword XPath portion as a string. - // - private string HandleKeywordHashValue(Object value) - { - Int64 keywordsMask = 0; - Int64 keywordLong = 0; - - if (value is Array) - { - foreach (Object keyword in (Array) value) + } + else { - if (KeywordStringToInt64(keyword.ToString(), ref keywordLong)) + if (!KeywordStringToInt64(value.ToString(), ref keywordLong)) { - keywordsMask |= keywordLong; + return ""; } - } + keywordsMask |= keywordLong; + } + + return string.Format(CultureInfo.InvariantCulture, "System[band(Keywords,{0})]", keywordsMask); } - else + + // + // HandleContextHashValue helper for hashtable structured query builder. + // Constructs and returns UserID XPath portion as a string. + // Handles both SIDs and domain account names. + // Writes an error and returns an empty string if the SID or account names are not valid. + // + private string HandleContextHashValue(Object value) { - if ( !KeywordStringToInt64(value.ToString(), ref keywordLong)) - { - return ""; - } - keywordsMask |= keywordLong; - } - - return string.Format(CultureInfo.InvariantCulture, "System[band(Keywords,{0})]",keywordsMask); - } - - // - // HandleContextHashValue helper for hashtable structured query builder. - // Constructs and returns UserID XPath portion as a string. - // Handles both SIDs and domain account names. - // Writes an error and returns an empty string if the SID or account names are not valid. - // - private string HandleContextHashValue(Object value) - { - - SecurityIdentifier sidCandidate = null; - try - { - sidCandidate = new SecurityIdentifier(value.ToString()); - } - catch(ArgumentException) - { - WriteDebug(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidSIDFormat"), value)); - } - - if (sidCandidate == null) - { + SecurityIdentifier sidCandidate = null; try { - NTAccount acct = new NTAccount(value.ToString()); - sidCandidate = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); - + sidCandidate = new SecurityIdentifier(value.ToString()); } - catch(ArgumentException exc) + catch (ArgumentException) { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidContext"), value.ToString()); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord(outerExc, "InvalidContext", ErrorCategory.InvalidArgument, null)); - return ""; + WriteDebug(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidSIDFormat"), value)); } - } - - return string.Format(CultureInfo.InvariantCulture, "(System/Security[@UserID='{0}'])", sidCandidate.ToString()); - } - - // - // HandleStartTimeHashValue helper for hashtable structured query builder. - // Constructs and returns TimeCreated XPath portion as a string. - // NOTE that it also handles the hashtable "endtime" value (if supplied). - // - private string HandleStartTimeHashValue(Object value, Hashtable hash) - { - string ret = ""; - - DateTime startTime = new DateTime(); - if (!StringToDateTime(value.ToString(), ref startTime)) - { - return ""; - } - - startTime = startTime.ToUniversalTime(); - string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; - - if (hash.ContainsKey(hashkey_endtime_lc)) - { - DateTime endTime = new DateTime(); - if (!StringToDateTime(hash[hashkey_endtime_lc].ToString(), ref endTime)) + if (sidCandidate == null) { - return ""; + try + { + NTAccount acct = new NTAccount(value.ToString()); + sidCandidate = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); + } + catch (ArgumentException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidContext"), value.ToString()); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "InvalidContext", ErrorCategory.InvalidArgument, null)); + return ""; + } } - endTime = endTime.ToUniversalTime(); - string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; - - ret += string.Format(CultureInfo.InvariantCulture, - "(System/TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}'])", - startTimeFormatted, endTimeFormatted); - } - else - { - ret += string.Format(CultureInfo.InvariantCulture, - "(System/TimeCreated[@SystemTime>='{0}'])", - startTimeFormatted); + return string.Format(CultureInfo.InvariantCulture, "(System/Security[@UserID='{0}'])", sidCandidate.ToString()); } - return ret; - } - - // - // HandleEndTimeHashValue helper for hashtable structured query builder. - // Constructs and returns TimeCreated XPath portion as a string. - // NOTE that it also handles the hashtable "starttime" value (if supplied). - // - private string HandleEndTimeHashValue(Object value, Hashtable hash) - { - string ret = ""; - - DateTime endTime = new DateTime(); - if (!StringToDateTime(value.ToString(), ref endTime)) + // + // HandleStartTimeHashValue helper for hashtable structured query builder. + // Constructs and returns TimeCreated XPath portion as a string. + // NOTE that it also handles the hashtable "endtime" value (if supplied). + // + private string HandleStartTimeHashValue(Object value, Hashtable hash) { - return ""; - } + string ret = ""; - endTime = endTime.ToUniversalTime(); - string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." - + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; - - if (hash.ContainsKey(hashkey_starttime_lc)) - { DateTime startTime = new DateTime(); - if (!StringToDateTime(hash[hashkey_starttime_lc].ToString(), ref startTime)) + if (!StringToDateTime(value.ToString(), ref startTime)) { return ""; } startTime = startTime.ToUniversalTime(); - string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." - + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; - ret += string.Format(CultureInfo.InvariantCulture, "(System/TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}'])", - startTimeFormatted, endTimeFormatted); - } - else - { - ret += string.Format(CultureInfo.InvariantCulture, "(System/TimeCreated[@SystemTime<='{0}'])", - endTimeFormatted); - } - - return ret; - } - - // - // HandleDataHashValue helper for hashtable structured query builder. - // Constructs and returns EventData/Data XPath portion as a string. - // - private string HandleDataHashValue(Object value) - { - string ret = ""; - if (value is Array) - { - Array dataArray = (Array)(value); - ret += "("; - for (int i = 0; i < dataArray.Length; i++) + if (hash.ContainsKey(hashkey_endtime_lc)) { - ret += string.Format(CultureInfo.InvariantCulture, "(EventData/Data='{0}')", dataArray.GetValue(i).ToString()); - if ( i < (dataArray.Length - 1)) + DateTime endTime = new DateTime(); + if (!StringToDateTime(hash[hashkey_endtime_lc].ToString(), ref endTime)) { - ret += " or "; + return ""; } - } - ret += ")"; - } - else - { - ret += string.Format(CultureInfo.InvariantCulture, "(EventData/Data='{0}')", value); - } - - return ret; - } - - // - // Helper checking whether at least one of log, _path, provider is specified. - // It will ThrowTerminatingError in case none of those keys are present. - // - private void CheckHashTableForQueryPathPresence(Hashtable hash) - { - bool isLogHash = (hash.ContainsKey(hashkey_logname_lc)); - bool isPathHash = (hash.ContainsKey(hashkey_path_lc)); - bool isProviderHash = (hash.ContainsKey(hashkey_providername_lc)); + endTime = endTime.ToUniversalTime(); + string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; - if (!isLogHash && !isProviderHash && !isPathHash) - { - string msg = _resourceMgr.GetString("LogProviderOrPathNeeded"); - Exception exc = new Exception(msg); - ThrowTerminatingError(new ErrorRecord(exc, "LogProviderOrPathNeeded", ErrorCategory.InvalidArgument, null)); - } - } - - // - // TerminateForNonEvtxFileWithoutOldest terminates for .evt and .etl files unless -Oldest is specified. - // - private void TerminateForNonEvtxFileWithoutOldest (string fileName) - { - if (!Oldest.IsPresent) - { - if (System.IO.Path.GetExtension(fileName).Equals(".etl", StringComparison.OrdinalIgnoreCase) || - System.IO.Path.GetExtension(fileName).Equals(".evt", StringComparison.OrdinalIgnoreCase)) - { - string msg = _resourceMgr.GetString("SpecifyOldestForEtlEvt"); - Exception exc = new Exception (string.Format(CultureInfo.InvariantCulture, msg, fileName)); - ThrowTerminatingError (new ErrorRecord(exc, "SpecifyOldestForEtlEvt", ErrorCategory.InvalidArgument, fileName)); - } - } - } - - // - // ValidateLogName writes an error if logName is not a valid log. - // It also terminates for direct ETW channels unless -Oldest is specified. - // - private bool ValidateLogName (string logName, EventLogSession eventLogSession) - { - - EventLogConfiguration logObj; - try - { - logObj = new EventLogConfiguration(logName, eventLogSession); - } - catch (EventLogNotFoundException) - { - string msg = _resourceMgr.GetString("NoMatchingLogsFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, this._computerName, logName)); - WriteError (new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logName)); - return false; - } - catch (Exception exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("LogInfoUnavailable"), - logName, exc.Message); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord( outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); - return false; - } - if (!Oldest.IsPresent) - { - if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) - { - string msg = _resourceMgr.GetString("SpecifyOldestForLog"); - Exception exc = new Exception (string.Format(CultureInfo.InvariantCulture, msg, logName)); - ThrowTerminatingError (new ErrorRecord(exc, "SpecifyOldestForLog", ErrorCategory.InvalidArgument, logName)); - } - } - return true; - } - - // - // ExtendPredicate helper for the query builder. - // Extends the XPath predicate string. - // - private void ExtendPredicate(ref string xpathString) - { - if (xpathString.Length != 0) - { - xpathString += " and "; - } - } - - - // - // KeywordStringToInt64 helper converts a string to Int64. - // Returns true and keyLong ref if successful. - // Writes an error and returns false if keyString cannot be converted. - // - private bool KeywordStringToInt64(string keyString, ref Int64 keyLong) - { - try - { - keyLong = Convert.ToInt64(keyString, CultureInfo.InvariantCulture); - - } - catch (Exception exc) - { - string msg = _resourceMgr.GetString("KeywordLongExpected"); - Exception outerExc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, keyString), exc); - WriteError(new ErrorRecord(outerExc, "KeywordLongExpected", ErrorCategory.InvalidArgument, null)); - return false; - } - - return true; - } - - // - // StringToDateTime helper converts a string to DateTime object. - // Returns true and DateTime ref if successful. - // Writes an error and returns false if dtString cannot be converted. - // - private bool StringToDateTime(string dtString, ref DateTime dt) - { - try - { - dt = DateTime.Parse(dtString, CultureInfo.CurrentCulture); - } - catch (FormatException exc) - { - string msg = _resourceMgr.GetString("DateTimeExpected"); - Exception outerExc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, dtString), exc); - WriteError(new ErrorRecord(outerExc, "DateTimeExpected", ErrorCategory.InvalidArgument, null)); - return false; - } - - return true; - } - - // - // ValidateAndResolveFilePath helper. - // Returns a string collection of resolved file paths. - // Writes non-terminating errors for invalid paths - // and returns an empty colleciton. - // - StringCollection ValidateAndResolveFilePath (string path) - { - - StringCollection retColl = new StringCollection(); - - Collection resolvedPathSubset = null; - try - { - resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(path); - } - catch (PSNotSupportedException notSupported) - { - WriteError(new ErrorRecord(notSupported, "", ErrorCategory.ObjectNotFound, path)); - return retColl; - } - catch (System.Management.Automation.DriveNotFoundException driveNotFound) - { - WriteError(new ErrorRecord(driveNotFound, "", ErrorCategory.ObjectNotFound, path)); - return retColl; - } - catch (ProviderNotFoundException providerNotFound) - { - WriteError(new ErrorRecord(providerNotFound, "", ErrorCategory.ObjectNotFound, path)); - return retColl; - } - catch (ItemNotFoundException pathNotFound) - { - WriteError(new ErrorRecord(pathNotFound, "", ErrorCategory.ObjectNotFound, path)); - return retColl; - } - catch(Exception exc) - { - WriteError(new ErrorRecord(exc, "", ErrorCategory.ObjectNotFound, path)); - return retColl; - } - - 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, path)); - WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, path)); - continue; - } - - // - // Check the extension: only .evt, .evtx, and .etl files are allowed. - // If the file was specified without wildcards, display an error. - // Otherwise, skip silently. - // - if (!System.IO.Path.GetExtension(pi.Path).Equals(".evt", StringComparison.OrdinalIgnoreCase ) && - !System.IO.Path.GetExtension(pi.Path).Equals(".evtx", StringComparison.OrdinalIgnoreCase ) && - !System.IO.Path.GetExtension(pi.Path).Equals(".etl", StringComparison.OrdinalIgnoreCase )) - { - if (!WildcardPattern.ContainsWildcardCharacters(path)) - { - string msg = _resourceMgr.GetString("NotALogFile"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, pi.ProviderPath)); - WriteError(new ErrorRecord(exc, "NotALogFile", ErrorCategory.InvalidArgument, path)); - } - continue; - } - - TerminateForNonEvtxFileWithoutOldest (pi.ProviderPath); - - retColl.Add(pi.ProviderPath.ToLowerInvariant()); - - } - - return retColl; - } - - // - // CheckHashTablesForNullValues() checks all _selector values - // and writes a terminating error when it encounters a null - // as a single value or as part of an array. - // - private void CheckHashTablesForNullValues() - { - foreach (Hashtable hash in _selector) - { - foreach (string key in hash.Keys) - { - Object value = hash[key]; - if (value == null) - { - string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); - ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); - } - else if (value is Array) - { - foreach (Object elt in (Array)value) - { - if (elt == null) - { - string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); - ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); - } - } - } - } - } - } - - // - // AddProviderPredicatesToFilter() builds an XPath query - // by adding provider predicates to _filter. - // Note that this is by no means an XPath expression parser - // and will may produce garbage if the _filterXPath expression provided by the user is invalid. - // However, we are relying on the EventLog XPath parser to reject the garbage later on. - // - private string AddProviderPredicatesToFilter (StringCollection providers) - { - if (providers.Count == 0) - { - return _filter; - } - - string ret = _filter; - string predicate = BuildProvidersPredicate (providers); - - if (_filter.Equals("*", StringComparison.OrdinalIgnoreCase)) - { - ret += "[" + predicate + "]"; - } - else - { - // - // Extend the XPath provided in the _filter - // - int lastPredClose = _filter.LastIndexOf(']'); - if (lastPredClose == -1) - { - - ret += "[" + predicate + "]"; + ret += string.Format(CultureInfo.InvariantCulture, + "(System/TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}'])", + startTimeFormatted, endTimeFormatted); } else { - ret = ret.Insert (lastPredClose, " and " + predicate); + ret += string.Format(CultureInfo.InvariantCulture, + "(System/TimeCreated[@SystemTime>='{0}'])", + startTimeFormatted); + } + + return ret; + } + + + // + // HandleEndTimeHashValue helper for hashtable structured query builder. + // Constructs and returns TimeCreated XPath portion as a string. + // NOTE that it also handles the hashtable "starttime" value (if supplied). + // + private string HandleEndTimeHashValue(Object value, Hashtable hash) + { + string ret = ""; + + DateTime endTime = new DateTime(); + if (!StringToDateTime(value.ToString(), ref endTime)) + { + return ""; + } + + endTime = endTime.ToUniversalTime(); + string endTimeFormatted = endTime.ToString("s", CultureInfo.InvariantCulture) + "." + + endTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + if (hash.ContainsKey(hashkey_starttime_lc)) + { + DateTime startTime = new DateTime(); + if (!StringToDateTime(hash[hashkey_starttime_lc].ToString(), ref startTime)) + { + return ""; + } + + startTime = startTime.ToUniversalTime(); + string startTimeFormatted = startTime.ToString("s", CultureInfo.InvariantCulture) + "." + + startTime.Millisecond.ToString("d3", CultureInfo.InvariantCulture) + "Z"; + + ret += string.Format(CultureInfo.InvariantCulture, "(System/TimeCreated[@SystemTime>='{0}' and @SystemTime<='{1}'])", + startTimeFormatted, endTimeFormatted); + } + else + { + ret += string.Format(CultureInfo.InvariantCulture, "(System/TimeCreated[@SystemTime<='{0}'])", + endTimeFormatted); + } + + return ret; + } + + // + // HandleDataHashValue helper for hashtable structured query builder. + // Constructs and returns EventData/Data XPath portion as a string. + // + private string HandleDataHashValue(Object value) + { + string ret = ""; + if (value is Array) + { + Array dataArray = (Array)(value); + ret += "("; + for (int i = 0; i < dataArray.Length; i++) + { + ret += string.Format(CultureInfo.InvariantCulture, "(EventData/Data='{0}')", dataArray.GetValue(i).ToString()); + if (i < (dataArray.Length - 1)) + { + ret += " or "; + } + } + ret += ")"; + } + else + { + ret += string.Format(CultureInfo.InvariantCulture, "(EventData/Data='{0}')", value); + } + + return ret; + } + + + // + // Helper checking whether at least one of log, _path, provider is specified. + // It will ThrowTerminatingError in case none of those keys are present. + // + private void CheckHashTableForQueryPathPresence(Hashtable hash) + { + bool isLogHash = (hash.ContainsKey(hashkey_logname_lc)); + bool isPathHash = (hash.ContainsKey(hashkey_path_lc)); + bool isProviderHash = (hash.ContainsKey(hashkey_providername_lc)); + + if (!isLogHash && !isProviderHash && !isPathHash) + { + string msg = _resourceMgr.GetString("LogProviderOrPathNeeded"); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "LogProviderOrPathNeeded", ErrorCategory.InvalidArgument, null)); } } - return ret; - } - - - // - // BuildProvidersPredicate() builds a predicate expression like: - // "System/Provider[@Name='a' or @Name='b']" - // for all provider names specified in the "providers" argument. - // - private string BuildProvidersPredicate(StringCollection providers) - { - if (providers.Count == 0) + // + // TerminateForNonEvtxFileWithoutOldest terminates for .evt and .etl files unless -Oldest is specified. + // + private void TerminateForNonEvtxFileWithoutOldest(string fileName) { - return ""; - } - - string predicate = "System/Provider["; - for (int i = 0; i < providers.Count; i++) - { - predicate += "@Name='" + providers[i] + "'"; - if (i < (providers.Count - 1)) + if (!Oldest.IsPresent) { - predicate += " or "; - } - } - predicate += "]"; - - return predicate; - } - - - // - // BuildAllProvidersPredicate() builds a predicate expression like: - // "System/Provider[@Name='a' or @Name='b']" - // for all unique provider names specified in _providersByLogMap. - // Eliminates duplicates, too, since the same provider can - // be writing to several different logs. - // - private string BuildAllProvidersPredicate() - { - if (_providersByLogMap.Count == 0) - { - return ""; - } - - string predicate = "System/Provider["; - - List uniqueProviderNames = new List(); - - foreach (string logKey in _providersByLogMap.Keys) - { - for (int i = 0; i < _providersByLogMap[logKey].Count; i++) - { - string lowerCaseProviderName = _providersByLogMap[logKey][i].ToLowerInvariant(); - if (!uniqueProviderNames.Contains(lowerCaseProviderName)) + if (System.IO.Path.GetExtension(fileName).Equals(".etl", StringComparison.OrdinalIgnoreCase) || + System.IO.Path.GetExtension(fileName).Equals(".evt", StringComparison.OrdinalIgnoreCase)) { - uniqueProviderNames.Add(lowerCaseProviderName); + string msg = _resourceMgr.GetString("SpecifyOldestForEtlEvt"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, fileName)); + ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForEtlEvt", ErrorCategory.InvalidArgument, fileName)); } } } - for (int i = 0; i < uniqueProviderNames.Count; i++) + // + // ValidateLogName writes an error if logName is not a valid log. + // It also terminates for direct ETW channels unless -Oldest is specified. + // + private bool ValidateLogName(string logName, EventLogSession eventLogSession) { - predicate += "@Name='" + uniqueProviderNames[i] + "'"; - if (i < uniqueProviderNames.Count - 1) + EventLogConfiguration logObj; + try { - predicate += " or "; + logObj = new EventLogConfiguration(logName, eventLogSession); } - } - - predicate += "]"; - - return predicate; - } - - - // - // AddLogsForProviderToInternalMap helper. - // Retrieves log names to which _providerName writes. - // NOTE: there are many misconfigured providers in the system. - // We therefore catch EventLogException excpetions and write them out as non-terminating errors. - // The results are added to _providersByLogMap dictionary. - // - private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, string providerName) - { - - try - { - ProviderMetadata providerMetadata = new ProviderMetadata(providerName, eventLogSession, CultureInfo.CurrentCulture); - - System.Collections.IEnumerable logLinks = providerMetadata.LogLinks; - - foreach (EventLogLink logLink in logLinks) + catch (EventLogNotFoundException) { + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logName)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logName)); + return false; + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + logName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); + return false; + } + if (!Oldest.IsPresent) + { + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) + { + string msg = _resourceMgr.GetString("SpecifyOldestForLog"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, logName)); + ThrowTerminatingError(new ErrorRecord(exc, "SpecifyOldestForLog", ErrorCategory.InvalidArgument, logName)); + } + } + return true; + } - if (!_providersByLogMap.ContainsKey(logLink.LogName.ToLowerInvariant())) - { - // - // Skip direct ETW channels unless -force is present. - // Error out for direct channels unless -oldest is present. - // - EventLogConfiguration logObj = new EventLogConfiguration(logLink.LogName, eventLogSession); - if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) - { - if (!Force.IsPresent) + // + // ExtendPredicate helper for the query builder. + // Extends the XPath predicate string. + // + private void ExtendPredicate(ref string xpathString) + { + if (xpathString.Length != 0) + { + xpathString += " and "; + } + } + + + // + // KeywordStringToInt64 helper converts a string to Int64. + // Returns true and keyLong ref if successful. + // Writes an error and returns false if keyString cannot be converted. + // + private bool KeywordStringToInt64(string keyString, ref Int64 keyLong) + { + try + { + keyLong = Convert.ToInt64(keyString, CultureInfo.InvariantCulture); + } + catch (Exception exc) + { + string msg = _resourceMgr.GetString("KeywordLongExpected"); + Exception outerExc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, keyString), exc); + WriteError(new ErrorRecord(outerExc, "KeywordLongExpected", ErrorCategory.InvalidArgument, null)); + return false; + } + + return true; + } + + // + // StringToDateTime helper converts a string to DateTime object. + // Returns true and DateTime ref if successful. + // Writes an error and returns false if dtString cannot be converted. + // + private bool StringToDateTime(string dtString, ref DateTime dt) + { + try + { + dt = DateTime.Parse(dtString, CultureInfo.CurrentCulture); + } + catch (FormatException exc) + { + string msg = _resourceMgr.GetString("DateTimeExpected"); + Exception outerExc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, dtString), exc); + WriteError(new ErrorRecord(outerExc, "DateTimeExpected", ErrorCategory.InvalidArgument, null)); + return false; + } + + return true; + } + + // + // ValidateAndResolveFilePath helper. + // Returns a string collection of resolved file paths. + // Writes non-terminating errors for invalid paths + // and returns an empty colleciton. + // + private StringCollection ValidateAndResolveFilePath(string path) + { + StringCollection retColl = new StringCollection(); + + Collection resolvedPathSubset = null; + try + { + resolvedPathSubset = SessionState.Path.GetResolvedPSPathFromPSPath(path); + } + catch (PSNotSupportedException notSupported) + { + WriteError(new ErrorRecord(notSupported, "", ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + WriteError(new ErrorRecord(driveNotFound, "", ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError(new ErrorRecord(providerNotFound, "", ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError(new ErrorRecord(pathNotFound, "", ErrorCategory.ObjectNotFound, path)); + return retColl; + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, "", ErrorCategory.ObjectNotFound, path)); + return retColl; + } + + 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, path)); + WriteError(new ErrorRecord(exc, "NotAFileSystemPath", ErrorCategory.InvalidArgument, path)); + continue; + } + + // + // Check the extension: only .evt, .evtx, and .etl files are allowed. + // If the file was specified without wildcards, display an error. + // Otherwise, skip silently. + // + if (!System.IO.Path.GetExtension(pi.Path).Equals(".evt", StringComparison.OrdinalIgnoreCase) && + !System.IO.Path.GetExtension(pi.Path).Equals(".evtx", StringComparison.OrdinalIgnoreCase) && + !System.IO.Path.GetExtension(pi.Path).Equals(".etl", StringComparison.OrdinalIgnoreCase)) + { + if (!WildcardPattern.ContainsWildcardCharacters(path)) + { + string msg = _resourceMgr.GetString("NotALogFile"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, pi.ProviderPath)); + WriteError(new ErrorRecord(exc, "NotALogFile", ErrorCategory.InvalidArgument, path)); + } + continue; + } + + TerminateForNonEvtxFileWithoutOldest(pi.ProviderPath); + + retColl.Add(pi.ProviderPath.ToLowerInvariant()); + } + + return retColl; + } + + // + // CheckHashTablesForNullValues() checks all _selector values + // and writes a terminating error when it encounters a null + // as a single value or as part of an array. + // + private void CheckHashTablesForNullValues() + { + foreach (Hashtable hash in _selector) + { + foreach (string key in hash.Keys) + { + Object value = hash[key]; + if (value == null) + { + string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); + ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); + } + else if (value is Array) + { + foreach (Object elt in (Array)value) { + if (elt == null) + { + string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); + ThrowTerminatingError(new ErrorRecord(exc, "NullNotAllowedInHashtable", ErrorCategory.InvalidArgument, key)); + } + } + } + } + } + } + + // + // AddProviderPredicatesToFilter() builds an XPath query + // by adding provider predicates to _filter. + // Note that this is by no means an XPath expression parser + // and will may produce garbage if the _filterXPath expression provided by the user is invalid. + // However, we are relying on the EventLog XPath parser to reject the garbage later on. + // + private string AddProviderPredicatesToFilter(StringCollection providers) + { + if (providers.Count == 0) + { + return _filter; + } + + string ret = _filter; + string predicate = BuildProvidersPredicate(providers); + + if (_filter.Equals("*", StringComparison.OrdinalIgnoreCase)) + { + ret += "[" + predicate + "]"; + } + else + { + // + // Extend the XPath provided in the _filter + // + int lastPredClose = _filter.LastIndexOf(']'); + if (lastPredClose == -1) + { + ret += "[" + predicate + "]"; + } + else + { + ret = ret.Insert(lastPredClose, " and " + predicate); + } + } + + return ret; + } + + + // + // BuildProvidersPredicate() builds a predicate expression like: + // "System/Provider[@Name='a' or @Name='b']" + // for all provider names specified in the "providers" argument. + // + private string BuildProvidersPredicate(StringCollection providers) + { + if (providers.Count == 0) + { + return ""; + } + + string predicate = "System/Provider["; + for (int i = 0; i < providers.Count; i++) + { + predicate += "@Name='" + providers[i] + "'"; + if (i < (providers.Count - 1)) + { + predicate += " or "; + } + } + predicate += "]"; + + return predicate; + } + + + // + // BuildAllProvidersPredicate() builds a predicate expression like: + // "System/Provider[@Name='a' or @Name='b']" + // for all unique provider names specified in _providersByLogMap. + // Eliminates duplicates, too, since the same provider can + // be writing to several different logs. + // + private string BuildAllProvidersPredicate() + { + if (_providersByLogMap.Count == 0) + { + return ""; + } + + string predicate = "System/Provider["; + + List uniqueProviderNames = new List(); + + foreach (string logKey in _providersByLogMap.Keys) + { + for (int i = 0; i < _providersByLogMap[logKey].Count; i++) + { + string lowerCaseProviderName = _providersByLogMap[logKey][i].ToLowerInvariant(); + if (!uniqueProviderNames.Contains(lowerCaseProviderName)) + { + uniqueProviderNames.Add(lowerCaseProviderName); + } + } + } + + for (int i = 0; i < uniqueProviderNames.Count; i++) + { + predicate += "@Name='" + uniqueProviderNames[i] + "'"; + if (i < uniqueProviderNames.Count - 1) + { + predicate += " or "; + } + } + + predicate += "]"; + + return predicate; + } + + + // + // AddLogsForProviderToInternalMap helper. + // Retrieves log names to which _providerName writes. + // NOTE: there are many misconfigured providers in the system. + // We therefore catch EventLogException excpetions and write them out as non-terminating errors. + // The results are added to _providersByLogMap dictionary. + // + private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, string providerName) + { + try + { + ProviderMetadata providerMetadata = new ProviderMetadata(providerName, eventLogSession, CultureInfo.CurrentCulture); + + System.Collections.IEnumerable logLinks = providerMetadata.LogLinks; + + foreach (EventLogLink logLink in logLinks) + { + if (!_providersByLogMap.ContainsKey(logLink.LogName.ToLowerInvariant())) + { + // + // Skip direct ETW channels unless -force is present. + // Error out for direct channels unless -oldest is present. + // + EventLogConfiguration logObj = new EventLogConfiguration(logLink.LogName, eventLogSession); + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) + { + if (!Force.IsPresent) + { + continue; + } + + ValidateLogName(logLink.LogName, eventLogSession); + } + + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); + + StringCollection provColl = new StringCollection(); + provColl.Add(providerName.ToLowerInvariant()); + + _providersByLogMap.Add(logLink.LogName.ToLowerInvariant(), provColl); + } + else + + { + // + // Log is there: add provider, if needed + // + StringCollection coll = _providersByLogMap[logLink.LogName.ToLowerInvariant()]; + + if (!coll.Contains(providerName.ToLowerInvariant())) + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); + + coll.Add(providerName.ToLowerInvariant()); + } + } + } + } + catch (System.Diagnostics.Eventing.Reader.EventLogException exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("ProviderMetadataUnavailable"), + providerName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); + return; + } + } + + // + // FindLogNamesMatchingWildcards helper. + // Finds all logs whose names match wildcard patterns in the 'logPatterns' argument. + // For each non-matched pattern, a non-terminating error is written. + // The results are added to _logNamesMatchingWildcard array. + // + private void FindLogNamesMatchingWildcards(EventLogSession eventLogSession, IEnumerable logPatterns) + { + if (_logNamesMatchingWildcard == null) + { + _logNamesMatchingWildcard = new StringCollection(); + } + else + { + _logNamesMatchingWildcard.Clear(); + } + + foreach (string logPattern in logPatterns) + { + bool bMatched = false; + foreach (string actualLogName in eventLogSession.GetLogNames()) + { + WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); + + if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) + && (logPattern.Equals(actualLogName, StringComparison.CurrentCultureIgnoreCase))) + || + (wildLogPattern.IsMatch(actualLogName))) + { + // + // Skip direct ETW channels matching wildcards unless -force is present. + // Error out for direct channels unless -oldest is present. + // + EventLogConfiguration logObj; + try + { + logObj = new EventLogConfiguration(actualLogName, eventLogSession); + } + catch (Exception exc) + { + string msg = string.Format(CultureInfo.InvariantCulture, + _resourceMgr.GetString("LogInfoUnavailable"), + actualLogName, exc.Message); + Exception outerExc = new Exception(msg, exc); + WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); continue; } - ValidateLogName (logLink.LogName, eventLogSession); - } - - WriteVerbose(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); - - StringCollection provColl = new StringCollection(); - provColl.Add(providerName.ToLowerInvariant()); - - _providersByLogMap.Add(logLink.LogName.ToLowerInvariant(), provColl); - } - else - - { - // - // Log is there: add provider, if needed - // - StringCollection coll = _providersByLogMap[logLink.LogName.ToLowerInvariant()]; - - if (!coll.Contains(providerName.ToLowerInvariant())) - { - WriteVerbose (string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderLogLink"), providerName, logLink.LogName)); - - coll.Add(providerName.ToLowerInvariant()); - } - } - } - } - catch (System.Diagnostics.Eventing.Reader.EventLogException exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("ProviderMetadataUnavailable"), - providerName, exc.Message); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord( outerExc, "ProviderMetadataUnavailable", ErrorCategory.NotSpecified, null)); - return; - } - } - - // - // FindLogNamesMatchingWildcards helper. - // Finds all logs whose names match wildcard patterns in the 'logPatterns' argument. - // For each non-matched pattern, a non-terminating error is written. - // The results are added to _logNamesMatchingWildcard array. - // - private void FindLogNamesMatchingWildcards (EventLogSession eventLogSession, IEnumerable logPatterns) - { - if (_logNamesMatchingWildcard == null) - { - _logNamesMatchingWildcard = new StringCollection(); - } - else - { - _logNamesMatchingWildcard.Clear(); - } - - foreach (string logPattern in logPatterns) - { - bool bMatched = false; - foreach (string actualLogName in eventLogSession.GetLogNames()) - { - WildcardPattern wildLogPattern = new WildcardPattern(logPattern, WildcardOptions.IgnoreCase); - - if (((!WildcardPattern.ContainsWildcardCharacters(logPattern)) - && (logPattern.Equals(actualLogName, StringComparison.CurrentCultureIgnoreCase))) - || - (wildLogPattern.IsMatch(actualLogName))) - { - // - // Skip direct ETW channels matching wildcards unless -force is present. - // Error out for direct channels unless -oldest is present. - // - EventLogConfiguration logObj; - try - { - logObj = new EventLogConfiguration(actualLogName, eventLogSession); - } - catch (Exception exc) - { - string msg = string.Format(CultureInfo.InvariantCulture, - _resourceMgr.GetString("LogInfoUnavailable"), - actualLogName, exc.Message); - Exception outerExc = new Exception (msg, exc); - WriteError(new ErrorRecord( outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); - continue; - } - - if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) - { - if (WildcardPattern.ContainsWildcardCharacters(logPattern) && !Force.IsPresent) + if (logObj.LogType == EventLogType.Debug || logObj.LogType == EventLogType.Analytical) { - continue; + if (WildcardPattern.ContainsWildcardCharacters(logPattern) && !Force.IsPresent) + { + continue; + } + + ValidateLogName(actualLogName, eventLogSession); } - ValidateLogName(actualLogName, eventLogSession); + if (!_logNamesMatchingWildcard.Contains(actualLogName.ToLowerInvariant())) + { + _logNamesMatchingWildcard.Add(actualLogName.ToLowerInvariant()); + } + bMatched = true; } - - if (!_logNamesMatchingWildcard.Contains(actualLogName.ToLowerInvariant())) - { - _logNamesMatchingWildcard.Add(actualLogName.ToLowerInvariant()); - } - bMatched = true; - } - } - if (!bMatched) - { - string msg = _resourceMgr.GetString("NoMatchingLogsFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, this._computerName, logPattern)); - WriteError (new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logPattern)); - } - } - - } - - // - // FindProvidersByLogForWildcardPatterns helper. - // Finds all providers whose names match wildcard patterns in 'providerPatterns' argument. - // For each non-matched pattern, a non-terminating error is written. - // The results are added to _providersByLogMap dictionary (keyed by log names to which these providers write). - // - private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSession, IEnumerable providerPatterns) - { - _providersByLogMap.Clear(); - - foreach (string provPattern in providerPatterns) - { - bool bMatched = false; - foreach (string provName in eventLogSession.GetProviderNames()) - { - WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); - - if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) - && (provPattern.Equals(provName, StringComparison.CurrentCultureIgnoreCase))) - || - (wildProvPattern.IsMatch(provName))) + } + if (!bMatched) { - WriteVerbose (string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName)); - AddLogsForProviderToInternalMap(eventLogSession, provName); - bMatched = true; - } + string msg = _resourceMgr.GetString("NoMatchingLogsFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, logPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingLogsFound", ErrorCategory.ObjectNotFound, logPattern)); + } } - if (!bMatched) + } + + // + // FindProvidersByLogForWildcardPatterns helper. + // Finds all providers whose names match wildcard patterns in 'providerPatterns' argument. + // For each non-matched pattern, a non-terminating error is written. + // The results are added to _providersByLogMap dictionary (keyed by log names to which these providers write). + // + private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSession, IEnumerable providerPatterns) + { + _providersByLogMap.Clear(); + + foreach (string provPattern in providerPatterns) { - string msg = _resourceMgr.GetString("NoMatchingProvidersFound"); - Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, this._computerName, provPattern)); - WriteError (new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, provPattern)); + bool bMatched = false; + foreach (string provName in eventLogSession.GetProviderNames()) + { + WildcardPattern wildProvPattern = new WildcardPattern(provPattern, WildcardOptions.IgnoreCase); + + if (((!WildcardPattern.ContainsWildcardCharacters(provPattern)) + && (provPattern.Equals(provName, StringComparison.CurrentCultureIgnoreCase))) + || + (wildProvPattern.IsMatch(provName))) + { + WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName)); + AddLogsForProviderToInternalMap(eventLogSession, provName); + bMatched = true; + } + } + if (!bMatched) + { + string msg = _resourceMgr.GetString("NoMatchingProvidersFound"); + Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, _computerName, provPattern)); + WriteError(new ErrorRecord(exc, "NoMatchingProvidersFound", ErrorCategory.ObjectNotFound, provPattern)); + } } } } - - } - } - + diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs index d73dcab27..5eb1a5d22 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs @@ -6,106 +6,105 @@ using System; using System.Collections.Generic; using System.Text; -using System.Management.Automation; +using System.Management.Automation; using System.ComponentModel; - -namespace Microsoft.PowerShell.Commands + +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. + /// 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. /// - public GetEventPSSnapIn() - : base() + [RunInstaller(true)] + public class GetEventPSSnapIn : PSSnapIn { - } - - /// - /// 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 mshsnapin. - /// - public override string[] Types - { - get + /// + /// Create an instance of the GetEventPSSnapIn class. + /// + public GetEventPSSnapIn() + : base() { - return _types; } - } - private string[] _types = new string[] {"getevent.types.ps1xml"}; - /// - /// Get format files to be used for this mshsnapin. - /// - public override string[] Formats - { - get + /// + /// Specify the name of the PowerShell snap-in. + /// + public override string Name { - return _formats; + get + { + return "Microsoft.Powershell.GetEvent"; + } } - } - private string[] _formats = new string[] {"Event.format.ps1xml"}; - } + /// + /// 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 mshsnapin. + /// + public override string[] Types + { + get + { + return _types; + } + } + private string[] _types = new string[] { "getevent.types.ps1xml" }; + + /// + /// Get format files to be used for this mshsnapin. + /// + 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 index ffa460119..ad5da97ff 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs @@ -8,7 +8,7 @@ using System.Text; using System.IO; using System.Xml; using System.Net; -using System.Management.Automation; +using System.Management.Automation; using System.ComponentModel; using System.Reflection; using System.Globalization; @@ -30,647 +30,635 @@ using Microsoft.PowerShell.Commands.Diagnostics.Common; namespace Microsoft.PowerShell.Commands { - - /// - /// Class that implements the Get-Counter cmdlet. - /// - [Cmdlet("Import", "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "http://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 + /// + /// Class that implements the Get-Counter cmdlet. + /// + [Cmdlet("Import", "Counter", DefaultParameterSetName = "GetCounterSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=138338")] + public sealed class ImportCounterCommand : PSCmdlet { - get {return _path;} - set {_path = value;} - } - private string[] _path; + // + // Path parameter + // + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true, + HelpMessageBaseName = "GetEventResources")] + [Alias("PSPath")] - private StringCollection _resolvedPaths = new StringCollection(); + [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 List _accumulatedFileNames = new List(); - + private StringCollection _resolvedPaths = new StringCollection(); - // - // 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 = new string[0]; + private List _accumulatedFileNames = new List(); - // - // 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 = new string[0]; - - // - // 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() - { - _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); - _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); - } - - // - // EndProcessing() is invoked once per pipeline - // - protected override void EndProcessing() - { - // - // Resolve and validate the Path argument: present for all parametersets. - // - if (!ResolveFilePaths ()) + // 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 { - return; + get { return _listSet; } + set { _listSet = value; } } - ValidateFilePaths(); - - switch (ParameterSetName) - { - case "ListSetSet": - ProcessListSet(); - break; + private string[] _listSet = new string[0]; - case "GetCounterSet": - ProcessGetCounter(); - break; - - case "SummarySet": - ProcessSummary(); - break; - - default: - Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); - break; + + // + // StartTime parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "GetCounterSet", + HelpMessageBaseName = "GetEventResources")] + public DateTime StartTime + { + get { return _startTime; } + set { _startTime = value; } } - - _pdhHelper.Dispose(); - } - - - // - // Handle Control-C - // - protected override void StopProcessing() - { - _stopping = true; - _pdhHelper.Dispose(); - } + private DateTime _startTime = DateTime.MinValue; - // - // 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) + // + // EndTime parameter + // + [Parameter( + ValueFromPipeline = false, + ValueFromPipelineByPropertyName = false, + ParameterSetName = "GetCounterSet", + HelpMessageBaseName = "GetEventResources")] + public DateTime EndTime { - ReportPdhError(res, true); - return; + 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 = new string[0]; + + // + // 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); } - CounterFileInfo summaryObj; - res = _pdhHelper.GetFilesSummary (out summaryObj); - if (res != 0) + // + // BeginProcessing() is invoked once per pipeline + // + protected override void BeginProcessing() { - 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; + _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + _pdhHelper = new PdhHelper(System.Environment.OSVersion.Version.Major < 6); } - StringCollection machineNames = new StringCollection(); - res = _pdhHelper.EnumBlgFilesMachines(ref machineNames); - if (res != 0) + // + // EndProcessing() is invoked once per pipeline + // + protected override void EndProcessing() { - ReportPdhError(res, true); - return; + // + // 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, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + break; + } + + _pdhHelper.Dispose(); } - foreach (string machine in machineNames) + + // + // Handle Control-C + // + protected override void StopProcessing() { - StringCollection counterSets = new StringCollection(); - res = _pdhHelper.EnumObjects(machine, ref counterSets); + _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(); - - foreach (string pattern in _listSet) + if (_counter.Length > 0) { - 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); + foreach (string path in _counter) + { + StringCollection expandedPaths; + res = _pdhHelper.ExpandWildCardPath(path, out expandedPaths); if (res != 0) { + WriteDebug(path); ReportPdhError(res, false); continue; } - string[] instanceArray = new string[counterSetInstances.Count]; - int i = 0; - foreach (string instance in counterSetInstances) + foreach (string expandedPath in expandedPaths) { - instanceArray[i++] = instance; - } + 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)); - Dictionary counterInstanceMapping = new Dictionary(); - foreach (string counter in counterSetCounters) - { - counterInstanceMapping.Add(counter, instanceArray); + continue; + } + validPaths.Add(expandedPath); } - - 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) + if (validPaths.Count == 0) { - 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)); + return; } } - } - - - - } - - // - // 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) + else { - 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); + res = _pdhHelper.GetValidPathsFromFiles(ref validPaths); 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; + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterPathsInFilesInvalid")); + Exception exc = new Exception(msg); + ThrowTerminatingError(new ErrorRecord(exc, "CounterPathsInFilesInvalid", ErrorCategory.InvalidResult, null)); } - } - else - { - res = _pdhHelper.GetValidPathsFromFiles(ref validPaths); + + res = _pdhHelper.OpenQuery(); 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); + } + } - if (_startTime != DateTime.MinValue || _endTime != DateTime.MaxValue) - { - res = _pdhHelper.SetQueryTimeRange(_startTime, _endTime); + res = _pdhHelper.AddCounters(ref validPaths, true); 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)); + PerformanceCounterSampleSet nextSet; - samplesRead++; - - if (_maxSamples != KEEP_ON_SAMPLING && samplesRead >= _maxSamples) - { - break; - } - } - } - + uint samplesRead = 0; - // - // 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.CurrentCultureIgnoreCase) - && !curExtension.Equals(".csv", StringComparison.CurrentCultureIgnoreCase) - && !curExtension.Equals(".tsv", StringComparison.CurrentCultureIgnoreCase)) + while (!_stopping) { - 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.CurrentCultureIgnoreCase)) - { - 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.CurrentCultureIgnoreCase)) - { - 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 colleciton. - // - 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, "", ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (System.Management.Automation.DriveNotFoundException driveNotFound) - { - WriteError(new ErrorRecord(driveNotFound, "", ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (ProviderNotFoundException providerNotFound) - { - WriteError(new ErrorRecord(providerNotFound, "", ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch (ItemNotFoundException pathNotFound) - { - WriteError(new ErrorRecord(pathNotFound, "", ErrorCategory.ObjectNotFound, origPath)); - continue; - } - catch(Exception exc) - { - WriteError(new ErrorRecord(exc, "", ErrorCategory.ObjectNotFound, origPath)); - continue; - } - - foreach (PathInfo pi in resolvedPathSubset) - { - // - // Check the provider: only FileSystem provider paths are acceptable. - // - if (pi.Provider.Name != "FileSystem") + res = _pdhHelper.ReadNextSet(out nextSet, false); + if (res == PdhResults.PDH_NO_MORE_DATA) { - 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.ToLower(CultureInfo.InvariantCulture)); - } - } - - 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; } - } + 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.CurrentCultureIgnoreCase) + && !curExtension.Equals(".csv", StringComparison.CurrentCultureIgnoreCase) + && !curExtension.Equals(".tsv", StringComparison.CurrentCultureIgnoreCase)) + { + 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.CurrentCultureIgnoreCase)) + { + 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.CurrentCultureIgnoreCase)) + { + 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 colleciton. + // + 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, "", ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (System.Management.Automation.DriveNotFoundException driveNotFound) + { + WriteError(new ErrorRecord(driveNotFound, "", ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (ProviderNotFoundException providerNotFound) + { + WriteError(new ErrorRecord(providerNotFound, "", ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (ItemNotFoundException pathNotFound) + { + WriteError(new ErrorRecord(pathNotFound, "", ErrorCategory.ObjectNotFound, origPath)); + continue; + } + catch (Exception exc) + { + WriteError(new ErrorRecord(exc, "", 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.ToLower(CultureInfo.InvariantCulture)); + } + } + + 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); } - - WriteObject (set); } - - } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 0f80fa729..cb1d364e0 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -3,7 +3,7 @@ // using System; -using System.Management.Automation; +using System.Management.Automation; using System.Globalization; using System.Reflection; using System.Diagnostics.Eventing; @@ -13,7 +13,7 @@ using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Xml; using System.IO; - + namespace Microsoft.PowerShell.Commands { /// @@ -23,8 +23,8 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsCommon.New, "WinEvent", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217469")] public sealed class NewWinEventCommand : PSCmdlet { - private ProviderMetadata providerMetadata; - private EventDescriptor? eventDescriptor; + private ProviderMetadata _providerMetadata; + private EventDescriptor? _eventDescriptor; private const string TemplateTag = "template"; private const string DataTag = "data"; @@ -42,14 +42,14 @@ namespace Microsoft.PowerShell.Commands { get { - return providerName; + return _providerName; } set { - providerName = value; + _providerName = value; } } - private string providerName; + private string _providerName; /// /// Id (EventId defined in manifest file) @@ -62,16 +62,16 @@ namespace Microsoft.PowerShell.Commands { get { - return id; + return _id; } set { - id = value; - idSpecified = true; + _id = value; + _idSpecified = true; } } - private int id; - private bool idSpecified = false; + private int _id; + private bool _idSpecified = false; /// @@ -84,16 +84,16 @@ namespace Microsoft.PowerShell.Commands { get { - return version; + return _version; } set { - version = value; - versionSpecified = true; + _version = value; + _versionSpecified = true; } } - private byte version; - private bool versionSpecified = false; + private byte _version; + private bool _versionSpecified = false; /// @@ -106,19 +106,19 @@ namespace Microsoft.PowerShell.Commands AllowEmptyCollection, SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Target = "Microsoft.PowerShell.Commands", - Justification="A string[] is required here because that is the type Powershell supports")] + Justification = "A string[] is required here because that is the type Powershell supports")] public object[] Payload { get { - return payload; + return _payload; } set { - payload = value; + _payload = value; } } - private object[] payload; + private object[] _payload; /// /// BeginProcessing @@ -133,20 +133,20 @@ namespace Microsoft.PowerShell.Commands private void LoadProvider() { - if (string.IsNullOrEmpty(this.providerName)) + if (string.IsNullOrEmpty(_providerName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName"); } - + using (EventLogSession session = new EventLogSession()) { foreach (string providerName in session.GetProviderNames()) { - if (string.Equals(providerName, this.providerName, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(providerName, _providerName, StringComparison.OrdinalIgnoreCase)) { try { - this.providerMetadata = new ProviderMetadata(providerName); + _providerMetadata = new ProviderMetadata(providerName); } catch (EventLogException exc) { @@ -158,21 +158,21 @@ namespace Microsoft.PowerShell.Commands } } - if (this.providerMetadata == null) + if (_providerMetadata == null) { - string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), providerName); + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName); throw new ArgumentException(msg); } } private void LoadEventDescriptor() { - if (idSpecified) + if (_idSpecified) { List matchedEvents = new List(); - foreach (EventMetadata emd in this.providerMetadata.Events) + foreach (EventMetadata emd in _providerMetadata.Events) { - if (emd.Id == this.id) + if (emd.Id == _id) { matchedEvents.Add(emd); } @@ -180,25 +180,25 @@ namespace Microsoft.PowerShell.Commands if (matchedEvents.Count == 0) { - string msg = string.Format(CultureInfo.InvariantCulture, + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("IncorrectEventId"), - this.id, - this.providerName); + _id, + _providerName); throw new EventWriteException(msg); } EventMetadata matchedEvent = null; - if (!versionSpecified && matchedEvents.Count == 1) + if (!_versionSpecified && matchedEvents.Count == 1) { matchedEvent = matchedEvents[0]; } else { - if (versionSpecified) + if (_versionSpecified) { foreach (EventMetadata emd in matchedEvents) { - if (emd.Version == this.version) + if (emd.Version == _version) { matchedEvent = emd; break; @@ -206,28 +206,28 @@ namespace Microsoft.PowerShell.Commands } if (matchedEvent == null) { - string msg = string.Format(CultureInfo.InvariantCulture, + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("IncorrectEventVersion"), - this.version, - this.id, - this.providerName); - + _version, + _id, + _providerName); + throw new EventWriteException(msg); } } else { - string msg = string.Format(CultureInfo.InvariantCulture, + string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("VersionNotSpecified"), - this.id, - this.providerName); + _id, + _providerName); throw new EventWriteException(msg); } } VerifyTemplate(matchedEvent); - this.eventDescriptor = CreateEventDescriptor(this.providerMetadata, matchedEvent); + _eventDescriptor = CreateEventDescriptor(_providerMetadata, matchedEvent); } else { @@ -265,10 +265,10 @@ namespace Microsoft.PowerShell.Commands } } - if ((this.payload == null && definedParameterCount != 0) - || ((this.payload != null) && this.payload.Length != definedParameterCount)) + if ((_payload == null && definedParameterCount != 0) + || ((_payload != null) && _payload.Length != definedParameterCount)) { - string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), this.id, emd.Template); + string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template); WriteWarning(warning); return false; @@ -294,11 +294,11 @@ namespace Microsoft.PowerShell.Commands } return new EventDescriptor( - (int) emd.Id, + (int)emd.Id, emd.Version, channel, - (byte) emd.Level.Value, - (byte) emd.Opcode.Value, + (byte)emd.Level.Value, + (byte)emd.Opcode.Value, emd.Task.Value, keywords); } @@ -308,21 +308,23 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - using (EventProvider provider = new EventProvider(this.providerMetadata.Id)) + using (EventProvider provider = new EventProvider(_providerMetadata.Id)) { - EventDescriptor ed = this.eventDescriptor.Value; + EventDescriptor ed = _eventDescriptor.Value; - if (this.payload != null && this.payload.Length > 0) + if (_payload != null && _payload.Length > 0) { - for (int i = 0; i < this.payload.Length; i++) + for (int i = 0; i < _payload.Length; i++) { - if (this.payload[i] == null) + if (_payload[i] == null) { - this.payload[i] = string.Empty; + _payload[i] = string.Empty; } } - provider.WriteEvent(ref ed, this.payload); - } else { + provider.WriteEvent(ref ed, _payload); + } + else + { provider.WriteEvent(ref ed); } } @@ -334,19 +336,21 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (this.providerMetadata != null) - providerMetadata.Dispose(); + if (_providerMetadata != null) + _providerMetadata.Dispose(); base.EndProcessing(); } } - - internal class EventWriteException : Exception + + internal class EventWriteException : Exception { internal EventWriteException(string msg, Exception innerException) - : base (msg, innerException) {} - + : base(msg, innerException) + { } + internal EventWriteException(string msg) - : base (msg) {} + : base(msg) + { } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 4e8697f22..3bd937fda 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Diagnostics; using System.Globalization; @@ -14,7 +15,6 @@ using Microsoft.Win32; namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { - internal static class PdhResults { public const long PDH_CSTATUS_VALID_DATA = 0x0L; @@ -105,7 +105,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative public const long PDH_QUERY_PERF_DATA_TIMEOUT = 0xC0000BFEL; } - + internal static class PerfDetail { @@ -154,40 +154,40 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative internal static class PdhLogOpenMode { - public const uint PDH_LOG_CREATE_NEW = 0x00000001; - public const uint PDH_LOG_CREATE_ALWAYS = 0x00000002; - public const uint PDH_LOG_OPEN_ALWAYS = 0x00000003; - public const uint PDH_LOG_OPEN_EXISTING = 0x00000004; - public const uint PDH_LOG_CREATE_MASK = 0x0000000F; + public const uint PDH_LOG_CREATE_NEW = 0x00000001; + public const uint PDH_LOG_CREATE_ALWAYS = 0x00000002; + public const uint PDH_LOG_OPEN_ALWAYS = 0x00000003; + public const uint PDH_LOG_OPEN_EXISTING = 0x00000004; + public const uint PDH_LOG_CREATE_MASK = 0x0000000F; } internal static class PdhLogOpenOption { - public const uint PDH_LOG_OPT_USER_STRING = 0x01000000; - public const uint PDH_LOG_OPT_CIRCULAR = 0x02000000; + public const uint PDH_LOG_OPT_USER_STRING = 0x01000000; + public const uint PDH_LOG_OPT_CIRCULAR = 0x02000000; public const uint PDH_LOG_OPT_MAX_IS_BYTES = 0x04000000; - public const uint PDH_LOG_OPT_APPEND = 0x08000000; + public const uint PDH_LOG_OPT_APPEND = 0x08000000; } internal enum PdhLogFileType { - PDH_LOG_TYPE_UNDEFINED = 0, - PDH_LOG_TYPE_CSV = 1, - PDH_LOG_TYPE_TSV = 2, - PDH_LOG_TYPE_TRACE_KERNEL = 4, - PDH_LOG_TYPE_TRACE_GENERIC = 5, - PDH_LOG_TYPE_PERFMON = 6, - PDH_LOG_TYPE_SQL = 7, - PDH_LOG_TYPE_BINARY = 8 + PDH_LOG_TYPE_UNDEFINED = 0, + PDH_LOG_TYPE_CSV = 1, + PDH_LOG_TYPE_TSV = 2, + PDH_LOG_TYPE_TRACE_KERNEL = 4, + PDH_LOG_TYPE_TRACE_GENERIC = 5, + PDH_LOG_TYPE_PERFMON = 6, + PDH_LOG_TYPE_SQL = 7, + PDH_LOG_TYPE_BINARY = 8 } internal static class PdhWildCardFlag { - public const uint PDH_NOEXPANDCOUNTERS = 1; - public const uint PDH_NOEXPANDINSTANCES = 2; - public const uint PDH_REFRESHCOUNTERS = 4; + public const uint PDH_NOEXPANDCOUNTERS = 1; + public const uint PDH_NOEXPANDINSTANCES = 2; + public const uint PDH_REFRESHCOUNTERS = 4; } - + internal struct CounterHandleNInstance { public IntPtr hCounter; @@ -196,18 +196,17 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative internal class PdhHelper : IDisposable { + private bool _isPreVista = false; - private bool m_isPreVista = false; - - public PdhHelper (bool isPreVista) + public PdhHelper(bool isPreVista) { - m_isPreVista = isPreVista; - } + _isPreVista = isPreVista; + } + - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - struct PDH_COUNTER_PATH_ELEMENTS - { + private struct PDH_COUNTER_PATH_ELEMENTS + { [MarshalAs(UnmanagedType.LPWStr)] public string MachineName; @@ -225,50 +224,50 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative [MarshalAs(UnmanagedType.LPWStr)] public string CounterName; } - + [StructLayout(LayoutKind.Sequential)] - struct PDH_FMT_COUNTERVALUE_LARGE - { - public uint CStatus; - - public Int64 largeValue; + private struct PDH_FMT_COUNTERVALUE_LARGE + { + public uint CStatus; + + public Int64 largeValue; //[FieldOffset (4), MarshalAs(UnmanagedType.LPStr)] //public string AnsiStringValue; //[FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)] //public string WideStringValue; - } ; + }; [StructLayout(LayoutKind.Sequential)] - struct PDH_FMT_COUNTERVALUE_DOUBLE - { - public uint CStatus; - - public double doubleValue; - } ; + private struct PDH_FMT_COUNTERVALUE_DOUBLE + { + public uint CStatus; + + public double doubleValue; + }; [StructLayout(LayoutKind.Sequential)] - struct PDH_FMT_COUNTERVALUE_UNICODE + private struct PDH_FMT_COUNTERVALUE_UNICODE { public uint CStatus; [MarshalAs(UnmanagedType.LPWStr)] - public string WideStringValue; - } ; + public string WideStringValue; + }; [StructLayout(LayoutKind.Sequential)] - struct PDH_RAW_COUNTER - { - public uint CStatus; - public System.Runtime.InteropServices.ComTypes.FILETIME TimeStamp; - public Int64 FirstValue; - public Int64 SecondValue; + private struct PDH_RAW_COUNTER + { + public uint CStatus; + public System.Runtime.InteropServices.ComTypes.FILETIME TimeStamp; + public Int64 FirstValue; + public Int64 SecondValue; public uint MultiCount; - } + } [StructLayout(LayoutKind.Sequential)] - struct PDH_TIME_INFO + private struct PDH_TIME_INFO { public Int64 StartTime; public Int64 EndTime; @@ -303,9 +302,9 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative [FieldOffset(96)] public string szExplainText; [FieldOffset(104)]public IntPtr DataBuffer; - }*/ + }*/ + - [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhBindInputDataSource(out PdhSafeDataSourceHandle phDataSource, string szLogFileNameList); @@ -317,9 +316,9 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative //Win7+ only [DllImport("pdh.dll", CharSet = CharSet.Unicode)] - private static extern uint PdhAddRelogCounter (PdhSafeQueryHandle queryHandle, string counterPath, - UInt32 counterType, UInt32 counterDefaultScale, - UInt64 timeBase, out IntPtr counterHandle); + private static extern uint PdhAddRelogCounter(PdhSafeQueryHandle queryHandle, string counterPath, + UInt32 counterType, UInt32 counterDefaultScale, + UInt64 timeBase, out IntPtr counterHandle); //not on XP [DllImport("pdh.dll")] @@ -341,7 +340,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PdhSafeQueryHandle hQuery, uint dwMaxSize, string szUserCaption, - out PdhSafeLogHandle phLog + out PdhSafeLogHandle phLog ); //Win7+ only @@ -351,7 +350,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative //Win7+ only [DllImport("pdh.dll", CharSet = CharSet.Unicode)] - private static extern uint PdhSetCounterValue (IntPtr CounterHandle, + private static extern uint PdhSetCounterValue(IntPtr CounterHandle, ref PDH_RAW_COUNTER Value, /*PPDH_RAW_COUNTER */ string InstanceName ); @@ -364,102 +363,102 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhGetFormattedCounterValue(IntPtr counterHandle, uint dwFormat, out IntPtr lpdwType, out PDH_FMT_COUNTERVALUE_DOUBLE pValue); - + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhGetRawCounterValue(IntPtr hCounter, out IntPtr lpdwType, out PDH_RAW_COUNTER pValue); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhEnumMachinesH(PdhSafeDataSourceHandle hDataSource, IntPtr mszMachineNameList, ref IntPtr pcchBufferLength); - - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhEnumObjectsH(PdhSafeDataSourceHandle hDataSource, string szMachineName, IntPtr mszObjectList, ref IntPtr pcchBufferLength, uint dwDetailLevel, bool bRefresh); - - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhEnumObjectItemsH(PdhSafeDataSourceHandle hDataSource, - string szMachineName, + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhEnumObjectsH(PdhSafeDataSourceHandle hDataSource, string szMachineName, IntPtr mszObjectList, ref IntPtr pcchBufferLength, uint dwDetailLevel, bool bRefresh); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhEnumObjectItemsH(PdhSafeDataSourceHandle hDataSource, + string szMachineName, string szObjectName, - IntPtr mszCounterList, - ref IntPtr pcchCounterListLength, - IntPtr mszInstanceList, + IntPtr mszCounterList, + ref IntPtr pcchCounterListLength, + IntPtr mszInstanceList, ref IntPtr pcchInstanceListLength, - uint dwDetailLevel, - uint dwFlags); - - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhMakeCounterPath(ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements, + uint dwDetailLevel, + uint dwFlags); + + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhMakeCounterPath(ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements, IntPtr szFullPathBuffer, - ref IntPtr pcchBufferSize, + ref IntPtr pcchBufferSize, UInt32 dwFlags); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhParseCounterPath(string szFullPathBuffer, IntPtr pCounterPathElements, //PDH_COUNTER_PATH_ELEMENTS - ref IntPtr pdwBufferSize, - uint dwFlags ); + ref IntPtr pdwBufferSize, + uint dwFlags); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhExpandWildCardPathH(PdhSafeDataSourceHandle hDataSource, + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhExpandWildCardPathH(PdhSafeDataSourceHandle hDataSource, string szWildCardPath, IntPtr mszExpandedPathList, ref IntPtr pcchPathListLength, - uint dwFlags ); + uint dwFlags); //not available on XP - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhValidatePathEx(PdhSafeDataSourceHandle hDataSource, string szFullPathBuffer); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhValidatePath(string szFullPathBuffer); //not available on XP - [DllImport("pdh.dll", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall, PreserveSig=true)] //private export - private static extern IntPtr PdhGetExplainText( string szMachineName, string szObjectName, string szCounterName); + [DllImport("pdh.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, PreserveSig = true)] //private export + private static extern IntPtr PdhGetExplainText(string szMachineName, string szObjectName, string szCounterName); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhGetCounterInfo(IntPtr hCounter, [MarshalAs(UnmanagedType.U1)]bool bRetrieveExplainText, ref IntPtr pdwBufferSize, IntPtr lpBuffer); + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetCounterInfo(IntPtr hCounter, [MarshalAs(UnmanagedType.U1)]bool bRetrieveExplainText, ref IntPtr pdwBufferSize, IntPtr lpBuffer); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhGetCounterTimeBase(IntPtr hCounter, out UInt64 pTimeBase); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhGetDataSourceTimeRangeH(PdhSafeDataSourceHandle hDataSource, ref IntPtr pdwNumEntries, ref PDH_TIME_INFO pInfo, ref IntPtr pdwBufferSize); + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhGetDataSourceTimeRangeH(PdhSafeDataSourceHandle hDataSource, ref IntPtr pdwNumEntries, ref PDH_TIME_INFO pInfo, ref IntPtr pdwBufferSize); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] private static extern uint PdhSetQueryTimeRange(PdhSafeQueryHandle hQuery, ref PDH_TIME_INFO pInfo); - [DllImport("pdh.dll", CharSet=CharSet.Unicode)] - private static extern uint PdhLookupPerfNameByIndex(string szMachineName, UInt32 dwNameIndex, IntPtr szNameBuffer, ref int pcchNameBufferSize); - + [DllImport("pdh.dll", CharSet = CharSet.Unicode)] + private static extern uint PdhLookupPerfNameByIndex(string szMachineName, UInt32 dwNameIndex, IntPtr szNameBuffer, ref int pcchNameBufferSize); - private PdhSafeDataSourceHandle m_hDataSource = null; - - private PdhSafeQueryHandle m_hQuery = null; - private bool m_firstReading = true; + private PdhSafeDataSourceHandle _hDataSource = null; - private PdhSafeLogHandle m_hOutputLog = null; + private PdhSafeQueryHandle _hQuery = null; + + private bool _firstReading = true; + + private PdhSafeLogHandle _hOutputLog = null; // // Implement IDisposable::Dispose() to close native safe handles // public void Dispose() { - if (m_hDataSource != null && !m_hDataSource.IsInvalid) + if (_hDataSource != null && !_hDataSource.IsInvalid) { - m_hDataSource.Dispose(); + _hDataSource.Dispose(); } - if (m_hOutputLog != null && !m_hOutputLog.IsInvalid) + if (_hOutputLog != null && !_hOutputLog.IsInvalid) { - m_hOutputLog.Dispose(); - } + _hOutputLog.Dispose(); + } - if (m_hQuery != null && !m_hQuery.IsInvalid) + if (_hQuery != null && !_hQuery.IsInvalid) { - m_hQuery.Dispose(); - } + _hQuery.Dispose(); + } GC.SuppressFinalize(this); } @@ -467,13 +466,13 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative // // m_ConsumerPathToHandleAndInstanceMap map is used for reading counter date (live or from files). // - private Dictionary m_ConsumerPathToHandleAndInstanceMap = new Dictionary(); - + private Dictionary _consumerPathToHandleAndInstanceMap = new Dictionary(); + // // m_ReloggerPathToHandleAndInstanceMap map is used for writing relog counters. // - private Dictionary m_ReloggerPathToHandleAndInstanceMap = new Dictionary(); + private Dictionary _reloggerPathToHandleAndInstanceMap = new Dictionary(); /// /// A helper reading in a Unicode string with embedded NULLs and splitting it into a StringCollection. @@ -487,16 +486,16 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative Debug.Assert(strSize >= 2); int offset = 0; string allSubstringsWithNulls = ""; - while (offset <= ((strSize * sizeof (char)) - 4)) + while (offset <= ((strSize * sizeof(char)) - 4)) { Int32 next4 = Marshal.ReadInt32(strNative, offset); if (next4 == 0) { break; } - + allSubstringsWithNulls += (char)next4; - + offset += 2; } @@ -506,18 +505,18 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative } - + private uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, out UInt32 defaultScale, out UInt64 timeBase) { uint res = 0; - counterType = 0; + counterType = 0; defaultScale = 0; timeBase = 0; Debug.Assert(hCounter != null); IntPtr pBufferSize = new IntPtr(0); - res = PdhGetCounterInfo (hCounter, false, ref pBufferSize, IntPtr.Zero); + res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, IntPtr.Zero); if (res != PdhResults.PDH_MORE_DATA) { return res; @@ -528,37 +527,37 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative try { - res = PdhGetCounterInfo (hCounter, false, ref pBufferSize, bufCounterInfo); + res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, bufCounterInfo); if (res == 0 && bufCounterInfo != IntPtr.Zero) { //PDH_COUNTER_INFO pdhCounterInfo = (PDH_COUNTER_INFO)Marshal.PtrToStructure(bufCounterInfo, typeof(PDH_COUNTER_INFO)); counterType = (uint)Marshal.ReadInt32(bufCounterInfo, 4); - defaultScale = (uint)Marshal.ReadInt32(bufCounterInfo, 20); + defaultScale = (uint)Marshal.ReadInt32(bufCounterInfo, 20); } } finally { - Marshal.FreeHGlobal(bufCounterInfo); + Marshal.FreeHGlobal(bufCounterInfo); } - res = PdhGetCounterTimeBase (hCounter, out timeBase); + res = PdhGetCounterTimeBase(hCounter, out timeBase); if (res != 0) { return res; - } - - return res; + } + + return res; } public uint ConnectToDataSource() { - if (m_hDataSource != null && !m_hDataSource.IsInvalid) + if (_hDataSource != null && !_hDataSource.IsInvalid) { - m_hDataSource.Dispose(); + _hDataSource.Dispose(); } - - uint res = PdhHelper.PdhBindInputDataSource(out m_hDataSource, null); + + uint res = PdhHelper.PdhBindInputDataSource(out _hDataSource, null); if (res != 0) { //Console.WriteLine("error in PdhBindInputDataSource: " + res); @@ -574,12 +573,12 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative /// public uint ConnectToDataSource(string dataSourceName) { - if (m_hDataSource != null && !m_hDataSource.IsInvalid) + if (_hDataSource != null && !_hDataSource.IsInvalid) { - m_hDataSource.Dispose(); + _hDataSource.Dispose(); } - uint res = PdhHelper.PdhBindInputDataSource(out m_hDataSource, dataSourceName); + uint res = PdhHelper.PdhBindInputDataSource(out _hDataSource, dataSourceName); if (res != 0) { //Console.WriteLine("error in PdhBindInputDataSource: " + res); @@ -594,7 +593,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { return ConnectToDataSource(blgFileNames[0]); } - + string doubleNullTerminated = ""; foreach (string fileName in blgFileNames) { @@ -608,7 +607,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative public uint OpenQuery() { - uint res = PdhOpenQueryH(m_hDataSource, IntPtr.Zero, out m_hQuery); + uint res = PdhOpenQueryH(_hDataSource, IntPtr.Zero, out _hQuery); if (res != 0) { @@ -619,29 +618,28 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative public uint OpenLogForWriting(string logName, PdhLogFileType logFileType, bool bOverwrite, UInt32 maxSize, bool bCircular, string caption) { - Debug.Assert (m_hQuery != null); + Debug.Assert(_hQuery != null); - UInt32 accessFlags = PdhLogAccess.PDH_LOG_WRITE_ACCESS; - accessFlags |= bCircular? PdhLogOpenOption.PDH_LOG_OPT_CIRCULAR : 0; - accessFlags |= bOverwrite? PdhLogOpenMode.PDH_LOG_CREATE_ALWAYS : PdhLogOpenMode.PDH_LOG_CREATE_NEW; + UInt32 accessFlags = PdhLogAccess.PDH_LOG_WRITE_ACCESS; + accessFlags |= bCircular ? PdhLogOpenOption.PDH_LOG_OPT_CIRCULAR : 0; + accessFlags |= bOverwrite ? PdhLogOpenMode.PDH_LOG_CREATE_ALWAYS : PdhLogOpenMode.PDH_LOG_CREATE_NEW; - uint res = PdhOpenLog(logName, + uint res = PdhOpenLog(logName, accessFlags, - ref logFileType, - m_hQuery, - maxSize, - caption, - out m_hOutputLog); - + ref logFileType, + _hQuery, + maxSize, + caption, + out _hOutputLog); + return res; - } - + public uint SetQueryTimeRange(DateTime startTime, DateTime endTime) { - Debug.Assert (m_hQuery != null); - Debug.Assert (endTime >= startTime); + Debug.Assert(_hQuery != null); + Debug.Assert(endTime >= startTime); PDH_TIME_INFO pTimeInfo = new PDH_TIME_INFO(); @@ -657,16 +655,15 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative } pTimeInfo.EndTime = (endTime == DateTime.MaxValue) ? Int64.MaxValue : endTime.ToFileTimeUtc(); - pTimeInfo.SampleCount = 0; + pTimeInfo.SampleCount = 0; - return PdhSetQueryTimeRange (m_hQuery, ref pTimeInfo); + return PdhSetQueryTimeRange(_hQuery, ref pTimeInfo); } public uint EnumBlgFilesMachines(ref StringCollection machineNames) { - IntPtr MachineListTcharSizePtr = new IntPtr(0); - uint res = PdhHelper.PdhEnumMachinesH(m_hDataSource, IntPtr.Zero, ref MachineListTcharSizePtr); + uint res = PdhHelper.PdhEnumMachinesH(_hDataSource, IntPtr.Zero, ref MachineListTcharSizePtr); if (res != PdhResults.PDH_MORE_DATA) { return res; @@ -677,14 +674,14 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative try { - res = PdhHelper.PdhEnumMachinesH(m_hDataSource, (IntPtr)strMachineList, ref MachineListTcharSizePtr); + res = PdhHelper.PdhEnumMachinesH(_hDataSource, (IntPtr)strMachineList, ref MachineListTcharSizePtr); if (res == 0) - { + { ReadPdhMultiString(ref strMachineList, MachineListTcharSizePtr.ToInt32(), ref machineNames); } } finally - { + { Marshal.FreeHGlobal(strMachineList); } @@ -693,40 +690,38 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative public uint EnumObjects(string machineName, ref StringCollection objectNames) { - IntPtr pBufferSize = new IntPtr(0); - uint res = PdhEnumObjectsH(m_hDataSource, machineName, IntPtr.Zero, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); + uint res = PdhEnumObjectsH(_hDataSource, machineName, IntPtr.Zero, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); if (res != PdhResults.PDH_MORE_DATA) { return res; } - + Int32 cChars = pBufferSize.ToInt32(); IntPtr strObjectList = Marshal.AllocHGlobal(cChars * sizeof(char)); - + try { - res = PdhEnumObjectsH(m_hDataSource, machineName, (IntPtr)strObjectList, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); + res = PdhEnumObjectsH(_hDataSource, machineName, (IntPtr)strObjectList, ref pBufferSize, PerfDetail.PERF_DETAIL_WIZARD, false); if (res == 0) - { + { ReadPdhMultiString(ref strObjectList, pBufferSize.ToInt32(), ref objectNames); } } finally { - Marshal.FreeHGlobal(strObjectList); + Marshal.FreeHGlobal(strObjectList); } - + return res; } public uint EnumObjectItems(string machineName, string objectName, ref StringCollection counterNames, ref StringCollection instanceNames) { - IntPtr pCounterBufferSize = new IntPtr(0); IntPtr pInstanceBufferSize = new IntPtr(0); - uint res = PdhEnumObjectItemsH(m_hDataSource, machineName, objectName, + uint res = PdhEnumObjectItemsH(_hDataSource, machineName, objectName, IntPtr.Zero, ref pCounterBufferSize, IntPtr.Zero, ref pInstanceBufferSize, PerfDetail.PERF_DETAIL_WIZARD, 0); @@ -739,35 +734,35 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { counterNames.Clear(); return 0; //masking the error - } + } else if (res != PdhResults.PDH_MORE_DATA) { //Console.WriteLine("error in PdhEnumObjectItemsH 1st call: " + res); return res; } - Int32 cChars = pCounterBufferSize.ToInt32(); - IntPtr strCountersList = (cChars > 0) ? + Int32 cChars = pCounterBufferSize.ToInt32(); + IntPtr strCountersList = (cChars > 0) ? Marshal.AllocHGlobal((cChars) * sizeof(char)) : IntPtr.Zero; //re-set count to 0 if it is lte 2 if (cChars < 0) { pCounterBufferSize = new IntPtr(0); - } + } cChars = pInstanceBufferSize.ToInt32(); - IntPtr strInstancesList = (cChars > 0) ? - Marshal.AllocHGlobal((cChars) * sizeof(char)): IntPtr.Zero; + IntPtr strInstancesList = (cChars > 0) ? + Marshal.AllocHGlobal((cChars) * sizeof(char)) : IntPtr.Zero; //re-set count to 0 if it is lte 2 if (cChars < 0) { pInstanceBufferSize = new IntPtr(0); - } + } - try - { - res = PdhEnumObjectItemsH(m_hDataSource, machineName, objectName, + try + { + res = PdhEnumObjectItemsH(_hDataSource, machineName, objectName, strCountersList, ref pCounterBufferSize, strInstancesList, ref pInstanceBufferSize, PerfDetail.PERF_DETAIL_WIZARD, 0); @@ -780,7 +775,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { ReadPdhMultiString(ref strCountersList, pCounterBufferSize.ToInt32(), ref counterNames); if (strInstancesList != IntPtr.Zero) - { + { ReadPdhMultiString(ref strInstancesList, pInstanceBufferSize.ToInt32(), ref instanceNames); } } @@ -802,8 +797,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative public uint GetValidPathsFromFiles(ref StringCollection validPaths) { - - Debug.Assert(m_hDataSource != null && !m_hDataSource.IsInvalid, "Call ConnectToDataSource before GetValidPathsFromFiles"); + Debug.Assert(_hDataSource != null && !_hDataSource.IsInvalid, "Call ConnectToDataSource before GetValidPathsFromFiles"); StringCollection machineNames = new StringCollection(); @@ -825,17 +819,17 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative foreach (string counterSet in counterSets) { //Console.WriteLine("Counter set " + counterSet); - + StringCollection counterSetCounters = new StringCollection(); StringCollection counterSetInstances = new StringCollection(); - res = this.EnumObjectItems(machine , counterSet, ref counterSetCounters, ref counterSetInstances); + res = this.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances); if (res != 0) { return res; - } - - res = this.GetValidPaths(machine , counterSet, ref counterSetCounters, ref counterSetInstances, ref validPaths); + } + + res = this.GetValidPaths(machine, counterSet, ref counterSetCounters, ref counterSetInstances, ref validPaths); if (res != 0) { return res; @@ -864,12 +858,12 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { res = PdhMakeCounterPath(ref pathElts, strPath, ref pPathBufferSize, 0); if (res == 0) - { + { outPath = Marshal.PtrToStringUni(strPath); - if (!m_isPreVista) + if (!_isPreVista) { - ret = (PdhValidatePathEx(m_hDataSource, outPath) == 0); + ret = (PdhValidatePathEx(_hDataSource, outPath) == 0); } else { @@ -883,14 +877,13 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative } return ret; - } public bool IsPathValid(string path) { - if (!m_isPreVista) + if (!_isPreVista) { - return (PdhValidatePathEx(m_hDataSource, path) == 0); + return (PdhValidatePathEx(_hDataSource, path) == 0); } else { @@ -900,7 +893,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative return (PdhValidatePath(path) == 0); } } - + private uint MakePath(PDH_COUNTER_PATH_ELEMENTS pathElts, out string outPath, bool bWildcardInstances) { @@ -927,7 +920,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { res = PdhMakeCounterPath(ref pathElts, strPath, ref pPathBufferSize, 0); if (res == 0) - { + { outPath = Marshal.PtrToStringUni(strPath); } } @@ -936,33 +929,33 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative Marshal.FreeHGlobal(strPath); } - return res; + return res; } - private uint MakeAllInstancePath (string origPath, out string unifiedPath) + private uint MakeAllInstancePath(string origPath, out string unifiedPath) { unifiedPath = origPath; - + PDH_COUNTER_PATH_ELEMENTS elts = new PDH_COUNTER_PATH_ELEMENTS(); - + uint res = ParsePath(origPath, ref elts); if (res != 0) { return res; } - return MakePath (elts, out unifiedPath, true); + return MakePath(elts, out unifiedPath, true); } - - private uint ParsePath (string fullPath, ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements) - { - IntPtr bufSize = new IntPtr(0); + + private uint ParsePath(string fullPath, ref PDH_COUNTER_PATH_ELEMENTS pCounterPathElements) + { + IntPtr bufSize = new IntPtr(0); uint res = PdhParseCounterPath(fullPath, - IntPtr.Zero, + IntPtr.Zero, ref bufSize, - 0 ); + 0); if (res != PdhResults.PDH_MORE_DATA && res != 0) { //Console.WriteLine("error in PdhParseCounterPath: " + res); @@ -976,21 +969,21 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative res = PdhParseCounterPath(fullPath, structPtr, ref bufSize, - 0 ); + 0); if (res == 0) { // // Marshal.PtrToStructure will allocate managed memory for the object, // so the unmanaged ptr can be freed safely // - pCounterPathElements = (PDH_COUNTER_PATH_ELEMENTS)Marshal.PtrToStructure(structPtr, typeof(PDH_COUNTER_PATH_ELEMENTS)); + pCounterPathElements = (PDH_COUNTER_PATH_ELEMENTS)Marshal.PtrToStructure(structPtr, typeof(PDH_COUNTER_PATH_ELEMENTS)); } } finally { - Marshal.FreeHGlobal (structPtr); + Marshal.FreeHGlobal(structPtr); } - + return res; } @@ -1011,7 +1004,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative uint res = 0; localizedPath = ""; PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); - res = ParsePath(englishPath, ref pathElts); + res = ParsePath(englishPath, ref pathElts); if (res != 0) { return res; @@ -1020,8 +1013,8 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative // Check if the path is local and assert if not: string machineNameMassaged = pathElts.MachineName.ToLower(CultureInfo.InvariantCulture); machineNameMassaged = machineNameMassaged.TrimStart('\\'); - Debug.Assert (machineNameMassaged == System.Environment.MachineName.ToLower(CultureInfo.InvariantCulture)); - + Debug.Assert(machineNameMassaged == System.Environment.MachineName.ToLower(CultureInfo.InvariantCulture)); + string lowerEngCtrName = pathElts.CounterName.ToLower(CultureInfo.InvariantCulture); string lowerEngObjectName = pathElts.ObjectName.ToLower(CultureInfo.InvariantCulture); @@ -1035,29 +1028,28 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative Int32 objIndex = -1; for (uint enumIndex = 1; enumIndex < regCounters.Length; enumIndex++) { - string regString = regCounters[enumIndex]; + string regString = regCounters[enumIndex]; if (regString.ToLower(CultureInfo.InvariantCulture) == lowerEngCtrName) { try { - counterIndex = Convert.ToInt32(regCounters[enumIndex-1], CultureInfo.InvariantCulture); + counterIndex = Convert.ToInt32(regCounters[enumIndex - 1], CultureInfo.InvariantCulture); } catch (Exception) { - return (uint)PdhResults.PDH_INVALID_PATH; + return (uint)PdhResults.PDH_INVALID_PATH; } - } - else if (regString.ToLower(CultureInfo.InvariantCulture) == lowerEngObjectName) + } + else if (regString.ToLower(CultureInfo.InvariantCulture) == lowerEngObjectName) { - try { - objIndex = Convert.ToInt32(regCounters[enumIndex-1], CultureInfo.InvariantCulture); + objIndex = Convert.ToInt32(regCounters[enumIndex - 1], CultureInfo.InvariantCulture); } catch (Exception) { - return (uint)PdhResults.PDH_INVALID_PATH; - } + return (uint)PdhResults.PDH_INVALID_PATH; + } } if (counterIndex != -1 && objIndex != -1) { @@ -1067,10 +1059,10 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative if (counterIndex == -1 || objIndex == -1) { - return (uint)PdhResults.PDH_INVALID_PATH; + return (uint)PdhResults.PDH_INVALID_PATH; } - + // Now, call retrieve the localized names of the object and the counter by index: string objNameLocalized; res = LookupPerfNameByIndex(pathElts.MachineName, (uint)objIndex, out objNameLocalized); @@ -1094,51 +1086,50 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative res = MakePath(pathElts, out localizedPath, false); - return res; + return res; } public uint LookupPerfNameByIndex(string machineName, uint index, out string locName) - { + { // // NOTE: to make PdhLookupPerfNameByIndex() work, // localizedPath needs to be pre-allocated on the first call. // This is different from most other PDH functions that tolerate NULL buffers and return required size. // - int strSize = 256; + int strSize = 256; IntPtr localizedPathPtr = Marshal.AllocHGlobal(strSize * sizeof(char)); locName = ""; uint res = 0; try { - res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); + res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); if (res == PdhResults.PDH_MORE_DATA) { - Marshal.FreeHGlobal (localizedPathPtr); + Marshal.FreeHGlobal(localizedPathPtr); localizedPathPtr = Marshal.AllocHGlobal(strSize * sizeof(char)); - res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); - } + res = PdhLookupPerfNameByIndex(machineName, index, localizedPathPtr, ref strSize); + } if (res == 0) - { + { locName = Marshal.PtrToStringUni(localizedPathPtr); } } finally { - Marshal.FreeHGlobal (localizedPathPtr); + Marshal.FreeHGlobal(localizedPathPtr); } return res; - } - public uint GetValidPaths (string machineName, - string objectName, - ref StringCollection counters, - ref StringCollection instances, + public uint GetValidPaths(string machineName, + string objectName, + ref StringCollection counters, + ref StringCollection instances, ref StringCollection validPaths) { uint res = 0; @@ -1146,7 +1137,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); pathElts.MachineName = machineName; pathElts.ObjectName = objectName; - + foreach (string counterName in counters) { pathElts.CounterName = counterName; @@ -1155,7 +1146,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { string pathCandidate; if (IsPathValid(ref pathElts, out pathCandidate)) - { + { validPaths.Add(pathCandidate); } } @@ -1168,9 +1159,9 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative string pathCandidate; if (IsPathValid(ref pathElts, out pathCandidate)) - { + { validPaths.Add(pathCandidate); - } + } } } } @@ -1178,13 +1169,13 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative } - public uint AddCounters (ref StringCollection validPaths, bool bFlushOldCounters) + public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) { - Debug.Assert(m_hQuery != null && !m_hQuery.IsInvalid); + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); if (bFlushOldCounters) { - m_ConsumerPathToHandleAndInstanceMap.Clear(); + _consumerPathToHandleAndInstanceMap.Clear(); } bool bAtLeastOneAdded = false; @@ -1193,41 +1184,41 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative foreach (string counterPath in validPaths) { IntPtr counterHandle; - res = PdhAddCounter(m_hQuery, counterPath, IntPtr.Zero, out counterHandle); + res = PdhAddCounter(_hQuery, counterPath, IntPtr.Zero, out counterHandle); if (res == 0) - { + { CounterHandleNInstance chi = new CounterHandleNInstance(); chi.hCounter = counterHandle; chi.InstanceName = null; PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); - res = ParsePath(counterPath, ref pathElts); + res = ParsePath(counterPath, ref pathElts); if (res == 0 && pathElts.InstanceName != null) { chi.InstanceName = pathElts.InstanceName.ToLower(CultureInfo.InvariantCulture); } - - if (!m_ConsumerPathToHandleAndInstanceMap.ContainsKey(counterPath.ToLower(CultureInfo.InvariantCulture))) + + if (!_consumerPathToHandleAndInstanceMap.ContainsKey(counterPath.ToLower(CultureInfo.InvariantCulture))) { - m_ConsumerPathToHandleAndInstanceMap.Add(counterPath.ToLower(CultureInfo.InvariantCulture), chi); + _consumerPathToHandleAndInstanceMap.Add(counterPath.ToLower(CultureInfo.InvariantCulture), chi); } - + bAtLeastOneAdded = true; } } return bAtLeastOneAdded ? 0 : res; } - - + + // // AddRelogCounters combines instances and adds counters to m_hQuery. // The counter handles and full paths // public uint AddRelogCounters(PerformanceCounterSampleSet sampleSet) { - Debug.Assert(m_hQuery != null && !m_hQuery.IsInvalid); - + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + uint res = 0; Dictionary> prefixInstanceMap = new Dictionary>(); @@ -1240,10 +1231,10 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); res = ParsePath(sample.Path, ref pathElts); if (res != 0) - { + { // Skipping for now, but should be a non-terminating error continue; - } + } string lowerCaseMachine = pathElts.MachineName.ToLower(CultureInfo.InvariantCulture); string lowerCaseObject = pathElts.ObjectName.ToLower(CultureInfo.InvariantCulture); @@ -1259,9 +1250,9 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative else { List newList = new List(); - newList.Add (sample); - prefixInstanceMap.Add (lcPathMinusInstance, newList); - } + newList.Add(sample); + prefixInstanceMap.Add(lcPathMinusInstance, newList); + } //Console.WriteLine ("Added path " + sample.Path + " to the 1ist map with prefix " + lcPathMinusInstance); } @@ -1284,34 +1275,34 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative if (res != 0) { // Skipping for now, but should be a non-terminating error - continue; + continue; } } - res = PdhAddRelogCounter(m_hQuery, - unifiedPath, - (UInt32)prefixInstanceMap[prefix][0].CounterType, - prefixInstanceMap[prefix][0].DefaultScale, - prefixInstanceMap[prefix][0].TimeBase, + res = PdhAddRelogCounter(_hQuery, + unifiedPath, + (UInt32)prefixInstanceMap[prefix][0].CounterType, + prefixInstanceMap[prefix][0].DefaultScale, + prefixInstanceMap[prefix][0].TimeBase, out counterHandle); if (res != 0) { // Skipping for now, but should be a non-terminating error // Console.WriteLine ("PdhAddCounter returned " + res + " for counter path " + unifiedPath); - continue; + continue; } //Console.WriteLine ("added pdh query path:" + unifiedPath ); - + //now, add all actual paths to m_ReloggerPathToHandleAndInstanceMap foreach (PerformanceCounterSample sample in prefixInstanceMap[prefix]) { PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); - res = ParsePath(sample.Path, ref pathElts); + res = ParsePath(sample.Path, ref pathElts); if (res != 0) { // Skipping for now, but should be a non-terminating error - continue; + continue; } CounterHandleNInstance chi = new CounterHandleNInstance(); @@ -1322,30 +1313,30 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { chi.InstanceName = pathElts.InstanceName.ToLower(CultureInfo.InvariantCulture); } - - if (!m_ReloggerPathToHandleAndInstanceMap.ContainsKey(sample.Path.ToLower(CultureInfo.InvariantCulture))) + + if (!_reloggerPathToHandleAndInstanceMap.ContainsKey(sample.Path.ToLower(CultureInfo.InvariantCulture))) { - m_ReloggerPathToHandleAndInstanceMap.Add(sample.Path.ToLower(CultureInfo.InvariantCulture), chi); + _reloggerPathToHandleAndInstanceMap.Add(sample.Path.ToLower(CultureInfo.InvariantCulture), chi); //Console.WriteLine ("added map path:" + sample.Path ); } - } + } } //TODO: verify that all counters are in the map - return (m_ReloggerPathToHandleAndInstanceMap.Keys.Count > 0) ? 0 : res; + return (_reloggerPathToHandleAndInstanceMap.Keys.Count > 0) ? 0 : res; } - - + + // // AddRelogCountersPreservingPaths preserves all paths and adds as relog counters to m_hQuery. // The counter handles and full paths are added to m_ReloggerPathToHandleAndInstanceMap // public uint AddRelogCountersPreservingPaths(PerformanceCounterSampleSet sampleSet) { - Debug.Assert(m_hQuery != null && !m_hQuery.IsInvalid); - + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + uint res = 0; // @@ -1356,22 +1347,22 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); res = ParsePath(sample.Path, ref pathElts); if (res != 0) - { + { // Skipping for now, but should be a non-terminating error continue; - } + } IntPtr counterHandle; - res = PdhAddRelogCounter(m_hQuery, - sample.Path, - (uint)sample.CounterType, - sample.DefaultScale, - sample.TimeBase, + res = PdhAddRelogCounter(_hQuery, + sample.Path, + (uint)sample.CounterType, + sample.DefaultScale, + sample.TimeBase, out counterHandle); if (res != 0) { // Skipping for now, but should be a non-terminating error - continue; + continue; } CounterHandleNInstance chi = new CounterHandleNInstance(); @@ -1381,34 +1372,32 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { chi.InstanceName = pathElts.InstanceName.ToLower(CultureInfo.InvariantCulture); } - - if (!m_ReloggerPathToHandleAndInstanceMap.ContainsKey(sample.Path.ToLower(CultureInfo.InvariantCulture))) - { - m_ReloggerPathToHandleAndInstanceMap.Add(sample.Path.ToLower(CultureInfo.InvariantCulture), chi); - } + if (!_reloggerPathToHandleAndInstanceMap.ContainsKey(sample.Path.ToLower(CultureInfo.InvariantCulture))) + { + _reloggerPathToHandleAndInstanceMap.Add(sample.Path.ToLower(CultureInfo.InvariantCulture), chi); + } } - - return (m_ReloggerPathToHandleAndInstanceMap.Keys.Count > 0) ? 0 : res; + + return (_reloggerPathToHandleAndInstanceMap.Keys.Count > 0) ? 0 : res; } public string GetCounterSetHelp(string szMachineName, string szObjectName) { - if (m_isPreVista) + if (_isPreVista) { return string.Empty; } - IntPtr retString = PdhGetExplainText(szMachineName, szObjectName, null); + IntPtr retString = PdhGetExplainText(szMachineName, szObjectName, null); return Marshal.PtrToStringUni(retString); } - public uint ReadNextSetPreVista (out PerformanceCounterSampleSet nextSet, bool bSkipReading) - { - + public uint ReadNextSetPreVista(out PerformanceCounterSampleSet nextSet, bool bSkipReading) + { uint res = 0; nextSet = null; - res = PdhCollectQueryData(m_hQuery); + res = PdhCollectQueryData(_hQuery); if (bSkipReading) { return res; @@ -1418,22 +1407,22 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative return res; } - PerformanceCounterSample[] samplesArr = new PerformanceCounterSample[m_ConsumerPathToHandleAndInstanceMap.Count]; + PerformanceCounterSample[] samplesArr = new PerformanceCounterSample[_consumerPathToHandleAndInstanceMap.Count]; uint sampleIndex = 0; uint numInvalidDataSamples = 0; uint lastErr = 0; DateTime sampleTimeStamp = DateTime.Now; - foreach (string path in m_ConsumerPathToHandleAndInstanceMap.Keys) + foreach (string path in _consumerPathToHandleAndInstanceMap.Keys) { IntPtr counterTypePtr = new IntPtr(0); UInt32 counterType = (UInt32)PerformanceCounterType.RawBase; UInt32 defaultScale = 0; UInt64 timeBase = 0; - IntPtr hCounter = m_ConsumerPathToHandleAndInstanceMap[path].hCounter; - Debug.Assert (hCounter != null); + IntPtr hCounter = _consumerPathToHandleAndInstanceMap[path].hCounter; + Debug.Assert(hCounter != null); res = GetCounterInfoPlus(hCounter, out counterType, out defaultScale, out timeBase); if (res != 0) @@ -1443,11 +1432,11 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_RAW_COUNTER rawValue; res = PdhGetRawCounterValue(hCounter, out counterTypePtr, out rawValue); - if ( res == PdhResults.PDH_INVALID_DATA || res == PdhResults.PDH_NO_DATA ) + if (res == PdhResults.PDH_INVALID_DATA || res == PdhResults.PDH_NO_DATA) { //Console.WriteLine ("PdhGetRawCounterValue returned " + res); samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, 0, (ulong)0, (ulong)0, @@ -1467,7 +1456,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { return res; } - + long dtFT = (((long)rawValue.TimeStamp.dwHighDateTime) << 32) + (uint)rawValue.TimeStamp.dwLowDateTime; @@ -1480,15 +1469,15 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative sampleTimeStamp = new DateTime(DateTime.FromFileTimeUtc(dtFT).Ticks, DateTimeKind.Local); PDH_FMT_COUNTERVALUE_DOUBLE fmtValueDouble; - res = PdhGetFormattedCounterValue(hCounter, - PdhFormat.PDH_FMT_DOUBLE | PdhFormat.PDH_FMT_NOCAP100, - out counterTypePtr, - out fmtValueDouble); - if (res == PdhResults.PDH_INVALID_DATA || res == PdhResults.PDH_NO_DATA ) + res = PdhGetFormattedCounterValue(hCounter, + PdhFormat.PDH_FMT_DOUBLE | PdhFormat.PDH_FMT_NOCAP100, + out counterTypePtr, + out fmtValueDouble); + if (res == PdhResults.PDH_INVALID_DATA || res == PdhResults.PDH_NO_DATA) { //Console.WriteLine ("PdhGetFormattedCounterValue returned " + res); samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, 0, (ulong)rawValue.FirstValue, (ulong)rawValue.SecondValue, @@ -1509,20 +1498,19 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative //Console.WriteLine ("PdhGetFormattedCounterValue returned " + res); return res; } - + samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, fmtValueDouble.doubleValue, (ulong)rawValue.FirstValue, (ulong)rawValue.SecondValue, rawValue.MultiCount, - (PerformanceCounterType)counterTypePtr.ToInt32(), + (PerformanceCounterType)counterTypePtr.ToInt32(), defaultScale, timeBase, sampleTimeStamp, (UInt64)dtFT, fmtValueDouble.CStatus); - } // @@ -1530,8 +1518,8 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative // so we could not collect a timestamp for the entire sample set. // We will use the last sample's timstamp instead. // - nextSet = new PerformanceCounterSampleSet(sampleTimeStamp, samplesArr, m_firstReading); - m_firstReading = false; + nextSet = new PerformanceCounterSampleSet(sampleTimeStamp, samplesArr, _firstReading); + _firstReading = false; if (numInvalidDataSamples == samplesArr.Length) { @@ -1549,21 +1537,21 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative } - public uint ReadNextSet (out PerformanceCounterSampleSet nextSet, bool bSkipReading) + public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReading) { - Debug.Assert(m_hQuery != null && !m_hQuery.IsInvalid); + Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); - if (m_isPreVista) + if (_isPreVista) { - return ReadNextSetPreVista (out nextSet, bSkipReading); + return ReadNextSetPreVista(out nextSet, bSkipReading); } - + uint res = 0; nextSet = null; - Int64 batchTimeStampFT = 0; + Int64 batchTimeStampFT = 0; - res = PdhCollectQueryDataWithTime(m_hQuery, ref batchTimeStampFT); + res = PdhCollectQueryDataWithTime(_hQuery, ref batchTimeStampFT); if (bSkipReading) { return res; @@ -1582,23 +1570,23 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative DateTime batchStamp = DateTime.Now; if (res != PdhResults.PDH_NO_DATA) { - batchStamp = new DateTime (DateTime.FromFileTimeUtc(batchTimeStampFT).Ticks, DateTimeKind.Local); + batchStamp = new DateTime(DateTime.FromFileTimeUtc(batchTimeStampFT).Ticks, DateTimeKind.Local); } - PerformanceCounterSample[] samplesArr = new PerformanceCounterSample[m_ConsumerPathToHandleAndInstanceMap.Count]; + PerformanceCounterSample[] samplesArr = new PerformanceCounterSample[_consumerPathToHandleAndInstanceMap.Count]; uint sampleIndex = 0; uint numInvalidDataSamples = 0; uint lastErr = 0; - foreach (string path in m_ConsumerPathToHandleAndInstanceMap.Keys) + foreach (string path in _consumerPathToHandleAndInstanceMap.Keys) { IntPtr counterTypePtr = new IntPtr(0); UInt32 counterType = (UInt32)PerformanceCounterType.RawBase; UInt32 defaultScale = 0; UInt64 timeBase = 0; - IntPtr hCounter = m_ConsumerPathToHandleAndInstanceMap[path].hCounter; - Debug.Assert (hCounter != null); + IntPtr hCounter = _consumerPathToHandleAndInstanceMap[path].hCounter; + Debug.Assert(hCounter != null); res = GetCounterInfoPlus(hCounter, out counterType, out defaultScale, out timeBase); if (res != 0) @@ -1611,7 +1599,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative if (res != 0) { samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, 0, (ulong)0, (ulong)0, @@ -1621,27 +1609,27 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative timeBase, batchStamp, (UInt64)batchStamp.ToFileTime(), - (rawValue.CStatus == 0) ? res : rawValue.CStatus); - + (rawValue.CStatus == 0) ? res : rawValue.CStatus); + numInvalidDataSamples++; lastErr = res; continue; - } - + } + long dtFT = (((long)rawValue.TimeStamp.dwHighDateTime) << 32) + (uint)rawValue.TimeStamp.dwLowDateTime; DateTime dt = new DateTime(DateTime.FromFileTimeUtc(dtFT).Ticks, DateTimeKind.Local); PDH_FMT_COUNTERVALUE_DOUBLE fmtValueDouble; - res = PdhGetFormattedCounterValue(hCounter, - PdhFormat.PDH_FMT_DOUBLE | PdhFormat.PDH_FMT_NOCAP100, - out counterTypePtr, - out fmtValueDouble); + res = PdhGetFormattedCounterValue(hCounter, + PdhFormat.PDH_FMT_DOUBLE | PdhFormat.PDH_FMT_NOCAP100, + out counterTypePtr, + out fmtValueDouble); if (res != 0) { samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, 0, (ulong)rawValue.FirstValue, (ulong)rawValue.SecondValue, @@ -1650,32 +1638,31 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative defaultScale, timeBase, dt, - (UInt64)dtFT, - (fmtValueDouble.CStatus == 0) ? res : rawValue.CStatus); - + (UInt64)dtFT, + (fmtValueDouble.CStatus == 0) ? res : rawValue.CStatus); + numInvalidDataSamples++; lastErr = res; continue; } - + samplesArr[sampleIndex++] = new PerformanceCounterSample(path, - m_ConsumerPathToHandleAndInstanceMap[path].InstanceName, + _consumerPathToHandleAndInstanceMap[path].InstanceName, fmtValueDouble.doubleValue, (ulong)rawValue.FirstValue, (ulong)rawValue.SecondValue, rawValue.MultiCount, - (PerformanceCounterType)counterTypePtr.ToInt32(), + (PerformanceCounterType)counterTypePtr.ToInt32(), defaultScale, timeBase, dt, (UInt64)dtFT, fmtValueDouble.CStatus); - } - nextSet = new PerformanceCounterSampleSet(batchStamp, samplesArr, m_firstReading); - m_firstReading = false; + nextSet = new PerformanceCounterSampleSet(batchStamp, samplesArr, _firstReading); + _firstReading = false; if (numInvalidDataSamples == samplesArr.Length) { @@ -1691,7 +1678,7 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative return res; } - + public uint GetFilesSummary(out CounterFileInfo summary) { @@ -1699,31 +1686,31 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_TIME_INFO pInfo = new PDH_TIME_INFO(); IntPtr bufSize = new IntPtr(System.Runtime.InteropServices.Marshal.SizeOf(pInfo)); - uint res = PdhGetDataSourceTimeRangeH(m_hDataSource, - ref pNumEntries, - ref pInfo, + uint res = PdhGetDataSourceTimeRangeH(_hDataSource, + ref pNumEntries, + ref pInfo, ref bufSize); if (res != 0) { summary = new CounterFileInfo(); return res; } - - summary = new CounterFileInfo (new DateTime (DateTime.FromFileTimeUtc(pInfo.StartTime).Ticks, DateTimeKind.Local), - new DateTime (DateTime.FromFileTimeUtc(pInfo.EndTime).Ticks, DateTimeKind.Local), + + summary = new CounterFileInfo(new DateTime(DateTime.FromFileTimeUtc(pInfo.StartTime).Ticks, DateTimeKind.Local), + new DateTime(DateTime.FromFileTimeUtc(pInfo.EndTime).Ticks, DateTimeKind.Local), pInfo.SampleCount); return res; } - public uint ExpandWildCardPath (string path, out StringCollection expandedPaths) + public uint ExpandWildCardPath(string path, out StringCollection expandedPaths) { expandedPaths = new StringCollection(); IntPtr pcchPathListLength = new IntPtr(0); - uint res = PdhExpandWildCardPathH(m_hDataSource, + uint res = PdhExpandWildCardPathH(_hDataSource, path, - IntPtr.Zero, + IntPtr.Zero, ref pcchPathListLength, PdhWildCardFlag.PDH_REFRESHCOUNTERS); @@ -1737,42 +1724,41 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative try { - res = PdhExpandWildCardPathH(m_hDataSource, path, strPathList, ref pcchPathListLength, PdhWildCardFlag.PDH_REFRESHCOUNTERS); + res = PdhExpandWildCardPathH(_hDataSource, path, strPathList, ref pcchPathListLength, PdhWildCardFlag.PDH_REFRESHCOUNTERS); if (res == 0) - { + { ReadPdhMultiString(ref strPathList, pcchPathListLength.ToInt32(), ref expandedPaths); } } finally { - Marshal.FreeHGlobal (strPathList); + Marshal.FreeHGlobal(strPathList); } return res; } - public void ResetRelogValues () + public void ResetRelogValues() { - Debug.Assert(m_hOutputLog != null && !m_hOutputLog.IsInvalid); - PdhResetRelogCounterValues(m_hOutputLog); + Debug.Assert(_hOutputLog != null && !_hOutputLog.IsInvalid); + PdhResetRelogCounterValues(_hOutputLog); } - public uint WriteRelogSample (DateTime timeStamp) + public uint WriteRelogSample(DateTime timeStamp) { - Debug.Assert(m_hOutputLog != null && !m_hOutputLog.IsInvalid); - return PdhWriteRelogSample(m_hOutputLog, (new DateTime(timeStamp.Ticks, DateTimeKind.Utc)).ToFileTimeUtc() ); - + Debug.Assert(_hOutputLog != null && !_hOutputLog.IsInvalid); + return PdhWriteRelogSample(_hOutputLog, (new DateTime(timeStamp.Ticks, DateTimeKind.Utc)).ToFileTimeUtc()); } - public uint SetCounterValue (PerformanceCounterSample sample, out bool bUnknownPath) + public uint SetCounterValue(PerformanceCounterSample sample, out bool bUnknownPath) { - Debug.Assert(m_hOutputLog != null && !m_hOutputLog.IsInvalid); + Debug.Assert(_hOutputLog != null && !_hOutputLog.IsInvalid); bUnknownPath = false; string lcPath = sample.Path.ToLower(CultureInfo.InvariantCulture); - if (!m_ReloggerPathToHandleAndInstanceMap.ContainsKey(lcPath)) + if (!_reloggerPathToHandleAndInstanceMap.ContainsKey(lcPath)) { bUnknownPath = true; return 0; @@ -1780,18 +1766,16 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative PDH_RAW_COUNTER rawStruct = new PDH_RAW_COUNTER(); rawStruct.FirstValue = (long)sample.RawValue; - rawStruct.SecondValue = (long)sample.SecondValue; + rawStruct.SecondValue = (long)sample.SecondValue; rawStruct.MultiCount = sample.MultipleCount; rawStruct.TimeStamp.dwHighDateTime = (int)((new DateTime(sample.Timestamp.Ticks, DateTimeKind.Utc).ToFileTimeUtc() >> 32) & 0xFFFFFFFFL); rawStruct.TimeStamp.dwLowDateTime = (int)(new DateTime(sample.Timestamp.Ticks, DateTimeKind.Utc).ToFileTimeUtc() & 0xFFFFFFFFL); rawStruct.CStatus = sample.Status; - - return PdhSetCounterValue (m_ReloggerPathToHandleAndInstanceMap[lcPath].hCounter, + + return PdhSetCounterValue(_reloggerPathToHandleAndInstanceMap[lcPath].hCounter, ref rawStruct, /*PPDH_RAW_COUNTER */ - m_ReloggerPathToHandleAndInstanceMap[lcPath].InstanceName); + _reloggerPathToHandleAndInstanceMap[lcPath].InstanceName); } - - - } + } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs index 756a24c00..7337d6590 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs @@ -1,23 +1,23 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { - internal sealed class PdhSafeDataSourceHandle : SafeHandle { private PdhSafeDataSourceHandle() : base(IntPtr.Zero, true) { } - public override bool IsInvalid - { - get - { - return handle == IntPtr.Zero; - } + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } } @@ -35,19 +35,18 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { private PdhSafeQueryHandle() : base(IntPtr.Zero, true) { } - public override bool IsInvalid - { - get - { - return handle == IntPtr.Zero; - } + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected override bool ReleaseHandle() { - return (PdhHelper.PdhCloseQuery(handle) == 0); } } @@ -56,22 +55,21 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { private PdhSafeLogHandle() : base(IntPtr.Zero, true) { } - public override bool IsInvalid - { - get - { - return handle == IntPtr.Zero; - } + public override bool IsInvalid + { + get + { + return handle == IntPtr.Zero; + } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected override bool ReleaseHandle() { - return (PdhHelper.PdhCloseLog(handle, 0) == 0); } } } - + diff --git a/src/Microsoft.PowerShell.Commands.Management/AssemblyInfo.cs b/src/Microsoft.PowerShell.Commands.Management/AssemblyInfo.cs index 8be322935..dd4e8f282 100644 --- a/src/Microsoft.PowerShell.Commands.Management/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Management/AssemblyInfo.cs @@ -1,8 +1,8 @@ using System.Reflection; using System.Resources; -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersionAttribute("3.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 93ec6d12e..314976161 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Cmdletization #region IDisposable Members - private bool disposed; + private bool _disposed; /// /// Releases resources associated with this object @@ -51,17 +51,17 @@ namespace Microsoft.PowerShell.Cmdletization /// protected virtual void Dispose(bool disposing) { - if (!disposed) + if (!_disposed) { if (disposing) { - if (this.parentJob != null) + if (_parentJob != null) { - this.parentJob.Dispose(); - this.parentJob = null; + _parentJob.Dispose(); + _parentJob = null; } } - disposed = true; + _disposed = true; } } @@ -72,16 +72,16 @@ namespace Microsoft.PowerShell.Cmdletization /// /// Session to operate on /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected TSession[] Session { get { - if (this.session == null) + if (_session == null) { - this.session = new TSession[] {this.DefaultSession}; + _session = new TSession[] { this.DefaultSession }; } - return this.session; + return _session; } set { @@ -90,12 +90,12 @@ namespace Microsoft.PowerShell.Cmdletization throw new ArgumentNullException("value"); } - this.session = value; - this.sessionWasSpecified = true; + _session = value; + _sessionWasSpecified = true; } } - private TSession[] session; - private bool sessionWasSpecified; + private TSession[] _session; + private bool _sessionWasSpecified; /// /// Whether to wrap and emit the whole operation as a background job @@ -103,10 +103,10 @@ namespace Microsoft.PowerShell.Cmdletization [Parameter] public SwitchParameter AsJob { - get { return this.asJob; } - set { this.asJob = value; } + get { return _asJob; } + set { _asJob = value; } } - private bool asJob; + private bool _asJob; /// /// Maximum number of remote connections that can remain active at any given time. @@ -153,12 +153,12 @@ namespace Microsoft.PowerShell.Cmdletization sessionForJob, discardNonPipelineResults, actionAgainstResults == null - ? (Action) null - : delegate(PSObject pso) + ? (Action)null + : delegate (PSObject pso) { var objectInstance = (TObjectInstance) - LanguagePrimitives.ConvertTo(pso, typeof (TObjectInstance), + LanguagePrimitives.ConvertTo(pso, typeof(TObjectInstance), CultureInfo.InvariantCulture); actionAgainstResults(sessionForJob, objectInstance); }); @@ -189,17 +189,17 @@ namespace Microsoft.PowerShell.Cmdletization private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru, bool asJob) { - StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru); + StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru); - if (methodInvocationJob != null) - { - bool discardNonPipelineResults = !asJob; - HandleJobOutput( - methodInvocationJob, - sessionForJob, - discardNonPipelineResults, - outputAction: null); - } + if (methodInvocationJob != null) + { + bool discardNonPipelineResults = !asJob; + HandleJobOutput( + methodInvocationJob, + sessionForJob, + discardNonPipelineResults, + outputAction: null); + } return methodInvocationJob; } @@ -242,7 +242,7 @@ namespace Microsoft.PowerShell.Cmdletization private void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPipelineResults, Action outputAction) { Action processOutput = - delegate(PSObject pso) + delegate (PSObject pso) { if (pso == null) { @@ -256,9 +256,9 @@ namespace Microsoft.PowerShell.Cmdletization }; job.Output.DataAdded += - delegate(object sender, DataAddedEventArgs eventArgs) + delegate (object sender, DataAddedEventArgs eventArgs) { - var dataCollection = (PSDataCollection) sender; + var dataCollection = (PSDataCollection)sender; if (discardNonPipelineResults) { @@ -306,7 +306,7 @@ namespace Microsoft.PowerShell.Cmdletization private static void DiscardJobOutputs(PSDataCollection psDataCollection) { psDataCollection.DataAdded += - delegate(object sender, DataAddedEventArgs e) + delegate (object sender, DataAddedEventArgs e) { var localDataCollection = (PSDataCollection)sender; localDataCollection.Clear(); @@ -369,7 +369,7 @@ namespace Microsoft.PowerShell.Cmdletization #region Implementation of ObjectModelWrapper functionality - private ThrottlingJob parentJob; + private ThrottlingJob _parentJob; /// /// Queries for object instances in the object model. @@ -378,7 +378,7 @@ namespace Microsoft.PowerShell.Cmdletization /// A lazy evaluated collection of object instances public override void ProcessRecord(QueryBuilder query) { - this.parentJob.DisableFlowControlForPendingCmdletActionsQueue(); + _parentJob.DisableFlowControlForPendingCmdletActionsQueue(); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) { StartableJob childJob = this.DoCreateQueryJob(sessionForJob, query, actionAgainstResults: null); @@ -386,11 +386,11 @@ namespace Microsoft.PowerShell.Cmdletization { if (!this.AsJob.IsPresent) { - this.parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { - this.parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } @@ -404,9 +404,9 @@ namespace Microsoft.PowerShell.Cmdletization /// true if successful method invocations should emit downstream the object instance being operated on public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) { - this.parentJob.DisableFlowControlForPendingJobsQueue(); + _parentJob.DisableFlowControlForPendingJobsQueue(); - ThrottlingJob closureOverParentJob = this.parentJob; + ThrottlingJob closureOverParentJob = _parentJob; SwitchParameter closureOverAsJob = this.AsJob; foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) @@ -414,30 +414,30 @@ namespace Microsoft.PowerShell.Cmdletization StartableJob queryJob = this.DoCreateQueryJob( sessionForJob, query, - delegate(TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) + delegate (TSession sessionForMethodInvocationJob, TObjectInstance objectInstance) { - StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob( - sessionForMethodInvocationJob, - objectInstance, - methodInvocationInfo, - passThru, - closureOverAsJob.IsPresent); + StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob( + sessionForMethodInvocationJob, + objectInstance, + methodInvocationInfo, + passThru, + closureOverAsJob.IsPresent); - if (methodInvocationJob != null) - { - closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); - } + if (methodInvocationJob != null) + { + closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); + } }); if (queryJob != null) { if (!this.AsJob.IsPresent) { - this.parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } else { - this.parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); + _parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs); } } } @@ -445,7 +445,7 @@ namespace Microsoft.PowerShell.Cmdletization private IEnumerable GetSessionsToActAgainst(TObjectInstance objectInstance) { - if (this.sessionWasSpecified) + if (_sessionWasSpecified) { return this.Session; } @@ -453,7 +453,7 @@ namespace Microsoft.PowerShell.Cmdletization TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); if (associatedSession != null) { - return new[] {associatedSession}; + return new[] { associatedSession }; } return new[] { this.GetImpliedSession() }; @@ -491,7 +491,7 @@ namespace Microsoft.PowerShell.Cmdletization private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) { - if (this.sessionWasSpecified) + if (_sessionWasSpecified) { return this.Session; } @@ -517,7 +517,7 @@ namespace Microsoft.PowerShell.Cmdletization private IEnumerable GetSessionsToActAgainst(MethodInvocationInfo methodInvocationInfo) { - if (this.sessionWasSpecified) + if (_sessionWasSpecified) { return this.Session; } @@ -547,8 +547,8 @@ namespace Microsoft.PowerShell.Cmdletization internal PSModuleInfo PSModuleInfo { - get - { + get + { var scriptCommandInfo = this.Cmdlet.CommandInfo as IScriptCommandInfo; return scriptCommandInfo.ScriptBlock.Module; } @@ -592,11 +592,11 @@ namespace Microsoft.PowerShell.Cmdletization { if (!this.AsJob.IsPresent) { - this.parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { - this.parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } @@ -617,11 +617,11 @@ namespace Microsoft.PowerShell.Cmdletization { if (!this.AsJob.IsPresent) { - this.parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, childJob, ThrottlingJob.ChildJobFlags.None); } else { - this.parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); + _parentJob.AddChildJobWithoutBlocking(childJob, ThrottlingJob.ChildJobFlags.None); } } } @@ -654,7 +654,7 @@ namespace Microsoft.PowerShell.Cmdletization } } - this.parentJob = new ThrottlingJob( + _parentJob = new ThrottlingJob( command: Job.GetCommandTextFromInvocationInfo(this.Cmdlet.MyInvocation), jobName: this.GenerateParentJobName(), jobTypeName: CIMJobType, @@ -667,17 +667,17 @@ namespace Microsoft.PowerShell.Cmdletization /// public override void EndProcessing() { - this.parentJob.EndOfChildJobs(); + _parentJob.EndOfChildJobs(); if (this.AsJob.IsPresent) { - this.Cmdlet.WriteObject(this.parentJob); - this.Cmdlet.JobRepository.Add(this.parentJob); - this.parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world + this.Cmdlet.WriteObject(_parentJob); + this.Cmdlet.JobRepository.Add(_parentJob); + _parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world } else { - this.parentJob.ForwardAllResultsToCmdlet(this.Cmdlet); - this.parentJob.Finished.WaitOne(); + _parentJob.ForwardAllResultsToCmdlet(this.Cmdlet); + _parentJob.Finished.WaitOne(); } } @@ -686,7 +686,7 @@ namespace Microsoft.PowerShell.Cmdletization /// public override void StopProcessing() { - Job jobToStop = this.parentJob; + Job jobToStop = _parentJob; if (jobToStop != null) { jobToStop.StopJob(); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 71611c520..907795da2 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -63,7 +63,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim throw new ArgumentNullException("info"); } - this.errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof (ErrorRecord)); + _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); } /// @@ -79,14 +79,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } base.GetObjectData(info, context); - info.AddValue("errorRecord", this.errorRecord); + info.AddValue("errorRecord", _errorRecord); } #endregion internal static CimJobException CreateFromCimException( - string jobDescription, - CimJobContext jobContext, + string jobDescription, + CimJobContext jobContext, CimException cimException) { Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null"); @@ -100,8 +100,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } internal static CimJobException CreateFromAnyException( - string jobDescription, - CimJobContext jobContext, + string jobDescription, + CimJobContext jobContext, Exception inner) { Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null"); @@ -114,13 +114,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return CreateFromCimException(jobDescription, jobContext, cimException); } - string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); + string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new CimJobException(message, inner); var containsErrorRecord = inner as IContainsErrorRecord; if (containsErrorRecord != null) { cimJobException.InitializeErrorRecord( - jobContext, + jobContext, errorId: "CimJob_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId, errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category); } @@ -201,10 +201,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private void InitializeErrorRecordCore(CimJobContext jobContext, Exception exception, string errorId, ErrorCategory errorCategory) { ErrorRecord coreErrorRecord = new ErrorRecord( - exception: exception, - errorId: errorId, - errorCategory: errorCategory, - targetObject: jobContext != null ? jobContext.TargetObject : null); + exception: exception, + errorId: errorId, + errorCategory: errorCategory, + targetObject: jobContext != null ? jobContext.TargetObject : null); if (jobContext != null) { @@ -212,40 +212,40 @@ namespace Microsoft.PowerShell.Cmdletization.Cim jobContext.Session.ComputerName, Guid.Empty); - this.errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord( + _errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord( coreErrorRecord, originInfo); - errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo); - errorRecord.PreserveInvocationInfoOnce = true; + _errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo); + _errorRecord.PreserveInvocationInfoOnce = true; } else { - this.errorRecord = coreErrorRecord; + _errorRecord = coreErrorRecord; } } private void InitializeErrorRecord(CimJobContext jobContext, string errorId, ErrorCategory errorCategory) { InitializeErrorRecordCore( - jobContext: jobContext, - exception: this, - errorId: errorId, + jobContext: jobContext, + exception: this, + errorId: errorId, errorCategory: errorCategory); } private void InitializeErrorRecord(CimJobContext jobContext, CimException cimException) { InitializeErrorRecordCore( - jobContext: jobContext, - exception: cimException, - errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode, + jobContext: jobContext, + exception: cimException, + errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode, errorCategory: ConvertCimExceptionToErrorCategory(cimException)); if (cimException.ErrorData != null) { - errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; - errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null; + _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; + _errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null; } } @@ -273,57 +273,57 @@ namespace Microsoft.PowerShell.Cmdletization.Cim case NativeErrorCode.Ok: return ErrorCategory.NotSpecified; case NativeErrorCode.Failed: - return ErrorCategory.NotSpecified;; + return ErrorCategory.NotSpecified; ; case NativeErrorCode.AccessDenied: - return ErrorCategory.PermissionDenied;; + return ErrorCategory.PermissionDenied; ; case NativeErrorCode.InvalidNamespace: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.InvalidParameter: - return ErrorCategory.InvalidArgument;; + return ErrorCategory.InvalidArgument; ; case NativeErrorCode.InvalidClass: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.NotFound: - return ErrorCategory.ObjectNotFound;; + return ErrorCategory.ObjectNotFound; ; case NativeErrorCode.NotSupported: - return ErrorCategory.NotImplemented;; + return ErrorCategory.NotImplemented; ; case NativeErrorCode.ClassHasChildren: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.ClassHasInstances: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.InvalidSuperClass: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.AlreadyExists: - return ErrorCategory.ResourceExists;; + return ErrorCategory.ResourceExists; ; case NativeErrorCode.NoSuchProperty: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.TypeMismatch: - return ErrorCategory.InvalidType;; + return ErrorCategory.InvalidType; ; case NativeErrorCode.QueryLanguageNotSupported: - return ErrorCategory.NotImplemented;; + return ErrorCategory.NotImplemented; ; case NativeErrorCode.InvalidQuery: - return ErrorCategory.InvalidArgument;; + return ErrorCategory.InvalidArgument; ; case NativeErrorCode.MethodNotAvailable: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.MethodNotFound: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.NamespaceNotEmpty: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.InvalidEnumerationContext: - return ErrorCategory.MetadataError;; + return ErrorCategory.MetadataError; ; case NativeErrorCode.InvalidOperationTimeout: - return ErrorCategory.InvalidArgument;; + return ErrorCategory.InvalidArgument; ; case NativeErrorCode.PullHasBeenAbandoned: - return ErrorCategory.OperationStopped;; + return ErrorCategory.OperationStopped; ; case NativeErrorCode.PullCannotBeAbandoned: - return ErrorCategory.CloseError;; + return ErrorCategory.CloseError; ; case NativeErrorCode.FilteredEnumerationNotSupported: - return ErrorCategory.NotImplemented;; + return ErrorCategory.NotImplemented; ; case NativeErrorCode.ContinuationOnErrorNotSupported: - return ErrorCategory.NotImplemented;; + return ErrorCategory.NotImplemented; ; case NativeErrorCode.ServerLimitsExceeded: - return ErrorCategory.ResourceBusy;; + return ErrorCategory.ResourceBusy; ; case NativeErrorCode.ServerIsShuttingDown: - return ErrorCategory.ResourceUnavailable;; + return ErrorCategory.ResourceUnavailable; ; default: return ErrorCategory.NotSpecified; } @@ -356,13 +356,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// public ErrorRecord ErrorRecord { - get { return this.errorRecord; } + get { return _errorRecord; } } - private ErrorRecord errorRecord; + private ErrorRecord _errorRecord; internal bool IsTerminatingError { - get { + get + { var cimException = this.InnerException as CimException; if ((cimException == null) || (cimException.ErrorData == null)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs index 22fd7f060..4389aa64e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -46,7 +46,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Dbg.Assert(_resultFromCreateInstance != null, "GetInstance should only be called after CreteInstance came back with a keyed instance"); IObservable observable = this.JobContext.Session.GetInstanceAsync( this.JobContext.Namespace, - this._resultFromCreateInstance, + _resultFromCreateInstance, this.CreateOperationOptions()); return observable; } @@ -118,8 +118,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Dbg.Assert(this.DidUserSuppressTheOperation || (_resultFromCreateInstance != null), "OnNext should always be called before OnComplete by CreateInstance"); #if DEBUG Dbg.Assert( - !this._getInstanceOperationGotStarted || this.DidUserSuppressTheOperation || (this._resultFromGetInstance != null), - // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance != null)) + !_getInstanceOperationGotStarted || this.DidUserSuppressTheOperation || (_resultFromGetInstance != null), + // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance != null)) "GetInstance should cause OnNext to be called which should set this._resultFromGetInstance to non-null"); #endif if (this.IsPassThruObjectNeeded() && (_resultFromGetInstance == null)) @@ -141,6 +141,5 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return _resultFromGetInstance; } } - } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs index 1bb5d61f2..075be25cc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs @@ -13,17 +13,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class DeleteInstanceJob : MethodInvocationJobBase { - private readonly CimInstance objectToDelete; + private readonly CimInstance _objectToDelete; internal DeleteInstanceJob(CimJobContext jobContext, bool passThru, CimInstance objectToDelete, MethodInvocationInfo methodInvocationInfo) : base( - jobContext, - passThru, + jobContext, + passThru, objectToDelete.ToString(), methodInvocationInfo) { Dbg.Assert(objectToDelete != null, "Caller should verify objectToDelete != null"); - this.objectToDelete = objectToDelete; + _objectToDelete = objectToDelete; } internal override IObservable GetCimOperation() @@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim IObservable observable = this.JobContext.Session.DeleteInstanceAsync( this.JobContext.Namespace, - this.objectToDelete, + _objectToDelete, this.CreateOperationOptions()); return observable; } @@ -47,14 +47,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override object PassThruObject { - get { return this.objectToDelete; } + get { return _objectToDelete; } } internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() { return CimCustomOptionsDictionary.MergeOptions( base.CalculateJobSpecificCustomOptions(), - this.objectToDelete); + _objectToDelete); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs index 54a57512f..9ea248ff7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -15,25 +15,25 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class EnumerateAssociatedInstancesJob : QueryJobBase { - private readonly CimInstance associatedObject; - private readonly string associationName; - private readonly string resultRole; - private readonly string sourceRole; + private readonly CimInstance _associatedObject; + private readonly string _associationName; + private readonly string _resultRole; + private readonly string _sourceRole; internal EnumerateAssociatedInstancesJob(CimJobContext jobContext, CimQuery cimQuery, CimInstance associatedObject, string associationName, string resultRole, string sourceRole) : base(jobContext, cimQuery) { - this.associatedObject = associatedObject; - Dbg.Assert(this.associatedObject != null, "Caller should verify that associatedObject is not null"); + _associatedObject = associatedObject; + Dbg.Assert(_associatedObject != null, "Caller should verify that associatedObject is not null"); - this.associationName = associationName; - Dbg.Assert(this.associationName != null, "Caller should verify that associationName is not null"); + _associationName = associationName; + Dbg.Assert(_associationName != null, "Caller should verify that associationName is not null"); - this.resultRole = resultRole; - Dbg.Assert(this.resultRole != null, "Caller should verify that resultRole is not null"); + _resultRole = resultRole; + Dbg.Assert(_resultRole != null, "Caller should verify that resultRole is not null"); - this.sourceRole = sourceRole; - Dbg.Assert(this.sourceRole != null, "Caller should verify that sourceRole is not null"); + _sourceRole = sourceRole; + Dbg.Assert(_sourceRole != null, "Caller should verify that sourceRole is not null"); } internal override IObservable GetCimOperation() @@ -41,11 +41,11 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.WriteVerboseStartOfCimOperation(); IObservable observable = this.JobContext.Session.EnumerateAssociatedInstancesAsync( this.JobContext.Namespace, - this.associatedObject, - this.associationName, + _associatedObject, + _associationName, this.JobContext.ClassNameOrNullIfResourceUriIsUsed, - this.sourceRole, - this.resultRole, + _sourceRole, + _resultRole, this.CreateOperationOptions()); return observable; @@ -53,20 +53,20 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override string Description { - get + get { return string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimJob_AssociationDescription, this.JobContext.CmdletizationClassName, this.JobContext.Session.ComputerName, - this.associatedObject.ToString()); + _associatedObject.ToString()); } } internal override string FailSafeDescription { - get + get { return string.Format( CultureInfo.InvariantCulture, @@ -80,12 +80,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { return CimCustomOptionsDictionary.MergeOptions( base.CalculateJobSpecificCustomOptions(), - this.associatedObject); + _associatedObject); } internal override void WriteObject(object outputObject) { - if (IsShowComputerNameMarkerPresent(this.associatedObject)) + if (IsShowComputerNameMarkerPresent(_associatedObject)) { PSObject pso = PSObject.AsPSObject(outputObject); AddShowComputerNameMarker(pso); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index a13d8b748..023a1fda9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -82,10 +82,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } else if (MethodParameterBindings.Error == (methodParameter.Bindings & MethodParameterBindings.Error)) { - var gotError = (bool)LanguagePrimitives.ConvertTo(dotNetValue, typeof (bool), CultureInfo.InvariantCulture); + var gotError = (bool)LanguagePrimitives.ConvertTo(dotNetValue, typeof(bool), CultureInfo.InvariantCulture); if (gotError) { - var errorCodeAsString = (string)LanguagePrimitives.ConvertTo(dotNetValue, typeof (string), CultureInfo.InvariantCulture); + var errorCodeAsString = (string)LanguagePrimitives.ConvertTo(dotNetValue, typeof(string), CultureInfo.InvariantCulture); CimJobException cje = CimJobException.CreateFromMethodErrorCode(this.GetDescription(), this.JobContext, this.MethodName, errorCodeAsString); throw cje; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs index b8a348d14..d9d7db6a2 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs @@ -14,17 +14,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class InstanceMethodInvocationJob : ExtrinsicMethodInvocationJob { - private readonly CimInstance targetInstance; + private readonly CimInstance _targetInstance; internal InstanceMethodInvocationJob(CimJobContext jobContext, bool passThru, CimInstance targetInstance, MethodInvocationInfo methodInvocationInfo) : base( - jobContext, - passThru, + jobContext, + passThru, targetInstance.ToString(), methodInvocationInfo) { Dbg.Assert(targetInstance != null, "Caller should verify targetInstance != null"); - this.targetInstance = targetInstance; + _targetInstance = targetInstance; } internal override IObservable GetCimOperation() @@ -41,7 +41,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim IObservable observable = this.JobContext.Session.InvokeMethodAsync( this.JobContext.Namespace, - this.targetInstance, + _targetInstance, this.MethodName, methodParameters, operationOptions); @@ -50,14 +50,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override object PassThruObject { - get { return this.targetInstance; } + get { return _targetInstance; } } internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() { return CimCustomOptionsDictionary.MergeOptions( base.CalculateJobSpecificCustomOptions(), - this.targetInstance); + _targetInstance); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs index 2c0914abf..cfae4877f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of an extrinsic CIM method /// - abstract internal class MethodInvocationJobBase : CimChildJobBase + abstract internal class MethodInvocationJobBase : CimChildJobBase { internal MethodInvocationJobBase(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo) : base(jobContext) @@ -25,9 +25,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Dbg.Assert(methodInvocationInfo != null, "Caller should verify methodInvocationInfo != null"); Dbg.Assert(methodSubject != null, "Caller should verify methodSubject != null"); - this._passThru = passThru; - this._methodSubject = methodSubject; - this._methodInvocationInfo = methodInvocationInfo; + _passThru = passThru; + _methodSubject = methodSubject; + _methodInvocationInfo = methodInvocationInfo; } private readonly string _methodSubject; @@ -36,14 +36,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal string MethodName { - get { return this._methodInvocationInfo.MethodName; } + get { return _methodInvocationInfo.MethodName; } } private const string CustomOperationOptionPrefix = "cim:operationOption:"; private IEnumerable GetMethodInputParametersCore(Func filter) { - IEnumerable inputParameters = this._methodInvocationInfo.Parameters.Where(filter); + IEnumerable inputParameters = _methodInvocationInfo.Parameters.Where(filter); var result = new List(); foreach (MethodParameter inputParameter in inputParameters) @@ -52,13 +52,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Type cimType = CimSensitiveValueConverter.GetCimType(inputParameter.ParameterType); CimValueConverter.AssertIntrinsicCimType(cimType); result.Add(new MethodParameter - { - Name = inputParameter.Name, - ParameterType = cimType, - Bindings = inputParameter.Bindings, - Value = cimValue, - IsValuePresent = inputParameter.IsValuePresent - }); + { + Name = inputParameter.Name, + ParameterType = cimType, + Bindings = inputParameter.Bindings, + Value = cimValue, + IsValuePresent = inputParameter.IsValuePresent + }); } return result; } @@ -72,7 +72,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal IEnumerable GetCimInstancesFromArguments() { - return this._methodInvocationInfo.GetArgumentsOfType(); + return _methodInvocationInfo.GetArgumentsOfType(); } internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() @@ -96,10 +96,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal IEnumerable GetMethodOutputParameters() { - IEnumerable allParameters_plus_returnValue = this._methodInvocationInfo.Parameters; - if (this._methodInvocationInfo.ReturnValue != null) + IEnumerable allParameters_plus_returnValue = _methodInvocationInfo.Parameters; + if (_methodInvocationInfo.ReturnValue != null) { - allParameters_plus_returnValue = allParameters_plus_returnValue.Append(this._methodInvocationInfo.ReturnValue); + allParameters_plus_returnValue = allParameters_plus_returnValue.Append(_methodInvocationInfo.ReturnValue); } var outParameters = allParameters_plus_returnValue @@ -110,7 +110,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal string MethodSubject { - get { return this._methodSubject; } + get { return _methodSubject; } } internal bool ShouldProcess() @@ -158,7 +158,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal bool IsPassThruObjectNeeded() { - return (this._passThru) && (!this.DidUserSuppressTheOperation) && (!this.JobHadErrors); + return (_passThru) && (!this.DidUserSuppressTheOperation) && (!this.JobHadErrors); } public override void OnCompleted() @@ -187,7 +187,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override string Description { - get + get { return string.Format( CultureInfo.InvariantCulture, @@ -211,6 +211,5 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } #endregion - } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs index d2be78d00..4efc7d12b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs @@ -75,7 +75,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { return CimCustomOptionsDictionary.MergeOptions( base.CalculateJobSpecificCustomOptions(), - this._originalInstance); + _originalInstance); } protected override void Dispose(bool disposing) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs index 9410e91af..c92ad7e54 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs @@ -14,8 +14,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { internal PropertySettingJob(CimJobContext jobContext, bool passThru, CimInstance objectToModify, MethodInvocationInfo methodInvocationInfo) : base( - jobContext, - passThru, + jobContext, + passThru, objectToModify.ToString(), methodInvocationInfo) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs index 286825257..8a3d45715 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs @@ -27,17 +27,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim wqlQueryBuilder.Append(this.JobContext.ClassName); wqlQueryBuilder.Append(" "); wqlQueryBuilder.Append(wqlCondition); - this._wqlQuery = wqlQueryBuilder.ToString(); + _wqlQuery = wqlQueryBuilder.ToString(); if (string.IsNullOrWhiteSpace(wqlCondition)) { - this._useEnumerateInstances = true; + _useEnumerateInstances = true; } else { if (jobContext.CmdletInvocationContext.CmdletDefinitionContext.UseEnumerateInstancesInsteadOfWql) { - this._useEnumerateInstances = true; + _useEnumerateInstances = true; } } } @@ -45,9 +45,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override IObservable GetCimOperation() { this.WriteVerboseStartOfCimOperation(); - + IObservable observable; - if (this._useEnumerateInstances) + if (_useEnumerateInstances) { observable = this.JobContext.Session.EnumerateInstancesAsync( this.JobContext.Namespace, @@ -59,7 +59,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim observable = this.JobContext.Session.QueryInstancesAsync( this.JobContext.Namespace, "WQL", - this._wqlQuery, + _wqlQuery, this.CreateOperationOptions()); } @@ -68,7 +68,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override string Description { - get + get { return this.FailSafeDescription; } @@ -76,14 +76,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override string FailSafeDescription { - get + get { return string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimJob_SafeQueryDescription, this.JobContext.CmdletizationClassName, this.JobContext.Session.ComputerName, - this._wqlQuery); + _wqlQuery); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs index 9db644656..3f04a81ec 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -33,7 +33,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return; } - if (!this._cimQuery.IsMatchingResult(item)) + if (!_cimQuery.IsMatchingResult(item)) { return; } @@ -46,7 +46,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.ExceptionSafeWrapper( delegate { - foreach (ClientSideQuery.NotFoundError notFoundError in this._cimQuery.GenerateNotFoundErrors()) + foreach (ClientSideQuery.NotFoundError notFoundError in _cimQuery.GenerateNotFoundErrors()) { string errorId = "CmdletizationQuery_NotFound"; if (!string.IsNullOrEmpty(notFoundError.PropertyName)) @@ -70,7 +70,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() { - return CimCustomOptionsDictionary.Create(this._cimQuery.queryOptions); + return CimCustomOptionsDictionary.Create(_cimQuery.queryOptions); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index 4fab5b44e..12e484ef0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { #region Getting tracker for a given cmdlet invocation - private static readonly ConditionalWeakTable InvocationToTracker = + private static readonly ConditionalWeakTable s_invocationToTracker = new ConditionalWeakTable(); private static int GetNumberOfSessions(InvocationInfo invocationInfo) @@ -31,7 +31,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim object cimSessionArgument; if (invocationInfo.BoundParameters.TryGetValue("CimSession", out cimSessionArgument)) { - IList cimSessionArgumentAsList = (IList) cimSessionArgument; + IList cimSessionArgumentAsList = (IList)cimSessionArgument; return cimSessionArgumentAsList.Count; } // else - either CimSession=localhost OR CimSession is based on CimInstance->CimSession affinity @@ -59,7 +59,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim .Distinct() .Count(); maxNumberOfSessionsIndicatedByCimInstanceArguments = Math.Max( - maxNumberOfSessionsIndicatedByCimInstanceArguments, + maxNumberOfSessionsIndicatedByCimInstanceArguments, numberOfSessionsAssociatedWithArgument); } } @@ -68,17 +68,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo, bool isStaticCmdlet) { - var tracker = InvocationToTracker.GetValue( + var tracker = s_invocationToTracker.GetValue( invocationInfo, _ => new TerminatingErrorTracker(GetNumberOfSessions(invocationInfo))); return tracker; } - + internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo) { TerminatingErrorTracker tracker; - bool foundTracker = InvocationToTracker.TryGetValue(invocationInfo, out tracker); + bool foundTracker = s_invocationToTracker.TryGetValue(invocationInfo, out tracker); Dbg.Assert(foundTracker, "The other overload of GetTracker should always be called first"); return tracker; } @@ -92,7 +92,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private TerminatingErrorTracker(int numberOfSessions) { - this._numberOfSessions = numberOfSessions; + _numberOfSessions = numberOfSessions; } #region Tracking session's "connectivity" status @@ -101,13 +101,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal void MarkSessionAsConnected(CimSession connectedSession) { - this._sessionToIsConnected.TryAdd(connectedSession, true); + _sessionToIsConnected.TryAdd(connectedSession, true); } internal bool DidSessionAlreadyPassedConnectivityTest(CimSession session) { bool alreadyPassedConnectivityTest = false; - if (this._sessionToIsConnected.TryGetValue(session, out alreadyPassedConnectivityTest)) + if (_sessionToIsConnected.TryGetValue(session, out alreadyPassedConnectivityTest)) { return alreadyPassedConnectivityTest; } @@ -115,7 +115,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } internal Exception GetExceptionIfBrokenSession( - CimSession potentiallyBrokenSession, + CimSession potentiallyBrokenSession, bool skipTestConnection, out bool sessionWasAlreadyTerminated) { @@ -167,11 +167,11 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal void MarkSessionAsTerminated(CimSession terminatedSession, out bool sessionWasAlreadyTerminated) { bool closureSafeSessionWasAlreadyTerminated = false; - this._sessionToIsTerminated.AddOrUpdate( + _sessionToIsTerminated.AddOrUpdate( key: terminatedSession, addValue: true, updateValueFactory: - delegate(CimSession key, bool isTerminatedValueInDictionary) + delegate (CimSession key, bool isTerminatedValueInDictionary) { closureSafeSessionWasAlreadyTerminated = isTerminatedValueInDictionary; return true; @@ -182,7 +182,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal bool IsSessionTerminated(CimSession session) { - bool isTerminated = this._sessionToIsTerminated.GetOrAdd(session, false); + bool isTerminated = _sessionToIsTerminated.GetOrAdd(session, false); return isTerminated; } @@ -196,8 +196,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim object lockObject = new object(); Func action = delegate (Cmdlet cmdlet) { - this._numberOfReportedSessionTerminatingErrors++; - if (this._numberOfReportedSessionTerminatingErrors >= this._numberOfSessions) + _numberOfReportedSessionTerminatingErrors++; + if (_numberOfReportedSessionTerminatingErrors >= _numberOfSessions) { cmdlet.ThrowTerminatingError(errorRecord); } @@ -210,11 +210,11 @@ namespace Microsoft.PowerShell.Cmdletization.Cim }; return new CmdletMethodInvoker - { - Action = action, - Finished = manualResetEventSlim, // not really needed here, but required by CmdletMethodInvoker - SyncObject = lockObject, // not really needed here, but required by CmdletMethodInvoker - }; + { + Action = action, + Finished = manualResetEventSlim, // not really needed here, but required by CmdletMethodInvoker + SyncObject = lockObject, // not really needed here, but required by CmdletMethodInvoker + }; } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index efb20de37..8d803b180 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -27,19 +27,19 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Base class for all child jobs that wrap CIM operations /// - internal abstract class CimChildJobBase : - StartableJob, + internal abstract class CimChildJobBase : + StartableJob, IObserver { - private static long _globalJobNumberCounter; - private readonly long _myJobNumber = Interlocked.Increment(ref _globalJobNumberCounter); + private static long s_globalJobNumberCounter; + private readonly long _myJobNumber = Interlocked.Increment(ref s_globalJobNumberCounter); private const string CIMJobType = "CimJob"; internal CimJobContext JobContext { get { - return this._jobContext; + return _jobContext; } } private readonly CimJobContext _jobContext; @@ -47,18 +47,18 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal CimChildJobBase(CimJobContext jobContext) : base(Job.GetCommandTextFromInvocationInfo(jobContext.CmdletInvocationInfo), " " /* temporary name - reset below */) { - this._jobContext = jobContext; + _jobContext = jobContext; this.PSJobTypeName = CIMJobType; - this.Name = this.GetType().Name + this._myJobNumber.ToString(CultureInfo.InvariantCulture); + this.Name = this.GetType().Name + _myJobNumber.ToString(CultureInfo.InvariantCulture); UsesResultsCollection = true; - lock (GlobalRandom) + lock (s_globalRandom) { - this._random = new Random(GlobalRandom.Next()); + _random = new Random(s_globalRandom.Next()); } - this._jobSpecificCustomOptions = new Lazy(this.CalculateJobSpecificCustomOptions); + _jobSpecificCustomOptions = new Lazy(this.CalculateJobSpecificCustomOptions); } private CimSensitiveValueConverter _cimSensitiveValueConverter = new CimSensitiveValueConverter(); @@ -77,7 +77,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim ERROR_WSMAN_QUOTA_SYSTEM = 0x803381A8, ERROR_WSMAN_QUOTA_MAX_SHELLUSERS = 0x803381AB, ERROR_WSMAN_QUOTA_MAX_SHELLS_PPQ = 0x803381E4, - ERROR_WSMAN_QUOTA_MAX_USERS_PPQ = 0x803381E5, + ERROR_WSMAN_QUOTA_MAX_USERS_PPQ = 0x803381E5, ERROR_WSMAN_QUOTA_MAX_PLUGINSHELLS_PPQ = 0x803381E6, ERROR_WSMAN_QUOTA_MAX_PLUGINOPERATIONS_PPQ = 0x803381E7, ERROR_WSMAN_QUOTA_MAX_OPERATIONS_USER_PPQ = 0x803381E8, @@ -114,7 +114,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return false; } - WsManErrorCode wsManErrorCode = (WsManErrorCode) (UInt32) (errorCodeProperty.Value); + WsManErrorCode wsManErrorCode = (WsManErrorCode)(UInt32)(errorCodeProperty.Value); switch (wsManErrorCode) // error codes that should result in sleep-and-retry are based on an email from Ryan { case WsManErrorCode.ERROR_WSMAN_QUOTA_MAX_SHELLS: @@ -161,7 +161,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim }); } - private static readonly Random GlobalRandom = new Random(); + private static readonly Random s_globalRandom = new Random(); private readonly Random _random; private int _sleepAndRetryDelayRangeMs = 1000; private int _sleepAndRetryExtraDelayMs = 0; @@ -173,14 +173,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.ExceptionSafeWrapper( delegate { - lock (this._jobStateLock) + lock (_jobStateLock) { - if (this._sleepAndRetryTimer != null) + if (_sleepAndRetryTimer != null) { - this._sleepAndRetryTimer.Dispose(); - this._sleepAndRetryTimer = null; + _sleepAndRetryTimer.Dispose(); + _sleepAndRetryTimer = null; } - if (this._jobWasStopped) + if (_jobWasStopped) { this.SetCompletedJobState(JobState.Stopped, null); return; @@ -191,12 +191,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } private void SleepAndRetry() { - int tmpRandomDelay = _random.Next(0, this._sleepAndRetryDelayRangeMs); - int delay = MinRetryDelayMs + this._sleepAndRetryExtraDelayMs + tmpRandomDelay; - this._sleepAndRetryExtraDelayMs = _sleepAndRetryDelayRangeMs - tmpRandomDelay; - if (this._sleepAndRetryDelayRangeMs < MaxRetryDelayMs) + int tmpRandomDelay = _random.Next(0, _sleepAndRetryDelayRangeMs); + int delay = MinRetryDelayMs + _sleepAndRetryExtraDelayMs + tmpRandomDelay; + _sleepAndRetryExtraDelayMs = _sleepAndRetryDelayRangeMs - tmpRandomDelay; + if (_sleepAndRetryDelayRangeMs < MaxRetryDelayMs) { - this._sleepAndRetryDelayRangeMs *= 2; + _sleepAndRetryDelayRangeMs *= 2; } string verboseMessage = string.Format( @@ -207,16 +207,16 @@ namespace Microsoft.PowerShell.Cmdletization.Cim delay / 1000.0); this.WriteVerbose(verboseMessage); - lock (this._jobStateLock) + lock (_jobStateLock) { - if (this._jobWasStopped) + if (_jobWasStopped) { this.SetCompletedJobState(JobState.Stopped, null); } else { - Dbg.Assert(this._sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer"); - this._sleepAndRetryTimer = new Timer( + Dbg.Assert(_sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer"); + _sleepAndRetryTimer = new Timer( state: null, dueTime: delay, period: Timeout.Infinite, @@ -230,7 +230,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// public override string Location { - get + get { // this.JobContext is set in the constructor of CimChildJobBase, // but the constructor of Job wants to access Location property @@ -250,7 +250,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// public override string StatusMessage { - get + get { return this.JobStateInfo.State.ToString(); } @@ -261,8 +261,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// public override bool HasMoreData { - get - { + get + { return (Results.IsOpen || Results.Count > 0); } } @@ -281,15 +281,15 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal override void StartJob() { - lock (this._jobStateLock) + lock (_jobStateLock) { - if (this._jobWasStopped) + if (_jobWasStopped) { this.SetCompletedJobState(JobState.Stopped, null); return; } - Dbg.Assert(!this._alreadyReachedCompletedState, "Job shouldn't reach completed state, before ThrottlingJob has a chance to register for job-completed/failed events"); + Dbg.Assert(!_alreadyReachedCompletedState, "Job shouldn't reach completed state, before ThrottlingJob has a chance to register for job-completed/failed events"); TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.JobContext.CmdletInvocationInfo); if (tracker.IsSessionTerminated(this.JobContext.Session)) @@ -298,16 +298,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return; } - if (!this._jobWasStarted) + if (!_jobWasStarted) { - this._jobWasStarted = true; + _jobWasStarted = true; this.SetJobState(JobState.Running); } } // This invocation can block (i.e. by calling Job.ShouldProcess) and wait for pipeline thread to unblock it // Therefore we have to do the invocation outside of the pipeline thread. - ThreadPool.QueueUserWorkItem(delegate { + ThreadPool.QueueUserWorkItem(delegate + { this.ExceptionSafeWrapper(delegate { IObservable observable = this.GetCimOperation(); @@ -358,14 +359,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } catch (PSInvalidOperationException) { - lock (this._jobStateLock) + lock (_jobStateLock) { bool everythingIsOk = false; - if (this._jobWasStopped) + if (_jobWasStopped) { everythingIsOk = true; } - if (this._alreadyReachedCompletedState && this._jobHadErrors) + if (_alreadyReachedCompletedState && _jobHadErrors) { everythingIsOk = true; } @@ -394,13 +395,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal CimOperationOptions CreateOperationOptions() { var operationOptions = new CimOperationOptions(mustUnderstand: false) - { - CancellationToken = this._cancellationTokenSource.Token, - WriteProgress = this.WriteProgressCallback, - WriteMessage = this.WriteMessageCallback, - WriteError = this.WriteErrorCallback, - PromptUser = this.PromptUserCallback, - }; + { + CancellationToken = _cancellationTokenSource.Token, + WriteProgress = this.WriteProgressCallback, + WriteMessage = this.WriteMessageCallback, + WriteError = this.WriteErrorCallback, + PromptUser = this.PromptUserCallback, + }; operationOptions.SetOption("__MI_OPERATIONOPTIONS_IMPROVEDPERF_STREAMING", 1); @@ -464,7 +465,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim case MshCommandRuntime.ShouldProcessPossibleOptimization.NoOptimizationPossible: default: - operationOptions.PromptUserMode = CimCallbackMode.Inquire; + operationOptions.PromptUserMode = CimCallbackMode.Inquire; break; } @@ -486,31 +487,31 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (!string.IsNullOrWhiteSpace(this.GetProviderVersionExpectedByJob())) { CimOperationOptionsHelper.SetCustomOption( - operationOptions, - "MI_OPERATIONOPTIONS_PROVIDERVERSION", - this.GetProviderVersionExpectedByJob(), + operationOptions, + "MI_OPERATIONOPTIONS_PROVIDERVERSION", + this.GetProviderVersionExpectedByJob(), CimSensitiveValueConverter); } if (this.JobContext.CmdletizationModuleVersion != null) { CimOperationOptionsHelper.SetCustomOption( - operationOptions, - "MI_OPERATIONOPTIONS_POWERSHELL_MODULEVERSION", - this.JobContext.CmdletizationModuleVersion, + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_MODULEVERSION", + this.JobContext.CmdletizationModuleVersion, CimSensitiveValueConverter); } CimOperationOptionsHelper.SetCustomOption( - operationOptions, - "MI_OPERATIONOPTIONS_POWERSHELL_CMDLETNAME", - this.JobContext.CmdletInvocationInfo.MyCommand.Name, + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_CMDLETNAME", + this.JobContext.CmdletInvocationInfo.MyCommand.Name, CimSensitiveValueConverter); if (!string.IsNullOrWhiteSpace(this.JobContext.Session.ComputerName)) { CimOperationOptionsHelper.SetCustomOption( - operationOptions, - "MI_OPERATIONOPTIONS_POWERSHELL_COMPUTERNAME", - this.JobContext.Session.ComputerName, + operationOptions, + "MI_OPERATIONOPTIONS_POWERSHELL_COMPUTERNAME", + this.JobContext.Session.ComputerName, CimSensitiveValueConverter); } @@ -542,22 +543,22 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// public override void StopJob() { - lock (this._jobStateLock) + lock (_jobStateLock) { - if (this._jobWasStopped || this._alreadyReachedCompletedState) + if (_jobWasStopped || _alreadyReachedCompletedState) { return; } - this._jobWasStopped = true; + _jobWasStopped = true; if (!_jobWasStarted) { this.SetCompletedJobState(JobState.Stopped, null); } - else if (this._sleepAndRetryTimer != null) + else if (_sleepAndRetryTimer != null) { - this._sleepAndRetryTimer.Dispose(); - this._sleepAndRetryTimer = null; + _sleepAndRetryTimer.Dispose(); + _sleepAndRetryTimer = null; this.SetCompletedJobState(JobState.Stopped, null); } else @@ -565,7 +566,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.SetJobState(JobState.Stopping); } } - this._cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); } private readonly object _jobStateLock = new object(); @@ -578,9 +579,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { get { - lock (this._jobStateLock) + lock (_jobStateLock) { - return this._jobHadErrors; + return _jobHadErrors; } } } @@ -592,9 +593,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim bool sessionWasAlreadyTerminated = false; bool isThisTerminatingError = false; Exception brokenSessionException = null; - lock (this._jobStateLock) + lock (_jobStateLock) { - if (!this._jobWasStopped) + if (!_jobWasStopped) { brokenSessionException = terminatingErrorTracker.GetExceptionIfBrokenSession( this.JobContext.Session, @@ -629,9 +630,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim bool writeError = !sessionWasAlreadyTerminated; if (writeError) { - lock (this._jobStateLock) + lock (_jobStateLock) { - if (this._jobWasStopped) + if (_jobWasStopped) { writeError = false; } @@ -644,7 +645,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (writeError) { - lock (this._jobStateLock) + lock (_jobStateLock) { if (!_alreadyReachedCompletedState) { @@ -661,7 +662,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } } } - + this.SetCompletedJobState(JobState.Failed, errorRecord.Exception); } @@ -685,7 +686,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal void SetCompletedJobState(JobState state, Exception reason) { - lock (this._jobStateLock) + lock (_jobStateLock) { if (_alreadyReachedCompletedState) { @@ -696,14 +697,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if ((state == JobState.Failed) || (reason != null)) { - this._jobHadErrors = true; + _jobHadErrors = true; } - if (this._jobWasStopped) + if (_jobWasStopped) { state = JobState.Stopped; } - else if (this._jobHadErrors) + else if (_jobHadErrors) { state = JobState.Failed; } @@ -712,22 +713,22 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.FinishProgressReporting(); this.SetJobState(state, reason); this.CloseAllStreams(); - this._cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); } #endregion #region Support for progress reporting - private readonly ConcurrentDictionary _activityIdToLastProgressRecord = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _activityIdToLastProgressRecord = new ConcurrentDictionary(); internal override void WriteProgress(ProgressRecord progressRecord) { progressRecord.Activity = this.JobContext.PrependComputerNameToMessage(progressRecord.Activity); - this._activityIdToLastProgressRecord.AddOrUpdate( - progressRecord.ActivityId, - progressRecord, + _activityIdToLastProgressRecord.AddOrUpdate( + progressRecord.ActivityId, + progressRecord, (activityId, oldProgressRecord) => progressRecord); base.WriteProgress(progressRecord); @@ -735,7 +736,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal void FinishProgressReporting() { - foreach (ProgressRecord lastProgressRecord in this._activityIdToLastProgressRecord.Values) + foreach (ProgressRecord lastProgressRecord in _activityIdToLastProgressRecord.Values) { if (lastProgressRecord.RecordType != ProgressRecordType.Completed) { @@ -746,7 +747,6 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.WriteProgress(newProgressRecord); } } - } #endregion @@ -771,7 +771,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } else if (secondsRemaining <= Int32.MaxValue) { - signedSecondsRemaining = (Int32) secondsRemaining; + signedSecondsRemaining = (Int32)secondsRemaining; } else { @@ -785,20 +785,20 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } else if (percentageCompleted <= 100) { - signedPercentageComplete = (Int32) percentageCompleted; + signedPercentageComplete = (Int32)percentageCompleted; } else { signedPercentageComplete = 100; } - var progressRecord = new ProgressRecord(unchecked((int)(this._myJobNumber % int.MaxValue)), activity, statusDescription) - { - CurrentOperation = currentOperation, - PercentComplete = signedPercentageComplete, - SecondsRemaining = signedSecondsRemaining, - RecordType = ProgressRecordType.Processing, - }; + var progressRecord = new ProgressRecord(unchecked((int)(_myJobNumber % int.MaxValue)), activity, statusDescription) + { + CurrentOperation = currentOperation, + PercentComplete = signedPercentageComplete, + SecondsRemaining = signedSecondsRemaining, + RecordType = ProgressRecordType.Processing, + }; this.ExceptionSafeWrapper( delegate @@ -856,9 +856,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private CimResponseType WriteErrorCallback(CimInstance cimError) { - lock (this._jobStateLock) + lock (_jobStateLock) { - this._jobHadErrors = true; + _jobHadErrors = true; } var cimException = new CimException(cimError); @@ -898,7 +898,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return ShouldProcess(verboseDescription, null, null); } - + internal CimResponseType ShouldProcess( string verboseDescription, string verboseWarning, @@ -949,7 +949,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Exception exceptionThrownOnCmdletThread = null; CimResponseType result = CimResponseType.No; - this._userWasPromptedForContinuationOfProcessing = true; + _userWasPromptedForContinuationOfProcessing = true; switch (promptType) { case CimPromptType.Critical: @@ -987,7 +987,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if ((result == CimResponseType.Yes) || (result == CimResponseType.YesToAll)) { - this._userRespondedYesToAtLeastOneShouldProcess = true; + _userRespondedYesToAtLeastOneShouldProcess = true; } return result; } @@ -1041,12 +1041,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { if (pso == null) { - pso = PSObject.AsPSObject(outputObject); + pso = PSObject.AsPSObject(outputObject); } AddShowComputerNameMarker(pso); - if(cimInstance == null) + if (cimInstance == null) { - pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty,this.JobContext.Session.ComputerName)); + pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, this.JobContext.Session.ComputerName)); } } @@ -1058,9 +1058,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (disposing) { bool isCompleted; - lock (this._jobStateLock) + lock (_jobStateLock) { - isCompleted = this._alreadyReachedCompletedState; + isCompleted = _alreadyReachedCompletedState; } if (!isCompleted) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs index ededce3bf..f08b4e69b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs @@ -13,17 +13,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal class CimCmdletDefinitionContext { internal CimCmdletDefinitionContext( - string cmdletizationClassName, - string cmdletizationClassVersion, - Version cmdletizationModuleVersion, - bool supportsShouldProcess, + string cmdletizationClassName, + string cmdletizationClassVersion, + Version cmdletizationModuleVersion, + bool supportsShouldProcess, IDictionary privateData) { this.CmdletizationClassName = cmdletizationClassName; this.CmdletizationClassVersion = cmdletizationClassVersion; this.CmdletizationModuleVersion = cmdletizationModuleVersion; this.SupportsShouldProcess = supportsShouldProcess; - this._privateData = privateData; + _privateData = privateData; } public string CmdletizationClassName { get; private set; } @@ -42,15 +42,15 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { bool newValue = false; string queryLanguage; - if (this._privateData != null && - this._privateData.TryGetValue(QueryLanguageKey, out queryLanguage) && + if (_privateData != null && + _privateData.TryGetValue(QueryLanguageKey, out queryLanguage) && queryLanguage.Equals("None", StringComparison.OrdinalIgnoreCase)) { newValue = true; } - this._useEnumerateInstancesInsteadOfWql = newValue; + _useEnumerateInstancesInsteadOfWql = newValue; } - return this._useEnumerateInstancesInsteadOfWql.Value; + return _useEnumerateInstancesInsteadOfWql.Value; } } @@ -68,10 +68,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim public int DefaultThrottleLimit { - get - { + get + { string defaultThrottleLimitString; - if (!this._privateData.TryGetValue("DefaultThrottleLimit", out defaultThrottleLimitString)) + if (!_privateData.TryGetValue("DefaultThrottleLimit", out defaultThrottleLimitString)) { return FallbackDefaultThrottleLimit; } @@ -88,19 +88,19 @@ namespace Microsoft.PowerShell.Cmdletization.Cim public bool ExposeCimNamespaceParameter { - get { return this._privateData.ContainsKey("CimNamespaceParameter"); } + get { return _privateData.ContainsKey("CimNamespaceParameter"); } } public bool ClientSideWriteVerbose { - get { return this._privateData.ContainsKey("ClientSideWriteVerbose"); } + get { return _privateData.ContainsKey("ClientSideWriteVerbose"); } } public bool ClientSideShouldProcess { get { - return this._privateData.ContainsKey("ClientSideShouldProcess"); + return _privateData.ContainsKey("ClientSideShouldProcess"); } } @@ -114,22 +114,22 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { string newResourceUriString; Uri newResourceUri; - if (this._privateData != null && - this._privateData.TryGetValue("ResourceUri", out newResourceUriString) && + if (_privateData != null && + _privateData.TryGetValue("ResourceUri", out newResourceUriString) && Uri.TryCreate(newResourceUriString, UriKind.RelativeOrAbsolute, out newResourceUri)) { - this._resourceUri = newResourceUri; + _resourceUri = newResourceUri; } - this._resourceUriHasBeenCalculated = true; + _resourceUriHasBeenCalculated = true; } - return this._resourceUri; + return _resourceUri; } } public bool SkipTestConnection { - get { return this._privateData.ContainsKey("SkipTestConnection"); } + get { return _privateData.ContainsKey("SkipTestConnection"); } } private CimOperationFlags? _schemaConformanceLevel; @@ -142,8 +142,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim CimOperationFlags newSchemaConformanceLevel = 0; string schemaConformanceFromCdxml; - if (this._privateData != null && - this._privateData.TryGetValue("TypeInformation", out schemaConformanceFromCdxml)) + if (_privateData != null && + _privateData.TryGetValue("TypeInformation", out schemaConformanceFromCdxml)) { if (schemaConformanceFromCdxml.Equals("Basic", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs index 27e8c6a6a..b89f7c4de 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { internal CimCmdletInvocationContext( CimCmdletDefinitionContext cmdletDefinitionContext, - Cmdlet cmdlet, + Cmdlet cmdlet, string namespaceOverride) { this.CmdletDefinitionContext = cmdletDefinitionContext; @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim // Cmdlet might have a shorter lifespan than CimCmdletInvocationContext // - we need to extract information out of Cmdlet to extend information's lifespan - this.CmdletInvocationInfo = cmdlet.MyInvocation; + this.CmdletInvocationInfo = cmdlet.MyInvocation; var runtime = cmdlet.CommandRuntime as MshCommandRuntime; Dbg.Assert(runtime != null, "CIM cmdlets should only be run from within PS runtime"); @@ -30,17 +30,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.DebugActionPreference = runtime.DebugPreference; WarnAboutUnsupportedActionPreferences( cmdlet, - this.DebugActionPreference, - "Debug", - inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_DebugInquire, + this.DebugActionPreference, + "Debug", + inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_DebugInquire, stopMessageGetter: () => string.Empty); this.WarningActionPreference = runtime.WarningPreference; WarnAboutUnsupportedActionPreferences( cmdlet, - this.WarningActionPreference, - "WarningAction", - inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_WarningInquire, + this.WarningActionPreference, + "WarningAction", + inquireMessageGetter: () => CmdletizationResources.CimCmdletAdapter_WarningInquire, stopMessageGetter: () => CmdletizationResources.CimCmdletAdapter_WarningStop); this.VerboseActionPreference = runtime.VerbosePreference; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 98f35b704..64ced9d87 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -44,7 +44,7 @@ namespace Microsoft.PowerShell.Cim #if !CORECLR // String.IsInterned Not In CoreCLR Debug.Assert( - string.IsInterned(_string) == null, + string.IsInterned(_string) == null, "We will overwrite string contents - we can't / shouldn't do this for interned strings."); #endif @@ -170,9 +170,9 @@ namespace Microsoft.PowerShell.Cim PSObject psObject = PSObject.AsPSObject(dotNetObject); Type dotNetType = psObject.BaseObject.GetType(); - if (typeof (PSCredential).IsAssignableFrom(dotNetType)) + if (typeof(PSCredential).IsAssignableFrom(dotNetType)) { - var credential = (PSCredential) (psObject.BaseObject); + var credential = (PSCredential)(psObject.BaseObject); string escapedUsername = credential.UserName; escapedUsername = escapedUsername.Replace("\\", "\\\\"); // Esc backslashes @@ -186,9 +186,9 @@ namespace Microsoft.PowerShell.Cim return sensitiveString.Value; } - if (typeof (SecureString).IsAssignableFrom(dotNetType)) + if (typeof(SecureString).IsAssignableFrom(dotNetType)) { - SecureString secureString = (SecureString) psObject.BaseObject; + SecureString secureString = (SecureString)psObject.BaseObject; var sensitiveString = new SensitiveString(secureString.Length); lock (_trackedDisposables) { _trackedDisposables.Add(sensitiveString); } sensitiveString.Copy(secureString, 0); @@ -244,7 +244,7 @@ namespace Microsoft.PowerShell.Cim PSObject psObject = PSObject.AsPSObject(dotNetObject); Type dotNetType = psObject.BaseObject.GetType(); Dbg.Assert( - !(dotNetType.GetTypeInfo().IsGenericType && dotNetType.GetGenericTypeDefinition() == typeof (Nullable<>)), + !(dotNetType.GetTypeInfo().IsGenericType && dotNetType.GetGenericTypeDefinition() == typeof(Nullable<>)), "GetType on a boxed object should never return Nullable"); if (LanguagePrimitives.IsCimIntrinsicScalarType(dotNetType)) @@ -394,7 +394,7 @@ namespace Microsoft.PowerShell.Cim return dotNetObject; } - Func, object> exceptionSafeReturn = delegate(Func innerAction) + Func, object> exceptionSafeReturn = delegate (Func innerAction) { try { @@ -402,7 +402,6 @@ namespace Microsoft.PowerShell.Cim } catch (Exception e) { - CommandProcessor.CheckForSevereException(e); throw CimValueConverter.GetInvalidCastException( e, @@ -470,7 +469,7 @@ namespace Microsoft.PowerShell.Cim return exceptionSafeReturn(delegate { XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( - cimIntrinsicValue, + cimIntrinsicValue, true, /* preserve non elements: whitespace, processing instructions, comments, etc. */ null); /* default maxCharactersInDocument */ return doc; @@ -671,8 +670,8 @@ namespace Microsoft.PowerShell.Cim (type.IsArray && LanguagePrimitives.IsCimIntrinsicScalarType(type.GetElementType())) || typeof(CimInstance).IsAssignableFrom(type) || typeof(PSReference).IsAssignableFrom(type) || - type == typeof (CimInstance[]) || - type == typeof (PSReference[]), + type == typeof(CimInstance[]) || + type == typeof(PSReference[]), "Caller should verify that type is an intrinsic CIM type"); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs index 086fcc912..a3caada57 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { internal CimJobContext( CimCmdletInvocationContext cmdletInvocationContext, - CimSession session, + CimSession session, object targetObject) { this.CmdletInvocationContext = cmdletInvocationContext; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs index 5e3f855d4..ededc6cd1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -13,7 +13,7 @@ using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Cmdletization.Cim { - internal class CimCustomOptionsDictionary + internal class CimCustomOptionsDictionary { private readonly IDictionary _dict; private readonly object _dictModificationLock = new object(); @@ -21,18 +21,18 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private CimCustomOptionsDictionary(IEnumerable> wrappedDictionary) { // no need to lock _dictModificationLock inside the constructor - this._dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + _dict = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var kvp in wrappedDictionary) { - this._dict[kvp.Key] = kvp.Value; + _dict[kvp.Key] = kvp.Value; } } private IEnumerable> GetSnapshot() { - lock (this._dictModificationLock) + lock (_dictModificationLock) { - return this._dict.ToList(); + return _dict.ToList(); } } @@ -41,7 +41,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return new CimCustomOptionsDictionary(wrappedDictionary); } - private static readonly ConditionalWeakTable CimInstanceToCustomOptions = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_cimInstanceToCustomOptions = new ConditionalWeakTable(); internal static void AssociateCimInstanceWithCustomOptions(CimInstance cimInstance, CimCustomOptionsDictionary newCustomOptions) { @@ -59,7 +59,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } bool foundAssociatedOptions = true; - CimCustomOptionsDictionary oldCustomOptions = CimInstanceToCustomOptions.GetValue( + CimCustomOptionsDictionary oldCustomOptions = s_cimInstanceToCustomOptions.GetValue( cimInstance, delegate { @@ -82,7 +82,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictionary optionsFromCommandLine, CimInstance instanceRelatedToThisOperation) { CimCustomOptionsDictionary instanceRelatedOptions; - if (CimInstanceToCustomOptions.TryGetValue(instanceRelatedToThisOperation, out instanceRelatedOptions) && instanceRelatedOptions != null) + if (s_cimInstanceToCustomOptions.TryGetValue(instanceRelatedToThisOperation, out instanceRelatedOptions) && instanceRelatedOptions != null) { IEnumerable> instanceRelatedOptionsSnapshot = instanceRelatedOptions.GetSnapshot(); IEnumerable> optionsFromCommandLineSnapshot = optionsFromCommandLine.GetSnapshot(); @@ -120,7 +120,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal static class CimOperationOptionsHelper { internal static void SetCustomOptions( - CimOperationOptions operationOptions, + CimOperationOptions operationOptions, IEnumerable> customOptions, CimSensitiveValueConverter cimSensitiveValueConverter) { @@ -134,8 +134,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } internal static void SetCustomOption( - CimOperationOptions operationOptions, - string optionName, + CimOperationOptions operationOptions, + string optionName, object optionValue, CimSensitiveValueConverter cimSensitiveValueConverter) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index 077ddac4c..a13895943 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -21,12 +21,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class CimQuery : QueryBuilder, ISessionBoundQueryBuilder { - private readonly StringBuilder wqlCondition; + private readonly StringBuilder _wqlCondition; - private CimInstance associatedObject; - private string associationName; - private string resultRole; - private string sourceRole; + private CimInstance _associatedObject; + private string _associationName; + private string _resultRole; + private string _sourceRole; internal readonly Dictionary queryOptions = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -34,7 +34,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal CimQuery() { - this.wqlCondition = new StringBuilder(); + _wqlCondition = new StringBuilder(); this.ClientSideQuery = new ClientSideQuery(); } @@ -42,11 +42,11 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private void AddWqlCondition(string condition) { - this.wqlCondition.Append(this.wqlCondition.Length != 0 ? " AND " : " WHERE "); + _wqlCondition.Append(_wqlCondition.Length != 0 ? " AND " : " WHERE "); - this.wqlCondition.Append('('); - this.wqlCondition.Append(condition); - this.wqlCondition.Append(')'); + _wqlCondition.Append('('); + _wqlCondition.Append(condition); + _wqlCondition.Append(')'); } private static string ObjectToWqlLiteral(object o) @@ -76,7 +76,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (typeCode == TypeCode.DateTime) { - var dateTime = (DateTime) LanguagePrimitives.ConvertTo(o, typeof (DateTime), CultureInfo.InvariantCulture); + var dateTime = (DateTime)LanguagePrimitives.ConvertTo(o, typeof(DateTime), CultureInfo.InvariantCulture); string result = ClrFacade.ToDmtfDateTime(dateTime); return "'" + result + "'"; } @@ -301,10 +301,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch) { this.ClientSideQuery.FilterByAssociatedInstance(associatedInstance, associationName, sourceRole, resultRole, behaviorOnNoMatch); - this.associatedObject = associatedInstance as CimInstance; - this.associationName = associationName; - this.resultRole = resultRole; - this.sourceRole = sourceRole; + _associatedObject = associatedInstance as CimInstance; + _associationName = associationName; + _resultRole = resultRole; + _sourceRole = sourceRole; } /// @@ -332,13 +332,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal StartableJob GetQueryJob(CimJobContext jobContext) { - if (this.associationName == null) + if (_associationName == null) { - return new QueryInstancesJob(jobContext, this, this.wqlCondition.ToString()); + return new QueryInstancesJob(jobContext, this, _wqlCondition.ToString()); } else { - return new EnumerateAssociatedInstancesJob(jobContext, this, this.associatedObject, this.associationName, this.resultRole, this.sourceRole); + return new EnumerateAssociatedInstancesJob(jobContext, this, _associatedObject, _associationName, _resultRole, _sourceRole); } } @@ -357,9 +357,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim CimSession ISessionBoundQueryBuilder.GetTargetSession() { - if (this.associatedObject != null) + if (_associatedObject != null) { - return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(this.associatedObject); + return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(_associatedObject); } return null; } @@ -370,7 +370,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// A string that represents the current CIM query public override string ToString() { - return this.wqlCondition.ToString(); + return _wqlCondition.ToString(); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index 77fb3b804..9e86a3b84 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// CIM-specific ObjectModelWrapper /// - public sealed class CimCmdletAdapter : + public sealed class CimCmdletAdapter : SessionBasedCmdletAdapter, IDynamicParameters { @@ -37,7 +37,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [Alias("Session")] + [Alias("Session")] public CimSession[] CimSession { get @@ -58,17 +58,17 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { get { - if (this._throttleLimitIsSetExplicitly) + if (_throttleLimitIsSetExplicitly) { return base.ThrottleLimit; } return this.CmdletDefinitionContext.DefaultThrottleLimit; } - set - { + set + { base.ThrottleLimit = value; - this._throttleLimitIsSetExplicitly = true; + _throttleLimitIsSetExplicitly = true; } } private bool _throttleLimitIsSetExplicitly; @@ -92,7 +92,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { if (_cmdletInvocationContext == null) { - this._cmdletInvocationContext = new CimCmdletInvocationContext( + _cmdletInvocationContext = new CimCmdletInvocationContext( this.CmdletDefinitionContext, this.Cmdlet, this.GetDynamicNamespace()); @@ -108,7 +108,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { if (_cmdletDefinitionContext == null) { - this._cmdletDefinitionContext = new CimCmdletDefinitionContext( + _cmdletDefinitionContext = new CimCmdletDefinitionContext( this.ClassName, this.ClassVersion, this.ModuleVersion, @@ -129,7 +129,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim #region SessionBasedCmdletAdapter overrides - private static long _jobNumber; + private static long s_jobNumber; /// /// Returns a new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation. @@ -137,7 +137,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// Job name protected override string GenerateParentJobName() { - return "CimJob" + Interlocked.Increment(ref CimCmdletAdapter._jobNumber).ToString(CultureInfo.InvariantCulture); + return "CimJob" + Interlocked.Increment(ref CimCmdletAdapter.s_jobNumber).ToString(CultureInfo.InvariantCulture); } /// @@ -211,7 +211,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } CimJobContext jobContext = this.CreateJobContext(session, objectInstance); - + Dbg.Assert(objectInstance != null, "Caller should verify objectInstance != null"); StartableJob result; @@ -228,7 +228,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim result = new ModifyInstanceJob( jobContext, passThru, - objectInstance, + objectInstance, methodInvocationInfo); } else @@ -240,7 +240,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim methodInvocationInfo); } - return result; + return result; } private bool IsSupportedSession(CimSession cimSession, TerminatingErrorTracker terminatingErrorTracker) @@ -252,8 +252,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (cimSession.ComputerName != null && (!cimSession.ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))) { PSPropertyInfo protocolProperty = PSObject.AsPSObject(cimSession).Properties["Protocol"]; - if ((protocolProperty != null) && - (protocolProperty.Value != null) && + if ((protocolProperty != null) && + (protocolProperty.Value != null) && (protocolProperty.Value.ToString().Equals("DCOM", StringComparison.OrdinalIgnoreCase))) { bool sessionWasAlreadyTerminated; @@ -326,19 +326,19 @@ namespace Microsoft.PowerShell.Cmdletization.Cim methodInvocationInfo); } - return result; + return result; } #endregion SessionBasedCmdletAdapter overrides #region Session affinity management - private static readonly ConditionalWeakTable cimInstanceToSessionOfOrigin = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_cimInstanceToSessionOfOrigin = new ConditionalWeakTable(); internal static void AssociateSessionOfOriginWithInstance(CimInstance cimInstance, CimSession sessionOfOrigin) { // GetValue adds value to the table, if the key is not present in the table - cimInstanceToSessionOfOrigin.GetValue(cimInstance, _ => sessionOfOrigin); + s_cimInstanceToSessionOfOrigin.GetValue(cimInstance, _ => sessionOfOrigin); } internal static CimSession GetSessionOfOriginFromCimInstance(CimInstance instance) @@ -346,7 +346,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim CimSession result = null; if (instance != null) { - cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); + s_cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); } return result; } @@ -392,7 +392,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim namespaceAttributes.Add(new ParameterAttribute()); RuntimeDefinedParameter namespaceRuntimeParameter = new RuntimeDefinedParameter( CimNamespaceParameter, - typeof (string), + typeof(string), namespaceAttributes); _dynamicParameters.Add(CimNamespaceParameter, namespaceRuntimeParameter); } @@ -402,6 +402,5 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } #endregion - } } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index d1a5135b8..155be28c3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -49,7 +49,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } else { - this.ErrorMessageGenerator = + this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForEquality(this.PropertyName, this.PropertyValue, className); } } @@ -134,7 +134,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim } else { - return new[] {new NotFoundError()}; + return new[] { new NotFoundError() }; } case BehaviorOnNoMatch.SilentlyContinue: @@ -151,10 +151,10 @@ namespace Microsoft.PowerShell.Cmdletization.Cim private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase { private readonly List _propertyValueFilters = new List(); - protected IEnumerable PropertyValueFilters { get { return this._propertyValueFilters; } } + protected IEnumerable PropertyValueFilters { get { return _propertyValueFilters; } } protected void AddPropertyValueFilter(PropertyValueFilter propertyValueFilter) { - this._propertyValueFilters.Add(propertyValueFilter); + _propertyValueFilters.Add(propertyValueFilter); } protected override bool IsMatchCore(CimInstance cimInstance) @@ -183,7 +183,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim foreach (object allowedPropertyValue in allowedPropertyValues) { - PropertyValueFilter filter = + PropertyValueFilter filter = new PropertyValueRegularFilter( propertyName, allowedPropertyValue, @@ -332,37 +332,37 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { protected PropertyValueFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) { - this.propertyName = propertyName; - this._behaviorOnNoMatch = behaviorOnNoMatch; - this._originalExpectedPropertyValue = expectedPropertyValue; - this._cimTypedExpectedPropertyValue = CimValueConverter.ConvertFromDotNetToCim(expectedPropertyValue); + _propertyName = propertyName; + _behaviorOnNoMatch = behaviorOnNoMatch; + _originalExpectedPropertyValue = expectedPropertyValue; + _cimTypedExpectedPropertyValue = CimValueConverter.ConvertFromDotNetToCim(expectedPropertyValue); } public BehaviorOnNoMatch BehaviorOnNoMatch { get { - if (this._behaviorOnNoMatch == BehaviorOnNoMatch.Default) + if (_behaviorOnNoMatch == BehaviorOnNoMatch.Default) { - this._behaviorOnNoMatch = this.GetDefaultBehaviorWhenNoMatchesFound(this.CimTypedExpectedPropertyValue); + _behaviorOnNoMatch = this.GetDefaultBehaviorWhenNoMatchesFound(this.CimTypedExpectedPropertyValue); } - return this._behaviorOnNoMatch; + return _behaviorOnNoMatch; } } protected abstract BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue); private BehaviorOnNoMatch _behaviorOnNoMatch; - public string PropertyName { get { return this.propertyName; } } - private readonly string propertyName; + public string PropertyName { get { return _propertyName; } } + private readonly string _propertyName; - public object CimTypedExpectedPropertyValue { get { return this._cimTypedExpectedPropertyValue; } } + public object CimTypedExpectedPropertyValue { get { return _cimTypedExpectedPropertyValue; } } private readonly object _cimTypedExpectedPropertyValue; - public object OriginalExpectedPropertyValue { get { return this._originalExpectedPropertyValue; } } + public object OriginalExpectedPropertyValue { get { return _originalExpectedPropertyValue; } } private readonly object _originalExpectedPropertyValue; - public bool HadMatch { get { return this.hadMatch; } } - private bool hadMatch; + public bool HadMatch { get { return _hadMatch; } } + private bool _hadMatch; public bool IsMatch(CimInstance o) { @@ -371,7 +371,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return false; } - CimProperty propertyInfo = o.CimInstanceProperties[propertyName]; + CimProperty propertyInfo = o.CimInstanceProperties[_propertyName]; if (propertyInfo == null) { return false; @@ -380,7 +380,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (_cimTypedExpectedPropertyValue == null) { - hadMatch = hadMatch || (actualPropertyValue == null); + _hadMatch = _hadMatch || (actualPropertyValue == null); return actualPropertyValue == null; } @@ -391,7 +391,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim Dbg.Assert(IsSameType(actualPropertyValue, _cimTypedExpectedPropertyValue), "Types of actual vs expected property value should always match"); bool isMatch = this.IsMatchingValue(actualPropertyValue); - hadMatch = hadMatch || isMatch; + _hadMatch = _hadMatch || isMatch; return isMatch; } @@ -409,7 +409,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim var errorMessage = string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimJob_MismatchedTypeOfPropertyReturnedByQuery, - propertyName, + _propertyName, actualPropertyValue.GetType().FullName, expectedPropertyValue.GetType().FullName); throw CimJobException.CreateWithoutJobContext( @@ -448,12 +448,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim public PropertyValueRegularFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) { - this._wildcardsEnabled = wildcardsEnabled; + _wildcardsEnabled = wildcardsEnabled; } protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue) { - if (!this._wildcardsEnabled) + if (!_wildcardsEnabled) { return BehaviorOnNoMatch.ReportErrors; } @@ -473,7 +473,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal NotFoundError GetGranularNotFoundError() { - return new NotFoundError(this.PropertyName, this.OriginalExpectedPropertyValue, this._wildcardsEnabled); + return new NotFoundError(this.PropertyName, this.OriginalExpectedPropertyValue, _wildcardsEnabled); } protected override bool IsMatchingValue(object actualPropertyValue) @@ -487,7 +487,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim return NonWildcardEqual(this.PropertyName, actualPropertyValue, this.CimTypedExpectedPropertyValue); } } - + private static bool NonWildcardEqual(string propertyName, object actualPropertyValue, object expectedPropertyValue) { // perform .NET-based, case-insensitive equality test for 1) characters and 2) strings @@ -626,7 +626,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim lock (_myLock) { _numberOfResultsFromMi++; - + if (_filters.All(f => f.IsMatch(result))) { _numberOfMatchingResults++; @@ -641,22 +641,22 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal IEnumerable GenerateNotFoundErrors() { - if (this._filters.Count > 1) + if (_filters.Count > 1) { - if (this._numberOfMatchingResults > 0) + if (_numberOfMatchingResults > 0) { return Enumerable.Empty(); } - if (this._filters.All(f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters())) + if (_filters.All(f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters())) { return Enumerable.Empty(); } - return new[] {new NotFoundError()}; + return new[] { new NotFoundError() }; } - CimInstanceFilterBase filter = this._filters.SingleOrDefault(); + CimInstanceFilterBase filter = _filters.SingleOrDefault(); if (filter != null) { return filter.GetNotFoundErrors_IfThisIsTheOnlyFilter(); @@ -671,27 +671,27 @@ namespace Microsoft.PowerShell.Cmdletization.Cim public override void FilterByProperty(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) { - this._filters.Add(new CimInstanceRegularFilter(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); + _filters.Add(new CimInstanceRegularFilter(propertyName, allowedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); } public override void ExcludeByProperty(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) { - this._filters.Add(new CimInstanceExcludeFilter(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); + _filters.Add(new CimInstanceExcludeFilter(propertyName, excludedPropertyValues, wildcardsEnabled, behaviorOnNoMatch)); } public override void FilterByMinPropertyValue(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) { - this._filters.Add(new CimInstanceMinFilter(propertyName, minPropertyValue, behaviorOnNoMatch)); + _filters.Add(new CimInstanceMinFilter(propertyName, minPropertyValue, behaviorOnNoMatch)); } public override void FilterByMaxPropertyValue(string propertyName, object maxPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) { - this._filters.Add(new CimInstanceMaxFilter(propertyName, maxPropertyValue, behaviorOnNoMatch)); + _filters.Add(new CimInstanceMaxFilter(propertyName, maxPropertyValue, behaviorOnNoMatch)); } public override void FilterByAssociatedInstance(object associatedInstance, string associationName, string sourceRole, string resultRole, BehaviorOnNoMatch behaviorOnNoMatch) { - this._filters.Add(new CimInstanceAssociationFilter(behaviorOnNoMatch)); + _filters.Add(new CimInstanceAssociationFilter(behaviorOnNoMatch)); } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs index c6d7572d2..d5084f051 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -14,7 +15,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command that appends the specified content to the item at the specified path. /// - [Cmdlet (VerbsCommon.Add, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Add, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113278")] public class AddContentCommand : WriteContentCommandBase { @@ -85,13 +86,12 @@ namespace Microsoft.PowerShell.Commands { string action = NavigationResources.AddContentAction; - string target = StringUtil.Format(NavigationResources.AddContentTarget,path); + string target = StringUtil.Format(NavigationResources.AddContentTarget, path); return ShouldProcess(target, action); } #endregion protected members } // AddContentCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs index 3a10b94bf..d4bab8957 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command that appends the specified content to the item at the specified path. /// - [Cmdlet (VerbsCommon.Clear, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Clear, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113282")] public class ClearContentCommand : ContentCommandBase { @@ -19,7 +20,7 @@ namespace Microsoft.PowerShell.Commands /// /// Clears the contents from the item at the specified path. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // Default to the CmdletProviderContext that will direct output to // the pipeline. @@ -100,10 +101,9 @@ namespace Microsoft.PowerShell.Commands // Go ahead an let any exceptions terminate the pipeline. return InvokeProvider.Content.ClearContentDynamicParameters(Path[0], context); } - + return InvokeProvider.Content.ClearContentDynamicParameters(".", context); } // GetDynamicParameters } // ClearContentCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs index 900cf2ba2..96d937660 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation; @@ -11,7 +12,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to clear the value of a property of an item at a specified path /// - [Cmdlet (VerbsCommon.Clear, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Clear, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113284")] public class ClearItemPropertyCommand : PassThroughItemPropertyCommandBase { @@ -21,7 +22,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path parameter to the command /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -59,17 +60,17 @@ namespace Microsoft.PowerShell.Commands /// The properties to clear from the item /// /// - [Parameter(Position=1, Mandatory=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string Name { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Name @@ -91,16 +92,15 @@ namespace Microsoft.PowerShell.Commands internal override object GetDynamicParameters(CmdletProviderContext context) { Collection propertyCollection = new Collection(); - propertyCollection.Add(property); + propertyCollection.Add(_property); if (Path != null && Path.Length > 0) { - // Go ahead and let any exception terminate the pipeline. return InvokeProvider.Property.ClearPropertyDynamicParameters( - Path[0], - propertyCollection, + Path[0], + propertyCollection, context); } return InvokeProvider.Property.ClearPropertyDynamicParameters( @@ -112,11 +112,11 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region parameter data - + /// /// The properties to be cleared. /// - private string property; + private string _property; #endregion parameter data @@ -125,21 +125,21 @@ namespace Microsoft.PowerShell.Commands /// /// Clears the properties of an item at the specified path /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; currentContext.PassThru = PassThru; Collection propertyCollection = new Collection(); - propertyCollection.Add(property); + propertyCollection.Add(_property); foreach (string path in Path) { try { InvokeProvider.Property.Clear( - path, - propertyCollection, + path, + propertyCollection, currentContext); } catch (PSNotSupportedException notSupported) @@ -176,5 +176,4 @@ namespace Microsoft.PowerShell.Commands } // ClearItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 60653a6de..65efb9d25 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -17,20 +17,20 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsCommon.Clear, "RecycleBin", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=524082", ConfirmImpact = ConfirmImpact.High)] public class ClearRecycleBinCommand : PSCmdlet { - private string[] drivesList; - private DriveInfo[] availableDrives; - private bool force; + private string[] _drivesList; + private DriveInfo[] _availableDrives; + private bool _force; /// /// Property that sets DriveLetter parameter. /// - [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] DriveLetter { - get { return drivesList; } - set { drivesList = value; } + get { return _drivesList; } + set { _drivesList = value; } } /// @@ -41,11 +41,11 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } @@ -54,7 +54,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - availableDrives = DriveInfo.GetDrives(); + _availableDrives = DriveInfo.GetDrives(); } /// @@ -64,9 +64,9 @@ namespace Microsoft.PowerShell.Commands { // There are two scenarios: // 1) The user provides a list of drives. - if (drivesList != null) + if (_drivesList != null) { - foreach (var drive in drivesList) + foreach (var drive in _drivesList) { if (!IsValidPattern(drive)) { @@ -82,7 +82,7 @@ namespace Microsoft.PowerShell.Commands // Get the full path for the drive. string drivePath = GetDrivePath(drive); if (ValidDrivePath(drivePath)) - { + { EmptyRecycleBin(drivePath); } } @@ -102,18 +102,18 @@ namespace Microsoft.PowerShell.Commands private bool ValidDrivePath(string drivePath) { DriveInfo actualDrive = null; - if (availableDrives != null) + if (_availableDrives != null) { - foreach (DriveInfo drive in availableDrives) + foreach (DriveInfo drive in _availableDrives) { if (String.Compare(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase) == 0) { actualDrive = drive; break; - } - } - } - + } + } + } + // The drive was not found. if (actualDrive == null) { @@ -195,7 +195,7 @@ namespace Microsoft.PowerShell.Commands drivePath); } - if (force || (ShouldProcess(clearRecycleBinShouldProcessTarget, "Clear-RecycleBin"))) + if (_force || (ShouldProcess(clearRecycleBinShouldProcessTarget, "Clear-RecycleBin"))) { // If driveName is null, then clear the recyclebin for all drives; otherwise, just for the specified drivename. @@ -226,7 +226,7 @@ namespace Microsoft.PowerShell.Commands progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); - + // 0 is for a successful operation // 203 comes up when trying to empty an already emptied recyclebin // 18 comes up when there are no more files in the given recyclebin @@ -239,15 +239,15 @@ namespace Microsoft.PowerShell.Commands } } - static class NativeMethod + internal static class NativeMethod { // Internal code to SHEmptyRecycleBin internal enum RecycleFlags : uint { SHERB_NOCONFIRMATION = 0x00000001, - SHERB_NOPROGRESSUI = 0x00000002, - SHERB_NOSOUND = 0x00000004 - } + SHERB_NOPROGRESSUI = 0x00000002, + SHERB_NOSOUND = 0x00000004 + } [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs index 89560b00b..e854f0ac6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -18,22 +19,22 @@ namespace Microsoft.PowerShell.Commands public class JoinPathCommand : CoreCommandWithCredentialsBase { #region Parameters - + /// /// Gets or sets the path parameter to the command /// - [Parameter (Position=0,Mandatory=true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] Path { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -47,12 +48,12 @@ namespace Microsoft.PowerShell.Commands { get { - return childPath; + return _childPath; } // get set { - childPath = value; + _childPath = value; } // set } // childPath @@ -65,33 +66,33 @@ namespace Microsoft.PowerShell.Commands { get { - return resolve; + return _resolve; } // get set { - resolve = value; + _resolve = value; } //set } // Resolve #endregion Parameters #region parameter data - + /// /// The path to resolve /// - private string[] paths; + private string[] _paths; /// /// The child part of the path to be joined with the Path paramter /// - private string childPath = String.Empty; + private string _childPath = String.Empty; /// /// Determines if the path should be resolved after being joined. /// - private bool resolve; + private bool _resolve; #endregion parameter data @@ -101,10 +102,10 @@ namespace Microsoft.PowerShell.Commands /// Parses the specified path and returns the portion determined by the /// boolean parameters. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { Dbg.Diagnostics.Assert( - paths != null, + _paths != null, "Since Path is a mandatory parameter, paths should never be null"); foreach (string path in Path) @@ -115,7 +116,7 @@ namespace Microsoft.PowerShell.Commands try { - joinedPath = + joinedPath = SessionState.Path.Combine(path, ChildPath, CmdletProviderContext); } catch (PSNotSupportedException notSupported) @@ -235,9 +236,7 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } // for each path - } else { @@ -252,6 +251,5 @@ namespace Microsoft.PowerShell.Commands } // JoinPathCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommandsCommon.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommandsCommon.cs index 8d829c3a0..5f0b89c40 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommandsCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommandsCommon.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands /// internal static class CommandsCommon { - #if CORECLR +#if CORECLR // AccessViolationException/StackOverflowException Not In CoreCLR. // The CoreCLR team told us to not check for these exceptions because they // usually won't be caught. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs index 63669c7e5..72bd41af9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Provider; @@ -17,18 +18,16 @@ namespace Microsoft.PowerShell.Commands /// /// Commits the current transaction /// - protected override void EndProcessing () + protected override void EndProcessing() { // Commit the transaction - if(ShouldProcess( + if (ShouldProcess( NavigationResources.TransactionResource, NavigationResources.CommitAction)) { this.Context.TransactionManager.Commit(); } } - } // CommitTransactionCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 74eb64935..50e7823f6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -44,7 +44,7 @@ using Microsoft.WSMan.Management; namespace Microsoft.PowerShell.Commands { - #region Test-Connection +#region Test-Connection /// /// This cmdlet is used to test whether a particular host is reachable across an @@ -58,7 +58,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus")] public class TestConnectionCommand : PSCmdlet { - #region "Parameters" +#region "Parameters" private const string RegularParameterSet = "Default"; private const string QuietParameterSet = "Quiet"; @@ -300,8 +300,8 @@ namespace Microsoft.PowerShell.Commands } private bool quiet = false; - #endregion "parameters" - #region "Overrides" +#endregion "parameters" +#region "Overrides" #if !CORECLR ///// @@ -391,7 +391,6 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - switch (_transportProtocol) { #if !CORECLR @@ -404,7 +403,6 @@ namespace Microsoft.PowerShell.Commands ProcessWSManProtocolForTestConnection(); break; } - } /// /// to implement ^C @@ -429,9 +427,9 @@ namespace Microsoft.PowerShell.Commands catch (ObjectDisposedException) { } catch (AggregateException) { } } - #endregion +#endregion - #region "Private Methods " +#region "Private Methods " private string QueryString(string[] machinenames, bool escaperequired, bool selectrequired) { StringBuilder FilterString = new StringBuilder(); @@ -529,7 +527,6 @@ namespace Microsoft.PowerShell.Commands } else { - if (statusCode != 0) { if (!quiet) @@ -550,7 +547,6 @@ namespace Microsoft.PowerShell.Commands } } } - } #if !CORECLR @@ -595,10 +591,8 @@ namespace Microsoft.PowerShell.Commands using (searcher = new ManagementObjectSearcher(scope, query, enumOptions)) { - for (int j = 0; j <= count - 1; j++) { - using (ManagementObjectCollection mobj = searcher.Get()) { int mobjCount = 0; @@ -649,7 +643,6 @@ namespace Microsoft.PowerShell.Commands #endif private void ProcessWSManProtocolForTestConnection() { - if (asjob) { // TODO: Need job for MI.Net WSMan protocol @@ -687,7 +680,6 @@ namespace Microsoft.PowerShell.Commands { for (int echoRequestCount = 0; echoRequestCount < count; echoRequestCount++) { - IEnumerable mCollection = cimSession.QueryInstances( ComputerWMIHelper.CimOperatingSystemNamespace, ComputerWMIHelper.CimQueryDialect, @@ -732,12 +724,12 @@ namespace Microsoft.PowerShell.Commands } } - #endregion "Private Methods " +#endregion "Private Methods " } - #endregion Test-Connection +#endregion Test-Connection #if !CORECLR - #region Enable-ComputerRestore +#region Enable-ComputerRestore /// /// Cmdlet for Enable-ComputerRestore @@ -745,7 +737,7 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsLifecycle.Enable, "ComputerRestore", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135209")] public sealed class EnableComputerRestoreCommand : PSCmdlet, IDisposable { - #region Parameters +#region Parameters /// /// Specifies the Drive on which the system restore will be enabled. /// The drive string should be of the form "C:\". @@ -763,10 +755,10 @@ namespace Microsoft.PowerShell.Commands } private string[] _drive; - #endregion Parameters +#endregion Parameters private const string ErrorBase = "ComputerResources"; private ManagementClass WMIClass; - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -794,9 +786,9 @@ namespace Microsoft.PowerShell.Commands } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region Overrides +#region Overrides /// /// To Enable the Restore Point of the drives @@ -824,7 +816,6 @@ namespace Microsoft.PowerShell.Commands object[] input = { sysdrive }; try { - retValue = Convert.ToInt32(WMIClass.InvokeMethod("Enable", input), System.Globalization.CultureInfo.CurrentCulture); //if success (return value is 0 or if already enabled (error code is 1056 in XP and 0 in vista) if ((retValue.Equals(0)) || (retValue.Equals(ComputerWMIHelper.ErrorCode_Service))) @@ -838,9 +829,7 @@ namespace Microsoft.PowerShell.Commands } if (!drive.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase)) { - driveNew = String.Concat(drive, "\\"); - } else driveNew = drive; @@ -871,7 +860,6 @@ namespace Microsoft.PowerShell.Commands WriteError(new ErrorRecord(Ex, "EnableComputerRestoreNotEnabled", ErrorCategory.InvalidOperation, null)); continue; } - } } else @@ -879,7 +867,6 @@ namespace Microsoft.PowerShell.Commands ArgumentException Ex = new ArgumentException(StringUtil.Format(ComputerResources.NotEnabled, sysdrive)); WriteError(new ErrorRecord(Ex, "EnableComputerRestoreNotEnabled", ErrorCategory.InvalidOperation, null)); } - } catch (ManagementException e) { @@ -893,15 +880,11 @@ namespace Microsoft.PowerShell.Commands ErrorRecord errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } - - } catch (COMException e) { - if (string.IsNullOrEmpty(e.Message)) { - Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled)); WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } @@ -917,8 +900,6 @@ namespace Microsoft.PowerShell.Commands ArgumentException Ex = new ArgumentException(StringUtil.Format(ComputerResources.NoSystemDrive)); WriteError(new ErrorRecord(Ex, "EnableComputerNoSystemDrive", ErrorCategory.InvalidArgument, null)); } - - }//end of BeginProcessing /// @@ -932,12 +913,11 @@ namespace Microsoft.PowerShell.Commands } } - #endregion Overrides - +#endregion Overrides }//end of class - #endregion +#endregion - #region Disable-ComputerRestore +#region Disable-ComputerRestore /// /// This cmdlet is to Disable Computer Restore points. @@ -945,7 +925,7 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsLifecycle.Disable, "ComputerRestore", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135207")] public sealed class DisableComputerRestoreCommand : PSCmdlet, IDisposable { - #region Parameters +#region Parameters /// /// Specifies the Drive on which the system restore will be enabled. /// The drive string should be of the form "C:\". @@ -963,11 +943,11 @@ namespace Microsoft.PowerShell.Commands } private string[] _drive; - #endregion Parameters +#endregion Parameters private ManagementClass WMIClass; private const string ErrorBase = "ComputerResources"; - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -995,9 +975,9 @@ namespace Microsoft.PowerShell.Commands } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region Overrides +#region Overrides /// /// To Disable the Restore Point of the drives @@ -1024,9 +1004,7 @@ namespace Microsoft.PowerShell.Commands if (!drive.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase)) { - driveNew = String.Concat(drive, "\\"); - } else driveNew = drive; @@ -1051,7 +1029,6 @@ namespace Microsoft.PowerShell.Commands WriteError(er); continue; } - } catch (ManagementException e) { @@ -1065,15 +1042,11 @@ namespace Microsoft.PowerShell.Commands ErrorRecord errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } - - } catch (COMException e) { - if (string.IsNullOrEmpty(e.Message)) { - Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled)); WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } @@ -1098,14 +1071,11 @@ namespace Microsoft.PowerShell.Commands } } - #endregion Overrides - - - +#endregion Overrides }//end of class - #endregion Disable-ComputerRestore +#endregion Disable-ComputerRestore - #region Checkpoint-Computer +#region Checkpoint-Computer /// /// Creates the Restore Point for the Local computer @@ -1114,7 +1084,7 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsData.Checkpoint, "Computer", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135197")] public class CheckpointComputerCommand : PSCmdlet, IDisposable { - #region Parameters +#region Parameters /// /// The description to be displayed so the user can easily identify a restore point. @@ -1165,9 +1135,9 @@ namespace Microsoft.PowerShell.Commands } } private string _restorepointtype = "APPLICATION_INSTALL"; - #endregion Parameters +#endregion Parameters - #region private +#region private private DateTime lastTimeProgressWasWritten = DateTime.UtcNow; private int intRestorePoint = 0; @@ -1267,7 +1237,7 @@ namespace Microsoft.PowerShell.Commands //create restore point ManagementBaseObject inParams = WMIClass.GetMethodParameters("CreateRestorePoint"); - object[] param ={ _description, intRestorePoint, 100 }; // the event type will be always 100,Begin_System_Change + object[] param = { _description, intRestorePoint, 100 }; // the event type will be always 100,Begin_System_Change ret = Convert.ToInt32(WMIClass.InvokeMethod("CreateRestorePoint", param), System.Globalization.CultureInfo.CurrentCulture); } catch (Exception ex) @@ -1284,9 +1254,9 @@ namespace Microsoft.PowerShell.Commands } } - #endregion +#endregion - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -1298,7 +1268,7 @@ namespace Microsoft.PowerShell.Commands GC.SuppressFinalize(this); } - #endregion "IDisposable Members" +#endregion "IDisposable Members" /// /// BeginProcessing method. @@ -1376,7 +1346,6 @@ namespace Microsoft.PowerShell.Commands throw exceptionfromnewthread; } } - }//End BeginProcessing() private bool CanCreateNewRestorePoint(DateTime startTime) @@ -1401,7 +1370,7 @@ namespace Microsoft.PowerShell.Commands if (key != null) { object value = key.GetValue(srFrequencyKeyName); - if (value is int) { timeInterval = (int) value; } + if (value is int) { timeInterval = (int)value; } } } @@ -1511,9 +1480,9 @@ namespace Microsoft.PowerShell.Commands return foundrestorepoint; } } - #endregion +#endregion - #region Get-ComputerRestorePoint +#region Get-ComputerRestorePoint /// /// This cmdlet is to Get Computer Restore points. @@ -1522,7 +1491,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(@"System.Management.ManagementObject#root\default\SystemRestore")] public sealed class GetComputerRestorePointCommand : PSCmdlet, IDisposable { - #region Parameters +#region Parameters /// /// This cmdlet is to get Computer Restore points. @@ -1536,7 +1505,6 @@ namespace Microsoft.PowerShell.Commands get { return _restorepoint; } set { - _restorepoint = value; } } @@ -1554,11 +1522,11 @@ namespace Microsoft.PowerShell.Commands } private SwitchParameter _laststatus; - #endregion +#endregion private ManagementClass WMIClass; - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -1586,9 +1554,9 @@ namespace Microsoft.PowerShell.Commands } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region overrides +#region overrides /// /// Gets the list of Computer Restore point. /// ID parameter id used to refer the sequence no. When given searched with particular @@ -1655,7 +1623,6 @@ namespace Microsoft.PowerShell.Commands WriteObject(obj); if (_restorepoint != null) { - int sequenceNo = Convert.ToInt32(obj.Properties["SequenceNumber"].Value, System.Globalization.CultureInfo.CurrentCulture); sequenceList.Remove(sequenceNo); } @@ -1669,7 +1636,7 @@ namespace Microsoft.PowerShell.Commands { foreach (int id in sequenceList.Keys) { - string message = StringUtil.Format(ComputerResources.NoResorePoint,id); + string message = StringUtil.Format(ComputerResources.NoResorePoint, id); ArgumentException e = new ArgumentException(message); ErrorRecord errorrecord = new ErrorRecord(e, "NoResorePoint", ErrorCategory.InvalidArgument, null); WriteError(errorrecord); @@ -1693,10 +1660,8 @@ namespace Microsoft.PowerShell.Commands } catch (COMException e) { - if (string.IsNullOrEmpty(e.Message)) { - Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled)); WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } @@ -1719,15 +1684,14 @@ namespace Microsoft.PowerShell.Commands } } - #endregion overrides - +#endregion overrides } - #endregion +#endregion #endif - #region Restart-Computer +#region Restart-Computer /// /// This exception is thrown when the timeout expires before a computer finishes restarting @@ -1764,7 +1728,7 @@ namespace Microsoft.PowerShell.Commands /// /// Construct a RestartComputerTimeoutException /// - public RestartComputerTimeoutException() : base() {} + public RestartComputerTimeoutException() : base() { } /// /// Constructs a RestartComputerTimeoutException @@ -1773,7 +1737,7 @@ namespace Microsoft.PowerShell.Commands /// /// The message used in the exception. /// - public RestartComputerTimeoutException(string message) : base(message) {} + public RestartComputerTimeoutException(string message) : base(message) { } /// /// Constructs a RestartComputerTimeoutException @@ -1786,9 +1750,9 @@ namespace Microsoft.PowerShell.Commands /// /// An exception that led to this exception. /// - public RestartComputerTimeoutException(string message, Exception innerException) : base(message, innerException) {} + public RestartComputerTimeoutException(string message, Exception innerException) : base(message, innerException) { } - #region Serialization +#region Serialization /// /// Serialization constructor for class RestartComputerTimeoutException /// @@ -1835,7 +1799,7 @@ namespace Microsoft.PowerShell.Commands info.AddValue("ComputerName", ComputerName); info.AddValue("Timeout", Timeout); } - #endregion Serialization +#endregion Serialization } /// @@ -1867,7 +1831,7 @@ namespace Microsoft.PowerShell.Commands HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135253", RemotingCapability = RemotingCapability.OwnedByCommand)] public class RestartComputerCommand : PSCmdlet, IDisposable { - #region "Parameters and PrivateData" +#region "Parameters and PrivateData" private const string DefaultParameterSet = "DefaultSet"; private const string AsJobParameterSet = "AsJobSet"; @@ -1932,7 +1896,6 @@ namespace Microsoft.PowerShell.Commands { _impersonation = value; _isImpersonationSpecified = true; - } } private ImpersonationLevel _impersonation = ImpersonationLevel.Impersonate; @@ -2129,7 +2092,7 @@ $result /// /// The indicator to use when show progress /// - private string[] _indicator = {"|", "/", "-", "\\"}; + private string[] _indicator = { "|", "/", "-", "\\" }; /// /// The activity id @@ -2176,9 +2139,9 @@ $result private const string WinrmConnectionTest = "WinRM"; private const string PowerShellConnectionTest = "PowerShell"; - #endregion "parameters and PrivateData" +#endregion "parameters and PrivateData" - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -2213,9 +2176,9 @@ $result } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region "Private Methods" +#region "Private Methods" /// /// Validate parameters for 'DefaultSet' @@ -2450,7 +2413,6 @@ $result CommandProcessorBase.CheckForSevereException(ex); restartStageTestList.Add(computer); } - } return restartStageTestList; @@ -2604,9 +2566,9 @@ $result } } - #endregion "Private Methods" +#endregion "Private Methods" - #region "Internal Methods" +#region "Internal Methods" internal static List TestWmiConnectionUsingWsman(List computerNames, List nextTestList, CancellationToken token, PSCredential credential, string wsmanAuthentication, PSCmdlet cmdlet) { @@ -2850,9 +2812,9 @@ $result } #endif - #endregion "Internal Methods" +#endregion "Internal Methods" - #region "Overrides" +#region "Overrides" /// /// BeginProcessing method. @@ -2943,7 +2905,7 @@ $result } else { - _timeoutInMilliseconds = _timeout*1000; + _timeoutInMilliseconds = _timeout * 1000; } // We don't support combined service types for now @@ -3067,7 +3029,6 @@ $result { _waitOnComputers.Add(computer); } - }//end foreach if (_waitOnComputers.Count > 0) @@ -3244,7 +3205,6 @@ $result } psTestList = TestPowerShell(psTestList, allDoneList, _powershell, this.Credential); } - } while (false); // if time is up or Ctrl+c is typed, break out @@ -3329,14 +3289,12 @@ $result } } - - #endregion "Overrides" - +#endregion "Overrides" } - #endregion Restart-Computer +#endregion Restart-Computer - #region Stop-Computer +#region Stop-Computer /// /// cmdlet to stop computer @@ -3345,7 +3303,7 @@ $result HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135263", RemotingCapability = RemotingCapability.SupportedByCommand)] public sealed class StopComputerCommand : PSCmdlet, IDisposable { - #region Private Members +#region Private Members #if !CORECLR private ManagementObjectSearcher _searcher; @@ -3353,9 +3311,9 @@ $result private readonly CancellationTokenSource _cancel = new CancellationTokenSource(); private TransportProtocol _transportProtocol = TransportProtocol.DCOM; - #endregion +#endregion - #region "Parameters" +#region "Parameters" /// /// parameter @@ -3535,9 +3493,9 @@ $result } private SwitchParameter _force = false; - #endregion "parameters" +#endregion "parameters" - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -3551,9 +3509,9 @@ $result catch (ObjectDisposedException) { } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region "Overrides" +#region "Overrides" /// /// BeginProcessing @@ -3675,9 +3633,9 @@ $result catch (AggregateException) { } } - #endregion "Overrides" +#endregion "Overrides" - #region Private Methods +#region Private Methods #if !CORECLR private void ProcessDCOMProtocol(object[] flags) @@ -3815,14 +3773,14 @@ $result } } - #endregion +#endregion } - #endregion +#endregion #if !CORECLR // TODO:CORECLR Enable once moved to MI .Net - #region Restore-Computer +#region Restore-Computer /// /// This cmdlet is to Restore Computer @@ -3830,7 +3788,7 @@ $result [Cmdlet(VerbsData.Restore, "Computer", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135254")] public sealed class RestoreComputerCommand : PSCmdlet, IDisposable { - #region Parameters +#region Parameters /// /// Restorepoint parameter /// @@ -3849,11 +3807,11 @@ $result } private int _restorepoint; - #endregion +#endregion private ManagementClass WMIClass; - #region "IDisposable Members" +#region "IDisposable Members" /// /// Dispose Method @@ -3881,9 +3839,9 @@ $result } } - #endregion "IDisposable Members" +#endregion "IDisposable Members" - #region overrides +#region overrides /// /// Restores the computer with /// @@ -3897,7 +3855,6 @@ $result try { - ConnectionOptions conn = ComputerWMIHelper.GetConnectionOptions(AuthenticationLevel.Packet, ImpersonationLevel.Impersonate, null); ManagementPath mPath = new ManagementPath(); mPath.Path = ComputerWMIHelper.WMI_Path_Default; @@ -3950,7 +3907,6 @@ $result } } } - } catch (ManagementException e) { @@ -3964,14 +3920,11 @@ $result ErrorRecord errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } - } catch (COMException e) { - if (string.IsNullOrEmpty(e.Message)) { - Exception Ex = new ArgumentException(StringUtil.Format(ComputerResources.SystemRestoreServiceDisabled)); WriteError(new ErrorRecord(Ex, "ServiceDisabled", ErrorCategory.InvalidOperation, null)); } @@ -3994,12 +3947,11 @@ $result } } - #endregion overrides - +#endregion overrides } - #endregion +#endregion - #region Add-Computer +#region Add-Computer /// /// Options for joining a computer to a domain @@ -4064,7 +4016,7 @@ $result [OutputType(typeof(ComputerChangeInfo))] public class AddComputerCommand : PSCmdlet { - #region parameter +#region parameter private const string DomainParameterSet = "Domain"; private const string WorkgroupParameterSet = "Workgroup"; @@ -4080,7 +4032,7 @@ $result get { return _computerName; } set { _computerName = value; } } - private string[] _computerName ={ "localhost" }; + private string[] _computerName = { "localhost" }; /// /// The local admin credential to the target computer @@ -4255,9 +4207,9 @@ $result private readonly string _shortLocalMachineName = Dns.GetHostName(); private readonly string _fullLocalMachineName = Dns.GetHostEntry("").HostName; - #endregion parameter +#endregion parameter - #region private +#region private /// /// Unjoin the computer from its current domain @@ -4751,9 +4703,9 @@ $result return targetComputer; } - #endregion private +#endregion private - #region override +#region override /// /// BeginProcessing method @@ -4771,19 +4723,19 @@ $result if ((_joinOptions & JoinOptions.AccountCreate) != 0) { - _joinDomainflags |= (int) JoinOptions.AccountCreate; + _joinDomainflags |= (int)JoinOptions.AccountCreate; } if ((_joinOptions & JoinOptions.Win9XUpgrade) != 0) { - _joinDomainflags |= (int) JoinOptions.Win9XUpgrade; + _joinDomainflags |= (int)JoinOptions.Win9XUpgrade; } if ((_joinOptions & JoinOptions.UnsecuredJoin) != 0) { - _joinDomainflags |= (int) JoinOptions.UnsecuredJoin; + _joinDomainflags |= (int)JoinOptions.UnsecuredJoin; } if ((_joinOptions & JoinOptions.PasswordPass) != 0) { - _joinDomainflags |= (int) JoinOptions.PasswordPass; + _joinDomainflags |= (int)JoinOptions.PasswordPass; } if ((_joinOptions & JoinOptions.DeferSPNSet) != 0) { @@ -4791,7 +4743,7 @@ $result } if ((_joinOptions & JoinOptions.JoinWithNewName) != 0) { - _joinDomainflags |= (int) JoinOptions.JoinWithNewName; + _joinDomainflags |= (int)JoinOptions.JoinWithNewName; } if ((_joinOptions & JoinOptions.JoinReadOnly) != 0) { @@ -4799,7 +4751,7 @@ $result } if ((_joinOptions & JoinOptions.InstallInvoke) != 0) { - _joinDomainflags |= (int) JoinOptions.InstallInvoke; + _joinDomainflags |= (int)JoinOptions.InstallInvoke; } if (_unsecure) @@ -4887,7 +4839,6 @@ $result _joinDomainflags = oldJoinDomainFlags; } } - }// end of ProcessRecord /// @@ -4911,13 +4862,12 @@ $result DoAddComputerAction("localhost", _newNameForLocalHost, true, options, enumOptions, computerSystemQuery); } - #endregion override - +#endregion override }//End Class - #endregion Add-Computer +#endregion Add-Computer - #region RemoveComputer +#region RemoveComputer /// /// Removes the Specified Computer(s) from the relevant Domain or Work Group @@ -4928,7 +4878,7 @@ $result [OutputType(typeof(ComputerChangeInfo))] public class RemoveComputerCommand : PSCmdlet { - #region "Parameters and Private Data" +#region "Parameters and Private Data" private const string LocalParameterSet = "Local"; private const string RemoteParameterSet = "Remote"; @@ -5025,9 +4975,9 @@ $result private readonly string _shortLocalMachineName = Dns.GetHostName(); private readonly string _fullLocalMachineName = Dns.GetHostEntry("").HostName; - #endregion "Parameters and Private Data" +#endregion "Parameters and Private Data" - #region "Private Methods" +#region "Private Methods" private void DoRemoveComputerAction(string computer, bool isLocalhost, ConnectionOptions options, EnumerationOptions enumOptions, ObjectQuery computerSystemQuery) { @@ -5198,9 +5148,9 @@ $result return targetComputer; } - #endregion "Private Methods" +#endregion "Private Methods" - #region "Override Methods" +#region "Override Methods" /// /// ProcessRecord method. @@ -5280,15 +5230,14 @@ $result DoRemoveComputerAction("localhost", true, options, enumOptions, computerSystemQuery); } - #endregion "Override Methods" - +#endregion "Override Methods" }//End Class - #endregion Remove-Computer +#endregion Remove-Computer #endif - #region Rename-Computer +#region Rename-Computer /// /// Renames a domain computer and its corresponding domain account or a @@ -5300,7 +5249,7 @@ $result HelpUri = "http://go.microsoft.com/fwlink/?LinkID=219990", RemotingCapability = RemotingCapability.SupportedByCommand)] public class RenameComputerCommand : PSCmdlet { - #region Private Members +#region Private Members private bool _containsLocalHost = false; private string _newNameForLocalHost = null; @@ -5310,9 +5259,9 @@ $result private readonly string _shortLocalMachineName = Dns.GetHostName(); private readonly string _fullLocalMachineName = Dns.GetHostEntryAsync("").Result.HostName; - #endregion +#endregion - #region Parameters +#region Parameters /// /// Target computers to rename @@ -5448,9 +5397,9 @@ $result private string _protocol = ComputerWMIHelper.DcomProtocol; #endif - #endregion +#endregion - #region "Private Methods" +#region "Private Methods" /// /// Check to see if the target computer is the local machine @@ -5562,7 +5511,7 @@ $result // If the target computer is not in a domain, just use null for the UserName and Password string dUserName = null; string dPassword = null; - if (((bool) cimInstance.CimInstanceProperties["PartOfDomain"].Value) && (DomainCredential != null)) + if (((bool)cimInstance.CimInstanceProperties["PartOfDomain"].Value) && (DomainCredential != null)) { dUserName = DomainCredential.UserName; dPassword = Utils.GetStringFromSecureString(DomainCredential.Password); @@ -5785,9 +5734,9 @@ $result } #endif - #endregion "Private Methods" +#endregion "Private Methods" - #region "Override Methods" +#region "Override Methods" /// /// Begin Processing @@ -5854,15 +5803,14 @@ $result DoRenameComputerAction("localhost", _newNameForLocalHost, true); } - #endregion "Override Methods" - +#endregion "Override Methods" } - #endregion Rename-Computer +#endregion Rename-Computer #if !CORECLR - #region Test-ComputerSecureChannel +#region Test-ComputerSecureChannel /// @@ -5874,8 +5822,7 @@ $result [OutputType(typeof(Boolean))] public class TestComputerSecureChannelCommand : PSCmdlet { - - #region Parameters +#region Parameters /// /// Repair the secure channel between the local machine with the domain, if it's broken @@ -5899,9 +5846,9 @@ $result private const uint NETLOGON_CONTROL_TC_QUERY = 6; private const uint NETLOGON_INFO_2 = 2; - #endregion Parameters +#endregion Parameters - #region "Private Methods" +#region "Private Methods" [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Justification = "Return results are used in debug asserts.")] private bool VerifySecureChannel(string domain, string localMachineName) @@ -5974,9 +5921,9 @@ $result return scInGoodState; } - #endregion "Private Methods" +#endregion "Private Methods" - #region "Override Methods" +#region "Override Methods" /// /// BeginProcessing method @@ -6080,14 +6027,13 @@ $result WriteVerbose(verboseMsg); } - #endregion "Override Methods" - +#endregion "Override Methods" }//End Class - #endregion +#endregion - #region Reset-ComputerMachinePassword +#region Reset-ComputerMachinePassword /// /// Resets the computer machine password used to authenticate with DCs. /// @@ -6096,7 +6042,7 @@ $result SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135252")] public class ResetComputerMachinePasswordCommand : PSCmdlet { - #region "Parameter and PrivateData" +#region "Parameter and PrivateData" /// /// The following is the definition of the input parameter "Server". @@ -6126,9 +6072,9 @@ $result private const int PasswordLength = 120; private const string SecretKey = "$MACHINE.ACC"; - #endregion "Parameter and PrivateData" +#endregion "Parameter and PrivateData" - #region "Private Methods" +#region "Private Methods" /// /// Throw out terminating error for LSA function invocations @@ -6144,9 +6090,9 @@ $result cmdlet.ThrowTerminatingError(error); } - #endregion "Private Methods" +#endregion "Private Methods" - #region "Internal Methods" +#region "Internal Methods" /// /// Reset machine account password @@ -6340,9 +6286,9 @@ $result } } - #endregion "Internal Methods" +#endregion "Internal Methods" - #region "Override Methods" +#region "Override Methods" /// /// BeginProcessing method. @@ -6426,13 +6372,12 @@ $result ResetMachineAccountPassword(domainName, localMachineName, Server, Credential, this); } - #endregion "Override Methods" - +#endregion "Override Methods" }//End Class - #endregion Reset-ComputerMachinePassword +#endregion Reset-ComputerMachinePassword - #region SAMCmdletsHelper +#region SAMCmdletsHelper /// /// the static class for calling the the NetJoinDomain function. @@ -6586,7 +6531,7 @@ $result // Unicode strings max 32KB. The max value for MaximumLength should be ushort.MaxValue-1 // because UnicodeEncoding.CharSize is 2. So the length of the string s should not be larger // than (ushort.MaxValue - 1)/UnicodeEncoding.CharSize - 1, which is 0x7ffe (32766) - ushort maxLength = (ushort.MaxValue - 1)/UnicodeEncoding.CharSize - 1; + ushort maxLength = (ushort.MaxValue - 1) / UnicodeEncoding.CharSize - 1; if (s.Length > maxLength) throw new ArgumentException("String too long"); lus.Buffer = Marshal.StringToHGlobalUni(s); @@ -6646,11 +6591,11 @@ $result internal const int MaxMachineNameLength = 15; } - # endregion +#endregion #endif - #region "Public API" +#region "Public API" /// /// The object returned by SAM Computer cmdlets representing the status of the target machine. /// @@ -6787,9 +6732,9 @@ $result return StringUtil.Format(MatchFormat, HasSucceeded, newcomputername, oldcomputername); } } - #endregion "Public API" +#endregion "Public API" - #region Helper +#region Helper /// /// Helper Class used by Stop-Computer,Restart-Computer and Test-Connection /// Also Contain constants used by System Restore related Cmdlets. @@ -7025,9 +6970,7 @@ $result { if (!drive.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase)) { - driveApp = String.Concat(drive, "\\"); - } else driveApp = drive; @@ -7035,7 +6978,6 @@ $result return true; } return false; - } /// @@ -7373,9 +7315,9 @@ $result return validatedComputerName; } } - #endregion Helper +#endregion Helper - #region Internal Enums +#region Internal Enums internal enum TransportProtocol { @@ -7383,8 +7325,7 @@ $result WSMan = 2 } - #endregion - +#endregion }//End namespace #endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index bc457d77e..c4f4ec934 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -17,22 +18,22 @@ namespace Microsoft.PowerShell.Commands public class ContentCommandBase : CoreCommandWithCredentialsBase, IDisposable { #region Parameters - + /// /// Gets or sets the path parameter to the command /// - [Parameter(Position=0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -40,19 +41,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -72,7 +73,7 @@ namespace Microsoft.PowerShell.Commands base.Filter = value; } // set } // Filter - + /// /// Gets or sets the include property /// @@ -138,11 +139,11 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region parameter data - + /// /// The path to the item to ping /// - private string[] paths; + private string[] _paths; #endregion parameter data @@ -198,30 +199,30 @@ namespace Microsoft.PowerShell.Commands // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; - if (currentContentItem != null && - ((currentContentItem.PathInfo == pathInfo) || - ( + if (_currentContentItem != null && + ((_currentContentItem.PathInfo == pathInfo) || + ( String.Compare( pathInfo.Path, - currentContentItem.PathInfo.Path, + _currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase) == 0) ) ) { - result = currentContentItem.AttachNotes(result); + result = _currentContentItem.AttachNotes(result); } else { // Generate a new cache item and cache the notes - currentContentItem = new ContentPathsCache(pathInfo); + _currentContentItem = new ContentPathsCache(pathInfo); // Construct a provider qualified path as the Path note string psPath = pathInfo.Path; note = new PSNoteProperty("PSPath", psPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); - currentContentItem.PSPath = psPath; + _currentContentItem.PSPath = psPath; try { @@ -240,7 +241,7 @@ namespace Microsoft.PowerShell.Commands note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); - currentContentItem.ParentPath = parentPath; + _currentContentItem.ParentPath = parentPath; // Get the child name @@ -248,7 +249,7 @@ namespace Microsoft.PowerShell.Commands note = new PSNoteProperty("PSChildName", childName); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); - currentContentItem.ChildName = childName; + _currentContentItem.ChildName = childName; } catch (NotSupportedException) { @@ -263,7 +264,7 @@ namespace Microsoft.PowerShell.Commands note = new PSNoteProperty("PSDrive", drive); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); - currentContentItem.Drive = drive; + _currentContentItem.Drive = drive; } // ProviderInfo @@ -272,7 +273,7 @@ namespace Microsoft.PowerShell.Commands note = new PSNoteProperty("PSProvider", provider); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); - currentContentItem.Provider = provider; + _currentContentItem.Provider = provider; } // Add the ReadCount note @@ -280,14 +281,13 @@ namespace Microsoft.PowerShell.Commands result.Properties.Add(note, true); WriteObject(result); - } // WriteContentObject /// /// A cache of the notes that get added to the content items as they are written /// to the pipeline. /// - private ContentPathsCache currentContentItem; + private ContentPathsCache _currentContentItem; /// /// A class that stores a cache of the notes that get attached to content items @@ -306,7 +306,7 @@ namespace Microsoft.PowerShell.Commands /// public ContentPathsCache(PathInfo pathInfo) { - this.pathInfo = pathInfo; + _pathInfo = pathInfo; } /// @@ -317,10 +317,10 @@ namespace Microsoft.PowerShell.Commands { get { - return pathInfo; + return _pathInfo; } } // PathInfo - private PathInfo pathInfo; + private PathInfo _pathInfo; /// /// The cached PSPath of the item. @@ -330,15 +330,15 @@ namespace Microsoft.PowerShell.Commands { get { - return psPath; + return _psPath; } set { - psPath = value; + _psPath = value; } } // PSPath - private string psPath; + private string _psPath; /// /// The cached parent path of the item. @@ -348,15 +348,15 @@ namespace Microsoft.PowerShell.Commands { get { - return parentPath; + return _parentPath; } set { - parentPath = value; + _parentPath = value; } } // ParentPath - private string parentPath; + private string _parentPath; /// /// The cached drive for the item. @@ -366,15 +366,15 @@ namespace Microsoft.PowerShell.Commands { get { - return drive; + return _drive; } set { - drive = value; + _drive = value; } } // Drive - private PSDriveInfo drive; + private PSDriveInfo _drive; /// /// The cached provider of the item. @@ -384,15 +384,15 @@ namespace Microsoft.PowerShell.Commands { get { - return provider; + return _provider; } set { - provider = value; + _provider = value; } } // Provider - private ProviderInfo provider; + private ProviderInfo _provider; /// @@ -403,15 +403,15 @@ namespace Microsoft.PowerShell.Commands { get { - return childName; + return _childName; } set { - childName = value; + _childName = value; } } // ChildName - private string childName; + private string _childName; /// /// Attaches the cached notes to the specified PSObject. @@ -447,7 +447,7 @@ namespace Microsoft.PowerShell.Commands // PSDriveInfo - if (pathInfo.Drive != null) + if (_pathInfo.Drive != null) { note = new PSNoteProperty("PSDrive", Drive); content.Properties.Add(note, true); @@ -473,8 +473,8 @@ namespace Microsoft.PowerShell.Commands internal struct ContentHolder { internal ContentHolder( - PathInfo pathInfo, - IContentReader reader, + PathInfo pathInfo, + IContentReader reader, IContentWriter writer) { if (pathInfo == null) @@ -482,9 +482,9 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("pathInfo"); } - this._pathInfo = pathInfo; - this._reader = reader; - this._writer = writer; + _pathInfo = pathInfo; + _reader = reader; + _writer = writer; } // constructor internal PathInfo PathInfo @@ -524,7 +524,6 @@ namespace Microsoft.PowerShell.Commands { holder.Writer.Close(); } - } catch (Exception e) // Catch-all OK. 3rd party callout { @@ -596,7 +595,6 @@ namespace Microsoft.PowerShell.Commands providerException)); } } - } } // CloseContent @@ -694,7 +692,7 @@ namespace Microsoft.PowerShell.Commands { if (readers.Count == 1 && readers[0] != null) { - ContentHolder holder = + ContentHolder holder = new ContentHolder(pathInfo, readers[0], null); results.Add(holder); @@ -731,7 +729,7 @@ namespace Microsoft.PowerShell.Commands /// /// internal Collection ResolvePaths( - string[] pathsToResolve, + string[] pathsToResolve, bool allowNonexistingPaths, bool allowEmptyResult, CmdletProviderContext currentCommandContext) @@ -747,11 +745,10 @@ namespace Microsoft.PowerShell.Commands try { - // First resolve each of the paths - Collection pathInfos = + Collection pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( - path, + path, currentCommandContext); if (pathInfos.Count == 0) @@ -803,9 +800,9 @@ namespace Microsoft.PowerShell.Commands if (pathNotFound) { if (allowNonexistingPaths && - (! filtersHidPath) && + (!filtersHidPath) && (currentCommandContext.SuppressWildcardExpansion || - (! WildcardPattern.ContainsWildcardCharacters(path)))) + (!WildcardPattern.ContainsWildcardCharacters(path)))) { ProviderInfo provider = null; PSDriveInfo drive = null; @@ -879,5 +876,4 @@ namespace Microsoft.PowerShell.Commands #endregion IDisposable } // ContentCommandBase - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs index 5e39e9d6f..89d0cce04 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -1,7 +1,8 @@ // // Copyright (C) Microsoft. All rights reserved. // -using System.Collections.ObjectModel; + +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Microsoft.Win32; @@ -100,7 +101,7 @@ namespace Microsoft.PowerShell.Commands /// /// Locale specific verb action Open string exposed by the control panel item. /// - private static string VerbActionOpenName = null; + private static string s_verbActionOpenName = null; /// /// Canonical name of the control panel item used as a refernece to fetch the verb @@ -109,7 +110,7 @@ namespace Microsoft.PowerShell.Commands private const string RegionCanonicalName = "Microsoft.RegionAndLanguage"; private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}"; - private static readonly string[] ControlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" }; + private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" }; private const string TestHeadlessServerScript = @" $result = $false $serverManagerModule = Get-Module -ListAvailable | ? {$_.Name -eq 'ServerManager'} @@ -153,7 +154,7 @@ $result if (applyControlPanelItemFilterList) { bool match = false; - foreach (string name in ControlPanelItemFilterList) + foreach (string name in s_controlPanelItemFilterList) { if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)) { @@ -212,8 +213,8 @@ $result FolderItemVerbs verbs = item.Verbs(); foreach (FolderItemVerb verb in verbs) { - if (!String.IsNullOrEmpty(verb.Name) && - (verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) || + if (!String.IsNullOrEmpty(verb.Name) && + (verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) || CompareVerbActionOpen(verb.Name))) { result = true; @@ -230,8 +231,8 @@ $result /// Locale spcific 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 (VerbActionOpenName == null) + { + if (s_verbActionOpenName == null) { const string allItemFolderPath = ControlPanelShellFolder + "\\0"; IShellDispatch4 shell2 = (IShellDispatch4)new Shell(); @@ -248,16 +249,16 @@ $result 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 - VerbActionOpenName = item.Verbs().Item(0).Name; + s_verbActionOpenName = item.Verbs().Item(0).Name; break; } } - Dbg.Assert(VerbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always " + 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 VerbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase); + return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase); } /// @@ -316,7 +317,7 @@ $result { string path = category.Path; string catNum = path.Substring(path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1); - + CategoryMap.Add(catNum, category.Name); } } @@ -341,10 +342,10 @@ $result int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category"); foreach (int cat in categories) { - string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof (string), CultureInfo.InvariantCulture); + 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)) @@ -690,7 +691,7 @@ $result #endregion "Private Methods" } - + /// /// Show the specified control panel applet /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs index 67ae9e659..489cac851 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation; @@ -12,13 +13,13 @@ namespace Microsoft.PowerShell.Commands /// A command to convert a drive qualifed or provider qualified path to /// a provider internal path. /// - [Cmdlet (VerbsData.Convert, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, + [Cmdlet(VerbsData.Convert, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113289", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(string))] public class ConvertPathCommand : CoreCommandBase { #region Parameters - + /// /// Gets or sets the path parameter to the command /// @@ -28,12 +29,12 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -41,30 +42,30 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath #endregion Parameters #region parameter data - + /// /// The path(s) to the item(s) to convert /// - private string[] paths; + private string[] _paths; #endregion parameter data @@ -74,7 +75,7 @@ namespace Microsoft.PowerShell.Commands /// Converts a drive qualified or provider qualified path to a provider /// internal path. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { ProviderInfo provider = null; @@ -122,13 +123,11 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord #endregion Command code } // ConvertPathCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs index 5b62318c6..9f1549286 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to copy a property on an item. /// - [Cmdlet (VerbsCommon.Copy, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Copy, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113293")] public class CopyItemPropertyCommand : PassThroughItemPropertyCommandBase { @@ -20,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path parameter to the command /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -64,12 +65,12 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property @@ -77,20 +78,20 @@ namespace Microsoft.PowerShell.Commands /// The path to the destination item to copy the property to. /// /// - [Parameter(Mandatory=true, Position = 1, ValueFromPipelineByPropertyName = true)] + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] public string Destination { get { - return destination; + return _destination; } // get set { - destination = value; + _destination = value; } } // Destination - + /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the @@ -111,33 +112,33 @@ namespace Microsoft.PowerShell.Commands if (Path != null & Path.Length > 0) { return InvokeProvider.Property.CopyPropertyDynamicParameters( - Path[0], - property, - Destination, - property, + Path[0], + _property, + Destination, + _property, context); } return InvokeProvider.Property.CopyPropertyDynamicParameters( ".", - property, + _property, Destination, - property, + _property, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The property to be copied. /// - private string property; + private string _property; /// /// The destination path of the item to copy the property to. /// - private string destination; + private string _destination; #endregion parameter data @@ -146,17 +147,17 @@ namespace Microsoft.PowerShell.Commands /// /// Copies the property from one item to another /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { try { InvokeProvider.Property.Copy( - path, - property, - Destination, - property, + path, + _property, + Destination, + _property, GetCurrentContext()); } catch (PSNotSupportedException notSupported) @@ -197,5 +198,4 @@ namespace Microsoft.PowerShell.Commands } // CopyItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index 15059f3e7..8c5a71b95 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -87,8 +88,8 @@ namespace Microsoft.PowerShell.Commands set { _after = value; - isDateSpecified = true; - isFilterSpecified = true; + _isDateSpecified = true; + _isFilterSpecified = true; } } private DateTime _after; @@ -104,8 +105,8 @@ namespace Microsoft.PowerShell.Commands set { _before = value; - isDateSpecified = true; - isFilterSpecified = true; + _isDateSpecified = true; + _isFilterSpecified = true; } } private DateTime _before; @@ -122,7 +123,7 @@ namespace Microsoft.PowerShell.Commands set { _username = value; - isFilterSpecified = true; + _isFilterSpecified = true; } } private String[] _username; @@ -134,15 +135,14 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 1, ParameterSetName = "LogName")] [ValidateNotNullOrEmpty()] [ValidateRangeAttribute((long)0, long.MaxValue)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public long[] InstanceId { get { return _instanceIds; } set { _instanceIds = value; - isFilterSpecified = true; - + _isFilterSpecified = true; } } private long[] _instanceIds = null; @@ -155,14 +155,14 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "LogName")] [ValidateNotNullOrEmpty()] [ValidateRangeAttribute((int)1, int.MaxValue)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] Index { get { return _indexes; } set { _indexes = value; - isFilterSpecified = true; + _isFilterSpecified = true; } } private int[] _indexes = null; @@ -183,7 +183,7 @@ namespace Microsoft.PowerShell.Commands set { _entryTypes = value; - isFilterSpecified = true; + _isFilterSpecified = true; } } private string[] _entryTypes = null; @@ -202,7 +202,7 @@ namespace Microsoft.PowerShell.Commands set { _sources = value; - isFilterSpecified = true; + _isFilterSpecified = true; } } private string[] _sources; @@ -222,7 +222,7 @@ namespace Microsoft.PowerShell.Commands set { _message = value; - isFilterSpecified = true; + _isFilterSpecified = true; } } private string _message; @@ -285,9 +285,9 @@ namespace Microsoft.PowerShell.Commands /// /// Sets true when Filter is Specified /// - private bool isFilterSpecified = false; - private bool isDateSpecified = false; - private bool isThrowError = true; + private bool _isFilterSpecified = false; + private bool _isDateSpecified = false; + private bool _isThrowError = true; /// /// Process the specified logs @@ -413,7 +413,6 @@ namespace Microsoft.PowerShell.Commands try { entry = entries[i]; - } catch (ArgumentException e) { @@ -450,7 +449,7 @@ namespace Microsoft.PowerShell.Commands || lastindex - entry.Index == 1))) { lastindex = entry.Index; - if (isFilterSpecified) + if (_isFilterSpecified) { if (!FiltersMatch(entry)) continue; @@ -473,7 +472,7 @@ namespace Microsoft.PowerShell.Commands processed++; } } - if (!matchesfound && isThrowError) + if (!matchesfound && _isThrowError) { Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, "")); WriteError(new ErrorRecord(Ex, "GetEventLogNoEntriesFound", ErrorCategory.ObjectNotFound, null)); @@ -518,7 +517,7 @@ namespace Microsoft.PowerShell.Commands { if (WildcardPattern.ContainsWildcardCharacters(source)) { - isThrowError = false; + _isThrowError = false; } WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase); if (wildcardpattern.IsMatch(entry.Source)) @@ -533,7 +532,7 @@ namespace Microsoft.PowerShell.Commands { if (WildcardPattern.ContainsWildcardCharacters(_message)) { - isThrowError = false; + _isThrowError = false; } WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase); if (!wildcardpattern.IsMatch(entry.Message)) @@ -546,7 +545,7 @@ namespace Microsoft.PowerShell.Commands bool usernamematch = false; foreach (string user in _username) { - isThrowError = false; + _isThrowError = false; if (entry.UserName != null) { WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase); @@ -559,25 +558,25 @@ namespace Microsoft.PowerShell.Commands } if (!usernamematch) return usernamematch; } - if (isDateSpecified) + if (_isDateSpecified) { - isThrowError = false; + _isThrowError = false; bool datematch = false; - if (!_after.Equals(Initial) && _before.Equals(Initial)) + if (!_after.Equals(_initial) && _before.Equals(_initial)) { if (entry.TimeGenerated > _after) { datematch = true; } } - else if (!_before.Equals(Initial) && _after.Equals(Initial)) + else if (!_before.Equals(_initial) && _after.Equals(_initial)) { if (entry.TimeGenerated < _before) { datematch = true; } } - else if (!_after.Equals(Initial) && !_before.Equals(Initial)) + else if (!_after.Equals(_initial) && !_before.Equals(_initial)) { if (_after > _before || _after == _before) { @@ -627,7 +626,7 @@ namespace Microsoft.PowerShell.Commands return matchingLogs; } //private string ErrorBase = "EventlogResources"; - private DateTime Initial = new DateTime(); + private DateTime _initial = new DateTime(); #endregion Private }//GetEventLogCommand @@ -733,12 +732,10 @@ namespace Microsoft.PowerShell.Commands WriteError(er); continue; } - } } } - //beginprocessing #endregion Overrides @@ -878,13 +875,13 @@ namespace Microsoft.PowerShell.Commands public string ComputerName { - get { return compname; } + get { return _compname; } set { - compname = value; + _compname = value; } } - private string compname = "."; + private string _compname = "."; #endregion Parameters # region private @@ -904,35 +901,32 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - string _computerName = string.Empty; - if ((compname.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase))) + if ((_compname.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (_compname.Equals(".", StringComparison.OrdinalIgnoreCase))) { _computerName = "localhost"; } else { - _computerName = compname; + _computerName = _compname; } try { - if (!(EventLog.SourceExists(_source, compname))) + if (!(EventLog.SourceExists(_source, _compname))) { ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, null, _computerName, _source)), null, ErrorCategory.InvalidOperation, null); WriteError(er); - } else { - if (!(EventLog.Exists(_logName, compname))) + if (!(EventLog.Exists(_logName, _compname))) { ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, _logName, _computerName)), null, ErrorCategory.InvalidOperation, null); WriteError(er); - } else { - EventLog _myevent = new EventLog(_logName, compname, _source); + EventLog _myevent = new EventLog(_logName, _compname, _source); _myevent.WriteEntry(_message, _entryType, _eventId, _category, _rawData); } } @@ -944,16 +938,14 @@ namespace Microsoft.PowerShell.Commands 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, compname, null), ErrorCategory.InvalidOperation); + WriteNonTerminatingError(ex, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, null, _compname, null), ErrorCategory.InvalidOperation); } }//beginprocessing @@ -1016,11 +1008,11 @@ namespace Microsoft.PowerShell.Commands set { _retention = value; - retentionSpecified = true; + _retentionSpecified = true; } } private Int32 _retention; - bool retentionSpecified = false; + private bool _retentionSpecified = false; /// /// Overflow action to be taken. /// @@ -1035,11 +1027,11 @@ namespace Microsoft.PowerShell.Commands set { _overflowaction = value; - overflowSpecified = true; + _overflowSpecified = true; } } private System.Diagnostics.OverflowAction _overflowaction; - bool overflowSpecified = false; + private bool _overflowSpecified = false; /// /// Maximum size of this log. /// @@ -1051,11 +1043,11 @@ namespace Microsoft.PowerShell.Commands set { _maximumKilobytes = value; - maxkbSpecified = true; + _maxkbSpecified = true; } } private Int64 _maximumKilobytes; - bool maxkbSpecified = false; + private bool _maxkbSpecified = false; #endregion Parameters # region private @@ -1109,7 +1101,7 @@ namespace Microsoft.PowerShell.Commands EventLog newLog = new EventLog(logname, compname); int _minRetention = newLog.MinimumRetentionDays; System.Diagnostics.OverflowAction _newFlowAction = newLog.OverflowAction; - if (retentionSpecified && overflowSpecified) + if (_retentionSpecified && _overflowSpecified) { if (_overflowaction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) { @@ -1122,7 +1114,7 @@ namespace Microsoft.PowerShell.Commands continue; } } - else if (retentionSpecified && !overflowSpecified) + else if (_retentionSpecified && !_overflowSpecified) { if (_newFlowAction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0) { @@ -1135,11 +1127,11 @@ namespace Microsoft.PowerShell.Commands continue; } } - else if (!retentionSpecified && overflowSpecified) + else if (!_retentionSpecified && _overflowSpecified) { newLog.ModifyOverflowPolicy(_overflowaction, _minRetention); } - if (maxkbSpecified) + if (_maxkbSpecified) { int kiloByte = 1024; _maximumKilobytes = _maximumKilobytes / kiloByte; @@ -1160,7 +1152,7 @@ namespace Microsoft.PowerShell.Commands } catch (ArgumentOutOfRangeException ex) { - if (!retentionSpecified && !maxkbSpecified) + if (!_retentionSpecified && !_maxkbSpecified) { WriteNonTerminatingError(ex, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null); } @@ -1239,7 +1231,7 @@ namespace Microsoft.PowerShell.Commands } catch (SystemException ex) { - ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, this._computerName); + ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, _computerName); WriteError(er); } } @@ -1271,7 +1263,6 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsCommon.New, "EventLog", HelpUri = "http://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". @@ -1443,7 +1434,6 @@ namespace Microsoft.PowerShell.Commands WriteNonTerminatingError(ex, EventlogResources.AccessIsDenied, "AccessIsDenied", ErrorCategory.InvalidOperation, null, null, null, null); continue; } - } } //End BeginProcessing() @@ -1474,13 +1464,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] ComputerName { - get { return computername; } + get { return _computername; } set { - computername = value; + _computername = value; } } - private string[] computername = { "." }; + private string[] _computername = { "." }; /// /// The following is the definition of the input parameter "LogName". @@ -1494,13 +1484,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] LogName { - get { return logname; } + get { return _logname; } set { - logname = value; + _logname = value; } } - private String[] logname; + private String[] _logname; /// /// The following is the definition of the input parameter "RemoveSource". @@ -1518,13 +1508,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Source { - get { return source; } + get { return _source; } set { - source = value; + _source = value; } } - private String[] source; + private String[] _source; @@ -1536,7 +1526,7 @@ namespace Microsoft.PowerShell.Commands try { string computer = string.Empty; - foreach (string compName in computername) + foreach (string compName in _computername) { if ((compName.Equals("localhost", StringComparison.CurrentCultureIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase))) { @@ -1548,12 +1538,10 @@ namespace Microsoft.PowerShell.Commands } if (ParameterSetName.Equals("Default")) { - foreach (string log in logname) + foreach (string log in _logname) { - try { - if (EventLog.Exists(log, compName)) { if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveEventLogWarning, log, computer))) @@ -1574,16 +1562,13 @@ namespace Microsoft.PowerShell.Commands 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) + foreach (string src in _source) { - try { if (EventLog.SourceExists(src, compName)) @@ -1603,12 +1588,9 @@ namespace Microsoft.PowerShell.Commands } catch (System.IO.IOException) { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null); WriteError(er); continue; - - } } } @@ -1618,16 +1600,10 @@ namespace Microsoft.PowerShell.Commands { ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.SecurityError, null); WriteError(er); - } }//End BeginProcessing() - - - }//End Class #endregion RemoveEventLogCommand - - }//Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index 49e8eafa0..9f370de67 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; @@ -13,7 +14,6 @@ using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { - /// /// The get-childitem command class. /// This command lists the contents of a container @@ -57,16 +57,16 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path for the operation /// [Parameter(Position = 0, ParameterSetName = childrenSet, - ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } @@ -74,19 +74,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = literalChildrenSet, - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -149,11 +149,11 @@ namespace Microsoft.PowerShell.Commands { get { - return recurse; + return _recurse; } set { - recurse = value; + _recurse = value; } } @@ -168,11 +168,11 @@ namespace Microsoft.PowerShell.Commands { get { - return depth; + return _depth; } set { - depth = value; + _depth = value; this.Recurse = true; // Bug 2391925 - Get-ChildItem -Depth should auto-set -Recurse } } @@ -212,11 +212,11 @@ namespace Microsoft.PowerShell.Commands { get { - return childNames; + return _childNames; } set { - childNames = value; + _childNames = value; } } @@ -285,9 +285,9 @@ namespace Microsoft.PowerShell.Commands object result = null; string path = String.Empty; - if (paths != null && paths.Length > 0) + if (_paths != null && _paths.Length > 0) { - path = paths[0]; + path = _paths[0]; } else { @@ -298,7 +298,7 @@ namespace Microsoft.PowerShell.Commands { case childrenSet: case literalChildrenSet: - if(Name) + if (Name) { result = InvokeProvider.ChildItem.GetChildNamesDynamicParameters(path, context); } @@ -329,12 +329,12 @@ namespace Microsoft.PowerShell.Commands /// /// The path for the get-location operation. /// - private string[] paths; + private string[] _paths; /// /// Determines if the command should do recursion. /// - private bool recurse; + private bool _recurse; /// /// Limits the depth of recursion; used with Recurse parameter; @@ -342,12 +342,12 @@ namespace Microsoft.PowerShell.Commands /// Value '1' will show 1 level deep, etc...; /// Default is uint.MaxValue - it performs full recursion (this parameter has no effect). /// - private uint depth = uint.MaxValue; + private uint _depth = uint.MaxValue; /// /// The flag that specifies whether to retrieve the child names or the child items /// - private bool childNames = false; + private bool _childNames = false; #endregion command data @@ -357,17 +357,17 @@ namespace Microsoft.PowerShell.Commands /// /// The main execution method for the get-childitem command. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; - if (paths == null || - (paths != null && paths.Length == 0)) + if (_paths == null || + (_paths != null && _paths.Length == 0)) { - paths = new string[] { String.Empty }; + _paths = new string[] { String.Empty }; } - foreach (string path in paths) + foreach (string path in _paths) { switch (ParameterSetName) { @@ -375,7 +375,7 @@ namespace Microsoft.PowerShell.Commands case literalChildrenSet: try { - if(Name) + if (Name) { // Get the names of the child items using the static namespace method. // The child names should be written directly to the pipeline using the @@ -499,7 +499,6 @@ namespace Microsoft.PowerShell.Commands private const string targetTreatAsType = "System.Management.Automation.RelationshipTarget"; #endif #endregion command code - } // class GetChildrenCommand } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs index 9db034e2c..aa59d5139 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -54,15 +54,15 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public TextDataFormat TextFormatType { - get { return textFormat; } + get { return _textFormat; } set { - isTextFormatTypeSet = true; - textFormat = value; + _isTextFormatTypeSet = true; + _textFormat = value; } } - private TextDataFormat textFormat = TextDataFormat.UnicodeText; - private bool isTextFormatTypeSet = false; + private TextDataFormat _textFormat = TextDataFormat.UnicodeText; + private bool _isTextFormatTypeSet = false; /// /// Property that sets raw parameter. This will allow clipboard return text or file list as one string. @@ -70,15 +70,15 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Raw { - get { return raw; } + get { return _raw; } set { - isRawSet = true; - raw = value; + _isRawSet = true; + _raw = value; } } - private bool raw; - private bool isRawSet = false; + private bool _raw; + private bool _isRawSet = false; /// /// This method implements the ProcessRecord method for Get-Clipboard command @@ -86,7 +86,7 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // TextFormatType should only combine with Text. - if (Format != ClipboardFormat.Text && isTextFormatTypeSet) + if (Format != ClipboardFormat.Text && _isTextFormatTypeSet) { ThrowTerminatingError(new ErrorRecord(new InvalidOperationException( String.Format(CultureInfo.InvariantCulture, ClipboardResources.InvalidTypeCombine)), @@ -94,7 +94,7 @@ namespace Microsoft.PowerShell.Commands } // Raw should only combine with Text or FileDropList. - if (Format != ClipboardFormat.Text && Format != ClipboardFormat.FileDropList && isRawSet) + if (Format != ClipboardFormat.Text && Format != ClipboardFormat.FileDropList && _isRawSet) { ThrowTerminatingError(new ErrorRecord(new InvalidOperationException( String.Format(CultureInfo.InvariantCulture, ClipboardResources.InvalidRawCombine)), @@ -103,7 +103,7 @@ namespace Microsoft.PowerShell.Commands if (Format == ClipboardFormat.Text) { - this.WriteObject(GetClipboardContentAsText(textFormat), true); + this.WriteObject(GetClipboardContentAsText(_textFormat), true); } else if (Format == ClipboardFormat.Image) { @@ -111,7 +111,7 @@ namespace Microsoft.PowerShell.Commands } else if (Format == ClipboardFormat.FileDropList) { - if (raw) + if (_raw) { this.WriteObject(Clipboard.GetFileDropList(), true); } @@ -141,7 +141,7 @@ namespace Microsoft.PowerShell.Commands // TextFormat default value is Text, by default it is same as Clipboard.GetText() string textContent = Clipboard.GetText(textFormat); - if (raw) + if (_raw) { result.Add(textContent); } @@ -159,7 +159,6 @@ namespace Microsoft.PowerShell.Commands /// private List GetClipboardContentAsFileList() { - if (!Clipboard.ContainsFileDropList()) { return null; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 940c4dbac..2dbf391f8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -29,49 +30,49 @@ namespace Microsoft.PowerShell.Commands #region Inner Types private class OSInfoGroup { - public WmiOperatingSystem os; - public HotFix[] hotFixes; - public WmiPageFileUsage[] pageFileUsage; - public string halVersion; - public TimeSpan? upTime; - public RegWinNtCurrentVersion regCurVer; + public WmiOperatingSystem os; + public HotFix[] hotFixes; + public WmiPageFileUsage[] pageFileUsage; + public string halVersion; + public TimeSpan? upTime; + public RegWinNtCurrentVersion regCurVer; } private class SystemInfoGroup { - public WmiBaseBoard baseboard; - public WmiBios bios; - public WmiComputerSystem computer; - public Processor[] processors; - public NetworkAdapter[] networkAdapters; + public WmiBaseBoard baseboard; + public WmiBios bios; + public WmiComputerSystem computer; + public Processor[] processors; + public NetworkAdapter[] networkAdapters; } private class HyperVInfo { - public bool? Present; - public bool? VMMonitorModeExtensions; - public bool? SecondLevelAddressTranslation; - public bool? VirtualizationFirmwareEnabled; - public bool? DataExecutionPreventionAvailable; + public bool? Present; + public bool? VMMonitorModeExtensions; + public bool? SecondLevelAddressTranslation; + public bool? VirtualizationFirmwareEnabled; + public bool? DataExecutionPreventionAvailable; } private class DeviceGuardInfo { - public DeviceGuardSmartStatus status; - public DeviceGuard deviceGuard; + public DeviceGuardSmartStatus status; + public DeviceGuard deviceGuard; } private class MiscInfoGroup { - public UInt64? physicallyInstalledMemory; - public string timeZone; - public string logonServer; - public FirmwareType? firmwareType; - public PowerPlatformRole? powerPlatformRole; - public WmiKeyboard[] keyboards; - public HyperVInfo hyperV; - public ServerLevel? serverLevel; - public DeviceGuardInfo deviceGuard; + public UInt64? physicallyInstalledMemory; + public string timeZone; + public string logonServer; + public FirmwareType? firmwareType; + public PowerPlatformRole? powerPlatformRole; + public WmiKeyboard[] keyboards; + public HyperVInfo hyperV; + public ServerLevel? serverLevel; + public DeviceGuardInfo deviceGuard; } #endregion Inner Types @@ -81,15 +82,15 @@ namespace Microsoft.PowerShell.Commands #endregion Static Data and Constants #region Instance Data - private string machineName = localMachineName; // we might need to have cmdlet work on another machine - private ProgressRecord progress = null; + private string _machineName = localMachineName; // we might need to have cmdlet work on another machine + private ProgressRecord _progress = null; /// /// Collection of property names from the Property parameter, /// including any names resulting from the expansion of wild-card /// patterns given. This list will itself contain no wildcard patterns. /// - private List namedProperties = null; + private List _namedProperties = null; #endregion Instance Data #region Parameters @@ -130,7 +131,7 @@ namespace Microsoft.PowerShell.Commands { try { - namedProperties = CollectPropertyNames(Property); + _namedProperties = CollectPropertyNames(Property); } catch (WildcardPatternException ex) { @@ -146,7 +147,7 @@ namespace Microsoft.PowerShell.Commands { // if the user provided property names but no matching properties // were found, return an empty custom object - if (namedProperties != null && namedProperties.Count == 0) + if (_namedProperties != null && _namedProperties.Count == 0) { WriteObject(new PSObject()); return; @@ -157,7 +158,7 @@ namespace Microsoft.PowerShell.Commands var systemInfo = new SystemInfoGroup(); var now = DateTime.Now; - using (var session = CimSession.Create(machineName)) + using (var session = CimSession.Create(_machineName)) { UpdateProgress(ComputerInfoResources.LoadingOperationSystemInfo); @@ -199,10 +200,10 @@ namespace Microsoft.PowerShell.Commands var infoOutput = CreateFullOutputObject(systemInfo, osInfo, miscInfo); - if (namedProperties != null) + if (_namedProperties != null) { //var output = CreateCustomOutputObject(namedProperties, systemInfo, osInfo, miscInfo); - var output = CreateCustomOutputObject(infoOutput, namedProperties); + var output = CreateCustomOutputObject(infoOutput, _namedProperties); WriteObject(output); } @@ -222,16 +223,16 @@ namespace Microsoft.PowerShell.Commands /// private void UpdateProgress(string status) { - if (progress != null) + if (_progress != null) { - progress.RecordType = ProgressRecordType.Completed; - WriteProgress(progress); + _progress.RecordType = ProgressRecordType.Completed; + WriteProgress(_progress); } if (status != null) { - progress = new ProgressRecord(0, activity, status); - WriteProgress(progress); + _progress = new ProgressRecord(0, activity, status); + WriteProgress(_progress); } } @@ -305,17 +306,17 @@ namespace Microsoft.PowerShell.Commands { // Only include adapters that have a non-null connection status // and a non-null index - if ( adapter.NetConnectionStatus != null + if (adapter.NetConnectionStatus != null && adapter.Index != null) { if (configDict.ContainsKey(adapter.Index.Value)) { var config = configDict[adapter.Index.Value]; var nwAdapter = new NetworkAdapter - { - Description = adapter.Description, - ConnectionID = adapter.NetConnectionID - }; + { + Description = adapter.Description, + ConnectionID = adapter.NetConnectionID + }; var status = EnumConverter.Convert(adapter.NetConnectionStatus); nwAdapter.ConnectionStatus = status == null ? NetConnectionStatus.Other @@ -386,11 +387,11 @@ namespace Microsoft.PowerShell.Commands private static bool CheckDeviceGuardLicense() { #if !CORECLR - const string propertyName = "CodeIntegrity-AllowConfigurablePolicy"; + const string propertyName = "CodeIntegrity-AllowConfigurablePolicy"; try { - int policy = 0; + int policy = 0; if (Native.SLGetWindowsInformationDWORD(propertyName, out policy) == Native.S_OK && policy == 1) @@ -434,10 +435,10 @@ namespace Microsoft.PowerShell.Commands } return new DeviceGuardInfo - { - status = status, - deviceGuard = guard - }; + { + status = status, + deviceGuard = guard + }; } /// @@ -558,7 +559,7 @@ namespace Microsoft.PowerShell.Commands // get amount of memory physically installed //TODO: Local machine only. Check for that? - UInt64 memory; + UInt64 memory; if (Native.GetPhysicallyInstalledSystemMemory(out memory)) rv.physicallyInstalledMemory = memory; @@ -709,7 +710,7 @@ namespace Microsoft.PowerShell.Commands { output.OsPagingFiles = new string[pageFileUsage.Length]; - for (int i=0; i < pageFileUsage.Length; i++) + for (int i = 0; i < pageFileUsage.Length; i++) output.OsPagingFiles[i] = pageFileUsage[i].Caption; } } @@ -1148,7 +1149,7 @@ namespace Microsoft.PowerShell.Commands internal static class EnumConverter where T : struct, IConvertible { // The converter object - private static readonly Func convert = MakeConverter(); + private static readonly Func s_convert = MakeConverter(); /// /// Convert an integer to a Nullable enum of type T @@ -1167,7 +1168,7 @@ namespace Microsoft.PowerShell.Commands try { if (value.HasValue) - return convert(value.Value); + return s_convert(value.Value); } catch (Exception) { @@ -1294,132 +1295,132 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiBaseBoard { - public string Caption; - public string[] ConfigOptions; - public float? Depth; - public string Description; - public float? Height; - public bool? HostingBoard; - public bool? HotSwappable; - public DateTime? InstallDate; - public string Manufacturer; - public string Model; - public string Name; - public string OtherIdentifyingInfo; - public string PartNumber; - public bool? PoweredOn; - public string Product; - public bool? Removable; - public bool? Replaceable; - public string RequirementsDescription; - public bool? RequiresDaughterBoard; - public string SerialNumber; - public string SKU; - public string SlotLayout; - public bool? SpecialRequirements; - public string Status; - public string Tag; - public string Version; - public float? Weight; - public float? Width; + public string Caption; + public string[] ConfigOptions; + public float? Depth; + public string Description; + public float? Height; + public bool? HostingBoard; + public bool? HotSwappable; + public DateTime? InstallDate; + public string Manufacturer; + public string Model; + public string Name; + public string OtherIdentifyingInfo; + public string PartNumber; + public bool? PoweredOn; + public string Product; + public bool? Removable; + public bool? Replaceable; + public string RequirementsDescription; + public bool? RequiresDaughterBoard; + public string SerialNumber; + public string SKU; + public string SlotLayout; + public bool? SpecialRequirements; + public string Status; + public string Tag; + public string Version; + public float? Weight; + public float? Width; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiBios : WmiClassBase { - public UInt16[] BiosCharacteristics; - public string[] BIOSVersion; - public string BuildNumber; - public string Caption; - public string CodeSet; - public string CurrentLanguage; - public string Description; - public byte? EmbeddedControllerMajorVersion; - public byte? EmbeddedControllerMinorVersion; - public string IdentificationCode; - public UInt16? InstallableLanguages; - public DateTime? InstallDate; - public string LanguageEdition; - public string[] ListOfLanguages; - public string Manufacturer; - public string Name; - public string OtherTargetOS; - public bool? PrimaryBIOS; - public DateTime? ReleaseDate; - public string SerialNumber; - public string SMBIOSBIOSVersion; - public UInt16? SMBIOSMajorVersion; - public UInt16? SMBIOSMinorVersion; - public bool? SMBIOSPresent; - public UInt16? SoftwareElementState; - public string Status; - public byte? SystemBiosMajorVersion; - public byte? SystemBiosMinorVersion; - public UInt16? TargetOperatingSystem; - public string Version; + public UInt16[] BiosCharacteristics; + public string[] BIOSVersion; + public string BuildNumber; + public string Caption; + public string CodeSet; + public string CurrentLanguage; + public string Description; + public byte? EmbeddedControllerMajorVersion; + public byte? EmbeddedControllerMinorVersion; + public string IdentificationCode; + public UInt16? InstallableLanguages; + public DateTime? InstallDate; + public string LanguageEdition; + public string[] ListOfLanguages; + public string Manufacturer; + public string Name; + public string OtherTargetOS; + public bool? PrimaryBIOS; + public DateTime? ReleaseDate; + public string SerialNumber; + public string SMBIOSBIOSVersion; + public UInt16? SMBIOSMajorVersion; + public UInt16? SMBIOSMinorVersion; + public bool? SMBIOSPresent; + public UInt16? SoftwareElementState; + public string Status; + public byte? SystemBiosMajorVersion; + public byte? SystemBiosMinorVersion; + public UInt16? TargetOperatingSystem; + public string Version; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiComputerSystem { - public UInt16? AdminPasswordStatus; - public bool? AutomaticManagedPagefile; - public bool? AutomaticResetBootOption; - public bool? AutomaticResetCapability; - public UInt16? BootOptionOnLimit; - public UInt16? BootOptionOnWatchDog; - public bool? BootROMSupported; - public string BootupState; - public UInt16[] BootStatus; - public string Caption; - public UInt16? ChassisBootupState; - public string ChassisSKUNumber; - public Int16? CurrentTimeZone; - public bool? DaylightInEffect; - public string Description; - public string DNSHostName; - public string Domain; - public UInt16? DomainRole; - public bool? EnableDaylightSavingsTime; - public UInt16? FrontPanelResetStatus; - public bool? HypervisorPresent; - public bool? InfraredSupported; - public string InitialLoadInfo; - public DateTime? InstallDate; - public UInt16? KeyboardPasswordStatus; - public string LastLoadInfo; - public string Manufacturer; - public string Model; - public string Name; - public bool? NetworkServerModeEnabled; - public UInt32? NumberOfLogicalProcessors; - public UInt32? NumberOfProcessors; - public string[] OEMStringArray; - public bool? PartOfDomain; - public Int64? PauseAfterReset; - public UInt16? PCSystemType; - public UInt16? PCSystemTypeEx; - public UInt16[] PowerManagementCapabilities; - public bool? PowerManagementSupported; - public UInt16? PowerOnPasswordStatus; - public UInt16? PowerState; - public UInt16? PowerSupplyState; - public string PrimaryOwnerContact; - public string PrimaryOwnerName; - public UInt16? ResetCapability; - public Int16? ResetCount; - public Int16? ResetLimit; - public string[] Roles; - public string Status; - public string[] SupportContactDescription; - public string SystemFamily; - public string SystemSKUNumber; - public string SystemType; - public UInt16? ThermalState; - public UInt64? TotalPhysicalMemory; - public string UserName; - public UInt16? WakeUpType; - public string Workgroup; + public UInt16? AdminPasswordStatus; + public bool? AutomaticManagedPagefile; + public bool? AutomaticResetBootOption; + public bool? AutomaticResetCapability; + public UInt16? BootOptionOnLimit; + public UInt16? BootOptionOnWatchDog; + public bool? BootROMSupported; + public string BootupState; + public UInt16[] BootStatus; + public string Caption; + public UInt16? ChassisBootupState; + public string ChassisSKUNumber; + public Int16? CurrentTimeZone; + public bool? DaylightInEffect; + public string Description; + public string DNSHostName; + public string Domain; + public UInt16? DomainRole; + public bool? EnableDaylightSavingsTime; + public UInt16? FrontPanelResetStatus; + public bool? HypervisorPresent; + public bool? InfraredSupported; + public string InitialLoadInfo; + public DateTime? InstallDate; + public UInt16? KeyboardPasswordStatus; + public string LastLoadInfo; + public string Manufacturer; + public string Model; + public string Name; + public bool? NetworkServerModeEnabled; + public UInt32? NumberOfLogicalProcessors; + public UInt32? NumberOfProcessors; + public string[] OEMStringArray; + public bool? PartOfDomain; + public Int64? PauseAfterReset; + public UInt16? PCSystemType; + public UInt16? PCSystemTypeEx; + public UInt16[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public UInt16? PowerOnPasswordStatus; + public UInt16? PowerState; + public UInt16? PowerSupplyState; + public string PrimaryOwnerContact; + public string PrimaryOwnerName; + public UInt16? ResetCapability; + public Int16? ResetCount; + public Int16? ResetLimit; + public string[] Roles; + public string Status; + public string[] SupportContactDescription; + public string SystemFamily; + public string SystemSKUNumber; + public string SystemType; + public UInt16? ThermalState; + public UInt64? TotalPhysicalMemory; + public string UserName; + public UInt16? WakeUpType; + public string Workgroup; public PowerManagementCapabilities[] GetPowerManagementCapabilities() { @@ -1446,12 +1447,12 @@ namespace Microsoft.PowerShell.Commands internal class WmiDeviceGuard { public UInt32[] AvailableSecurityProperties; - public UInt32? CodeIntegrityPolicyEnforcementStatus; - public UInt32? UsermodeCodeIntegrityPolicyEnforcementStatus; + public UInt32? CodeIntegrityPolicyEnforcementStatus; + public UInt32? UsermodeCodeIntegrityPolicyEnforcementStatus; public UInt32[] RequiredSecurityProperties; public UInt32[] SecurityServicesConfigured; public UInt32[] SecurityServicesRunning; - public UInt32? VirtualizationBasedSecurityStatus; + public UInt32? VirtualizationBasedSecurityStatus; public DeviceGuard AsOutputType { @@ -1463,7 +1464,7 @@ namespace Microsoft.PowerShell.Commands if (status != null && status != DeviceGuardSmartStatus.Off) { var listHardware = new List(); - for (int i=0; i < RequiredSecurityProperties.Length; i++) + for (int i = 0; i < RequiredSecurityProperties.Length; i++) { var temp = EnumConverter.Convert((int?)RequiredSecurityProperties[i]); @@ -1471,9 +1472,9 @@ namespace Microsoft.PowerShell.Commands listHardware.Add(temp.Value); } guard.RequiredSecurityProperties = listHardware.ToArray(); - + listHardware.Clear(); - for (int i=0; i < AvailableSecurityProperties.Length; i++) + for (int i = 0; i < AvailableSecurityProperties.Length; i++) { var temp = EnumConverter.Convert((int?)AvailableSecurityProperties[i]); @@ -1483,7 +1484,7 @@ namespace Microsoft.PowerShell.Commands guard.AvailableSecurityProperties = listHardware.ToArray(); var listSoftware = new List(); - for (int i=0; i < SecurityServicesConfigured.Length; i++) + for (int i = 0; i < SecurityServicesConfigured.Length; i++) { var temp = EnumConverter.Convert((int?)SecurityServicesConfigured[i]); @@ -1493,7 +1494,7 @@ namespace Microsoft.PowerShell.Commands guard.SecurityServicesConfigured = listSoftware.ToArray(); listSoftware.Clear(); - for (int i=0; i < SecurityServicesRunning.Length; i++) + for (int i = 0; i < SecurityServicesRunning.Length; i++) { var temp = EnumConverter.Convert((int?)SecurityServicesRunning[i]); @@ -1519,28 +1520,28 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiKeyboard { - public UInt16? Availability; - public string Caption; - public UInt32? ConfigManagerErrorCode; - public bool? ConfigManagerUserConfig; - public string Description; - public string DeviceID; - public bool? ErrorCleared; - public string ErrorDescription; - public DateTime? InstallDate; - public bool? IsLocked; - public UInt32? LastErrorCode; - public string Layout; - public string Name; - public UInt16? NumberOfFunctionKeys; - public UInt16? Password; - public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; - public bool? PowerManagementSupported; - public string Status; - public UInt16? StatusInfo; - public string SystemCreationClassName; - public string SystemName; + public UInt16? Availability; + public string Caption; + public UInt32? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public DateTime? InstallDate; + public bool? IsLocked; + public UInt32? LastErrorCode; + public string Layout; + public string Name; + public UInt16? NumberOfFunctionKeys; + public UInt16? Password; + public string PNPDeviceID; + public UInt16[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string Status; + public UInt16? StatusInfo; + public string SystemCreationClassName; + public string SystemName; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] @@ -1553,264 +1554,264 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiMsftNetAdapter { - public string Caption; - public string Description; - public DateTime? InstallDate; - public string Name; - public string Status; - public UInt16? Availability; - public UInt32? ConfigManagerErrorCode; - public bool? ConfigManagerUserConfig; - public string DeviceID; - public bool? ErrorCleared; - public string ErrorDescription; - public UInt32? LastErrorCode; - public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; - public bool? PowerManagementSupported; - public UInt16? StatusInfo; - public string SystemCreationClassName; - public string SystemName; - public UInt64? Speed; - public UInt64? MaxSpeed; - public UInt64? RequestedSpeed; - public UInt16? UsageRestriction; - public UInt16? PortType; - public string OtherPortType; - public string OtherNetworkPortType; - public UInt16? PortNumber; - public UInt16? LinkTechnology; - public string OtherLinkTechnology; - public string PermanentAddress; - public string[] NetworkAddresses; - public bool? FullDuplex; - public bool? AutoSense; - public UInt64? SupportedMaximumTransmissionUnit; - public UInt64? ActiveMaximumTransmissionUnit; - public string InterfaceDescription; - public string InterfaceName; - public UInt64? NetLuid; - public string InterfaceGuid; - public UInt32? InterfaceIndex; - public string DeviceName; - public UInt32? NetLuidIndex; - public bool? Virtual; - public bool? Hidden; - public bool? NotUserRemovable; - public bool? IMFilter; - public UInt32? InterfaceType; - public bool? HardwareInterface; - public bool? WdmInterface; - public bool? EndPointInterface; - public bool? iSCSIInterface; - public UInt32? State; - public UInt32? NdisMedium; - public UInt32? NdisPhysicalMedium; - public UInt32? InterfaceOperationalStatus; - public bool? OperationalStatusDownDefaultPortNotAuthenticated; - public bool? OperationalStatusDownMediaDisconnected; - public bool? OperationalStatusDownInterfacePaused; - public bool? OperationalStatusDownLowPowerState; - public UInt32? InterfaceAdminStatus; - public UInt32? MediaConnectState; - public UInt32? MtuSize; - public UInt16? VlanID; - public UInt64? TransmitLinkSpeed; - public UInt64? ReceiveLinkSpeed; - public bool? PromiscuousMode; - public bool? DeviceWakeUpEnable; - public bool? ConnectorPresent; - public UInt32? MediaDuplexState; - public string DriverDate; - public UInt64? DriverDateData; - public string DriverVersionString; - public string DriverName; - public string DriverDescription; - public UInt16? MajorDriverVersion; - public UInt16? MinorDriverVersion; - public byte? DriverMajorNdisVersion; - public byte? DriverMinorNdisVersion; - public string PnPDeviceID; - public string DriverProvider; - public string ComponentID; - public UInt32[] LowerLayerInterfaceIndices; - public UInt32[] HigherLayerInterfaceIndices; - public bool? AdminLocked; + public string Caption; + public string Description; + public DateTime? InstallDate; + public string Name; + public string Status; + public UInt16? Availability; + public UInt32? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public UInt32? LastErrorCode; + public string PNPDeviceID; + public UInt16[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public UInt16? StatusInfo; + public string SystemCreationClassName; + public string SystemName; + public UInt64? Speed; + public UInt64? MaxSpeed; + public UInt64? RequestedSpeed; + public UInt16? UsageRestriction; + public UInt16? PortType; + public string OtherPortType; + public string OtherNetworkPortType; + public UInt16? PortNumber; + public UInt16? LinkTechnology; + public string OtherLinkTechnology; + public string PermanentAddress; + public string[] NetworkAddresses; + public bool? FullDuplex; + public bool? AutoSense; + public UInt64? SupportedMaximumTransmissionUnit; + public UInt64? ActiveMaximumTransmissionUnit; + public string InterfaceDescription; + public string InterfaceName; + public UInt64? NetLuid; + public string InterfaceGuid; + public UInt32? InterfaceIndex; + public string DeviceName; + public UInt32? NetLuidIndex; + public bool? Virtual; + public bool? Hidden; + public bool? NotUserRemovable; + public bool? IMFilter; + public UInt32? InterfaceType; + public bool? HardwareInterface; + public bool? WdmInterface; + public bool? EndPointInterface; + public bool? iSCSIInterface; + public UInt32? State; + public UInt32? NdisMedium; + public UInt32? NdisPhysicalMedium; + public UInt32? InterfaceOperationalStatus; + public bool? OperationalStatusDownDefaultPortNotAuthenticated; + public bool? OperationalStatusDownMediaDisconnected; + public bool? OperationalStatusDownInterfacePaused; + public bool? OperationalStatusDownLowPowerState; + public UInt32? InterfaceAdminStatus; + public UInt32? MediaConnectState; + public UInt32? MtuSize; + public UInt16? VlanID; + public UInt64? TransmitLinkSpeed; + public UInt64? ReceiveLinkSpeed; + public bool? PromiscuousMode; + public bool? DeviceWakeUpEnable; + public bool? ConnectorPresent; + public UInt32? MediaDuplexState; + public string DriverDate; + public UInt64? DriverDateData; + public string DriverVersionString; + public string DriverName; + public string DriverDescription; + public UInt16? MajorDriverVersion; + public UInt16? MinorDriverVersion; + public byte? DriverMajorNdisVersion; + public byte? DriverMinorNdisVersion; + public string PnPDeviceID; + public string DriverProvider; + public string ComponentID; + public UInt32[] LowerLayerInterfaceIndices; + public UInt32[] HigherLayerInterfaceIndices; + public bool? AdminLocked; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiNetworkAdapter { - public string AdapterType; - public UInt16? AdapterTypeID; - public bool? AutoSense; - public UInt16? Availability; - public string Caption; - public UInt32? ConfigManagerErrorCode; - public bool? ConfigManagerUserConfig; - public string Description; - public string DeviceID; - public bool? ErrorCleared; - public string ErrorDescription; - public string GUID; - public UInt32? Index; - public DateTime? InstallDate; - public bool? Installed; - public UInt32? InterfaceIndex; - public UInt32? LastErrorCode; - public string MACAddress; - public string Manufacturer; - public UInt32? MaxNumberControlled; - public UInt64? MaxSpeed; - public string Name; - public string NetConnectionID; - public UInt16? NetConnectionStatus; - public bool? NetEnabled; - public string[] NetworkAddresses; - public string PermanentAddress; - public bool? PhysicalAdapter; - public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; - public bool? PowerManagementSupported; - public string ProductName; - public string ServiceName; - public UInt64? Speed; - public string Status; - public UInt16? StatusInfo; - public string SystemCreationClassName; - public string SystemName; - public DateTime? TimeOfLastReset; + public string AdapterType; + public UInt16? AdapterTypeID; + public bool? AutoSense; + public UInt16? Availability; + public string Caption; + public UInt32? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public string GUID; + public UInt32? Index; + public DateTime? InstallDate; + public bool? Installed; + public UInt32? InterfaceIndex; + public UInt32? LastErrorCode; + public string MACAddress; + public string Manufacturer; + public UInt32? MaxNumberControlled; + public UInt64? MaxSpeed; + public string Name; + public string NetConnectionID; + public UInt16? NetConnectionStatus; + public bool? NetEnabled; + public string[] NetworkAddresses; + public string PermanentAddress; + public bool? PhysicalAdapter; + public string PNPDeviceID; + public UInt16[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string ProductName; + public string ServiceName; + public UInt64? Speed; + public string Status; + public UInt16? StatusInfo; + public string SystemCreationClassName; + public string SystemName; + public DateTime? TimeOfLastReset; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiNetworkAdapterConfiguration { - public bool? ArpAlwaysSourceRoute; - public bool? ArpUseEtherSNAP; - public string Caption; - public string DatabasePath; - public bool? DeadGWDetectEnabled; - public string[] DefaultIPGateway; - public byte? DefaultTOS; - public byte? DefaultTTL; - public string Description; - public bool? DHCPEnabled; - public DateTime? DHCPLeaseExpires; - public DateTime? DHCPLeaseObtained; - public string DHCPServer; - public string DNSDomain; - public string[] DNSDomainSuffixSearchOrder; - public bool? DNSEnabledForWINSResolution; - public string DNSHostName; - public string[] DNSServerSearchOrder; - public bool? DomainDNSRegistrationEnabled; - public UInt32? ForwardBufferMemory; - public bool? FullDNSRegistrationEnabled; - public UInt16[] GatewayCostMetric; - public byte? IGMPLevel; - public UInt32? Index; - public UInt32? InterfaceIndex; - public string[] IPAddress; - public UInt32? IPConnectionMetric; - public bool? IPEnabled; - public bool? IPFilterSecurityEnabled; - public bool? IPPortSecurityEnabled; - public string[] IPSecPermitIPProtocols; - public string[] IPSecPermitTCPPorts; - public string[] IPSecPermitUDPPorts; - public string[] IPSubnet; - public bool? IPUseZeroBroadcast; - public string IPXAddress; - public bool? IPXEnabled; - public UInt32[] IPXFrameType; - public UInt32? IPXMediaType; - public string[] IPXNetworkNumber; - public string IPXVirtualNetNumber; - public UInt32? KeepAliveInterval; - public UInt32? KeepAliveTime; - public string MACAddress; - public UInt32? MTU; - public UInt32? NumForwardPackets; - public bool? PMTUBHDetectEnabled; - public bool? PMTUDiscoveryEnabled; - public string ServiceName; - public string SettingID; - public UInt32? TcpipNetbiosOptions; - public UInt32? TcpMaxConnectRetransmissions; - public UInt32? TcpMaxDataRetransmissions; - public UInt32? TcpNumConnections; - public bool? TcpUseRFC1122UrgentPointer; - public UInt16? TcpWindowSize; - public bool? WINSEnableLMHostsLookup; - public string WINSHostLookupFile; - public string WINSPrimaryServer; - public string WINSScopeID; - public string WINSSecondaryServer; + public bool? ArpAlwaysSourceRoute; + public bool? ArpUseEtherSNAP; + public string Caption; + public string DatabasePath; + public bool? DeadGWDetectEnabled; + public string[] DefaultIPGateway; + public byte? DefaultTOS; + public byte? DefaultTTL; + public string Description; + public bool? DHCPEnabled; + public DateTime? DHCPLeaseExpires; + public DateTime? DHCPLeaseObtained; + public string DHCPServer; + public string DNSDomain; + public string[] DNSDomainSuffixSearchOrder; + public bool? DNSEnabledForWINSResolution; + public string DNSHostName; + public string[] DNSServerSearchOrder; + public bool? DomainDNSRegistrationEnabled; + public UInt32? ForwardBufferMemory; + public bool? FullDNSRegistrationEnabled; + public UInt16[] GatewayCostMetric; + public byte? IGMPLevel; + public UInt32? Index; + public UInt32? InterfaceIndex; + public string[] IPAddress; + public UInt32? IPConnectionMetric; + public bool? IPEnabled; + public bool? IPFilterSecurityEnabled; + public bool? IPPortSecurityEnabled; + public string[] IPSecPermitIPProtocols; + public string[] IPSecPermitTCPPorts; + public string[] IPSecPermitUDPPorts; + public string[] IPSubnet; + public bool? IPUseZeroBroadcast; + public string IPXAddress; + public bool? IPXEnabled; + public UInt32[] IPXFrameType; + public UInt32? IPXMediaType; + public string[] IPXNetworkNumber; + public string IPXVirtualNetNumber; + public UInt32? KeepAliveInterval; + public UInt32? KeepAliveTime; + public string MACAddress; + public UInt32? MTU; + public UInt32? NumForwardPackets; + public bool? PMTUBHDetectEnabled; + public bool? PMTUDiscoveryEnabled; + public string ServiceName; + public string SettingID; + public UInt32? TcpipNetbiosOptions; + public UInt32? TcpMaxConnectRetransmissions; + public UInt32? TcpMaxDataRetransmissions; + public UInt32? TcpNumConnections; + public bool? TcpUseRFC1122UrgentPointer; + public UInt16? TcpWindowSize; + public bool? WINSEnableLMHostsLookup; + public string WINSHostLookupFile; + public string WINSPrimaryServer; + public string WINSScopeID; + public string WINSSecondaryServer; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiOperatingSystem : WmiClassBase { #region Fields - public string BootDevice; - public string BuildNumber; - public string BuildType; - public string Caption; - public string CodeSet; - public string CountryCode; - public string CSDVersion; - public string CSName; - public Int16? CurrentTimeZone; - public bool? DataExecutionPrevention_Available; - public bool? DataExecutionPrevention_32BitApplications; - public bool? DataExecutionPrevention_Drivers; - public byte? DataExecutionPrevention_SupportPolicy; - public bool? Debug; - public string Description; - public bool? Distributed; - public UInt32? EncryptionLevel; - public byte? ForegroundApplicationBoost; - public UInt64? FreePhysicalMemory; - public UInt64? FreeSpaceInPagingFiles; - public UInt64? FreeVirtualMemory; - public DateTime? InstallDate; - public DateTime? LastBootUpTime; - public DateTime? LocalDateTime; - public string Locale; - public string Manufacturer; - public UInt32? MaxNumberOfProcesses; - public UInt64? MaxProcessMemorySize; - public string[] MUILanguages; - public string Name; - public UInt32? NumberOfLicensedUsers; - public UInt32? NumberOfProcesses; - public UInt32? NumberOfUsers; - public UInt32? OperatingSystemSKU; - public string Organization; - public string OSArchitecture; - public UInt32? OSLanguage; - public UInt32? OSProductSuite; - public UInt16? OSType; - public string OtherTypeDescription; - public bool? PAEEnabled; - public bool? PortableOperatingSystem; - public bool? Primary; - public UInt32? ProductType; - public string RegisteredUser; - public string SerialNumber; - public UInt16? ServicePackMajorVersion; - public UInt16? ServicePackMinorVersion; - public UInt64? SizeStoredInPagingFiles; - public string Status; - public UInt32? SuiteMask; - public string SystemDevice; - public string SystemDirectory; - public string SystemDrive; - public UInt64? TotalSwapSpaceSize; - public UInt64? TotalVirtualMemorySize; - public UInt64? TotalVisibleMemorySize; - public string Version; - public string WindowsDirectory; + public string BootDevice; + public string BuildNumber; + public string BuildType; + public string Caption; + public string CodeSet; + public string CountryCode; + public string CSDVersion; + public string CSName; + public Int16? CurrentTimeZone; + public bool? DataExecutionPrevention_Available; + public bool? DataExecutionPrevention_32BitApplications; + public bool? DataExecutionPrevention_Drivers; + public byte? DataExecutionPrevention_SupportPolicy; + public bool? Debug; + public string Description; + public bool? Distributed; + public UInt32? EncryptionLevel; + public byte? ForegroundApplicationBoost; + public UInt64? FreePhysicalMemory; + public UInt64? FreeSpaceInPagingFiles; + public UInt64? FreeVirtualMemory; + public DateTime? InstallDate; + public DateTime? LastBootUpTime; + public DateTime? LocalDateTime; + public string Locale; + public string Manufacturer; + public UInt32? MaxNumberOfProcesses; + public UInt64? MaxProcessMemorySize; + public string[] MUILanguages; + public string Name; + public UInt32? NumberOfLicensedUsers; + public UInt32? NumberOfProcesses; + public UInt32? NumberOfUsers; + public UInt32? OperatingSystemSKU; + public string Organization; + public string OSArchitecture; + public UInt32? OSLanguage; + public UInt32? OSProductSuite; + public UInt16? OSType; + public string OtherTypeDescription; + public bool? PAEEnabled; + public bool? PortableOperatingSystem; + public bool? Primary; + public UInt32? ProductType; + public string RegisteredUser; + public string SerialNumber; + public UInt16? ServicePackMajorVersion; + public UInt16? ServicePackMinorVersion; + public UInt64? SizeStoredInPagingFiles; + public string Status; + public UInt32? SuiteMask; + public string SystemDevice; + public string SystemDirectory; + public string SystemDrive; + public UInt64? TotalSwapSpaceSize; + public UInt64? TotalVirtualMemorySize; + public UInt64? TotalVisibleMemorySize; + public string Version; + public string WindowsDirectory; #endregion Fields #region Public Properties @@ -1863,75 +1864,75 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiPageFileUsage { - public UInt32? AllocatedBaseSize; - public string Caption; - public UInt32? CurrentUsage; - public string Description; - public DateTime? InstallDate; - public string Name; - public UInt32? PeakUsage; - public string Status; - public bool? TempPageFile; + public UInt32? AllocatedBaseSize; + public string Caption; + public UInt32? CurrentUsage; + public string Description; + public DateTime? InstallDate; + public string Name; + public UInt32? PeakUsage; + public string Status; + public bool? TempPageFile; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] internal class WmiProcessor { - public UInt16? AddressWidth; - public UInt16? Architecture; - public string AssetTag; - public UInt16? Availability; - public string Caption; - public UInt32? Characteristics; - public UInt32? ConfigManagerErrorCode; - public bool? ConfigManagerUserConfig; - public UInt16? CpuStatus; - public UInt32? CurrentClockSpeed; - public UInt16? CurrentVoltage; - public UInt16? DataWidth; - public string Description; - public string DeviceID; - public bool? ErrorCleared; - public string ErrorDescription; - public UInt32? ExtClock; - public UInt16? Family; - public DateTime? InstallDate; - public UInt32? L2CacheSize; - public UInt32? L2CacheSpeed; - public UInt32? L3CacheSize; - public UInt32? L3CacheSpeed; - public UInt32? LastErrorCode; - public UInt16? Level; - public UInt16? LoadPercentage; - public string Manufacturer; - public UInt32? MaxClockSpeed; - public string Name; - public UInt32? NumberOfCores; - public UInt32? NumberOfEnabledCore; - public UInt32? NumberOfLogicalProcessors; - public string OtherFamilyDescription; - public string PartNumber; - public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; - public bool? PowerManagementSupported; - public string ProcessorId; - public UInt16? ProcessorType; - public UInt16? Revision; - public string Role; - public bool? SecondLevelAddressTranslationExtensions; - public string SerialNumber; - public string SocketDesignation; - public string Status; - public UInt16? StatusInfo; - public string Stepping; - public string SystemName; - public UInt32? ThreadCount; - public string UniqueId; - public UInt16? UpgradeMethod; - public string Version; - public bool? VirtualizationFirmwareEnabled; - public bool? VMMonitorModeExtensions; - public UInt32? VoltageCaps; + public UInt16? AddressWidth; + public UInt16? Architecture; + public string AssetTag; + public UInt16? Availability; + public string Caption; + public UInt32? Characteristics; + public UInt32? ConfigManagerErrorCode; + public bool? ConfigManagerUserConfig; + public UInt16? CpuStatus; + public UInt32? CurrentClockSpeed; + public UInt16? CurrentVoltage; + public UInt16? DataWidth; + public string Description; + public string DeviceID; + public bool? ErrorCleared; + public string ErrorDescription; + public UInt32? ExtClock; + public UInt16? Family; + public DateTime? InstallDate; + public UInt32? L2CacheSize; + public UInt32? L2CacheSpeed; + public UInt32? L3CacheSize; + public UInt32? L3CacheSpeed; + public UInt32? LastErrorCode; + public UInt16? Level; + public UInt16? LoadPercentage; + public string Manufacturer; + public UInt32? MaxClockSpeed; + public string Name; + public UInt32? NumberOfCores; + public UInt32? NumberOfEnabledCore; + public UInt32? NumberOfLogicalProcessors; + public string OtherFamilyDescription; + public string PartNumber; + public string PNPDeviceID; + public UInt16[] PowerManagementCapabilities; + public bool? PowerManagementSupported; + public string ProcessorId; + public UInt16? ProcessorType; + public UInt16? Revision; + public string Role; + public bool? SecondLevelAddressTranslationExtensions; + public string SerialNumber; + public string SocketDesignation; + public string Status; + public UInt16? StatusInfo; + public string Stepping; + public string SystemName; + public UInt32? ThreadCount; + public string UniqueId; + public UInt16? UpgradeMethod; + public string Version; + public bool? VirtualizationFirmwareEnabled; + public bool? VMMonitorModeExtensions; + public UInt32? VoltageCaps; } #pragma warning restore 649 @@ -1974,12 +1975,12 @@ namespace Microsoft.PowerShell.Commands /// Indicates which security services have been configured /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public DeviceGuardSoftwareSecure[] SecurityServicesConfigured { get; internal set; } + public DeviceGuardSoftwareSecure[] SecurityServicesConfigured { get; internal set; } /// /// Indicates which security services are running /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public DeviceGuardSoftwareSecure[] SecurityServicesRunning { get; internal set; } + public DeviceGuardSoftwareSecure[] SecurityServicesRunning { get; internal set; } /// /// Indicates the status of the Device Guard Code Integrity policy /// @@ -2079,15 +2080,15 @@ namespace Microsoft.PowerShell.Commands /// /// Name of the processor /// - public string Name { get; internal set; } + public string Name { get; internal set; } /// /// Name of the processor manufacturer /// - public string Manufacturer { get; internal set; } + public string Manufacturer { get; internal set; } /// /// Description of the processor /// - public string Description { get; internal set; } + public string Description { get; internal set; } /// /// Processor architecture used by the platform /// @@ -2136,11 +2137,11 @@ namespace Microsoft.PowerShell.Commands /// and contain the contents of the DX register at CPU reset—all others are set /// to 0 (zero), and the contents are in DWORD format /// - public string ProcessorID { get; internal set; } + public string ProcessorID { get; internal set; } /// /// Type of chip socket used on the circuit /// - public string SocketDesignation { get; internal set; } + public string SocketDesignation { get; internal set; } /// /// Primary function of the processor /// @@ -2148,11 +2149,11 @@ namespace Microsoft.PowerShell.Commands /// /// Role of the processor /// - public string Role { get; internal set; } + public string Role { get; internal set; } /// /// Current status of the processor /// - public string Status { get; internal set; } + public string Status { get; internal set; } /// /// Current status of the processor. /// Status changes indicate processor usage, but not the physical @@ -2180,42 +2181,42 @@ namespace Microsoft.PowerShell.Commands /// Windows version number, from the Windows Registry. /// public string WindowsCurrentVersion { get; internal set; } - + /// /// Windows edition, from the Windows Registry. /// public string WindowsEditionId { get; internal set; } - + /// /// Windows installation type, from the Windows Registry. /// public string WindowsInstallationType { get; internal set; } - + /// /// The data Windows was installed, from the Windows Registry. /// public DateTime? WindowsInstallDateFromRegistry { get; internal set; } - + /// /// The Windows product ID, from the Windows Registry. /// public string WindowsProductId { get; internal set; } - + /// /// The Windows product name, from the Windows Registry. /// public string WindowsProductName { get; internal set; } - + /// /// Name of the organization that this installation of Windows is registered to, from the Windows Registry. /// public string WindowsRegisteredOrganization { get; internal set; } - + /// /// Name of the registered owner of this installation of Windows, from the Windows Registry. /// public string WindowsRegisteredOwner { get; internal set; } - + /// /// Path to the operating system's root directory, from the Windows Registry. /// @@ -2237,32 +2238,32 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] BiosBIOSVersion { get; internal set; } - + /// /// Internal identifier for this compilation of the BIOS firmware /// public string BiosBuildNumber { get; internal set; } - + /// /// Short description of the BIOS. /// public string BiosCaption { get; internal set; } - + /// /// Code set used by the BIOS /// public string BiosCodeSet { get; internal set; } - + /// /// Name of the current BIOS language /// public string BiosCurrentLanguage { get; internal set; } - + /// /// Description of the BIOS /// public string BiosDescription { get; internal set; } - + /// /// Major version of the embedded controller firmware /// @@ -2280,7 +2281,7 @@ namespace Microsoft.PowerShell.Commands /// This is acquired via the GetFirmwareType Windows API function /// public FirmwareType? BiosFirmwareType { get; internal set; } - + /// /// Manufacturer's identifier for this software element. /// Often this will be a stock keeping unit (SKU) or a part number @@ -2291,14 +2292,14 @@ namespace Microsoft.PowerShell.Commands /// Number of languages available for installation on this system. /// Language may determine properties such as the need for Unicode and bidirectional text /// - public UInt16? BiosInstallableLanguages {get; internal set; } - + public UInt16? BiosInstallableLanguages { get; internal set; } + /// /// Date and time the object was installed. /// //TODO: do we want this? On my system this is null public DateTime? BiosInstallDate { get; internal set; } - + /// /// Language edition of the BIOS firmware. /// The language codes defined in ISO 639 should be used. @@ -2312,17 +2313,17 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] BiosListOfLanguages { get; internal set; } - + /// /// Manufacturer of the BIOS /// public string BiosManufacturer { get; internal set; } - + /// /// Name used to identify the BIOS /// public string BiosName { get; internal set; } - + /// /// Records the manufacturer and operating system type for the BIOS when /// the BiosTargetOperatingSystem property has a value of 1 (Other). @@ -2331,17 +2332,17 @@ namespace Microsoft.PowerShell.Commands /// BiosOtherTargetOS is NULL /// public string BiosOtherTargetOS { get; internal set; } - + /// /// If true, this is the primary BIOS of the computer system /// public bool? BiosPrimaryBIOS { get; internal set; } - + /// /// Release date of the Windows BIOS /// public DateTime? BiosReleaseDate { get; internal set; } - + /// /// Assigned serial number of the BIOS /// @@ -2361,7 +2362,7 @@ namespace Microsoft.PowerShell.Commands /// SMBIOS minor version number. This property is null if SMBIOS is not found /// public UInt16? BiosSMBIOSMinorVersion { get; internal set; } - + /// /// If true, the SMBIOS is available on this computer system /// @@ -2371,12 +2372,12 @@ namespace Microsoft.PowerShell.Commands /// State of a BIOS software element /// public SoftwareElementState? BiosSoftwareElementState { get; internal set; } - + /// /// Status of the BIOS /// public string BiosStatus { get; internal set; } - + /// /// Major elease of the System BIOS /// @@ -2386,12 +2387,12 @@ namespace Microsoft.PowerShell.Commands /// Minor release of the System BIOS /// public UInt16? BiosSystemBiosMinorVersion { get; internal set; } - + /// /// Target operating system /// public UInt16? BiosTargetOperatingSystem { get; internal set; } - + /// /// Version of the BIOS. /// This string is created by the BIOS manufacturer @@ -2405,33 +2406,33 @@ namespace Microsoft.PowerShell.Commands /// //public AdminPasswordStatus? CsAdminPasswordStatus { get; internal set; } public HardwareSecurity? CsAdminPasswordStatus { get; internal set; } - + /// /// If true, the system manages the page file /// public bool? CsAutomaticManagedPagefile { get; internal set; } - + /// /// If True, the automatic reset boot option is enabled /// public bool? CsAutomaticResetBootOption { get; internal set; } - + /// /// If True, the automatic reset is enabled /// public bool? CsAutomaticResetCapability { get; internal set; } - + /// /// Boot option limit is ON. Identifies the system action when the /// CsResetLimit value is reached /// public BootOptionAction? CsBootOptionOnLimit { get; internal set; } - + /// /// Type of reboot action after the time on the watchdog timer is elapsed /// public BootOptionAction? CsBootOptionOnWatchDog { get; internal set; } - + /// /// If true, indicates whether a boot ROM is supported /// @@ -2442,49 +2443,49 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public UInt16[] CsBootStatus { get; internal set; } - + /// /// System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot /// public string CsBootupState { get; internal set; } - + /// /// The name of this computer /// public string CsCaption { get; internal set; } //TODO: remove this? Same as CsName??? - + /// /// Boot up state of the chassis /// //public ChassisBootupState? CsChassisBootupState { get; internal set; } public SystemElementState? CsChassisBootupState { get; internal set; } - + /// /// The chassis or enclosure SKU number as a string /// public string CsChassisSKUNumber { get; internal set; } - + /// /// Amount of time the unitary computer system is offset from Coordinated /// Universal Time (UTC). /// public Int16? CsCurrentTimeZone { get; internal set; } - + /// /// If True, the daylight savings mode is ON /// public bool? CsDaylightInEffect { get; internal set; } - + /// /// Description of the computer system /// public string CsDescription { get; internal set; } - + /// /// Name of local computer according to the domain name server /// public string CsDNSHostName { get; internal set; } - + /// /// Name of the domain to which a computer belongs. /// @@ -2492,14 +2493,14 @@ namespace Microsoft.PowerShell.Commands /// If the computer is not part of a domain, then the name of the workgroup is returned /// public string CsDomain { get; internal set; } - + /// /// Role of a computer in an assigned domain workgroup. A domain workgroup /// is a collection of computers on the same network. For example, /// a DomainRole property may show that a computer is a member workstation /// public DomainRole? CsDomainRole { get; internal set; } - + /// /// Enables daylight savings time on a computer. A value of True indicates /// that the system time changes to an hour ahead or behind when DST starts @@ -2508,55 +2509,55 @@ namespace Microsoft.PowerShell.Commands /// indicates that the DST status is unknown on a system. /// public bool? CsEnableDaylightSavingsTime { get; internal set; } - + /// /// Hardware security setting for the reset button on a computer /// //public FrontPanelResetStatus? CsFrontPanelResetStatus { get; internal set; } public HardwareSecurity? CsFrontPanelResetStatus { get; internal set; } - + /// /// If True, a hypervisor is present /// public bool? CsHypervisorPresent { get; internal set; } - + /// /// If True, an infrared port exists on a computer system /// public bool? CsInfraredSupported { get; internal set; } - + /// /// Data required to find the initial load device or boot service to request that the operating system start up /// public string CsInitialLoadInfo { get; internal set; } - + /// /// Object is installed. An object does not need a value to indicate that it is installed /// public DateTime? CsInstallDate { get; internal set; } - + /// /// System hardware security setting for Keyboard Password Status /// //public KeyboardPasswordStatus? CsKeyboardPasswordStatus { get; internal set; } public HardwareSecurity? CsKeyboardPasswordStatus { get; internal set; } - + /// /// Array entry of the CsInitialLoadInfo property that contains the data /// to start the loaded operating system /// public string CsLastLoadInfo { get; internal set; } - + /// /// Name of the computer manufacturer /// public string CsManufacturer { get; internal set; } - + /// /// Product name that a manufacturer gives to a computer /// public string CsModel { get; internal set; } - + /// /// Key of a CIM_System instance in an enterprise environment /// @@ -2568,17 +2569,17 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public NetworkAdapter[] CsNetworkAdapters { get; internal set; } - + /// /// If True, the network Server Mode is enabled /// public bool? CsNetworkServerModeEnabled { get; internal set; } - + /// /// Number of logical processors available on the computer /// public UInt32? CsNumberOfLogicalProcessors { get; internal set; } - + /// /// Number of physical processors currently available on a system. /// @@ -2604,13 +2605,13 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CsOEMStringArray { get; internal set; } - + /// /// If True, the computer is part of a domain. /// If the value is NULL, the computer is not in a domain or the status is unknown /// public bool? CsPartOfDomain { get; internal set; } - + /// /// Time delay before a reboot is initiated, in milliseconds. /// It is used after a system power cycle, local or remote system reset, @@ -2618,12 +2619,12 @@ namespace Microsoft.PowerShell.Commands /// the pause value is unknown /// public Int64? CsPauseAfterReset { get; internal set; } - + /// /// Type of the computer in use, such as laptop, desktop, or tablet /// public PCSystemType? CsPCSystemType { get; internal set; } - + /// /// Type of the computer in use, such as laptop, desktop, or tablet. /// @@ -2634,7 +2635,7 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PowerManagementCapabilities[] CsPowerManagementCapabilities { get; internal set; } - + /// /// If True, device can be power-managed, for example, a device can be /// put into suspend mode, and so on. @@ -2651,40 +2652,40 @@ namespace Microsoft.PowerShell.Commands /// //public PowerOnPasswordStatus? CsPowerOnPasswordStatus { get; internal set; } public HardwareSecurity? CsPowerOnPasswordStatus { get; internal set; } - + /// /// Current power state of a computer and its associated operating system. /// public PowerState? CsPowerState { get; internal set; } - + /// /// State of the power supply or supplies when last booted /// //public PowerSupplyState? CsPowerSupplyState { get; internal set; } public SystemElementState? CsPowerSupplyState { get; internal set; } - + /// /// Contact information for the primary system owner. /// For example, phone number, email address, and so on /// public string CsPrimaryOwnerContact { get; internal set; } - + /// /// Name of the primary system owner /// public string CsPrimaryOwnerName { get; internal set; } - + /// /// Indicates if the computer system can be resut. /// public ResetCapability? CsResetCapability { get; internal set; } - + /// /// Number of automatic resets since the last reset. /// A value of –1 (minus one) indicates that the count is unknown /// public Int16? CsResetCount { get; internal set; } - + /// /// Number of consecutive times a system reset is attempted. /// A value of –1 (minus one) indicates that the limit is unknown @@ -2697,7 +2698,7 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CsRoles { get; internal set; } - + /// /// Statis pf the computer system /// @@ -2708,31 +2709,31 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CsSupportContactDescription { get; internal set; } - + /// /// The family to which a particular computer belongs. /// A family refers to a set of computers that are similar but not /// identical from a hardware or software point of view /// public string CsSystemFamily { get; internal set; } - + /// /// Identifies a particular computer configuration for sale. /// It is sometimes also called a product ID or purchase order number /// public string CsSystemSKUNumber { get; internal set; } - + /// /// System running on the Windows-based computer /// public string CsSystemType { get; internal set; } - + /// /// Thermal state of the system when last booted /// //public ThermalState? CsThermalState { get; internal set; } public SystemElementState? CsThermalState { get; internal set; } - + /// /// Total size of physical memory. /// @@ -2742,13 +2743,13 @@ namespace Microsoft.PowerShell.Commands /// it is not accurate if the BIOS is using some of the physical memory /// public UInt64? CsTotalPhysicalMemory { get; internal set; } - + /// /// Size of physically installed memory, as reported by the Windows API /// function GetPhysicallyInstalledSystemMemory /// public UInt64? CsPhyicallyInstalledMemory { get; internal set; } - + /// /// Name of a user that is logged on currently. /// @@ -2758,12 +2759,12 @@ namespace Microsoft.PowerShell.Commands /// terminal service session /// public string CsUserName { get; internal set; } - + /// /// Event that causes the system to power up /// public WakeUpType? CsWakeUpType { get; internal set; } - + /// /// Name of the workgroup for this computer /// @@ -2780,12 +2781,12 @@ namespace Microsoft.PowerShell.Commands /// Type of operating system /// public OSType? OsType { get; internal set; } - + /// /// SKU number for the operating system /// public OperatingSystemSKU? OsOperatingSystemSKU { get; internal set; } - + /// /// Version number of the operating system /// @@ -2796,7 +2797,7 @@ namespace Microsoft.PowerShell.Commands /// If no service pack is installed, the string is NULL /// public string OsCSDVersion { get; internal set; } - + /// /// Build number of the operating system /// @@ -2819,22 +2820,22 @@ namespace Microsoft.PowerShell.Commands /// Physical disk partition on which the operating system is installed /// public string OsSystemDevice { get; internal set; } - + /// /// System directory of the operating system /// public string OsSystemDirectory { get; internal set; } - + /// /// Letter of the disk drive on which the operating system resides /// public string OsSystemDrive { get; internal set; } - + /// /// Windows directory of the operating system /// public string OsWindowsDirectory { get; internal set; } - + /// /// Code for the country/region that an operating system uses /// @@ -2843,13 +2844,13 @@ namespace Microsoft.PowerShell.Commands /// referred to as IBM country/region codes /// public string OsCountryCode { get; internal set; } - + /// /// Number, in minutes, an operating system is offset from Greenwich /// mean time (GMT). The number is positive, negative, or zero /// public Int16? OsCurrentTimeZone { get; internal set; } - + /// /// Language identifier used by the operating system. /// @@ -2860,33 +2861,33 @@ namespace Microsoft.PowerShell.Commands /// language identifier /// public string OsLocaleID { get; internal set; } // From Win32_OperatingSystem.Locale - + /// /// The culture name, such as "en-US", derived from the property /// public string OsLocale { get; internal set; } - + /// /// Operating system version of the local date and time-of-day /// public DateTime? OsLocalDateTime { get; internal set; } - + /// /// Date and time the operating system was last restarted /// public DateTime? OsLastBootUpTime { get; internal set; } - + /// /// The interval between the time the operating system was last /// restarted and the current time /// public TimeSpan? OsUptime { get; internal set; } - + /// /// Type of build used for the operating system /// public string OsBuildType { get; internal set; } - + /// /// Code page value the operating system uses /// @@ -2903,42 +2904,42 @@ namespace Microsoft.PowerShell.Commands /// applications if true /// public bool? OsDataExecutionPrevention32BitApplications { get; internal set; } - + /// /// When the data execution prevention hardware feature is available, /// this property indicates that the feature is set to work for drivers /// if true /// public bool? OsDataExecutionPreventionDrivers { get; internal set; } - + /// /// Indicates which Data Execution Prevention (DEP) setting is applied. /// The DEP setting specifies the extent to which DEP applies to 32-bit /// applications on the system. DEP is always applied to the Windows kernel /// public DataExecutionPreventionSupportPolicy? OsDataExecutionPreventionSupportPolicy { get; internal set; } - + /// /// If true, the operating system is a checked (debug) build /// public bool? OsDebug { get; internal set; } - + /// /// If True, the operating system is distributed across several computer /// system nodes. If so, these nodes should be grouped as a cluster /// public bool? OsDistributed { get; internal set; } - + /// /// Encryption level for secure transactions: 40-bit, 128-bit, or n-bit. /// public OSEncryptionLevel? OsEncryptionLevel { get; internal set; } - + /// /// Increased priority given to the foreground application /// public ForegroundApplicationBoost? OsForegroundApplicationBoost { get; internal set; } - + /// /// Total amount, in kilobytes, of physical memory available to the /// operating system. @@ -2949,27 +2950,27 @@ namespace Microsoft.PowerShell.Commands /// as available to it. /// public UInt64? OsTotalVisibleMemorySize { get; internal set; } - + /// /// Number, in kilobytes, of physical memory currently unused and available /// public UInt64? OsFreePhysicalMemory { get; internal set; } - + /// /// Number, in kilobytes, of virtual memory /// public UInt64? OsTotalVirtualMemorySize { get; internal set; } - + /// /// Number, in kilobytes, of virtual memory currently unused and available /// public UInt64? OsFreeVirtualMemory { get; internal set; } - + /// /// Number, in kilobytes, of virtual memory currently in use /// public UInt64? OsInUseVirtualMemory { get; internal set; } - + /// /// Total swap space in kilobytes /// @@ -2981,7 +2982,7 @@ namespace Microsoft.PowerShell.Commands /// a specified amount /// public UInt64? OsTotalSwapSpaceSize { get; internal set; } - + /// /// Total number of kilobytes that can be stored in the operating system /// paging files—0 (zero) indicates that there are no paging files. @@ -2989,7 +2990,7 @@ namespace Microsoft.PowerShell.Commands /// size of the paging file on disk /// public UInt64? OsSizeStoredInPagingFiles { get; internal set; } - + /// /// Number, in kilobytes, that can be mapped into the operating system /// paging files without causing any other pages to be swapped out @@ -3001,28 +3002,28 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] OsPagingFiles { get; internal set; } - + /// /// Version of the operating system's Hardware Abstraction Layer (HAL) /// public string OsHardwareAbstractionLayer { get; internal set; } - + /// /// Indicates the install date /// public DateTime? OsInstallDate { get; internal set; } - + /// /// Name of the operating system manufacturer. /// For Windows-based systems, this value is "Microsoft Corporation" /// public string OsManufacturer { get; internal set; } - + /// /// Maximum number of process contexts the operating system can support /// public UInt32? OsMaxNumberOfProcesses { get; internal set; } - + /// /// Maximum number, in kilobytes, of memory that can be allocated to a process /// @@ -3034,33 +3035,33 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] OsMuiLanguages { get; internal set; } - + /// /// Number of user licenses for the operating system. /// public UInt32? OsNumberOfLicensedUsers { get; internal set; } - + /// /// Number of process contexts currently loaded or running on the operating system /// public UInt32? OsNumberOfProcesses { get; internal set; } - + /// /// Number of user sessions for which the operating system is storing /// state information currently /// public UInt32? OsNumberOfUsers { get; internal set; } - + /// /// Company name for the registered user of the operating system /// public string OsOrganization { get; internal set; } - + /// /// Architecture of the operating system, as opposed to the processor /// public string OsArchitecture { get; internal set; } - + /// /// Language version of the operating system installed /// @@ -3072,45 +3073,45 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public OSProductSuite[] OsProductSuites { get; internal set; } - + /// /// Additional description for the current operating system version /// public string OsOtherTypeDescription { get; internal set; } - + /// /// If True, the physical address extensions (PAE) are enabled by the /// operating system running on Intel processors /// public bool? OsPAEEnabled { get; internal set; } - + /// /// Specifies whether the operating system booted from an external USB device. /// If true, the operating system has detected it is booting on a supported /// locally connected storage device /// public bool? OsPortableOperatingSystem { get; internal set; } - + /// /// Specifies whether this is the primary operating system /// public bool? OsPrimary { get; internal set; } - + /// /// Additional system information /// public ProductType? OsProductType { get; internal set; } - + /// /// Name of the registered user of the operating system /// public string OsRegisteredUser { get; internal set; } - + /// /// Operating system product serial identification number /// public string OsSerialNumber { get; internal set; } - + /// /// Major version of the service pack installed on the computer system /// @@ -3120,7 +3121,7 @@ namespace Microsoft.PowerShell.Commands /// Minor version of the service pack installed on the computer system /// public UInt16? OsServicePackMinorVersion { get; internal set; } - + /// /// Current status /// @@ -3131,7 +3132,7 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public OSProductSuite[] OsSuites { get; internal set; } - + /// /// Server level of the operating system, if the operating system is a server /// @@ -3148,49 +3149,49 @@ namespace Microsoft.PowerShell.Commands /// Name of the system's current time zone /// public string TimeZone { get; internal set; } - + /// /// Path to the system's logon server /// public string LogonServer { get; internal set; } - + /// /// Power platform role /// public PowerPlatformRole? PowerPlatformRole { get; internal set; } - + /// /// If true, a HyperVisor was detected /// public bool? HyperVisorPresent { get; internal set; } - + /// /// If a HyperVisor is not present, indicates the state of the /// requirement that the Data Execution Prevention feature is available /// public bool? HyperVRequirementDataExecutionPreventionAvailable { get; internal set; } - + /// /// If a HyperVisor is not present, indicates the state of the /// requirement that the processor supports address translation /// extensions used for virtualization /// public bool? HyperVRequirementSecondLevelAddressTranslation { get; internal set; } - + /// /// If a HyperVisor is not present, indicates the state of the /// requirement that the firmware has enabled virtualization /// extensions /// public bool? HyperVRequirementVirtualizationFirmwareEnabled { get; internal set; } - + /// /// If a HyperVisor is not present, indicates the state of the /// requirement that the processor supports Intel or AMD Virtual /// Machine Monitor extensions /// public bool? HyperVRequirementVMMonitorModeExtensions { get; internal set; } - + /// /// Indicates the status of the Device Guard features /// @@ -3224,7 +3225,7 @@ namespace Microsoft.PowerShell.Commands /// Status of the Device Guard Code Integrity policy enforcement /// public DeviceGuardConfigCodeIntegrityStatus? DeviceGuardCodeIntegrityPolicyEnforcementStatus { get; internal set; } - + /// /// Status of the Device Guard user mode Code Integrity policy enforcement /// @@ -3536,12 +3537,12 @@ namespace Microsoft.PowerShell.Commands /// /// DEP is turned off for all 32-bit applications on the computer with no exceptions /// - AlwaysOff = 0, + AlwaysOff = 0, /// /// DEP is enabled for all 32-bit applications on the computer /// - AlwaysOn = 1, + AlwaysOn = 1, /// /// DEP is enabled for a limited number of binaries, the kernel, and all @@ -3550,14 +3551,14 @@ namespace Microsoft.PowerShell.Commands /// the Always On or the Opt Out setting before DEP can be applied to /// 32-bit applications /// - OptIn = 2, + OptIn = 2, /// /// DEP is enabled by default for all 32-bit applications. A user or /// administrator can explicitly remove support for a 32-bit /// application by adding the application to an exceptions list /// - OptOut = 3 + OptOut = 3 } /// @@ -3611,22 +3612,22 @@ namespace Microsoft.PowerShell.Commands /// /// Base Virtualization Support /// - BaseVirtualizationSupport = 1, + BaseVirtualizationSupport = 1, /// /// Secure Boot /// - SecureBoot = 2, + SecureBoot = 2, /// /// DMA Protection /// - DMAProtection = 3, + DMAProtection = 3, /// /// Secure Memory Overwrite /// - SecureMemoryOverwrite = 4 + SecureMemoryOverwrite = 4 } /// @@ -3690,22 +3691,22 @@ namespace Microsoft.PowerShell.Commands /// /// The firmware type is unknown /// - Unknown = 0, + Unknown = 0, /// /// The computer booted in legacy BIOS mode /// - Bios = 1, + Bios = 1, /// /// The computer booted in UEFI mode /// - Uefi = 2, + Uefi = 2, /// /// Not implemented /// - Max = 3 + Max = 3 } /// @@ -3716,7 +3717,7 @@ namespace Microsoft.PowerShell.Commands /// /// The system boosts the quantum length by 6 /// - None = 0, + None = 0, /// /// The system boosts the quantum length by 12 @@ -3865,17 +3866,17 @@ namespace Microsoft.PowerShell.Commands /// /// 40-bit encription /// - Encrypt40Bits = 0, + Encrypt40Bits = 0, /// /// 128-bit encription /// - Encrypt128Bits = 1, + Encrypt128Bits = 1, /// /// n-bit encription /// - EncryptNBits = 2 + EncryptNBits = 2 } /// @@ -3883,74 +3884,74 @@ namespace Microsoft.PowerShell.Commands /// [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "The underlying MOF definition does not contain a zero value. The converter method will handle it appropriately.")] [FlagsAttribute] - public enum OSProductSuite + public enum OSProductSuite { /// /// Microsoft Small Business Server was once installed, but may have /// been upgraded to another version of Windows /// - SmallBusinessServer = 0x0001, + SmallBusinessServer = 0x0001, /// /// Windows Server 2008 Enterprise is installed /// - Server2008Enterprise = 0x0002, + Server2008Enterprise = 0x0002, /// /// Windows BackOffice components are installed /// - BackOfficeComponents = 0x0004, + BackOfficeComponents = 0x0004, /// /// Communication Server is installed /// - CommunicationsServer = 0x0008, + CommunicationsServer = 0x0008, /// /// Terminal Services is installed /// - TerminalServices = 0x0010, + TerminalServices = 0x0010, /// /// Microsoft Small Business Server is installed with the restrictive /// client license /// - SmallBusinessServerRestricted = 0x0020, + SmallBusinessServerRestricted = 0x0020, /// /// Windows Embedded is installed /// - WindowsEmbedded = 0x0040, + WindowsEmbedded = 0x0040, /// /// A Datacenter edition is installed /// - DatacenterEdition = 0x0080, + DatacenterEdition = 0x0080, /// /// Terminal Services is installed, but only one interactive session is supported /// - TerminalServicesSingleSession = 0x0100, + TerminalServicesSingleSession = 0x0100, /// /// Windows Home Edition is installed /// - HomeEdition = 0x0200, + HomeEdition = 0x0200, /// /// Web Server Edition is installed /// - WebServerEdition = 0x0400, + WebServerEdition = 0x0400, /// /// Storage Server Edition is installed /// - StorageServerEdition = 0x2000, + StorageServerEdition = 0x2000, /// /// Compute Cluster Edition is installed /// - ComputeClusterEdition = 0x4000 + ComputeClusterEdition = 0x4000 } /// @@ -4891,47 +4892,47 @@ namespace Microsoft.PowerShell.Commands /// /// The OEM did not specify a specific role /// - Unspecified = 0, + Unspecified = 0, /// /// The OEM specified a desktop role /// - Desktop = 1, + Desktop = 1, /// /// The OEM specified a mobile role (for example, a laptop) /// - Mobile = 2, + Mobile = 2, /// /// The OEM specified a workstation role /// - Workstation = 3, + Workstation = 3, /// /// The OEM specified an enterprise server role /// - EnterpriseServer = 4, + EnterpriseServer = 4, /// /// The OEM specified a single office/home office (SOHO) server role /// - SOHOServer = 5, + SOHOServer = 5, /// /// The OEM specified an appliance PC role /// - AppliancePC = 6, + AppliancePC = 6, /// /// The OEM specified a performance server role /// - PerformanceServer = 7, // v1 last supported + PerformanceServer = 7, // v1 last supported /// /// The OEM specified a tablet form factor role /// - Slate = 8, // v2 last supported + Slate = 8, // v2 last supported /// /// Max enum value @@ -5005,12 +5006,12 @@ namespace Microsoft.PowerShell.Commands /// Software element is deployable /// Deployable = 0, - + /// /// Software element is installable /// Installable = 1, - + /// /// Software element is executable /// @@ -5030,15 +5031,15 @@ namespace Microsoft.PowerShell.Commands private static class PInvokeDllNames { #if CORECLR - public const string GetPhysicallyInstalledSystemMemoryDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; - public const string LCIDToLocaleNameDllName = "kernelbase.dll"; - public const string PowerDeterminePlatformRoleExDllName = "api-ms-win-power-base-l1-1-0.dll"; - public const string GetFirmwareTypeDllName = "api-ms-win-core-kernel32-legacy-l1-1-1"; + public const string GetPhysicallyInstalledSystemMemoryDllName = "api-ms-win-core-sysinfo-l1-2-1.dll"; + public const string LCIDToLocaleNameDllName = "kernelbase.dll"; + public const string PowerDeterminePlatformRoleExDllName = "api-ms-win-power-base-l1-1-0.dll"; + public const string GetFirmwareTypeDllName = "api-ms-win-core-kernel32-legacy-l1-1-1"; #else - public const string GetPhysicallyInstalledSystemMemoryDllName = "kernel32.dll"; - public const string LCIDToLocaleNameDllName = "kernel32.dll"; - public const string PowerDeterminePlatformRoleExDllName = "Powrprof.dll"; - public const string GetFirmwareTypeDllName = "kernel32.dll"; + public const string GetPhysicallyInstalledSystemMemoryDllName = "kernel32.dll"; + public const string LCIDToLocaleNameDllName = "kernel32.dll"; + public const string PowerDeterminePlatformRoleExDllName = "Powrprof.dll"; + public const string GetFirmwareTypeDllName = "kernel32.dll"; #endif } @@ -5062,7 +5063,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - [DllImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName, SetLastError=true)] + [DllImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetPhysicallyInstalledSystemMemory(out ulong MemoryInKilobytes); @@ -5074,7 +5075,7 @@ namespace Microsoft.PowerShell.Commands /// the resultant firmware type /// /// - [DllImport(PInvokeDllNames.GetFirmwareTypeDllName, SetLastError=true)] + [DllImport(PInvokeDllNames.GetFirmwareTypeDllName, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFirmwareType(ref FirmwareType firmwareType); @@ -5097,8 +5098,8 @@ namespace Microsoft.PowerShell.Commands /// Name of the licensing property to get. /// Out parameter for the value. /// An hresult indicating success or failure. - [DllImport("slc.dll", CharSet = CharSet.Unicode)] - internal static extern int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue); + [DllImport("slc.dll", CharSet = CharSet.Unicode)] + internal static extern int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue); /* * SLGetWindowsInformationDWORD function returns * S_OK (0x00000000): If the method succeeds @@ -5106,7 +5107,7 @@ namespace Microsoft.PowerShell.Commands * SL_E_DATATYPE_MISMATCHED (0xC004F013): The value portion of the name-value pair is not a DWORD. [DllImport("Slc.dll", EntryPoint = "SLGetWindowsInformationDWORD", CharSet = CharSet.Unicode)] public static extern UInt32 SLGetWindowsInformationDWORD(string pwszValueName, ref int pdwValue); - */ + */ #endif } #endregion Native diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index fff3893ff..5deed95ae 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -20,7 +21,7 @@ namespace Microsoft.PowerShell.Commands public class GetContentCommand : ContentCommandBase { #region Parameters - + /// /// The number of content items to retrieve per block. /// By default this value is 1 which means read one block @@ -33,12 +34,12 @@ namespace Microsoft.PowerShell.Commands { get { - return readCount; + return _readCount; } // get set { - readCount = value; + _readCount = value; } } // ReadCount @@ -53,12 +54,12 @@ namespace Microsoft.PowerShell.Commands { get { - return totalCount; + return _totalCount; } // get set { - totalCount = value; + _totalCount = value; _totalCountSpecified = true; } } // TotalCount @@ -80,7 +81,7 @@ namespace Microsoft.PowerShell.Commands } private int _backCount = -1; private bool _tailSpecified = false; - + /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the @@ -104,20 +105,20 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Content.GetContentReaderDynamicParameters(".", context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The number of content items to retrieve per block. /// - private long readCount = 1; + private long _readCount = 1; /// /// The number of content items to retrieve. /// - private long totalCount = -1; + private long _totalCount = -1; #endregion parameter data @@ -126,7 +127,7 @@ namespace Microsoft.PowerShell.Commands /// /// Gets the content of an item at the specified path /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // TotalCount and Tail should not be specified at the same time. // Throw out terminating error if this is the case. @@ -211,7 +212,7 @@ namespace Microsoft.PowerShell.Commands continue; } } - + if (TotalCount != 0) { IList results = null; @@ -272,10 +273,8 @@ namespace Microsoft.PowerShell.Commands WriteContentObject(results, countRead, holder.PathInfo, currentContext); } } - } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); } - } // foreach holder in contentStreams } finally @@ -350,7 +349,6 @@ namespace Microsoft.PowerShell.Commands tailResultQueue.Enqueue(entry); } } - } while (results != null && results.Count > 0); if (tailResultQueue.Count > 0) @@ -445,6 +443,5 @@ namespace Microsoft.PowerShell.Commands #endregion Command code } // GetContentCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs index 112605a01..874f8de23 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; @@ -21,7 +22,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path parameter to the command /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -39,7 +40,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { @@ -65,12 +66,12 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property @@ -94,22 +95,22 @@ namespace Microsoft.PowerShell.Commands if (Path != null && Path.Length > 0) { return InvokeProvider.Property.GetPropertyDynamicParameters( - Path[0], - SessionStateUtilities.ConvertArrayToCollection(property), context); + Path[0], + SessionStateUtilities.ConvertArrayToCollection(_property), context); } return InvokeProvider.Property.GetPropertyDynamicParameters( ".", - SessionStateUtilities.ConvertArrayToCollection(property), context); + SessionStateUtilities.ConvertArrayToCollection(_property), context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The properties to be retrieved. /// - private string[] property; + private string[] _property; #endregion parameter data @@ -118,15 +119,15 @@ namespace Microsoft.PowerShell.Commands /// /// Gets the properties of an item at the specified path /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - foreach (string path in Path) - { + foreach (string path in Path) + { try { InvokeProvider.Property.Get( - path, - SessionStateUtilities.ConvertArrayToCollection(property), + path, + SessionStateUtilities.ConvertArrayToCollection(_property), CmdletProviderContext); } catch (PSNotSupportedException notSupported) @@ -161,13 +162,10 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord #endregion Command code - - } // GetItemPropertyCommand /// @@ -228,12 +226,12 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property @@ -258,11 +256,11 @@ namespace Microsoft.PowerShell.Commands { return InvokeProvider.Property.GetPropertyDynamicParameters( Path[0], - SessionStateUtilities.ConvertArrayToCollection(property), context); + SessionStateUtilities.ConvertArrayToCollection(_property), context); } return InvokeProvider.Property.GetPropertyDynamicParameters( ".", - SessionStateUtilities.ConvertArrayToCollection(property), context); + SessionStateUtilities.ConvertArrayToCollection(_property), context); } // GetDynamicParameters #endregion Parameters @@ -272,7 +270,7 @@ namespace Microsoft.PowerShell.Commands /// /// The properties to be retrieved. /// - private string[] property; + private string[] _property; #endregion parameter data @@ -283,17 +281,17 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (Path == null || Path.Length == 0) - { - paths = new string[] { "." }; - } - foreach (string path in Path) - { + if (Path == null || Path.Length == 0) + { + paths = new string[] { "." }; + } + foreach (string path in Path) + { try { Collection itemProperties = InvokeProvider.Property.Get( new string[] { path }, - SessionStateUtilities.ConvertArrayToCollection(property), + SessionStateUtilities.ConvertArrayToCollection(_property), base.SuppressWildcardExpansion); if (itemProperties != null) @@ -304,7 +302,7 @@ namespace Microsoft.PowerShell.Commands { foreach (string currentPropertyName in this.Name) { - if (currentItem.Properties != null && + if (currentItem.Properties != null && currentItem.Properties[currentPropertyName] != null && currentItem.Properties[currentPropertyName].Value != null) { @@ -314,7 +312,6 @@ namespace Microsoft.PowerShell.Commands } } } - } catch (PSNotSupportedException notSupported) { @@ -348,10 +345,9 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } - } + } #endregion Command code - } + } } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs index 366b6274d..084e78dde 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -17,12 +18,10 @@ namespace Microsoft.PowerShell.Commands /// /// Creates a new transaction. /// - protected override void EndProcessing () + protected override void EndProcessing() { WriteObject(this.Context.TransactionManager.GetCurrent()); } - } // GetTransactionCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs index c2e6736f1..069ecef83 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Globalization; using System.Management.Automation; @@ -14,7 +15,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to get WMI Objects /// - [Cmdlet (VerbsCommon.Get, "WmiObject", DefaultParameterSetName = "query", + [Cmdlet(VerbsCommon.Get, "WmiObject", DefaultParameterSetName = "query", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113337", RemotingCapability = RemotingCapability.OwnedByCommand)] public class GetWmiObjectCommand : WmiBaseCmdlet { @@ -26,11 +27,11 @@ namespace Microsoft.PowerShell.Commands /// [Alias("ClassName")] [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] - [Parameter(Position =1, ParameterSetName = "list")] + [Parameter(Position = 1, ParameterSetName = "list")] public string Class { - get { return this.wmiClass; } - set { this.wmiClass = value; } + get { return _wmiClass; } + set { _wmiClass = value; } } /// /// To specify whether to get the results recursively @@ -38,8 +39,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "list")] public SwitchParameter Recurse { - get { return this.recurse; } - set { this.recurse = value; } + get { return _recurse; } + set { _recurse = value; } } /// @@ -48,8 +49,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 1, ParameterSetName = "query")] public string[] Property { - get { return (string[])this.property.Clone(); } - set { this.property = value; } + get { return (string[])_property.Clone(); } + set { _property = value; } } /// @@ -58,8 +59,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "query")] public string Filter { - get { return this.filter; } - set { this.filter = value; } + get { return _filter; } + set { _filter = value; } } /// @@ -68,19 +69,19 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Amended { - get { return amended; } - set { amended = value; } + get { return _amended; } + set { _amended = value; } } /// /// If Enumerate Deep flag to use. When 'list' parameter is specified 'EnumerateDeep' parameter is ignored. /// - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] public SwitchParameter DirectRead { - get { return directRead; } - set { directRead = value; } + get { return _directRead; } + set { _directRead = value; } } /// @@ -89,8 +90,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "list")] public SwitchParameter List { - get { return this.list; } - set { this.list = value; } + get { return _list; } + set { _list = value; } } /// @@ -99,21 +100,21 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, ParameterSetName = "WQLQuery")] public string Query { - get { return this.objectQuery; } - set { this.objectQuery = value; } + get { return _objectQuery; } + set { _objectQuery = value; } } #endregion Parameters #region parameter data - private string wmiClass; - private string[] property = new string[] {"*"}; - private string filter; - private SwitchParameter amended; - private SwitchParameter directRead; - private string objectQuery; - private SwitchParameter list = false; - private SwitchParameter recurse = false; + private string _wmiClass; + private string[] _property = new string[] { "*" }; + private string _filter; + private SwitchParameter _amended; + private SwitchParameter _directRead; + private string _objectQuery; + private SwitchParameter _list = false; + private SwitchParameter _recurse = false; #endregion parameter data @@ -125,67 +126,66 @@ namespace Microsoft.PowerShell.Commands internal string GetQueryString() { StringBuilder returnValue = new StringBuilder("select "); - returnValue.Append(String.Join(", ", this.property)); + returnValue.Append(String.Join(", ", _property)); returnValue.Append(" from "); - returnValue.Append(this.wmiClass); - if(!String.IsNullOrEmpty(this.filter)) + returnValue.Append(_wmiClass); + if (!String.IsNullOrEmpty(_filter)) { returnValue.Append(" where "); - returnValue.Append(this.filter); + 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) Supperted by WMI - /// % Matches zero or more characters starting at the specified position A% A,ag,Apple Supperted 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. + /// 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) Supperted by WMI + /// % Matches zero or more characters starting at the specified position A% A,ag,Apple Supperted 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)) + if (string.IsNullOrEmpty(this.Class)) return string.Empty; string filterClass = string.Copy(this.Class); - filterClass = filterClass.Replace('*','%'); - filterClass = filterClass.Replace('?','_'); + filterClass = filterClass.Replace('*', '%'); + filterClass = filterClass.Replace('?', '_'); return filterClass; - } internal bool IsLocalizedNamespace(string sNamespace) { bool toReturn = false; - if( sNamespace.StartsWith("ms_", StringComparison.OrdinalIgnoreCase) ) + if (sNamespace.StartsWith("ms_", StringComparison.OrdinalIgnoreCase)) { toReturn = true; } return toReturn; } - internal bool ValidateClassFormat() + internal bool ValidateClassFormat() { string filterClass = this.Class; - if( string.IsNullOrEmpty(filterClass) ) + if (string.IsNullOrEmpty(filterClass)) return true; StringBuilder newClassName = new StringBuilder(); - for (int i = 0; i < filterClass.Length; i ++) + 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('-') ) + if (Char.IsLetterOrDigit(filterClass[i]) || + filterClass[i].Equals('[') || filterClass[i].Equals(']') || + filterClass[i].Equals('*') || filterClass[i].Equals('?') || + filterClass[i].Equals('-')) { - newClassName.Append(filterClass[ i ]); + newClassName.Append(filterClass[i]); continue; } - else if ( filterClass[i].Equals('_') ) + else if (filterClass[i].Equals('_')) { newClassName.Append('['); - newClassName.Append(filterClass[ i ]); + newClassName.Append(filterClass[i]); newClassName.Append(']'); continue; } @@ -194,22 +194,22 @@ namespace Microsoft.PowerShell.Commands this.Class = newClassName.ToString(); return true; } - + /// /// Gets the ManagementObjectSearcher object /// internal ManagementObjectSearcher GetObjectList(ManagementScope scope) { - ManagementObjectSearcher searcher =null; - StringBuilder queryStringBuilder = new StringBuilder(); - if(string.IsNullOrEmpty(this.Class) ) + ManagementObjectSearcher searcher = null; + StringBuilder queryStringBuilder = new StringBuilder(); + if (string.IsNullOrEmpty(this.Class)) { queryStringBuilder.Append("select * from meta_class"); } else { string filterClass = GetFilterClassName(); - if( filterClass == null ) + if (filterClass == null) return searcher; queryStringBuilder.Append("select * from meta_class where __class like '"); queryStringBuilder.Append(filterClass); @@ -229,38 +229,37 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { ConnectionOptions options = GetConnectionOption(); - if( this.AsJob ) + if (this.AsJob) { RunAsJob("Get-WMIObject"); return; } else { - - if (this.list.IsPresent) + if (_list.IsPresent) { - if(!this.ValidateClassFormat() ) + 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); + 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; + WriteError(errorRecord); + return; } foreach (string name in ComputerName) { - if( this.Recurse.IsPresent) + if (this.Recurse.IsPresent) { Queue namespaceElement = new Queue(); namespaceElement.Enqueue(this.Namespace); - while(namespaceElement.Count > 0 ) + while (namespaceElement.Count > 0) { string connectNamespace = (string)namespaceElement.Dequeue(); ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options); @@ -270,55 +269,54 @@ namespace Microsoft.PowerShell.Commands } 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; + 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; + 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; + 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() ) + + ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); + foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) { - if( !IsLocalizedNamespace( (string)obj["Name"]) ) + if (!IsLocalizedNamespace((string)obj["Name"])) { namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]); } } ManagementObjectSearcher searcher = this.GetObjectList(scope); - if( searcher == null ) + if (searcher == null) continue; foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } - } } else @@ -330,39 +328,39 @@ namespace Microsoft.PowerShell.Commands } 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; + 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; + 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; + 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 ) + if (searcher == null) continue; foreach (ManagementBaseObject obj in searcher.Get()) { @@ -371,11 +369,10 @@ namespace Microsoft.PowerShell.Commands } } 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(wmiClass)) + if (this.Recurse.IsPresent && string.IsNullOrEmpty(_wmiClass)) { string errormMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class"); ErrorRecord er = new ErrorRecord(new InvalidOperationException(errormMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null); @@ -392,8 +389,8 @@ namespace Microsoft.PowerShell.Commands { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); EnumerationOptions enumOptions = new EnumerationOptions(); - enumOptions.UseAmendedQualifiers = amended; - enumOptions.DirectRead = this.directRead; + enumOptions.UseAmendedQualifiers = _amended; + enumOptions.DirectRead = _directRead; ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); foreach (ManagementBaseObject obj in searcher.Get()) { @@ -450,9 +447,9 @@ namespace Microsoft.PowerShell.Commands 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 (wmiClass != null) + if (_wmiClass != null) { - return wmiClass; + return _wmiClass; } int fromIndex = query.IndexOf(" from ", StringComparison.OrdinalIgnoreCase); @@ -462,9 +459,6 @@ namespace Microsoft.PowerShell.Commands } #endregion Command code - - } // GetWmiObjectCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index e693b0f69..348c0db42 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text; using System.Text.RegularExpressions; @@ -28,7 +29,6 @@ using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { - #region Get-HotFix /// @@ -44,7 +44,7 @@ namespace Microsoft.PowerShell.Commands /// /// Specifies the HotFixID. Unique identifier associated with a particular update. /// - [Parameter(Position = 0,ParameterSetName="Default")] + [Parameter(Position = 0, ParameterSetName = "Default")] [ValidateNotNullOrEmpty] [Alias("HFID")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -111,10 +111,10 @@ namespace Microsoft.PowerShell.Commands #region Overrides - - private ManagementObjectSearcher searchProcess; - private bool inputContainsWildcard = false; + private ManagementObjectSearcher _searchProcess; + + private bool _inputContainsWildcard = false; /// /// Get the List of HotFixes installed on the Local Machine. /// @@ -145,8 +145,8 @@ namespace Microsoft.PowerShell.Commands QueryString.Append("Select * from Win32_QuickFixEngineering"); foundRecord = true; } - searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString())); - foreach (ManagementObject obj in searchProcess.Get()) + _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString())); + foreach (ManagementObject obj in _searchProcess.Get()) { if (_description != null) { @@ -155,7 +155,7 @@ namespace Microsoft.PowerShell.Commands } else { - inputContainsWildcard = true; + _inputContainsWildcard = true; } // try to translate the SID to a more friendly username @@ -173,7 +173,7 @@ namespace Microsoft.PowerShell.Commands } catch (SystemException e) // thrown by SecurityIdentifier.constr { - CommandsCommon.CheckForSevereException(this, e); + CommandsCommon.CheckForSevereException(this, e); } //catch (ArgumentException) // thrown (indirectly) by SecurityIdentifier.constr (on XP only?) //{ catch not needed - this is already caught as SystemException @@ -189,12 +189,12 @@ namespace Microsoft.PowerShell.Commands WriteObject(obj); foundRecord = true; } - if (!foundRecord && !inputContainsWildcard) + if (!foundRecord && !_inputContainsWildcard) { Exception Ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer)); WriteError(new ErrorRecord(Ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); } - if (searchProcess != null) + if (_searchProcess != null) { this.Dispose(); } @@ -206,10 +206,10 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - if (searchProcess != null) + if (_searchProcess != null) { - searchProcess.Dispose(); - } + _searchProcess.Dispose(); + } } #endregion Overrides @@ -228,12 +228,12 @@ namespace Microsoft.PowerShell.Commands } if (WildcardPattern.ContainsWildcardCharacters(desc)) { - inputContainsWildcard = true; + _inputContainsWildcard = true; } } } catch (Exception e) - { + { CommandsCommon.CheckForSevereException(this, e); return false; } @@ -263,16 +263,14 @@ namespace Microsoft.PowerShell.Commands { if (disposing) { - if (searchProcess != null) + if (_searchProcess != null) { - searchProcess.Dispose(); + _searchProcess.Dispose(); } } } #endregion "IDisposable Members" - }//end class #endregion - }//Microsoft.Powershell.commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs index 904d4a909..1b7b6c896 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -27,20 +28,20 @@ namespace Microsoft.PowerShell.Commands /// The WMI Object to use /// /// - [Parameter(ValueFromPipeline = true,Mandatory = true,ParameterSetName = "object")] + [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] public ManagementObject InputObject { - get { return this.inputObject; } - set { this.inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } /// /// The WMI Path to use /// - [Parameter(ParameterSetName = "path",Mandatory = true)] + [Parameter(ParameterSetName = "path", Mandatory = true)] public string Path { - get { return this.path; } - set { this.path = value; } + get { return _path; } + set { _path = value; } } /// /// The WMI class to use @@ -48,19 +49,19 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] public string Class { - get { return this.className; } - set { this.className = value; } + get { return _className; } + set { _className = value; } } /// /// The WMI Method to execute /// - [Parameter(Position = 1,Mandatory = true)] + [Parameter(Position = 1, Mandatory = true)] public string Name { - get { return this.methodName; } - set { this.methodName = value; } + get { return _methodName; } + set { _methodName = value; } } - + /// /// The parameters to the method specified by MethodName /// @@ -70,18 +71,18 @@ namespace Microsoft.PowerShell.Commands [Alias("Args")] public object[] ArgumentList { - get { return this.argumentList; } - set { this.argumentList = value; } + 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; + 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 @@ -90,38 +91,38 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if( this.AsJob ) + if (this.AsJob) { RunAsJob("Invoke-WMIMethod"); return; } - if (inputObject != null) + if (_inputObject != null) { object result = null; - ManagementBaseObject inputParameters =null ; + ManagementBaseObject inputParameters = null; try { - inputParameters = inputObject.GetMethodParameters(methodName); - if(argumentList != null ) + inputParameters = _inputObject.GetMethodParameters(_methodName); + if (_argumentList != null) { - int inParamCount = argumentList.Length; + int inParamCount = _argumentList.Length; foreach (PropertyData property in inputParameters.Properties) { if (inParamCount == 0) break; - property.Value = argumentList[argumentList.Length - inParamCount]; + property.Value = _argumentList[_argumentList.Length - inParamCount]; inParamCount--; } } - if (!ShouldProcess( - StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, - inputObject["__CLASS"].ToString(), - this.Name) - )) + if (!ShouldProcess( + StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, + _inputObject["__CLASS"].ToString(), + this.Name) + )) { return; } - result = inputObject.InvokeMethod(methodName, inputParameters,null); + result = _inputObject.InvokeMethod(_methodName, inputParameters, null); } catch (ManagementException e) { @@ -145,14 +146,14 @@ namespace Microsoft.PowerShell.Commands ManagementPath mPath = null; object result = null; ManagementObject mObject = null; - if( path != null) + if (_path != null) { - mPath = new ManagementPath(path); - if(String.IsNullOrEmpty(mPath.NamespacePath)) + mPath = new ManagementPath(_path); + if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = this.Namespace; } - else if( namespaceSpecified ) + else if (namespaceSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( @@ -161,8 +162,8 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.InvalidOperation, this.Namespace)); } - - if( mPath.Server != "." && serverNameSpecified ) + + if (mPath.Server != "." && serverNameSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( @@ -172,7 +173,7 @@ namespace Microsoft.PowerShell.Commands ComputerName)); } //If server name is specified loop through it. - if ( !(mPath.Server == "." && serverNameSpecified)) + if (!(mPath.Server == "." && serverNameSpecified)) { string[] serverName = new string[] { mPath.Server }; ComputerName = serverName; @@ -183,7 +184,7 @@ namespace Microsoft.PowerShell.Commands result = null; try { - if( path != null ) + if (_path != null) { mPath.Server = name; if (mPath.IsClass) @@ -202,19 +203,19 @@ namespace Microsoft.PowerShell.Commands else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - ManagementClass mClass = new ManagementClass(className); + ManagementClass mClass = new ManagementClass(_className); mObject = mClass; mObject.Scope = scope; } - ManagementBaseObject inputParameters = mObject.GetMethodParameters(methodName); - if(argumentList != null ) + ManagementBaseObject inputParameters = mObject.GetMethodParameters(_methodName); + if (_argumentList != null) { - int inParamCount = argumentList.Length; + int inParamCount = _argumentList.Length; foreach (PropertyData property in inputParameters.Properties) { if (inParamCount == 0) break; - object argument = PSObject.Base(argumentList[argumentList.Length - inParamCount]); + object argument = PSObject.Base(_argumentList[_argumentList.Length - inParamCount]); if (property.IsArray) { property.Value = MakeBaseObjectArray(argument); @@ -226,15 +227,15 @@ namespace Microsoft.PowerShell.Commands inParamCount--; } } - if (!ShouldProcess( - StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, - mObject["__CLASS"].ToString(), - this.Name) - )) - { - return; - } - result = mObject.InvokeMethod(this.methodName, inputParameters,null); + if (!ShouldProcess( + StringUtil.Format(WmiResources.WmiMethodNameForConfirmation, + mObject["__CLASS"].ToString(), + this.Name) + )) + { + return; + } + result = mObject.InvokeMethod(_methodName, inputParameters, null); } catch (ManagementException e) { @@ -296,5 +297,5 @@ namespace Microsoft.PowerShell.Commands } #endregion Command code - }//InvokeWMIObject + }//InvokeWMIObject } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index 2306f0a58..215c77706 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to move a property on an item to another item /// - [Cmdlet (VerbsCommon.Move, "ItemProperty", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, + [Cmdlet(VerbsCommon.Move, "ItemProperty", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113351")] public class MoveItemPropertyCommand : PassThroughItemPropertyCommandBase { @@ -19,8 +20,8 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path parameter to the command /// - [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -64,7 +65,7 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set @@ -73,7 +74,7 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - property = value; + _property = value; } } // Property @@ -86,15 +87,15 @@ namespace Microsoft.PowerShell.Commands { get { - return destination; + return _destination; } // get set { - destination = value; + _destination = value; } } // Destination - + /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the @@ -129,20 +130,20 @@ namespace Microsoft.PowerShell.Commands propertyName, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The property to be created. /// - private string[] property = new string[0]; + private string[] _property = new string[0]; /// /// The destination path of the item to copy the property to. /// - private string destination; + private string _destination; #endregion parameter data @@ -151,7 +152,7 @@ namespace Microsoft.PowerShell.Commands /// /// Creates the property on the item /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { @@ -193,7 +194,6 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } } // ProcessRecord @@ -201,5 +201,4 @@ namespace Microsoft.PowerShell.Commands } // MoveItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 7ba238ccd..c0663908f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -26,8 +27,8 @@ namespace Microsoft.PowerShell.Commands /// using "NavigationCommands" as the category. /// /// - [Dbg.TraceSourceAttribute ("NavigationCommands", "The namespace navigation tracer")] - internal static Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer ("NavigationCommands", "The namespace navigation tracer"); + [Dbg.TraceSourceAttribute("NavigationCommands", "The namespace navigation tracer")] + internal static Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); #endregion Tracer @@ -40,15 +41,15 @@ namespace Microsoft.PowerShell.Commands { get { - CmdletProviderContext coreCommandContext = new CmdletProviderContext (this); + CmdletProviderContext coreCommandContext = new CmdletProviderContext(this); coreCommandContext.Force = Force; - Collection includeFilter = - SessionStateUtilities.ConvertArrayToCollection (Include); + Collection includeFilter = + SessionStateUtilities.ConvertArrayToCollection(Include); Collection excludeFilter = - SessionStateUtilities.ConvertArrayToCollection (Exclude); + SessionStateUtilities.ConvertArrayToCollection(Exclude); coreCommandContext.SetFilters(includeFilter, excludeFilter, Filter); coreCommandContext.SuppressWildcardExpansion = SuppressWildcardExpansion; @@ -61,16 +62,16 @@ namespace Microsoft.PowerShell.Commands virtual internal SwitchParameter SuppressWildcardExpansion { - get + get { - return suppressWildcardExpansion; + return _suppressWildcardExpansion; } - set - { - suppressWildcardExpansion = value; + set + { + _suppressWildcardExpansion = value; } } - private bool suppressWildcardExpansion; + private bool _suppressWildcardExpansion; /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets @@ -121,7 +122,7 @@ namespace Microsoft.PowerShell.Commands /// ShouldProcess, then the return value is false. If they all /// support ShouldProcess then the return value is true. /// - protected bool DoesProviderSupportShouldProcess (string[] paths) + protected bool DoesProviderSupportShouldProcess(string[] paths) { // If no paths are specified, then default to true as the paths // may be getting piped in. @@ -136,7 +137,7 @@ namespace Microsoft.PowerShell.Commands // I don't really care about the returned path, just the provider name SessionState.Path.GetUnresolvedProviderPathFromPSPath( - path, + path, this.CmdletProviderContext, out provider, out drive); @@ -164,7 +165,7 @@ namespace Microsoft.PowerShell.Commands { get { - return dynamicParameters; + return _dynamicParameters; } // get } // RetrievedDynamicParameters /// @@ -172,7 +173,7 @@ namespace Microsoft.PowerShell.Commands /// GetDynamicParameters virtual method. /// /// - private object dynamicParameters; + private object _dynamicParameters; #endregion Protected members @@ -184,7 +185,7 @@ namespace Microsoft.PowerShell.Commands /// the provider instance. /// /// - protected override void StopProcessing () + protected override void StopProcessing() { foreach (CmdletProviderContext stopContext in stopContextCollection) { @@ -208,14 +209,14 @@ namespace Microsoft.PowerShell.Commands { get { - return filter; + return _filter; } set { - filter = value; + _filter = value; } } - private string filter; + private string _filter; /// @@ -232,15 +233,15 @@ namespace Microsoft.PowerShell.Commands { get { - return include; + return _include; } // get set { - include = value; + _include = value; } // set } // Include - private string[] include = new string[0]; + private string[] _include = new string[0]; /// @@ -257,15 +258,15 @@ namespace Microsoft.PowerShell.Commands { get { - return exclude; + return _exclude; } // get set { - exclude = value; + _exclude = value; } // set } // Exclude - private string[] exclude = new string[0]; + private string[] _exclude = new string[0]; /// @@ -290,14 +291,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } // Force - private bool force; + private bool _force; /// @@ -313,22 +314,22 @@ namespace Microsoft.PowerShell.Commands try { - dynamicParameters = GetDynamicParameters(context); + _dynamicParameters = GetDynamicParameters(context); } catch (ItemNotFoundException) { - dynamicParameters = null; + _dynamicParameters = null; } catch (ProviderNotFoundException) { - dynamicParameters = null; + _dynamicParameters = null; } catch (DriveNotFoundException) { - dynamicParameters = null; + _dynamicParameters = null; } - return dynamicParameters; + return _dynamicParameters; } // GetDynamicParameters /// @@ -337,14 +338,13 @@ namespace Microsoft.PowerShell.Commands /// public bool SupportsShouldProcess { - get + get { return ProviderSupportsShouldProcess; } } // SupportsShouldProcess #endregion Public members - } // class CoreCommandBase #endregion CoreCommandBase @@ -367,8 +367,8 @@ namespace Microsoft.PowerShell.Commands [Credential()] public PSCredential Credential { - get { return credential; } - set { credential = value; } + get { return _credential; } + set { _credential = value; } } #endregion Parameters @@ -377,7 +377,7 @@ namespace Microsoft.PowerShell.Commands /// /// The credentials to be used for the command. /// - private PSCredential credential; + private PSCredential _credential; #endregion parameter data @@ -390,14 +390,14 @@ namespace Microsoft.PowerShell.Commands { get { - CmdletProviderContext coreCommandContext = new CmdletProviderContext (this, Credential); + CmdletProviderContext coreCommandContext = new CmdletProviderContext(this, Credential); coreCommandContext.Force = Force; Collection includeFilter = - SessionStateUtilities.ConvertArrayToCollection (Include); + SessionStateUtilities.ConvertArrayToCollection(Include); Collection excludeFilter = - SessionStateUtilities.ConvertArrayToCollection (Exclude); + SessionStateUtilities.ConvertArrayToCollection(Exclude); coreCommandContext.SetFilters(includeFilter, excludeFilter, Filter); coreCommandContext.SuppressWildcardExpansion = SuppressWildcardExpansion; @@ -409,7 +409,6 @@ namespace Microsoft.PowerShell.Commands } // CmdletProviderContext #endregion Protected members - } // CoreCommandWithCredentialsBase #endregion CoreCommandWithCredentialsBase @@ -425,7 +424,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - [Cmdlet (VerbsCommon.Get, "Location", DefaultParameterSetName ="Location", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113321")] + [Cmdlet(VerbsCommon.Get, "Location", DefaultParameterSetName = "Location", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113321")] [OutputType(typeof(PathInfo), ParameterSetName = new string[] { "locationSet" })] [OutputType(typeof(PathInfoStack), ParameterSetName = new string[] { "Stack" })] public class GetLocationCommand : DriveMatchingCoreCommandBase @@ -457,23 +456,23 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the provider from which to get the current location. /// /// - [Parameter(ParameterSetName= locationSet, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = locationSet, ValueFromPipelineByPropertyName = true)] public string[] PSProvider { get { - return provider; + return _provider; } // get set { if (value == null) { - provider = new string[0]; + _provider = new string[0]; } else { - provider = value; + _provider = value; } } // set } // Provider @@ -482,17 +481,17 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the drive from which to get the current location. /// /// - [Parameter (ParameterSetName = locationSet, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = locationSet, ValueFromPipelineByPropertyName = true)] public string[] PSDrive { get { - return drives; + return _drives; } // get set { - drives = value; + _drives = value; } // set } // Drive @@ -505,36 +504,36 @@ namespace Microsoft.PowerShell.Commands /// to disambiguate parameter sets /// /// - [Parameter (ParameterSetName = stackSet)] + [Parameter(ParameterSetName = stackSet)] public SwitchParameter Stack { get { - return stackSwitch; + return _stackSwitch; } set { - stackSwitch = value; + _stackSwitch = value; } } - private bool stackSwitch; + private bool _stackSwitch; /// /// Gets or sets the stack ID for the location stack that will /// be retrieved. /// /// - [Parameter (ParameterSetName = stackSet, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = stackSet, ValueFromPipelineByPropertyName = true)] public string[] StackName { get { - return stackNames; + return _stackNames; } // get set { - stackNames = value; + _stackNames = value; } // set } // StackName @@ -550,12 +549,12 @@ namespace Microsoft.PowerShell.Commands /// /// The name of the provider from which to return the current location. /// - private string[] provider = new string[0]; + private string[] _provider = new string[0]; /// /// The name of the drive from which to return the current location. /// - private string[] drives; + private string[] _drives; #endregion Location parameter set data @@ -564,7 +563,7 @@ namespace Microsoft.PowerShell.Commands /// /// The name of the location stack from which to return the stack. /// - private string[] stackNames; + private string[] _stackNames; #endregion Stack parameter set data @@ -581,7 +580,7 @@ namespace Microsoft.PowerShell.Commands /// -stackSet gets the directory stack of directories that have been /// pushed by the push-location command /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // It is OK to use a switch for string comparison here because we // want a case sensitive comparison in the current culture. @@ -663,7 +662,6 @@ namespace Microsoft.PowerShell.Commands else if ((PSDrive == null || PSDrive.Length == 0) && (PSProvider != null && PSProvider.Length > 0)) { - foreach (string providerName in PSProvider) { bool providerContainsWildcard = WildcardPattern.ContainsWildcardCharacters(providerName); @@ -730,16 +728,15 @@ namespace Microsoft.PowerShell.Commands } else { - // Get the current working directory using the core command API. WriteObject(SessionState.Path.CurrentLocation); } break; case stackSet: - if (stackNames != null) + if (_stackNames != null) { - foreach (string stackName in stackNames) + foreach (string stackName in _stackNames) { try { @@ -773,13 +770,12 @@ namespace Microsoft.PowerShell.Commands break; default: - Dbg.Diagnostics.Assert (false, String.Format (System.Globalization.CultureInfo.InvariantCulture, "One of the predefined parameter sets should have been specified, instead we got: {0}", ParameterSetName)); + Dbg.Diagnostics.Assert(false, String.Format(System.Globalization.CultureInfo.InvariantCulture, "One of the predefined parameter sets should have been specified, instead we got: {0}", ParameterSetName)); break; } // case (ParameterSetName) } // ProcessRecord - #endregion command code - + #endregion command code } // class GetLocationCommand #endregion GetLocationCommand @@ -827,35 +823,35 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, ParameterSetName = relationshipSet, ValueFromPipelineByPropertyName = true)] #endif - [Parameter(Position = 0, ParameterSetName = pathSet, - ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = pathSet, + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string Path { get { - return path; + return _path; } set { - path = value; + _path = value; } } /// /// Gets or sets the path path property, when bound from the pipeline. /// - [Parameter(ParameterSetName = literalPathSet, + [Parameter(ParameterSetName = literalPathSet, Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string LiteralPath - { + { get { - return path; + return _path; } set { - path = value; + _path = value; base.SuppressWildcardExpansion = true; } } // PSPath @@ -869,11 +865,11 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } // get set { - passThrough = value; + _passThrough = value; } //set } // PassThru @@ -887,11 +883,11 @@ namespace Microsoft.PowerShell.Commands { get { - return stackName; + return _stackName; } // get set { - stackName = value; + _stackName = value; } //set } // StackName @@ -964,18 +960,18 @@ namespace Microsoft.PowerShell.Commands /// /// The filter used when doing a dir /// - private string path = String.Empty; + private string _path = String.Empty; /// /// Determines if output should be passed through for /// set-location. /// - private bool passThrough; + private bool _passThrough; /// /// The ID of the stack to use for the pop. /// - private string stackName; + private string _stackName; #endregion Command data @@ -985,7 +981,7 @@ namespace Microsoft.PowerShell.Commands /// The functional part of the code that does the changing of the current /// working directory. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { object result = null; @@ -1135,14 +1131,13 @@ namespace Microsoft.PowerShell.Commands break; } - if (passThrough && result != null) + if (_passThrough && result != null) { WriteObject(result); } } // ProcessRecord - #endregion Command code - + #endregion Command code } // SetLocationCommand #endregion SetLocationCommand @@ -1170,17 +1165,17 @@ namespace Microsoft.PowerShell.Commands // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release [Parameter (Position = 0, ParameterSetName = relationshipSet, ValueFromPipelineByPropertyName = true)] #endif - [Parameter(Position=0, ParameterSetName = "Path", - ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string Path { get { - return path; + return _path; } set { - path = value; + _path = value; } } @@ -1188,19 +1183,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string LiteralPath { get { - return path; + return _path; } // get set { base.SuppressWildcardExpansion = true; - path = value; + _path = value; } // set } // LiteralPath @@ -1214,11 +1209,11 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } // get set { - passThrough = value; + _passThrough = value; } //set } // PassThru @@ -1231,16 +1226,16 @@ namespace Microsoft.PowerShell.Commands // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release [Parameter (ParameterSetName = relationshipSet)] #endif - [Parameter (ValueFromPipelineByPropertyName = true)] + [Parameter(ValueFromPipelineByPropertyName = true)] public string StackName { get { - return stackName; + return _stackName; } // get set { - stackName = value; + _stackName = value; } //set } // StackName @@ -1312,18 +1307,18 @@ namespace Microsoft.PowerShell.Commands /// /// The filter used when doing a dir /// - private string path = String.Empty; + private string _path = String.Empty; /// /// Determines if output should be passed through for /// push-location. /// - private bool passThrough; + private bool _passThrough; /// /// The ID of the stack to use for the pop. /// - private string stackName; + private string _stackName; #endregion Command data @@ -1333,11 +1328,11 @@ namespace Microsoft.PowerShell.Commands /// The functional part of the code that does the changing of the current /// working directory and pushes the container onto the stack. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // Push the current working directory onto the // working directory stack - SessionState.Path.PushCurrentLocation (stackName); + SessionState.Path.PushCurrentLocation(_stackName); #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release @@ -1431,8 +1426,7 @@ namespace Microsoft.PowerShell.Commands } // Path != null } // ProcessRecord - #endregion Command code - + #endregion Command code } // PushLocationCommand #endregion PushLocationCommand @@ -1443,7 +1437,7 @@ namespace Microsoft.PowerShell.Commands /// The core command for pop-location. This is the equivalent of the popd command. /// It pops a container from the stack and sets the current location to that container. /// - [Cmdlet (VerbsCommon.Pop, "Location", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113369")] + [Cmdlet(VerbsCommon.Pop, "Location", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113369")] public class PopLocationCommand : CoreCommandBase { #region Command parameters @@ -1457,11 +1451,11 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } // get set { - passThrough = value; + _passThrough = value; } //set } // PassThru @@ -1470,16 +1464,16 @@ namespace Microsoft.PowerShell.Commands /// to use for the pop. If the parameter is missing or empty the default /// location stack is used. /// - [Parameter (ValueFromPipelineByPropertyName = true)] + [Parameter(ValueFromPipelineByPropertyName = true)] public string StackName { get { - return stackName; + return _stackName; } // get set { - stackName = value; + _stackName = value; } //set } // StackName @@ -1491,12 +1485,12 @@ namespace Microsoft.PowerShell.Commands /// Determines if output should be passed through for /// pop-location. /// - private bool passThrough; + private bool _passThrough; /// /// The ID of the stack to use for the pop. /// - private string stackName; + private string _stackName; #endregion Command data @@ -1508,13 +1502,13 @@ namespace Microsoft.PowerShell.Commands /// Gets the top container from the location stack and sets the /// location to it. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { try { // Pop the top of the location stack. - PathInfo result = SessionState.Path.PopLocation(stackName); + PathInfo result = SessionState.Path.PopLocation(_stackName); if (PassThru) { @@ -1555,7 +1549,7 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - #endregion Command code + #endregion Command code } // PopLocationCommand #endregion PopLocationCommand @@ -1567,7 +1561,7 @@ namespace Microsoft.PowerShell.Commands /// /// Mounts a drive in the Monad namespace. /// - [Cmdlet (VerbsCommon.New, "PSDrive", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113357")] + [Cmdlet(VerbsCommon.New, "PSDrive", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113357")] public class NewPSDriveCommand : CoreCommandWithCredentialsBase { #region Command parameters @@ -1581,7 +1575,7 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set { @@ -1590,7 +1584,7 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("value"); } - name = value; + _name = value; } } // public string Name @@ -1603,7 +1597,7 @@ namespace Microsoft.PowerShell.Commands { get { - return provider; + return _provider; } set { @@ -1612,7 +1606,7 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("value"); } - provider = value; + _provider = value; } } // public string Provider @@ -1627,7 +1621,7 @@ namespace Microsoft.PowerShell.Commands { get { - return root; + return _root; } set { @@ -1636,7 +1630,7 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("value"); } - root = value; + _root = value; } } // public string Root @@ -1648,7 +1642,7 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { @@ -1657,7 +1651,7 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("value"); } - description = value; + _description = value; } } // public string Description @@ -1669,12 +1663,12 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } // get set { - scope = value; + _scope = value; } // set } // Scope @@ -1686,10 +1680,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Persist { - get { return persist; } - set { persist = value; } + get { return _persist; } + set { _persist = value; } } - private bool persist = false; + private bool _persist = false; /// /// Gets the dynamic parameters for the new-psdrive cmdlet. @@ -1727,28 +1721,28 @@ namespace Microsoft.PowerShell.Commands /// /// The name of the drive /// - private string name; + private string _name; /// /// The provider ID for the drive /// - private string provider; + private string _provider; /// /// The namespace specific path of the root of the drive /// - private string root; + private string _root; /// /// A description for the drive /// - private string description; + private string _description; /// /// The scope identifier for the scope to create the drive in. /// If null or empty the drive will be created in the current scope. /// - private string scope; + private string _scope; #endregion Command data @@ -1757,7 +1751,7 @@ namespace Microsoft.PowerShell.Commands /// /// Adds a new drive to the Monad namespace /// - protected override void ProcessRecord () + protected override void ProcessRecord() { ProviderInfo provider = null; @@ -1789,7 +1783,7 @@ namespace Microsoft.PowerShell.Commands Name, provider.FullName, Root); - + if (ShouldProcess(resource, action)) { // -Persist switch parameter is supported only for FileSystem provider. @@ -1919,8 +1913,8 @@ namespace Microsoft.PowerShell.Commands /// /// internal List GetMatchingDrives( - string driveName, - string[] providerNames, + string driveName, + string[] providerNames, string scope) { List results = new List(); @@ -2002,14 +1996,14 @@ namespace Microsoft.PowerShell.Commands { bool addDrive = driveNameEmpty; - if(base.SuppressWildcardExpansion) + if (base.SuppressWildcardExpansion) { - if(String.Equals(drive.Name, driveName, StringComparison.OrdinalIgnoreCase)) + if (String.Equals(drive.Name, driveName, StringComparison.OrdinalIgnoreCase)) addDrive = true; } else { - if(nameMatcher.IsMatch(drive.Name)) + if (nameMatcher.IsMatch(drive.Name)) addDrive = true; } @@ -2035,7 +2029,7 @@ namespace Microsoft.PowerShell.Commands /// /// Removes a drive that is mounted in the Monad namespace. /// - [Cmdlet (VerbsCommon.Remove, "PSDrive", DefaultParameterSetName = "Name", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Remove, "PSDrive", DefaultParameterSetName = "Name", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113376")] public class RemovePSDriveCommand : DriveMatchingCoreCommandBase { @@ -2044,7 +2038,7 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the name of the drive to remove. /// - [Parameter(Position=0, ParameterSetName = "Name", + [Parameter(Position = 0, ParameterSetName = "Name", Mandatory = true, ValueFromPipelineByPropertyName = true)] [AllowNull] [AllowEmptyCollection] @@ -2052,11 +2046,11 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } // Name @@ -2069,13 +2063,13 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } // get set { base.SuppressWildcardExpansion = true; - names = value; + _names = value; } // set } // LiteralName @@ -2087,7 +2081,7 @@ namespace Microsoft.PowerShell.Commands { get { - return provider; + return _provider; } set { @@ -2095,7 +2089,7 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - provider = value; + _provider = value; } } // Provider @@ -2110,12 +2104,12 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } // get set { - scope = value; + _scope = value; } // set } // Scope @@ -2157,12 +2151,12 @@ namespace Microsoft.PowerShell.Commands /// /// The name of the drive to remove. /// - private string[] names; + private string[] _names; /// /// The name of the provider(s) for which to remove all drives. /// - private string[] provider = new string[0]; + private string[] _provider = new string[0]; /// /// The scope identifier for the scope to remove the drive from. @@ -2170,7 +2164,7 @@ namespace Microsoft.PowerShell.Commands /// from the current scope through the parents to the global scope /// until a drive of the specified name is found and removed. /// - private string scope; + private string _scope; #endregion Command data @@ -2181,7 +2175,7 @@ namespace Microsoft.PowerShell.Commands /// Removes the specified drive from the Monad namespace using the name /// of the drive. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // Get the confirmation strings @@ -2189,13 +2183,13 @@ namespace Microsoft.PowerShell.Commands string resourceTemplate = NavigationResources.RemoveDriveConfirmResourceTemplate; bool verifyMatch = true; - if (names == null) + if (_names == null) { - names = new string[] { string.Empty }; + _names = new string[] { string.Empty }; verifyMatch = false; } - foreach (string driveName in names) + foreach (string driveName in _names) { bool foundMatch = false; try @@ -2204,7 +2198,7 @@ namespace Microsoft.PowerShell.Commands { string resource = String.Format( - System.Globalization.CultureInfo.CurrentCulture, + System.Globalization.CultureInfo.CurrentCulture, resourceTemplate, drive.Name, drive.Provider, @@ -2230,7 +2224,6 @@ namespace Microsoft.PowerShell.Commands SessionState.Drive.Remove(drive.Name, Force, Scope, CmdletProviderContext); } } - } catch (DriveNotFoundException) { @@ -2244,18 +2237,16 @@ namespace Microsoft.PowerShell.Commands if (verifyMatch && !foundMatch) { - DriveNotFoundException e = new DriveNotFoundException ( + DriveNotFoundException e = new DriveNotFoundException( driveName, "DriveNotFound", SessionStateStrings.DriveNotFound); - WriteError (new ErrorRecord (e.ErrorRecord, e)); + WriteError(new ErrorRecord(e.ErrorRecord, e)); } } - } // ProcessRecord - #endregion Command code - + #endregion Command code } // RemovePSDriveCommand #endregion RemovePSDriveCommand @@ -2282,13 +2273,13 @@ namespace Microsoft.PowerShell.Commands /// supplied and any drive names that match the expression /// will be returned. /// - [Parameter(Position=0, ParameterSetName = "Name", ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Name", ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string[] Name { get { - return name; + return _name; } set { @@ -2296,26 +2287,26 @@ namespace Microsoft.PowerShell.Commands { value = new string[] { "*" }; } - name = value; + _name = value; } } // Name /// /// Gets or sets the literal name parameter to the command /// - [Parameter(Position=0, ParameterSetName = "LiteralName", + [Parameter(Position = 0, ParameterSetName = "LiteralName", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] public string[] LiteralName { get { - return name; + return _name; } // get set { base.SuppressWildcardExpansion = true; - name = value; + _name = value; } // set } // LiteralName @@ -2328,12 +2319,12 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } //get set { - scope = value; + _scope = value; } } // Scope @@ -2353,7 +2344,7 @@ namespace Microsoft.PowerShell.Commands { get { - return provider; + return _provider; } set { @@ -2361,7 +2352,7 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - provider = value; + _provider = value; } } // Provider @@ -2372,17 +2363,17 @@ namespace Microsoft.PowerShell.Commands /// /// The name of the drive to be retrieved. /// - private string[] name = new string[] { "*" }; + private string[] _name = new string[] { "*" }; /// /// The provider ID for the drives you want to see. /// - private string[] provider = new string[0]; + private string[] _provider = new string[0]; /// /// The scope to get the drive(s) from. /// - private string scope; + private string _scope; #endregion Command data @@ -2405,7 +2396,7 @@ namespace Microsoft.PowerShell.Commands /// will be retrieved. If the provider is specified, only drives for that provider /// will be retrieved. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string driveName in Name) { @@ -2476,8 +2467,7 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - #endregion Command code - + #endregion Command code } // GetPSDriveCommand #endregion GetPSDriveCommand @@ -2505,11 +2495,11 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -2523,13 +2513,13 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -2631,14 +2621,14 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Item.GetItemDynamicParameters(".", context); } // GetDynamicParameters - + #endregion Command parameters #region Command data /// /// The path of the item to get. /// - private string[] paths; + private string[] _paths; #endregion Command data @@ -2647,9 +2637,9 @@ namespace Microsoft.PowerShell.Commands /// /// Gets the specified item. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - foreach (string path in paths) + foreach (string path in _paths) { try { @@ -2683,12 +2673,10 @@ namespace Microsoft.PowerShell.Commands pathNotFound.ErrorRecord, pathNotFound)); } - } } // ProcessRecord - #endregion Command code - + #endregion Command code } // GetItemCommand #endregion GetItemCommand @@ -2698,7 +2686,7 @@ namespace Microsoft.PowerShell.Commands /// /// Creates the specified item using the namespace providers. /// - [Cmdlet (VerbsCommon.New, "Item", DefaultParameterSetName = "pathSet", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.New, "Item", DefaultParameterSetName = "pathSet", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113353")] public class NewItemCommand : CoreCommandWithCredentialsBase { @@ -2706,21 +2694,21 @@ namespace Microsoft.PowerShell.Commands private const string nameSet = "nameSet"; private const string pathSet = "pathSet"; - + /// /// Gets or sets the container path to create the item in. /// - [Parameter(Position=0,ParameterSetName="pathSet", Mandatory = true,ValueFromPipelineByPropertyName = true)] - [Parameter(Position=0,ParameterSetName="nameSet", Mandatory = false,ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "pathSet", Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "nameSet", Mandatory = false, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -2734,11 +2722,11 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set { - name = value; + _name = value; } } // Name @@ -2751,29 +2739,29 @@ namespace Microsoft.PowerShell.Commands { get { - return type; + return _type; } set { - type = value; + _type = value; } } // Type /// /// Gets or sets the content of the item to create /// - [Parameter(ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("Target")] public object Value { get { - return content; + return _content; } set { - content = value; + _content = value; } } // Content @@ -2822,7 +2810,7 @@ namespace Microsoft.PowerShell.Commands if (Path != null && Path.Length > 0) { // Path is only globbed if Name is specified. - if(String.IsNullOrEmpty(Name)) + if (String.IsNullOrEmpty(Name)) return InvokeProvider.Item.NewItemDynamicParameters(WildcardPattern.Escape(Path[0]), ItemType, Value, context); else return InvokeProvider.Item.NewItemDynamicParameters(Path[0], ItemType, Value, context); @@ -2838,7 +2826,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } @@ -2849,22 +2837,22 @@ namespace Microsoft.PowerShell.Commands /// The path of the container to create the item in. It may /// contain glob characters. /// - private string[] paths; + private string[] _paths; /// /// The name of the item to create. It may not contain glob characters. /// - private string name; + private string _name; /// /// The type of the item to create. /// - private string type; + private string _type; /// /// The content to create the new item with. /// - private object content; + private object _content; #endregion Command Data @@ -2873,15 +2861,15 @@ namespace Microsoft.PowerShell.Commands /// /// Creates the specified item. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - if (paths == null || - (paths != null && paths.Length == 0)) + if (_paths == null || + (_paths != null && _paths.Length == 0)) { - paths = new string[] { String.Empty }; + _paths = new string[] { String.Empty }; } - foreach (string path in paths) + foreach (string path in _paths) { try { @@ -2915,12 +2903,10 @@ namespace Microsoft.PowerShell.Commands pathNotFound.ErrorRecord, pathNotFound)); } - } } // ProcessRecord #endregion Command code - } // NewItemCommand #endregion NewItemCommand @@ -2930,7 +2916,7 @@ namespace Microsoft.PowerShell.Commands /// /// Sets the specified item using the namespace providers. /// - [Cmdlet (VerbsCommon.Set, "Item", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113395")] + [Cmdlet(VerbsCommon.Set, "Item", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113395")] public class SetItemCommand : CoreCommandWithCredentialsBase { #region Command parameters @@ -2944,11 +2930,11 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -2962,13 +2948,13 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -2976,20 +2962,20 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the value of the item to be set /// - [Parameter(Position = 1, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public object Value { get { - return newValue; + return _newValue; } set { - newValue = value; + _newValue = value; } } - /// + /// /// Gets or sets the force property /// /// @@ -3015,7 +3001,7 @@ namespace Microsoft.PowerShell.Commands base.Force = value; } } // Force - + /// /// Gets or sets the pass through property which determines /// if the object that is set should be written to the pipeline. @@ -3027,12 +3013,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } set { - passThrough = value; + _passThrough = value; } } // PassThru @@ -3116,7 +3102,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } #endregion Command parameters @@ -3125,18 +3111,18 @@ namespace Microsoft.PowerShell.Commands /// /// The path of the item to set. /// - private string[] paths; + private string[] _paths; /// /// The value of the item to be set. /// - private object newValue; + private object _newValue; /// /// Determines if the object being set should be written to the pipeline. /// Defaults to false. /// - private bool passThrough; + private bool _passThrough; #endregion Command data @@ -3145,15 +3131,15 @@ namespace Microsoft.PowerShell.Commands /// /// Sets the specified item. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // Default to the CmdletProviderContext that will direct output to // the pipeline. CmdletProviderContext currentCommandContext = CmdletProviderContext; - currentCommandContext.PassThru = passThrough; + currentCommandContext.PassThru = _passThrough; - foreach (string path in paths) + foreach (string path in _paths) { try { @@ -3187,12 +3173,10 @@ namespace Microsoft.PowerShell.Commands pathNotFound.ErrorRecord, pathNotFound)); } - } } // ProcessRecord - #endregion Command code - + #endregion Command code } // SetItemCommand #endregion SetItemCommand @@ -3202,7 +3186,7 @@ namespace Microsoft.PowerShell.Commands /// /// Removes the specified item using the namespace providers. /// - [Cmdlet (VerbsCommon.Remove, "Item", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113373")] + [Cmdlet(VerbsCommon.Remove, "Item", SupportsShouldProcess = true, DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113373")] public class RemoveItemCommand : CoreCommandWithCredentialsBase { #region Command parameters @@ -3216,11 +3200,11 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -3234,13 +3218,13 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -3302,11 +3286,11 @@ namespace Microsoft.PowerShell.Commands { get { - return recurse; + return _recurse; } set { - recurse = value; + _recurse = value; } } // Recurse @@ -3336,7 +3320,7 @@ namespace Microsoft.PowerShell.Commands base.Force = value; } } // Force - + /// /// Gets the dynamic parameters for the remove-item cmdlet. /// @@ -3367,7 +3351,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } #endregion Command parameters @@ -3377,13 +3361,13 @@ namespace Microsoft.PowerShell.Commands /// /// The path used when doing a delete /// - private string[] paths; + private string[] _paths; /// /// Determines if the remove command should recurse into /// sub-containers. /// - private bool recurse; + private bool _recurse; #endregion Command data @@ -3392,7 +3376,7 @@ namespace Microsoft.PowerShell.Commands /// /// Removes the specified items. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; @@ -3403,7 +3387,7 @@ namespace Microsoft.PowerShell.Commands { // Resolve the path in case it contains any glob characters Collection resolvedPSPaths = null; - + try { // Save the include and exclude filters so that we can ignore @@ -3412,7 +3396,7 @@ namespace Microsoft.PowerShell.Commands Collection exclude = currentContext.Exclude; string filter = currentContext.Filter; - if (recurse) + if (_recurse) { currentContext.SetFilters( new Collection(), @@ -3473,8 +3457,7 @@ namespace Microsoft.PowerShell.Commands try { - - isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor (resolvedPath.Path, currentContext); + isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(resolvedPath.Path, currentContext); } catch (PSNotSupportedException notSupported) { @@ -3517,9 +3500,9 @@ namespace Microsoft.PowerShell.Commands NavigationResources.RemoveItemInUse, resolvedPath.Path); - WriteError ( - new ErrorRecord ( - invalidOperation.ErrorRecord, + WriteError( + new ErrorRecord( + invalidOperation.ErrorRecord, invalidOperation)); continue; } @@ -3587,13 +3570,13 @@ namespace Microsoft.PowerShell.Commands { // Get the localized prompt string - string prompt = StringUtil.Format(NavigationResources.RemoveItemWithChildren,resolvedPath.Path); + string prompt = StringUtil.Format(NavigationResources.RemoveItemWithChildren, resolvedPath.Path); // Confirm the user wants to remove all children and the item even if // they did not specify -recurse - if (!ShouldContinue (prompt, null, ref yesToAll, ref noToAll)) - { + if (!ShouldContinue(prompt, null, ref yesToAll, ref noToAll)) + { continue; } shouldRecurse = true; @@ -3649,8 +3632,7 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - #endregion Command code - + #endregion Command code } // RemoveItemCommand #endregion RemoveItemCommand @@ -3661,7 +3643,7 @@ namespace Microsoft.PowerShell.Commands /// Moves an item from the specified location to the specified destination using /// the namespace providers. /// - [Cmdlet (VerbsCommon.Move, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Move, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113350")] public class MoveItemCommand : CoreCommandWithCredentialsBase { @@ -3670,16 +3652,16 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path property /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -3687,19 +3669,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -3711,11 +3693,11 @@ namespace Microsoft.PowerShell.Commands { get { - return destination; + return _destination; } set { - destination = value; + _destination = value; } } // Destination @@ -3745,7 +3727,7 @@ namespace Microsoft.PowerShell.Commands base.Force = value; } } // Force - + /// /// Gets or sets the filter property /// @@ -3807,12 +3789,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } set { - passThrough = value; + _passThrough = value; } } // PassThru @@ -3846,7 +3828,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } @@ -3857,18 +3839,18 @@ namespace Microsoft.PowerShell.Commands /// The path of the item to move. It is set or retrieved via /// the Path property. /// - private string[] paths; + private string[] _paths; /// /// The destination of the move /// - private string destination = "."; + private string _destination = "."; /// /// Determines if the object being set should be written to the pipeline. /// Defaults to false. /// - private bool passThrough; + private bool _passThrough; #endregion Command data @@ -3916,11 +3898,11 @@ namespace Microsoft.PowerShell.Commands /// /// Moves the specified item to the specified destination /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { - if(base.SuppressWildcardExpansion) + if (base.SuppressWildcardExpansion) { MoveItem(path); } @@ -3946,7 +3928,7 @@ namespace Microsoft.PowerShell.Commands try { string escapedPath = path; - if(! base.SuppressWildcardExpansion) { escapedPath = WildcardPattern.Escape(path); } + if (!base.SuppressWildcardExpansion) { escapedPath = WildcardPattern.Escape(path); } if (!InvokeProvider.Item.Exists(escapedPath, currentContext)) { PSInvalidOperationException invalidOperation = @@ -4062,7 +4044,7 @@ namespace Microsoft.PowerShell.Commands { // Now do the move string escapedPath = path; - if(! base.SuppressWildcardExpansion) { escapedPath = WildcardPattern.Escape(path); } + if (!base.SuppressWildcardExpansion) { escapedPath = WildcardPattern.Escape(path); } InvokeProvider.Item.Move(escapedPath, Destination, currentCommandContext); } catch (PSNotSupportedException notSupported) @@ -4098,9 +4080,9 @@ namespace Microsoft.PowerShell.Commands continue; } } - while(false); + while (false); } - #endregion Command code + #endregion Command code } // MoveItemCommand @@ -4111,7 +4093,7 @@ namespace Microsoft.PowerShell.Commands /// /// Renames a specified item to a new name using the namespace providers /// - [Cmdlet (VerbsCommon.Rename, "Item", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath", + [Cmdlet(VerbsCommon.Rename, "Item", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113382")] public class RenameItemCommand : CoreCommandWithCredentialsBase { @@ -4120,16 +4102,16 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path property /// - [Parameter(Position=0, Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string Path { get { - return path; + return _path; } set { - path = value; + _path = value; } } // Path @@ -4142,11 +4124,11 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; + _path = value; base.SuppressWildcardExpansion = true; } } // Path @@ -4154,16 +4136,16 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the newName property /// - [Parameter(Position=1,Mandatory=true,ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string NewName { get { - return newName; + return _newName; } set { - newName = value; + _newName = value; } } // Name @@ -4206,12 +4188,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } set { - passThrough = value; + _passThrough = value; } } // PassThru @@ -4241,7 +4223,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (new string[] { path }); + return base.DoesProviderSupportShouldProcess(new string[] { _path }); } } @@ -4252,18 +4234,18 @@ namespace Microsoft.PowerShell.Commands /// The path of the item to rename. It is set or retrieved via /// the Path property. /// - private string path; + private string _path; /// /// The new name of the item being renamed /// - private string newName; + private string _newName; /// /// Determines if the object being set should be written to the pipeline. /// Defaults to false. /// - private bool passThrough; + private bool _passThrough; #endregion Command data @@ -4272,7 +4254,7 @@ namespace Microsoft.PowerShell.Commands /// /// Moves the specified item to the specified destination /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; @@ -4330,7 +4312,7 @@ namespace Microsoft.PowerShell.Commands bool isCurrentLocationOrAncestor = false; try { - isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(path, currentContext); + isCurrentLocationOrAncestor = SessionState.Path.IsCurrentLocationOrAncestor(_path, currentContext); } catch (PSNotSupportedException notSupported) { @@ -4384,8 +4366,8 @@ namespace Microsoft.PowerShell.Commands // the pipeline. currentContext.PassThru = PassThru; - - tracer.WriteLine ("Rename {0} to {1}", Path, NewName); + + tracer.WriteLine("Rename {0} to {1}", Path, NewName); try { @@ -4424,9 +4406,8 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); return; } - } // ProcessRecord - #endregion Command code + #endregion Command code } // RenameItemCommand @@ -4437,7 +4418,7 @@ namespace Microsoft.PowerShell.Commands /// /// Copies a specified item to a new location using the namespace providers /// - [Cmdlet (VerbsCommon.Copy, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Copy, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113292")] public class CopyItemCommand : CoreCommandWithCredentialsBase { @@ -4445,17 +4426,17 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path property /// - [Parameter(Position=0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -4463,35 +4444,35 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath /// /// Gets or sets the destination property /// - [Parameter(Position=1,ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] public string Destination { get { - return destination; + return _destination; } set { - destination = value; + _destination = value; } } // Destination @@ -4503,12 +4484,12 @@ namespace Microsoft.PowerShell.Commands { get { - return container; + return _container; } set { - containerSpecified = true; - container = value; + _containerSpecified = true; + _container = value; } } // Container @@ -4597,19 +4578,19 @@ namespace Microsoft.PowerShell.Commands { get { - return recurse; + return _recurse; } set { - recurse = value; + _recurse = value; // If -Container is not specified but -Recurse // is, then -Container takes on the same value // as -Recurse - if (!containerSpecified) + if (!_containerSpecified) { - container = recurse; + _container = _recurse; } } } // Recurse @@ -4625,12 +4606,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } set { - passThrough = value; + _passThrough = value; } } // PassThru @@ -4664,7 +4645,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } @@ -4675,30 +4656,30 @@ namespace Microsoft.PowerShell.Commands /// The path of the item to copy. It is set or retrieved via /// the Path property. /// - private string[] paths; + private string[] _paths; /// /// The destination of the item being copied /// - private string destination; + private string _destination; /// /// Determines if the containers should be copied with the items or not. /// - private bool container = true; - private bool containerSpecified; + private bool _container = true; + private bool _containerSpecified; /// /// Determines if the copy command should recurse into /// sub-containers. /// - private bool recurse; + private bool _recurse; /// /// Determines if the object being set should be written to the pipeline. /// Defaults to false. /// - private bool passThrough; + private bool _passThrough; #endregion Command data @@ -4707,14 +4688,14 @@ namespace Microsoft.PowerShell.Commands /// /// Copies the specified item(s) to the specified destination /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentCommandContext = CmdletProviderContext; currentCommandContext.PassThru = PassThru; - foreach (string path in paths) + foreach (string path in _paths) { - tracer.WriteLine ("Copy {0} to {1}", path, Destination); + tracer.WriteLine("Copy {0} to {1}", path, Destination); try { @@ -4755,10 +4736,9 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord - #endregion Command code + #endregion Command code } // CopyItemCommand @@ -4769,7 +4749,7 @@ namespace Microsoft.PowerShell.Commands /// /// Clears an item at the specified location /// - [Cmdlet (VerbsCommon.Clear, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Clear, "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113283")] public class ClearItemCommand : CoreCommandWithCredentialsBase { @@ -4777,17 +4757,17 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path property /// - [Parameter(Position=0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -4795,19 +4775,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -4837,7 +4817,7 @@ namespace Microsoft.PowerShell.Commands base.Force = value; } } // Force - + /// /// Gets or sets the filter property /// @@ -4918,7 +4898,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (paths); + return base.DoesProviderSupportShouldProcess(_paths); } } @@ -4929,7 +4909,7 @@ namespace Microsoft.PowerShell.Commands /// The path of the item to move. It is set or retrieved via /// the Path property. /// - private string[] paths; + private string[] _paths; #endregion Command data @@ -4938,19 +4918,18 @@ namespace Microsoft.PowerShell.Commands /// /// Clears the specified item /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - // Default to the CmdletProviderContext that will direct output to // the pipeline. CmdletProviderContext currentCommandContext = CmdletProviderContext; currentCommandContext.PassThru = false; - foreach (string path in paths) + foreach (string path in _paths) { - tracer.WriteLine ("Clearing {0}", path); - + tracer.WriteLine("Clearing {0}", path); + try { // Now do the move @@ -4988,10 +4967,9 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord - #endregion Command code + #endregion Command code } // ClearItemCommand @@ -5002,7 +4980,7 @@ namespace Microsoft.PowerShell.Commands /// /// Invokes an item at the specified location /// - [Cmdlet ("Invoke", "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet("Invoke", "Item", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113345")] public class InvokeItemCommand : CoreCommandWithCredentialsBase { @@ -5010,17 +4988,17 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path property /// - [Parameter(Position=0, ParameterSetName = "Path", - Mandatory = true,ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ParameterSetName = "Path", + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } // Path @@ -5028,19 +5006,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false,ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -5124,7 +5102,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess(paths); + return base.DoesProviderSupportShouldProcess(_paths); } } @@ -5135,7 +5113,7 @@ namespace Microsoft.PowerShell.Commands /// The path of the item to move. It is set or retrieved via /// the Path property. /// - private string[] paths; + private string[] _paths; #endregion Command data @@ -5144,12 +5122,11 @@ namespace Microsoft.PowerShell.Commands /// /// Invokes the specified item /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - - foreach (string path in paths) + foreach (string path in _paths) { - tracer.WriteLine ("Invoking {0}", path); + tracer.WriteLine("Invoking {0}", path); try { @@ -5188,10 +5165,9 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord - #endregion Command code + #endregion Command code } // InvokeItemCommand @@ -5216,22 +5192,22 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the provider that will be removed. /// /// - [Parameter(Position=0,ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] public string[] PSProvider { get { - return provider; + return _provider; } set { if (value == null) { - provider = new string[0]; + _provider = new string[0]; } else { - provider = value; + _provider = value; } } } // Provider @@ -5242,7 +5218,7 @@ namespace Microsoft.PowerShell.Commands /// /// The string ID of the provider to remove. /// - private string[] provider = new string[0]; + private string[] _provider = new string[0]; #endregion Command data @@ -5315,9 +5291,7 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - #endregion Command code - } // GetProviderCommand #endregion GetProviderCommand diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs index 52dd46fc3..0d5cc8b5d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to create a new property on an object. /// - [Cmdlet (VerbsCommon.New, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.New, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113354")] public class NewItemPropertyCommand : ItemPropertyCommandBase { @@ -63,12 +64,12 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property @@ -82,15 +83,15 @@ namespace Microsoft.PowerShell.Commands { get { - return type; + return _type; } // get set { - type = value; + _type = value; } } // Type - + /// /// The value of the property to create on the item. /// @@ -100,12 +101,12 @@ namespace Microsoft.PowerShell.Commands { get { - return propertyValue; + return _propertyValue; } // get set { - propertyValue = value; + _propertyValue = value; } } // Value @@ -159,25 +160,25 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Property.NewPropertyDynamicParameters(".", Name, PropertyType, Value, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The property to be created. /// - private string property; + private string _property; /// /// The type of the property to be created. /// - private string type; + private string _type; /// /// The value of the property to be created. /// - private object propertyValue; + private object _propertyValue; #endregion parameter data @@ -186,7 +187,7 @@ namespace Microsoft.PowerShell.Commands /// /// Creates the property on the item /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { @@ -226,12 +227,10 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } // ProcessRecord #endregion Command code } // NewItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index 09128a973..749d519f8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -24,7 +25,7 @@ namespace Microsoft.PowerShell.Commands public class SplitPathCommand : CoreCommandWithCredentialsBase { #region Parameters - + /// /// The parameter set name to get the parent path /// @@ -67,12 +68,12 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -85,13 +86,13 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -105,17 +106,17 @@ namespace Microsoft.PowerShell.Commands /// the MSH path. /// /// - [Parameter(Position=1, ValueFromPipelineByPropertyName = true, ParameterSetName=qualifierSet, Mandatory=false)] + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = qualifierSet, Mandatory = false)] public SwitchParameter Qualifier { get { - return qualifier; + return _qualifier; } // get set { - qualifier = value; + _qualifier = value; } //set } // Qualifier @@ -129,17 +130,17 @@ namespace Microsoft.PowerShell.Commands /// the MSH path. /// /// - [Parameter(ParameterSetName= noQualifierSet, Mandatory=false, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = noQualifierSet, Mandatory = false, ValueFromPipelineByPropertyName = true)] public SwitchParameter NoQualifier { get { - return noqualifier; + return _noqualifier; } // get set { - noqualifier = value; + _noqualifier = value; } //set } // NoQualifier @@ -152,17 +153,17 @@ namespace Microsoft.PowerShell.Commands /// If true the parent of the path will be returned. /// /// - [Parameter(ParameterSetName=parentSet, Mandatory=false, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = parentSet, Mandatory = false, ValueFromPipelineByPropertyName = true)] public SwitchParameter Parent { get { - return parent; + return _parent; } // get set { - parent = value; + _parent = value; } //set } // Parent @@ -174,17 +175,17 @@ namespace Microsoft.PowerShell.Commands /// If true the leaf name of the path will be returned. /// /// - [Parameter(ParameterSetName=leafSet, Mandatory=false, ValueFromPipelineByPropertyName = true)] + [Parameter(ParameterSetName = leafSet, Mandatory = false, ValueFromPipelineByPropertyName = true)] public SwitchParameter Leaf { get { - return leaf; + return _leaf; } // get set { - leaf = value; + _leaf = value; } //set } // Leaf @@ -197,12 +198,12 @@ namespace Microsoft.PowerShell.Commands { get { - return resolve; + return _resolve; } // get set { - resolve = value; + _resolve = value; } //set } // Resolve @@ -215,29 +216,29 @@ namespace Microsoft.PowerShell.Commands { get { - return isAbsolute; + return _isAbsolute; } // get set { - isAbsolute = value; + _isAbsolute = value; } //set } #endregion Parameters #region parameter data - + /// /// The path to resolve /// - private string[] paths; + private string[] _paths; /// /// Determines if the qualifier of the path should be returned. /// The qualifier is either the drive name or provider name that /// is qualifying the path. /// - private bool qualifier; + private bool _qualifier; /// /// Determines if the qualifier of the path should be returned. @@ -246,27 +247,27 @@ namespace Microsoft.PowerShell.Commands /// The qualifier is either the drive name or provider name that /// is qualifying the path. /// - private bool noqualifier; + private bool _noqualifier; /// /// Determines if the parent path of the specified path should be returned. /// - private bool parent = true; + private bool _parent = true; /// /// Determines if the leaf name of the specified path should be returned. /// - private bool leaf; + private bool _leaf; /// /// Determines if the path(s) should be resolved before being parsed. /// - private bool resolve; + private bool _resolve; /// /// Determines if the path(s) are absolute paths. /// - private bool isAbsolute; + private bool _isAbsolute; #endregion parameter data @@ -276,20 +277,20 @@ namespace Microsoft.PowerShell.Commands /// Parses the specified path and returns the portion determined by the /// boolean parameters. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { StringCollection pathsToParse = new StringCollection(); - if (resolve) + if (_resolve) { CmdletProviderContext currentContext = CmdletProviderContext; - foreach (string path in paths) + foreach (string path in _paths) { // resolve the paths and then parse each one. Collection resolvedPaths = null; - + try { resolvedPaths = @@ -369,7 +370,6 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } } @@ -383,7 +383,7 @@ namespace Microsoft.PowerShell.Commands for (int index = 0; index < pathsToParse.Count; ++index) { string result = null; - + switch (ParameterSetName) { case isAbsoluteSet: @@ -394,16 +394,16 @@ namespace Microsoft.PowerShell.Commands WriteObject(isPathAbsolute); continue; - case qualifierSet : + case qualifierSet: int separatorIndex = pathsToParse[index].IndexOf(":", StringComparison.CurrentCulture); if (separatorIndex < 0) { - FormatException e = - new FormatException ( + FormatException e = + new FormatException( StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); - WriteError ( - new ErrorRecord ( + WriteError( + new ErrorRecord( e, "ParsePathFormatError", // RENAME ErrorCategory.InvalidArgument, @@ -419,9 +419,9 @@ namespace Microsoft.PowerShell.Commands // The plus 2 is for the length of the provider separator // which is "::" - result = + result = pathsToParse[index].Substring( - 0, + 0, separatorIndex + 2); } else @@ -433,10 +433,10 @@ namespace Microsoft.PowerShell.Commands } } break; - - case parentSet : - case literalPathSet : - bool pathStartsWithRoot = + + case parentSet: + case literalPathSet: + bool pathStartsWithRoot = pathsToParse[index].StartsWith("\\", StringComparison.CurrentCulture) || pathsToParse[index].StartsWith("/", StringComparison.CurrentCulture); @@ -461,12 +461,12 @@ namespace Microsoft.PowerShell.Commands break; - case leafSet : + case leafSet: try { - result = + result = SessionState.Path.ParseChildName( - pathsToParse[index], + pathsToParse[index], CmdletProviderContext, true); } @@ -498,7 +498,7 @@ namespace Microsoft.PowerShell.Commands break; - case noQualifierSet : + case noQualifierSet: result = RemoveQualifier(pathsToParse[index]); break; @@ -547,7 +547,7 @@ namespace Microsoft.PowerShell.Commands result = path.Substring(index + 2); } } - else + else { string driveName = String.Empty; @@ -564,8 +564,6 @@ namespace Microsoft.PowerShell.Commands return result; } // RemoveQualifier - } // SplitPathCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs index 43f29febd..0164d645b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -14,7 +15,7 @@ namespace Microsoft.PowerShell.Commands public class PassThroughContentCommandBase : ContentCommandBase { #region Parameters - + /// /// Gets or sets the passthrough parameter to the command /// @@ -23,12 +24,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } // get set { - passThrough = value; + _passThrough = value; } // set } // PassThru @@ -40,19 +41,19 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (base.Path); + return base.DoesProviderSupportShouldProcess(base.Path); } } #endregion Parameters #region parameter data - + /// /// Determines if the content returned from the provider should /// be passed through to the pipeline. /// - private bool passThrough; + private bool _passThrough; #endregion parameter data @@ -77,6 +78,5 @@ namespace Microsoft.PowerShell.Commands #endregion protected members } // PassThroughContentCommandBase - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs index 98b6e8037..b1fd3f288 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -14,7 +15,7 @@ namespace Microsoft.PowerShell.Commands public class PassThroughItemPropertyCommandBase : ItemPropertyCommandBase { #region Parameters - + /// /// Gets or sets the passthrough parameter to the command /// @@ -23,12 +24,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passThrough; + return _passThrough; } // get set { - passThrough = value; + _passThrough = value; } // set } // PassThru @@ -62,12 +63,12 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region parameter data - + /// /// Determines if the property returned from the provider should /// be passed through to the pipeline. /// - private bool passThrough; + private bool _passThrough; #endregion parameter data @@ -81,7 +82,7 @@ namespace Microsoft.PowerShell.Commands { get { - return base.DoesProviderSupportShouldProcess (base.paths); + return base.DoesProviderSupportShouldProcess(base.paths); } } @@ -103,8 +104,6 @@ namespace Microsoft.PowerShell.Commands } // GetCurrentContext #endregion protected members - } // PassThroughItemPropertyCommandBase - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index 8d126272e..d08f7ae42 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -40,18 +41,18 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path parameter to the command /// - [Parameter (Position = 0, ParameterSetName = "Path", + [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -59,19 +60,19 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -134,12 +135,12 @@ namespace Microsoft.PowerShell.Commands { get { - return type; + return _type; } // get set { - type = value; + _type = value; } // set } // Type @@ -151,15 +152,15 @@ namespace Microsoft.PowerShell.Commands { get { - return isValid; + return _isValid; } // get set { - isValid = value; + _isValid = value; } // set } // IsValid - + /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the @@ -196,11 +197,11 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region parameter data - + /// /// The path to the item to ping /// - private string[] paths; + private string[] _paths; /// @@ -208,12 +209,12 @@ namespace Microsoft.PowerShell.Commands /// the specified path, a container exists at the specified path, or a /// leaf item exists at the specified path. /// - private TestPathType type = TestPathType.Any; + private TestPathType _type = TestPathType.Any; /// /// Determines if the path should be checked for validity. /// - private SwitchParameter isValid = new SwitchParameter(); + private SwitchParameter _isValid = new SwitchParameter(); #endregion parameter data @@ -222,25 +223,25 @@ namespace Microsoft.PowerShell.Commands /// /// Determines if an item at the specified path exists. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; - - foreach (string path in paths) + + foreach (string path in _paths) { bool result = false; try { - if(IsValid) + if (IsValid) { - result = SessionState.Path.IsValid (path, currentContext); + result = SessionState.Path.IsValid(path, currentContext); } else { if (this.PathType == TestPathType.Container) { - result = InvokeProvider.Item.IsContainer (path, currentContext); + result = InvokeProvider.Item.IsContainer(path, currentContext); } else if (this.PathType == TestPathType.Leaf) { @@ -253,7 +254,6 @@ namespace Microsoft.PowerShell.Commands result = InvokeProvider.Item.Exists(path, currentContext); } } - } // Any of the known exceptions means the path does not exist. catch (PSNotSupportedException) @@ -276,6 +276,5 @@ namespace Microsoft.PowerShell.Commands } // PingPathCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 8064122a1..abd52d87a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text; using System.Collections; @@ -36,11 +37,10 @@ using System.Security.Permissions; namespace Microsoft.PowerShell.Commands { - -// 2004/12/17-JonN ProcessNameGlobAttribute was deeply wrong. -// For example, if you pass in a single Process, it will match -// all processes with the same name. -// I have removed the globbing code. + // 2004/12/17-JonN ProcessNameGlobAttribute was deeply wrong. + // For example, if you pass in a single Process, it will match + // all processes with the same name. + // I have removed the globbing code. #region ProcessBaseCommand /// @@ -52,7 +52,8 @@ namespace Microsoft.PowerShell.Commands /// /// The various process selection modes /// - internal enum MatchMode { + internal enum MatchMode + { /// /// Select all processes /// @@ -81,10 +82,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected string[] SuppliedComputerName { - get { return computerName; } - set { computerName = value; } + get { return _computerName; } + set { _computerName = value; } } - private string[] computerName = new string[0]; + private string[] _computerName = new string[0]; /// /// The Name parameter is declared in subclasses, @@ -112,15 +113,15 @@ namespace Microsoft.PowerShell.Commands { get { - return input; + return _input; } set { myMode = MatchMode.ByInput; - input = value; + _input = value; } } - Process[] input = null; + private Process[] _input = null; #endregion Parameters #region Internal @@ -128,7 +129,7 @@ namespace Microsoft.PowerShell.Commands // We use a Dictionary to optimize the check whether the object // is already in the list. private List _matchingProcesses = new List(); - private Dictionary _keys = new Dictionary(); + private Dictionary _keys = new Dictionary(); /// /// Retrieve the list of all processes matching the Name, Id @@ -241,7 +242,7 @@ namespace Microsoft.PowerShell.Commands { if (SuppliedComputerName.Length > 0) { - foreach(string computerName in SuppliedComputerName) + foreach (string computerName in SuppliedComputerName) { process = Process.GetProcessById(processId, computerName); AddIdempotent(process); @@ -300,13 +301,13 @@ namespace Microsoft.PowerShell.Commands { get { - if (null == allProcesses) + if (null == _allProcesses) { List processes = new List(); - + if (SuppliedComputerName.Length > 0) { - foreach(string computerName in SuppliedComputerName) + foreach (string computerName in SuppliedComputerName) { processes.AddRange(Process.GetProcesses(computerName)); } @@ -316,12 +317,12 @@ namespace Microsoft.PowerShell.Commands processes.AddRange(Process.GetProcesses()); } - allProcesses = processes.ToArray(); + _allProcesses = processes.ToArray(); } - return allProcesses; + return _allProcesses; } } - private Process[] allProcesses = null; + private Process[] _allProcesses = null; /// /// Add to , @@ -354,14 +355,14 @@ namespace Microsoft.PowerShell.Commands Process process, Exception innerException, string resourceId, string errorId, - ErrorCategory category ) + ErrorCategory category) { WriteNonTerminatingError( SafeGetProcessName(process), SafeGetProcessId(process), process, innerException, - resourceId, + resourceId, errorId, category); } @@ -474,7 +475,6 @@ namespace Microsoft.PowerShell.Commands } #endregion Internal - }//ProcessBaseCommand #endregion ProcessBaseCommand @@ -511,7 +511,8 @@ namespace Microsoft.PowerShell.Commands public string[] Name { get { return processNames; } - set { + set + { myMode = MatchMode.ByName; processNames = value; } @@ -596,10 +597,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = IdParameterSet)] [Parameter(ParameterSetName = InputObjectParameterSet)] - [ValidateNotNull] + [ValidateNotNull] public SwitchParameter Module { - get + get { return _module; } @@ -616,7 +617,7 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = IdParameterSet)] [Parameter(ParameterSetName = InputObjectParameterSet)] - [Alias("FV","FVI")] + [Alias("FV", "FVI")] [ValidateNotNull] public SwitchParameter FileVersionInfo { @@ -674,7 +675,7 @@ namespace Microsoft.PowerShell.Commands { //assigning to tempmodule to rethrow for exceptions on 64 bit machines tempmodule = pmodule; - WriteObject(ClrFacade.GetProcessModuleFileVersionInfo(pmodule), true); + WriteObject(ClrFacade.GetProcessModuleFileVersionInfo(pmodule), true); } } catch (InvalidOperationException exception) @@ -705,7 +706,7 @@ namespace Microsoft.PowerShell.Commands } catch (Exception exception) { - CommandsCommon.CheckForSevereException(this, exception); + CommandsCommon.CheckForSevereException(this, exception); WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateModuleFileVer, "CouldnotEnumerateModuleFileVer", ErrorCategory.PermissionDenied); } } @@ -713,8 +714,8 @@ namespace Microsoft.PowerShell.Commands { //if only modules are to be displayed try - { - WriteObject(process.Modules, true); + { + WriteObject(process.Modules, true); } catch (Win32Exception exception) { @@ -733,13 +734,12 @@ namespace Microsoft.PowerShell.Commands { WriteNonTerminatingError(process, ex, ProcessResources.CouldnotEnumerateModules, "CouldnotEnumerateModules", ErrorCategory.PermissionDenied); } - - } + } catch (Exception exception) { - CommandsCommon.CheckForSevereException(this, exception); - WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateModules, "CouldnotEnumerateModules", ErrorCategory.PermissionDenied); - } + CommandsCommon.CheckForSevereException(this, exception); + WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateModules, "CouldnotEnumerateModules", ErrorCategory.PermissionDenied); + } } else if (_fileversioninfo.IsPresent) { @@ -752,9 +752,9 @@ namespace Microsoft.PowerShell.Commands { WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateFileVer, "CouldnotEnumerateFileVer", ErrorCategory.PermissionDenied); } - catch (ArgumentException exception) + catch (ArgumentException exception) { - WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateFileVer, "CouldnotEnumerateFileVer", ErrorCategory.PermissionDenied); + WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateFileVer, "CouldnotEnumerateFileVer", ErrorCategory.PermissionDenied); } catch (Win32Exception exception) { @@ -773,13 +773,12 @@ namespace Microsoft.PowerShell.Commands { WriteNonTerminatingError(process, ex, ProcessResources.CouldnotEnumerateFileVer, "CouldnotEnumerateFileVer", ErrorCategory.PermissionDenied); } - - } + } catch (Exception exception) { - CommandsCommon.CheckForSevereException(this, exception); + CommandsCommon.CheckForSevereException(this, exception); WriteNonTerminatingError(process, exception, ProcessResources.CouldnotEnumerateFileVer, "CouldnotEnumerateFileVer", ErrorCategory.PermissionDenied); - } + } } else { @@ -789,7 +788,6 @@ namespace Microsoft.PowerShell.Commands WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process, this) : process); #endif } - }//for loop } // ProcessRecord @@ -925,7 +923,6 @@ namespace Microsoft.PowerShell.Commands } userName = domainNameStr + "\\" + userNameStr; - } while (false); } catch (NotSupportedException) @@ -963,8 +960,6 @@ namespace Microsoft.PowerShell.Commands } #endregion IncludeUserName - - }//GetProcessCommand #endregion GetProcessCommand @@ -1032,21 +1027,21 @@ namespace Microsoft.PowerShell.Commands { get { - return timeout; + return _timeout; } set { - timeout = value; - timeOutSpecified = true; + _timeout = value; + _timeOutSpecified = true; } } - private int timeout = 0; - private bool timeOutSpecified; + private int _timeout = 0; + private bool _timeOutSpecified; #endregion Parameters - private bool disposed = false; + private bool _disposed = false; #region IDisposable /// @@ -1054,14 +1049,14 @@ namespace Microsoft.PowerShell.Commands /// public void Dispose() { - if (disposed == false) + if (_disposed == false) { - if (waitHandle != null) + if (_waitHandle != null) { - waitHandle.Dispose(); - waitHandle = null; + _waitHandle.Dispose(); + _waitHandle = null; } - disposed = true; + _disposed = true; } } @@ -1071,11 +1066,11 @@ namespace Microsoft.PowerShell.Commands // Handle Exited event and display process information. private void myProcess_Exited(object sender, System.EventArgs e) { - if (0 == System.Threading.Interlocked.Decrement(ref this.numberOfProcessesToWaitFor)) + if (0 == System.Threading.Interlocked.Decrement(ref _numberOfProcessesToWaitFor)) { - if (waitHandle != null) + if (_waitHandle != null) { - waitHandle.Set(); + _waitHandle.Set(); } } } @@ -1084,11 +1079,11 @@ namespace Microsoft.PowerShell.Commands #region Overrides - List processList = new List(); + private List _processList = new List(); //Wait handle which is used by thread to sleep. - ManualResetEvent waitHandle; - private int numberOfProcessesToWaitFor; + private ManualResetEvent _waitHandle; + private int _numberOfProcessesToWaitFor; /// @@ -1096,7 +1091,6 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - //adding the processes into the list foreach (Process process in MatchingProcesses()) { @@ -1113,9 +1107,8 @@ namespace Microsoft.PowerShell.Commands WriteNonTerminatingError(process, null, ProcessResources.WaitOnItself, "WaitOnItself", ErrorCategory.ObjectNotFound); continue; } - processList.Add(process); + _processList.Add(process); } - } // ProcessRecord /// @@ -1123,8 +1116,8 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - waitHandle = new ManualResetEvent(false); - foreach (Process process in processList) + _waitHandle = new ManualResetEvent(false); + foreach (Process process in _processList) { try { @@ -1134,7 +1127,7 @@ namespace Microsoft.PowerShell.Commands process.Exited += new EventHandler(myProcess_Exited); if (!process.HasExited) { - System.Threading.Interlocked.Increment(ref this.numberOfProcessesToWaitFor); + System.Threading.Interlocked.Increment(ref _numberOfProcessesToWaitFor); } } } @@ -1144,18 +1137,18 @@ namespace Microsoft.PowerShell.Commands } } - if (this.numberOfProcessesToWaitFor > 0) + if (_numberOfProcessesToWaitFor > 0) { - if (timeOutSpecified) + if (_timeOutSpecified) { - waitHandle.WaitOne(timeout * 1000); + _waitHandle.WaitOne(_timeout * 1000); } else { - waitHandle.WaitOne(); + _waitHandle.WaitOne(); } } - foreach (Process process in processList) + foreach (Process process in _processList) { try { @@ -1179,9 +1172,9 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - if (waitHandle != null) + if (_waitHandle != null) { - waitHandle.Set(); + _waitHandle.Set(); } } #endregion Overrides @@ -1215,13 +1208,14 @@ namespace Microsoft.PowerShell.Commands [Alias("ProcessName")] public string[] Name { - get { + get + { return processNames; } - set { + set + { processNames = value; myMode = MatchMode.ByName; - } } @@ -1267,15 +1261,15 @@ namespace Microsoft.PowerShell.Commands } } - private bool passThru; + private bool _passThru; /// /// The updated process object should be passed down the pipeline. /// [Parameter] public SwitchParameter PassThru { - get { return passThru; } - set { passThru = value; } + get { return _passThru; } + set { _passThru = value; } } @@ -1292,14 +1286,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; #endregion Parameters @@ -1362,7 +1356,7 @@ namespace Microsoft.PowerShell.Commands //check if the process is current process and kill it at last if (Process.GetCurrentProcess().Id == SafeGetProcessId(process)) { - shouldKillCurrentProcess = true; + _shouldKillCurrentProcess = true; continue; } @@ -1377,7 +1371,7 @@ namespace Microsoft.PowerShell.Commands SafeGetProcessId(process)); // caption: null = default caption - if (!ShouldContinue(message, null, ref yesToAll, ref noToAll)) + if (!ShouldContinue(message, null, ref _yesToAll, ref _noToAll)) continue; } } @@ -1424,17 +1418,16 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - + /// /// Kill the current process here. /// protected override void EndProcessing() { - if (shouldKillCurrentProcess) + if (_shouldKillCurrentProcess) { StopProcess(Process.GetCurrentProcess()); } - }//EndProcessing #endregion Overrides @@ -1443,17 +1436,17 @@ namespace Microsoft.PowerShell.Commands /// /// should the current powershell process to be killed /// - private bool shouldKillCurrentProcess; + private bool _shouldKillCurrentProcess; /// /// Boolean variables to display the warning using shouldcontinue /// - private bool yesToAll, noToAll; + private bool _yesToAll,_noToAll; /// /// Current windows user name /// - private string currentUserName; + private string _currentUserName; /// /// gets the owner of the process @@ -1468,17 +1461,17 @@ namespace Microsoft.PowerShell.Commands { if (Win32Native.OpenProcessToken(ClrFacade.GetSafeProcessHandle(process), TOKEN_QUERY, out ph)) { - if (currentUserName == null) + if (_currentUserName == null) { using (var currentUser = WindowsIdentity.GetCurrent()) { - currentUserName = currentUser.Name; + _currentUserName = currentUser.Name; } } using (var processUser = new WindowsIdentity(ph)) { - return string.Equals(processUser.Name, currentUserName, StringComparison.CurrentCultureIgnoreCase); + return string.Equals(processUser.Name, _currentUserName, StringComparison.CurrentCultureIgnoreCase); } } } @@ -1499,7 +1492,7 @@ namespace Microsoft.PowerShell.Commands return false; } - + /// /// Stop the service that depends on the process and its child services /// @@ -1578,7 +1571,6 @@ namespace Microsoft.PowerShell.Commands } #endregion Private - }//StopProcessCommand #endregion StopProcessCommand @@ -1636,7 +1628,7 @@ namespace Microsoft.PowerShell.Commands } #endregion Parameters - + #region Overrides /// @@ -1651,7 +1643,7 @@ namespace Microsoft.PowerShell.Commands ProcessResources.ProcessNameForConfirmation, SafeGetProcessName(process), SafeGetProcessId(process)); - + if (!ShouldProcess(targetMessage)) { continue; } // sometimes Idle process has processid zero,so handle that because we cannot attach debugger to it. @@ -1688,7 +1680,7 @@ namespace Microsoft.PowerShell.Commands AttachDebuggerToProcess(process); } } // ProcessRecord - + #endregion Overrides /// @@ -1738,10 +1730,10 @@ namespace Microsoft.PowerShell.Commands string errorMessage = string.Empty; switch (returnCode) { - case 2: errorMessage = ProcessResources.AttachDebuggerReturnCode2; break; - case 3: errorMessage = ProcessResources.AttachDebuggerReturnCode3; break; - case 8: errorMessage = ProcessResources.AttachDebuggerReturnCode8; break; - case 9: errorMessage = ProcessResources.AttachDebuggerReturnCode9; break; + case 2: errorMessage = ProcessResources.AttachDebuggerReturnCode2; break; + case 3: errorMessage = ProcessResources.AttachDebuggerReturnCode3; break; + case 8: errorMessage = ProcessResources.AttachDebuggerReturnCode8; break; + case 9: errorMessage = ProcessResources.AttachDebuggerReturnCode9; break; case 21: errorMessage = ProcessResources.AttachDebuggerReturnCode21; break; default: Diagnostics.Assert(false, "Unreachable code."); break; } @@ -1755,12 +1747,12 @@ namespace Microsoft.PowerShell.Commands /// /// This class implements the Start-process command /// - [Cmdlet(VerbsLifecycle.Start, "Process",DefaultParameterSetName="Default", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135261")] + [Cmdlet(VerbsLifecycle.Start, "Process", DefaultParameterSetName = "Default", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135261")] [OutputType(typeof(Process))] public sealed class StartProcessCommand : PSCmdlet, IDisposable { - private ManualResetEvent waithandle = null; - private bool isDefaultSetParameterSpecified = false; + private ManualResetEvent _waithandle = null; + private bool _isDefaultSetParameterSpecified = false; #region Parameters @@ -1802,7 +1794,7 @@ namespace Microsoft.PowerShell.Commands /// /// Credentials for the process /// - [Parameter(ParameterSetName="Default")] + [Parameter(ParameterSetName = "Default")] [Alias("RunAs")] [ValidateNotNullOrEmpty] [Credential] @@ -1812,7 +1804,7 @@ namespace Microsoft.PowerShell.Commands set { _credential = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private PSCredential _credential; @@ -1837,7 +1829,7 @@ namespace Microsoft.PowerShell.Commands /// /// load user profile from registry /// - [Parameter(ParameterSetName="Default")] + [Parameter(ParameterSetName = "Default")] [Alias("Lup")] public SwitchParameter LoadUserProfile { @@ -1845,7 +1837,7 @@ namespace Microsoft.PowerShell.Commands set { _loaduserprofile = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private SwitchParameter _loaduserprofile = SwitchParameter.Present; @@ -1853,7 +1845,7 @@ namespace Microsoft.PowerShell.Commands /// /// starts process in a new window /// - [Parameter(ParameterSetName="Default")] + [Parameter(ParameterSetName = "Default")] [Alias("nnw")] public SwitchParameter NoNewWindow { @@ -1861,7 +1853,7 @@ namespace Microsoft.PowerShell.Commands set { _nonewwindow = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private SwitchParameter _nonewwindow; @@ -1884,7 +1876,7 @@ namespace Microsoft.PowerShell.Commands /// /// Redirect error /// - [Parameter(ParameterSetName="Default")] + [Parameter(ParameterSetName = "Default")] [Alias("RSE")] [ValidateNotNullOrEmpty] public string RedirectStandardError @@ -1893,7 +1885,7 @@ namespace Microsoft.PowerShell.Commands set { _redirectstandarderror = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private string _redirectstandarderror; @@ -1911,7 +1903,7 @@ namespace Microsoft.PowerShell.Commands set { _redirectstandardinput = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private string _redirectstandardinput; @@ -1929,7 +1921,7 @@ namespace Microsoft.PowerShell.Commands set { _redirectstandardoutput = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private string _redirectstandardoutput; @@ -2000,13 +1992,13 @@ namespace Microsoft.PowerShell.Commands set { _UseNewEnvironment = value; - isDefaultSetParameterSpecified = true; + _isDefaultSetParameterSpecified = true; } } private SwitchParameter _UseNewEnvironment; - private StreamWriter OutputWriter; - private StreamWriter ErrorWriter; + private StreamWriter _outputWriter; + private StreamWriter _errorWriter; #endregion @@ -2069,7 +2061,7 @@ namespace Microsoft.PowerShell.Commands if (this.ParameterSetName.Equals("Default")) { - if (isDefaultSetParameterSpecified) + if (_isDefaultSetParameterSpecified) { startInfo.UseShellExecute = false; } @@ -2244,16 +2236,16 @@ namespace Microsoft.PowerShell.Commands { if (Platform.IsWindows) { - waithandle = new ManualResetEvent(false); + _waithandle = new ManualResetEvent(false); // Create and start the job object ProcessCollection jobObject = new ProcessCollection(); if (jobObject.AssignProcessToJobObject(process)) { // Wait for the job object to finish - jobObject.WaitOne(waithandle); + jobObject.WaitOne(_waithandle); } - else if (!process.HasExited) + else if (!process.HasExited) { // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. process.Exited += new EventHandler(myProcess_Exited); @@ -2280,9 +2272,9 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - if (waithandle != null) + if (_waithandle != null) { - waithandle.Set(); + _waithandle.Set(); } } @@ -2293,9 +2285,9 @@ namespace Microsoft.PowerShell.Commands /// private void myProcess_Exited(object sender, System.EventArgs e) { - if (waithandle != null) + if (_waithandle != null) { - waithandle.Set(); + _waithandle.Set(); } } @@ -2325,8 +2317,8 @@ namespace Microsoft.PowerShell.Commands { if (!String.IsNullOrEmpty(outLine.Data)) { - OutputWriter.WriteLine(outLine.Data); - OutputWriter.Flush(); + _outputWriter.WriteLine(outLine.Data); + _outputWriter.Flush(); } } @@ -2334,8 +2326,8 @@ namespace Microsoft.PowerShell.Commands { if (!String.IsNullOrEmpty(outLine.Data)) { - ErrorWriter.WriteLine(outLine.Data); - ErrorWriter.Flush(); + _errorWriter.WriteLine(outLine.Data); + _errorWriter.Flush(); } } @@ -2343,22 +2335,22 @@ namespace Microsoft.PowerShell.Commands { // To avoid a race condition with Std*Handler, let's wait a bit before closing the streams // System.Timer is not supported in CoreCLR, so let's spawn a new thread to do the wait - + Thread delayedStreamClosing = new Thread(StreamClosing); delayedStreamClosing.Start(); } - + private void StreamClosing() { Thread.Sleep(1000); - if (OutputWriter != null) + if (_outputWriter != null) { - OutputWriter.Dispose(); + _outputWriter.Dispose(); } - if (ErrorWriter != null) + if (_errorWriter != null) { - ErrorWriter.Dispose(); + _errorWriter.Dispose(); } } @@ -2381,12 +2373,12 @@ namespace Microsoft.PowerShell.Commands p.OutputDataReceived += new DataReceivedEventHandler(StdOutputHandler); // Can't do StreamWriter(string) in coreCLR - OutputWriter = new StreamWriter(new FileStream(_redirectstandardoutput, FileMode.Create)); + _outputWriter = new StreamWriter(new FileStream(_redirectstandardoutput, FileMode.Create)); } else { p.StartInfo.RedirectStandardOutput = false; - OutputWriter = null; + _outputWriter = null; } if (_redirectstandarderror != null) @@ -2396,12 +2388,12 @@ namespace Microsoft.PowerShell.Commands p.ErrorDataReceived += new DataReceivedEventHandler(StdErrorHandler); // Can't do StreamWriter(string) in coreCLR - ErrorWriter = new StreamWriter(new FileStream(_redirectstandarderror, FileMode.Create)); + _errorWriter = new StreamWriter(new FileStream(_redirectstandarderror, FileMode.Create)); } else { p.StartInfo.RedirectStandardError = false; - ErrorWriter = null; + _errorWriter = null; } p.EnableRaisingEvents = true; @@ -2421,7 +2413,6 @@ namespace Microsoft.PowerShell.Commands private Process StartWithCreateProcess(ProcessStartInfo startinfo) { - ProcessNativeMethods.STARTUPINFO lpStartupInfo = new ProcessNativeMethods.STARTUPINFO(); SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new SafeNativeMethods.PROCESS_INFORMATION(); int error = 0; @@ -2551,7 +2542,7 @@ namespace Microsoft.PowerShell.Commands { error = Marshal.GetLastWin32Error(); ErrorRecord er = null; - + if (error == 0xc1) { message = StringUtil.Format(ProcessResources.InvalidApplication, _path); @@ -2568,7 +2559,7 @@ namespace Microsoft.PowerShell.Commands Win32Exception win32ex = new Win32Exception(error); message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); } - + er = er ?? new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } @@ -2596,7 +2587,7 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(er); } - Label_03AE: + Label_03AE: // At this point, we should have a suspended process. Get the .Net Process object, resume the process, and return. Process result = Process.GetProcessById(lpProcessInformation.dwProcessId); @@ -2660,13 +2651,13 @@ namespace Microsoft.PowerShell.Commands Dispose(true); System.GC.SuppressFinalize(this); } - + private void Dispose(bool isDisposing) { - if (waithandle != null) + if (_waithandle != null) { - waithandle.Dispose(); - waithandle = null; + _waithandle.Dispose(); + _waithandle = null; } } @@ -2700,7 +2691,6 @@ namespace Microsoft.PowerShell.Commands string message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); - } SafeFileHandle sf = new SafeFileHandle(hFileHandle, true); return sf; @@ -2761,7 +2751,7 @@ namespace Microsoft.PowerShell.Commands } } - + private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { StringBuilder builder = new StringBuilder(); @@ -2797,7 +2787,7 @@ namespace Microsoft.PowerShell.Commands /// JobObjectHandle is a reference to the job object used to track /// the child processes created by the main process hosted by the Start-Process cmdlet. /// - private Microsoft.PowerShell.Commands.SafeJobHandle jobObjectHandle; + private Microsoft.PowerShell.Commands.SafeJobHandle _jobObjectHandle; /// /// ProcessCollection constructor. @@ -2805,7 +2795,7 @@ namespace Microsoft.PowerShell.Commands internal ProcessCollection() { IntPtr jobObjectHandleIntPtr = NativeMethods.CreateJobObject(IntPtr.Zero, null); - jobObjectHandle = new SafeJobHandle(jobObjectHandleIntPtr); + _jobObjectHandle = new SafeJobHandle(jobObjectHandleIntPtr); } /// @@ -2815,7 +2805,7 @@ namespace Microsoft.PowerShell.Commands internal bool AssignProcessToJobObject(Process process) { // Add the process to the job object - bool result = NativeMethods.AssignProcessToJobObject(jobObjectHandle, ClrFacade.GetRawProcessHandle(process)); + bool result = NativeMethods.AssignProcessToJobObject(_jobObjectHandle, ClrFacade.GetRawProcessHandle(process)); return result; } @@ -2831,7 +2821,7 @@ namespace Microsoft.PowerShell.Commands JOBOBJECT_BASIC_PROCESS_ID_LIST JobList = new JOBOBJECT_BASIC_PROCESS_ID_LIST(); dwSize = Marshal.SizeOf(JobList); - if (NativeMethods.QueryInformationJobObject(jobObjectHandle, + if (NativeMethods.QueryInformationJobObject(_jobObjectHandle, JOB_OBJECT_BASIC_PROCESS_ID_LIST, ref JobList, dwSize, IntPtr.Zero)) { @@ -2904,38 +2894,38 @@ namespace Microsoft.PowerShell.Commands // Methods // static NativeMethods(); - + [DllImport(PinvokeDllNames.GetStdHandleDllName, CharSet = CharSet.Ansi, SetLastError = true)] public static extern IntPtr GetStdHandle(int whichHandle); [DllImport(PinvokeDllNames.CreateProcessWithLogonWDllName, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] - internal static extern bool CreateProcessWithLogonW(string userName, - string domain, - IntPtr password, - LogonFlags logonFlags, - [MarshalAs(UnmanagedType.LPWStr)] string appName, - StringBuilder cmdLine, - int creationFlags, - IntPtr environmentBlock, - [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, - STARTUPINFO lpStartupInfo, + internal static extern bool CreateProcessWithLogonW(string userName, + string domain, + IntPtr password, + LogonFlags logonFlags, + [MarshalAs(UnmanagedType.LPWStr)] string appName, + StringBuilder cmdLine, + int creationFlags, + IntPtr environmentBlock, + [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, + STARTUPINFO lpStartupInfo, SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.CreateProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] - public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, - [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpCommandLine, - SECURITY_ATTRIBUTES lpProcessAttributes, + public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, + [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes, - bool bInheritHandles, - int dwCreationFlags, - IntPtr lpEnvironment, - [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, - STARTUPINFO lpStartupInfo, + bool bInheritHandles, + int dwCreationFlags, + IntPtr lpEnvironment, + [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, + STARTUPINFO lpStartupInfo, SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] - public static extern uint ResumeThread(IntPtr threadHandle); + public static extern uint ResumeThread(IntPtr threadHandle); [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern FileNakedHandle CreateFileW( @@ -2948,7 +2938,7 @@ namespace Microsoft.PowerShell.Commands System.IntPtr hTemplateFile ); - + [Flags] internal enum LogonFlags { @@ -2982,17 +2972,15 @@ namespace Microsoft.PowerShell.Commands : base(ownsHandle) { base.SetHandle(existingHandle); - } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(PinvokeDllNames.LocalFreeDllName)] private static extern IntPtr LocalFree(IntPtr hMem); protected override bool ReleaseHandle() { return (LocalFree(base.handle) == IntPtr.Zero); - } } - + [StructLayout(LayoutKind.Sequential)] internal class STARTUPINFO @@ -3025,7 +3013,6 @@ namespace Microsoft.PowerShell.Commands this.hStdOutput = new SafeFileHandle(IntPtr.Zero, false); this.hStdError = new SafeFileHandle(IntPtr.Zero, false); this.cb = Marshal.SizeOf(this); - } public void Dispose(bool disposing) @@ -3115,15 +3102,13 @@ namespace Microsoft.PowerShell.Commands internal SafeThreadHandle() : base(true) { - } protected override bool ReleaseHandle() { return SafeNativeMethods.CloseHandle(base.handle); - } } - + [SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)] internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid { @@ -3140,7 +3125,7 @@ namespace Microsoft.PowerShell.Commands } #endregion - + #region ProcessCommandException /// /// Non-terminating errors occurring in the process noun commands @@ -3172,7 +3157,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - public ProcessCommandException(string message, Exception innerException) + public ProcessCommandException(string message, Exception innerException) : base(message, innerException) { } @@ -3206,9 +3191,9 @@ namespace Microsoft.PowerShell.Commands { base.GetObjectData(info, context); - if(info == null) + if (info == null) throw new ArgumentNullException("info"); - + info.AddValue("ProcessName", _processName); } #endregion Serialization @@ -3228,6 +3213,5 @@ namespace Microsoft.PowerShell.Commands } // class ProcessCommandException #endregion ProcessCommandException - }//Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs index 410febf90..159e0c829 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -13,7 +14,7 @@ namespace Microsoft.PowerShell.Commands public class ItemPropertyCommandBase : CoreCommandWithCredentialsBase { #region Parameters - + /// /// Gets or sets the filter parameter /// @@ -30,7 +31,7 @@ namespace Microsoft.PowerShell.Commands base.Filter = value; } // set } // Filter - + /// /// Gets or sets the include property /// @@ -67,15 +68,12 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region parameter data - + /// /// The path to the item /// internal string[] paths = new string[0]; #endregion parameter data - - } // ItemPropertyCommandBase - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index a3be5e099..b28ecf465 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections; using System.Collections.Generic; @@ -29,10 +30,10 @@ namespace Microsoft.PowerShell.Commands [Alias("NS")] public string Namespace { - get { return this.nameSpace; } - set { this.nameSpace = value;} + get { return _nameSpace; } + set { _nameSpace = value; } } - + /// /// The credential to use /// @@ -40,10 +41,10 @@ namespace Microsoft.PowerShell.Commands [Credential()] public PSCredential Credential { - get { return this.credential; } - set { this.credential = value; } + get { return _credential; } + set { _credential = value; } } - + /// /// The ComputerName in which to query /// @@ -52,19 +53,19 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string ComputerName { - get { return this.computerName; } - set { this.computerName = value; } + get { return _computerName; } + set { _computerName = value; } } - + /// /// The WMI class to use /// [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] public string Class { - get { return this.className; } - set { this.className = value; } + get { return _className; } + set { _className = value; } } /// @@ -73,10 +74,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = true, ParameterSetName = "query")] public string Query { - get { return this.objectQuery; } - set { this.objectQuery = value; } + get { return _objectQuery; } + set { _objectQuery = value; } } - + /// /// Timeout in milliseconds /// @@ -86,22 +87,22 @@ namespace Microsoft.PowerShell.Commands { get { - return timeOut; + return _timeOut; } set { - timeOut = value; - timeoutSpecified = true; + _timeOut = value; + _timeoutSpecified = true; } } - - private Int64 timeOut = 0; - private bool timeoutSpecified = false; - private string objectQuery = null; - private string className = null; - private string computerName = "localhost"; - private string nameSpace = "root\\cimv2"; - private PSCredential credential; + + private Int64 _timeOut = 0; + private bool _timeoutSpecified = false; + private string _objectQuery = null; + private string _className = null; + private string _computerName = "localhost"; + private string _nameSpace = "root\\cimv2"; + private PSCredential _credential; #endregion parameters #region helper functions @@ -128,16 +129,16 @@ namespace Microsoft.PowerShell.Commands protected override Object GetSourceObject() { string wmiQuery = this.Query; - if(this.Class != null ) + if (this.Class != null) { //Validate class format - for (int i = 0; i < this.Class.Length; i ++) + for (int i = 0; i < this.Class.Length; i++) { - if( Char.IsLetterOrDigit(this.Class[i]) || this.Class[i].Equals('_') ) + if (Char.IsLetterOrDigit(this.Class[i]) || this.Class[i].Equals('_')) { continue; } - + ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( @@ -170,12 +171,12 @@ namespace Microsoft.PowerShell.Commands conOptions.Password = cred.Password; } - ManagementScope scope = new ManagementScope(GetScopeString(computerName, this.Namespace), conOptions); + ManagementScope scope = new ManagementScope(GetScopeString(_computerName, this.Namespace), conOptions); EventWatcherOptions evtOptions = new EventWatcherOptions(); - if(timeoutSpecified) + if (_timeoutSpecified) { - evtOptions.Timeout = new TimeSpan(timeOut * 10000); + evtOptions.Timeout = new TimeSpan(_timeOut * 10000); } ManagementEventWatcher watcher = new ManagementEventWatcher(scope, new EventQuery(wmiQuery), evtOptions); @@ -200,13 +201,13 @@ namespace Microsoft.PowerShell.Commands // Register for the "Unsubscribed" event so that we can stop the // event watcher. PSEventSubscriber newSubscriber = NewSubscriber; - if(newSubscriber != null) + if (newSubscriber != null) { newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); } } - void newSubscriber_Unsubscribed(object sender, PSEventUnsubscribedEventArgs e) + private void newSubscriber_Unsubscribed(object sender, PSEventUnsubscribedEventArgs e) { ManagementEventWatcher watcher = sender as ManagementEventWatcher; if (watcher != null) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs index a503a3fef..0082f9ec3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to remove a property from an item. /// - [Cmdlet (VerbsCommon.Remove, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Remove, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113374")] public class RemoveItemPropertyCommand : ItemPropertyCommandBase { @@ -20,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path parameter to the command /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get @@ -38,7 +39,7 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the literal path parameter to the command /// [Parameter(ParameterSetName = "LiteralPath", - Mandatory = true, ValueFromPipeline=false, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { @@ -58,24 +59,24 @@ namespace Microsoft.PowerShell.Commands /// The name of the property to create on the item /// /// - [Parameter(Mandatory=true, Position = 1, ValueFromPipelineByPropertyName = true)] + [Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true)] [Alias("PSProperty")] public string[] Name { get { - return property; + return _property; } // get set { if (value == null) { - property = new string[0]; + _property = new string[0]; } else { - property = value; + _property = value; } } } // Property @@ -136,15 +137,15 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Property.RemovePropertyDynamicParameters(".", propertyName, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The property to be created. /// - private string[] property = new string[0]; + private string[] _property = new string[0]; #endregion parameter data @@ -153,7 +154,7 @@ namespace Microsoft.PowerShell.Commands /// /// Removes the property from the item /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { @@ -195,7 +196,6 @@ namespace Microsoft.PowerShell.Commands pathNotFound)); continue; } - } } } // ProcessRecord @@ -203,5 +203,4 @@ namespace Microsoft.PowerShell.Commands } // RemoveItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs index 706196dc6..3ac74f6ab 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management; using System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to Remove WMI Object /// - [Cmdlet(VerbsCommon.Remove, "WmiObject", DefaultParameterSetName = "class",SupportsShouldProcess = true, + [Cmdlet(VerbsCommon.Remove, "WmiObject", DefaultParameterSetName = "class", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113381", RemotingCapability = RemotingCapability.OwnedByCommand)] public class RemoveWmiObject : WmiBaseCmdlet { @@ -22,34 +23,34 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] public ManagementObject InputObject { - get { return this.inputObject; } - set { this.inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } /// /// The WMI Path to use /// - [Parameter(Mandatory = true,ParameterSetName = "path")] + [Parameter(Mandatory = true, ParameterSetName = "path")] public string Path { - get { return this.path; } - set { this.path = value; } + get { return _path; } + set { _path = value; } } /// /// The WMI class to use /// - [Parameter(Position = 0, Mandatory = true,ParameterSetName = "class")] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] public string Class { - get { return this.className; } - set { this.className = value; } + get { return _className; } + set { _className = value; } } #endregion Parameters #region parameter data - private string path = null; - private string className = null; - private ManagementObject inputObject = null; + private string _path = null; + private string _className = null; + private ManagementObject _inputObject = null; #endregion parameter data #region Command code @@ -58,20 +59,20 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if( this.AsJob ) + if (this.AsJob) { RunAsJob("Remove-WMIObject"); return; } - if (inputObject != null) + if (_inputObject != null) { try { - if (!ShouldProcess(inputObject["__PATH"].ToString()) ) + if (!ShouldProcess(_inputObject["__PATH"].ToString())) { return; } - inputObject.Delete(); + _inputObject.Delete(); } catch (ManagementException e) { @@ -90,14 +91,14 @@ namespace Microsoft.PowerShell.Commands ConnectionOptions options = GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; - if (path != null) + if (_path != null) { - mPath = new ManagementPath(path); - if(String.IsNullOrEmpty(mPath.NamespacePath)) + mPath = new ManagementPath(_path); + if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = this.Namespace; } - else if( namespaceSpecified ) + else if (namespaceSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( @@ -107,7 +108,7 @@ namespace Microsoft.PowerShell.Commands this.Namespace)); } - if( mPath.Server != "." && serverNameSpecified ) + if (mPath.Server != "." && serverNameSpecified) { //ThrowTerminatingError ThrowTerminatingError(new ErrorRecord( @@ -126,7 +127,7 @@ namespace Microsoft.PowerShell.Commands { try { - if( path != null ) + if (_path != null) { mPath.Server = name; if (mPath.IsClass) @@ -145,11 +146,11 @@ namespace Microsoft.PowerShell.Commands else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); - ManagementClass mClass = new ManagementClass(className); + ManagementClass mClass = new ManagementClass(_className); mObject = mClass; mObject.Scope = scope; } - if (!ShouldProcess(mObject["__PATH"].ToString()) ) + if (!ShouldProcess(mObject["__PATH"].ToString())) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs index e99ed003d..e1279b398 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to rename a property of an item at a specified path /// - [Cmdlet (VerbsCommon.Rename, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Rename, "ItemProperty", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113383")] public class RenameItemPropertyCommand : PassThroughItemPropertyCommandBase { @@ -20,17 +21,17 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path parameter to the command /// [Parameter(Position = 0, ParameterSetName = "Path", - Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true)] + Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string Path { get { - return path; + return _path; } // get set { - path = value; + _path = value; } // set } // Path @@ -44,16 +45,16 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } // get set { base.SuppressWildcardExpansion = true; - path = value; + _path = value; } // set } // LiteralPath - + /// /// The properties to be renamed on the item /// @@ -64,12 +65,12 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property @@ -82,12 +83,12 @@ namespace Microsoft.PowerShell.Commands { get { - return newName; + return _newName; } // get set { - newName = value; + _newName = value; } } // NewName @@ -114,7 +115,7 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Property.RenamePropertyDynamicParameters(".", Name, NewName, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data @@ -122,17 +123,17 @@ namespace Microsoft.PowerShell.Commands /// /// The path to rename the property on. /// - private string path; + private string _path; /// /// The property to be renamed. /// - private string property; + private string _property; /// /// The new name of the item. /// - private string newName; + private string _newName; #endregion parameter data @@ -141,14 +142,14 @@ namespace Microsoft.PowerShell.Commands /// /// Renames a property on an item. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { try { CmdletProviderContext currentContext = CmdletProviderContext; currentContext.PassThru = PassThru; - InvokeProvider.Property.Rename(path, Name, NewName, currentContext); + InvokeProvider.Property.Rename(_path, Name, NewName, currentContext); } catch (PSNotSupportedException notSupported) { @@ -178,11 +179,9 @@ namespace Microsoft.PowerShell.Commands pathNotFound.ErrorRecord, pathNotFound)); } - } // ProcessRecord #endregion Command code } // RenameItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index 7ac0a4690..06005c07d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -12,12 +13,12 @@ namespace Microsoft.PowerShell.Commands /// A command to resolve MSH paths containing glob characters to /// MSH paths that match the glob strings. /// - [Cmdlet (VerbsDiagnostic.Resolve, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, + [Cmdlet(VerbsDiagnostic.Resolve, "Path", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113384")] public class ResolvePathCommand : CoreCommandWithCredentialsBase { #region Parameters - + /// /// Gets or sets the path parameter to the command /// @@ -27,12 +28,12 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { - paths = value; + _paths = value; } // set } // Path @@ -46,13 +47,13 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } // get set { base.SuppressWildcardExpansion = true; - paths = value; + _paths = value; } // set } // LiteralPath @@ -65,25 +66,25 @@ namespace Microsoft.PowerShell.Commands { get { - return relative; + return _relative; } // get set { - relative = value; + _relative = value; } // set } // Relative - private SwitchParameter relative; + private SwitchParameter _relative; #endregion Parameters #region parameter data - + /// /// The path to resolve /// - private string[] paths; + private string[] _paths; #endregion parameter data @@ -93,7 +94,7 @@ namespace Microsoft.PowerShell.Commands /// Resolves the path containing glob characters to the MSH paths that it /// represents. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { foreach (string path in Path) { @@ -102,7 +103,7 @@ namespace Microsoft.PowerShell.Commands { result = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); - if (relative) + if (_relative) { foreach (PathInfo currentPath in result) { @@ -149,7 +150,7 @@ namespace Microsoft.PowerShell.Commands continue; } - if (!relative) + if (!_relative) { WriteObject(result, true); } @@ -159,6 +160,5 @@ namespace Microsoft.PowerShell.Commands } // ResolvePathCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs index b5ae078fb..fa9a3c4be 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Provider; @@ -17,18 +18,16 @@ namespace Microsoft.PowerShell.Commands /// /// Rolls the current transaction back. /// - protected override void EndProcessing () + protected override void EndProcessing() { // Rollback the transaction - if(ShouldProcess( + if (ShouldProcess( NavigationResources.TransactionResource, NavigationResources.RollbackAction)) { this.Context.TransactionManager.Rollback(); } } - } // RollbackTransactionCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index df78a5849..3e2e68fca 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.ServiceProcess; @@ -275,15 +276,15 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; selectionMode = SelectionMode.InputObject; } } - private ServiceController[] inputObject = null; + private ServiceController[] _inputObject = null; #endregion Parameters #region Internal @@ -301,7 +302,7 @@ namespace Microsoft.PowerShell.Commands { get { - if (null == allServices) + if (null == _allServices) { List services = new List(); @@ -317,12 +318,12 @@ namespace Microsoft.PowerShell.Commands services.AddRange(ServiceController.GetServices()); } - allServices = services.ToArray(); + _allServices = services.ToArray(); } - return allServices; + return _allServices; } } - private ServiceController[] allServices = null; + private ServiceController[] _allServices = null; private void AddIfValidService(IList listOfValidServices, string nameOfService, string computerName) { @@ -368,10 +369,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected string[] SuppliedComputerName { - get { return computerName; } - set { computerName = value; } + get { return _computerName; } + set { _computerName = value; } } - private string[] computerName = new string[0]; + private string[] _computerName = new string[0]; /// /// Retrieve the list of all services matching the ServiceName, @@ -392,7 +393,6 @@ namespace Microsoft.PowerShell.Commands default: matchingServices = MatchingServicesByServiceName(); break; - } // 2004/12/16 Note that the services will be sorted // before being stopped. JimTru confirms that this is OK. @@ -657,14 +657,14 @@ namespace Microsoft.PowerShell.Commands { get { - return dependentservices; + return _dependentservices; } set { - dependentservices = value; + _dependentservices = value; } } - private SwitchParameter dependentservices; + private SwitchParameter _dependentservices; /// @@ -676,14 +676,14 @@ namespace Microsoft.PowerShell.Commands { get { - return requiredservices; + return _requiredservices; } set { - requiredservices = value; + _requiredservices = value; } } - private SwitchParameter requiredservices; + private SwitchParameter _requiredservices; #endregion Parameters @@ -695,20 +695,20 @@ namespace Microsoft.PowerShell.Commands { foreach (ServiceController service in MatchingServices()) { - if (!dependentservices.IsPresent && !requiredservices.IsPresent) + if (!_dependentservices.IsPresent && !_requiredservices.IsPresent) { WriteObject(service); } else { - if (dependentservices.IsPresent) + if (_dependentservices.IsPresent) { foreach (ServiceController dependantserv in service.DependentServices) { WriteObject(dependantserv); } } - if (requiredservices.IsPresent) + if (_requiredservices.IsPresent) { foreach (ServiceController servdependedon in service.ServicesDependedOn) { @@ -780,14 +780,14 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private SwitchParameter passThru; + private SwitchParameter _passThru; #endregion Parameters #region Internal @@ -1035,11 +1035,11 @@ namespace Microsoft.PowerShell.Commands } RemoveNotStoppedServices(stoppedServices); - if((serviceController.Status.Equals(ServiceControllerStatus.Stopped)) || (serviceController.Status.Equals(ServiceControllerStatus.StopPending))) - { + if ((serviceController.Status.Equals(ServiceControllerStatus.Stopped)) || (serviceController.Status.Equals(ServiceControllerStatus.StopPending))) + { stoppedServices.Add(serviceController); - } - + } + return stoppedServices; } @@ -1087,7 +1087,6 @@ namespace Microsoft.PowerShell.Commands /// true iff the service was paused internal bool DoPauseService(ServiceController serviceController) { - Exception exception = null; bool serviceNotRunning = false; try @@ -1166,7 +1165,6 @@ namespace Microsoft.PowerShell.Commands /// true iff the service was resumed internal bool DoResumeService(ServiceController serviceController) { - Exception exception = null; bool serviceNotRunning = false; try @@ -1202,7 +1200,6 @@ namespace Microsoft.PowerShell.Commands "CouldNotResumeServiceNotRunning", ServiceResources.CouldNotResumeServiceNotRunning, ErrorCategory.CloseError); - } else if (!serviceController.CanPauseAndContinue) { @@ -1263,14 +1260,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; /// /// Specifies whether to wait for a service to reach the stopped state before returning @@ -1280,14 +1277,14 @@ namespace Microsoft.PowerShell.Commands { get { - return nowait; + return _nowait; } set { - nowait = value; + _nowait = value; } } - private SwitchParameter nowait; + private SwitchParameter _nowait; /// /// Stop the services. @@ -1436,14 +1433,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; /// /// Stop and restart the services. @@ -1509,13 +1506,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] ComputerName { - get { return computername; } + get { return _computername; } set { - computername = value; + _computername = value; } } - private String[] computername = new string[] { "." }; + private String[] _computername = new string[] { "." }; /// /// service name @@ -1628,13 +1625,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = "InputObject")] public new ServiceController InputObject { - get { return inputobject; } + get { return _inputobject; } set { - inputobject = value; + _inputobject = value; } } - private ServiceController inputobject; + private ServiceController _inputobject; /// /// This is not a parameter for this cmdlet. @@ -1680,22 +1677,20 @@ namespace Microsoft.PowerShell.Commands [ArchitectureSensitive] protected override void ProcessRecord() { - ServiceController service = null; string ServiceComputerName = null; - foreach (string computer in computername) + foreach (string computer in _computername) { bool objServiceShouldBeDisposed = false; try { - if (_ParameterSetName.Equals("InputObject", StringComparison.OrdinalIgnoreCase) && inputobject != null) + if (_ParameterSetName.Equals("InputObject", StringComparison.OrdinalIgnoreCase) && _inputobject != null) { - service = inputobject; + service = _inputobject; Name = service.ServiceName; ServiceComputerName = service.MachineName; //computer = service.MachineName; objServiceShouldBeDisposed = false; - } else { @@ -1727,7 +1722,6 @@ namespace Microsoft.PowerShell.Commands try // In finally we ensure dispose, if object not pipelined. { - // confirm the operation first // this is always false if WhatIf is set if (!ShouldProcessServiceOperation(service)) @@ -1739,7 +1733,6 @@ namespace Microsoft.PowerShell.Commands NakedWin32Handle hService = IntPtr.Zero; try { - hScManager = NativeMethods.OpenSCManagerW( ServiceComputerName, null, @@ -1867,7 +1860,6 @@ namespace Microsoft.PowerShell.Commands //start service DoStartService(service); } - } else if (Status.Equals("Stopped", StringComparison.CurrentCultureIgnoreCase)) { @@ -1893,16 +1885,13 @@ namespace Microsoft.PowerShell.Commands //Specify NoWait parameter as always false since we are not adding this switch to this cmdlet DoStopService(service, true, true); } - } else if (Status.Equals("Paused", StringComparison.CurrentCultureIgnoreCase)) { if (!service.Status.Equals(ServiceControllerStatus.Paused)) //pause service DoPauseService(service); - } - } if (PassThru.IsPresent) { @@ -1910,7 +1899,6 @@ namespace Microsoft.PowerShell.Commands ServiceController displayservice = new ServiceController(Name, ServiceComputerName); WriteObject(displayservice); } - } finally { @@ -1943,7 +1931,6 @@ namespace Microsoft.PowerShell.Commands "CouldNotSetServiceDescription", ServiceResources.CouldNotSetServiceDescription, ErrorCategory.PermissionDenied); - } } } // finally @@ -2266,9 +2253,7 @@ namespace Microsoft.PowerShell.Commands "CouldNotNewServiceDescription", ServiceResources.CouldNotNewServiceDescription, ErrorCategory.PermissionDenied); - } - } } } @@ -2517,7 +2502,6 @@ namespace Microsoft.PowerShell.Commands public static extern bool QueryInformationJobObject(SafeHandle hJob, int JobObjectInfoClass, ref JOBOBJECT_BASIC_PROCESS_ID_LIST lpJobObjectInfo, int cbJobObjectLength, IntPtr lpReturnLength); - } #endregion NativeMethods } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index d83d4b870..3d13f6fea 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Commands [Alias("scb")] public class SetClipboardCommand : PSCmdlet { - private List contentList = new List(); + private List _contentList = new List(); private const string ValueParameterSet = "Value"; private const string PathParameterSet = "Path"; private const string LiteralPathParameterSet = "LiteralPath"; @@ -66,22 +66,22 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter AsHtml { - get { return asHtml; } + get { return _asHtml; } set { - isHtmlSet = true; - asHtml = value; + _isHtmlSet = true; + _asHtml = value; } } - private bool asHtml; - private bool isHtmlSet = false; + private bool _asHtml; + private bool _isHtmlSet = false; /// /// This method implements the BeginProcessing method for Set-Clipboard command /// protected override void BeginProcessing() { - contentList.Clear(); + _contentList.Clear(); } /// @@ -90,7 +90,7 @@ namespace Microsoft.PowerShell.Commands protected override void ProcessRecord() { // Html should only combine with Text content. - if (Value == null && isHtmlSet) + if (Value == null && _isHtmlSet) { ThrowTerminatingError(new ErrorRecord(new InvalidOperationException( String.Format(CultureInfo.InvariantCulture, ClipboardResources.InvalidHtmlCombine)), @@ -99,15 +99,15 @@ namespace Microsoft.PowerShell.Commands if (Value != null) { - contentList.AddRange(Value); + _contentList.AddRange(Value); } else if (Path != null) { - contentList.AddRange(Path); + _contentList.AddRange(Path); } else if (LiteralPath != null) { - contentList.AddRange(LiteralPath); + _contentList.AddRange(LiteralPath); } } @@ -118,15 +118,15 @@ namespace Microsoft.PowerShell.Commands { if (LiteralPath != null) { - CopyFilesToClipboard(contentList, Append, true); + CopyFilesToClipboard(_contentList, Append, true); } else if (Path != null) { - CopyFilesToClipboard(contentList, Append, false); + CopyFilesToClipboard(_contentList, Append, false); } else { - SetClipboardContent(contentList, Append, asHtml); + SetClipboardContent(_contentList, Append, _asHtml); } } @@ -416,6 +416,5 @@ EndSelection:<<<<<<<<4"; } return count; } - } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs index f01d2cbef..d806b9da8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -12,7 +13,7 @@ namespace Microsoft.PowerShell.Commands /// /// A command to set the content of an item at a specified path /// - [Cmdlet (VerbsCommon.Set, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, + [Cmdlet(VerbsCommon.Set, "Content", DefaultParameterSetName = "Path", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113392")] public class SetContentCommand : WriteContentCommandBase { @@ -43,7 +44,6 @@ namespace Microsoft.PowerShell.Commands { InvokeProvider.Content.Clear(path, context); context.ThrowFirstErrorOrDoNothing(true); - } catch (PSNotSupportedException) { @@ -72,7 +72,6 @@ namespace Microsoft.PowerShell.Commands //If the item is not found then there is nothing to clear so ignore this exception. continue; } - } } // BeforeOpenStreams @@ -98,6 +97,5 @@ namespace Microsoft.PowerShell.Commands } #endregion protected members } // SetContentCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs index aeac9f819..fc423bfb5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -24,9 +25,9 @@ namespace Microsoft.PowerShell.Commands /// /// Gets or sets the path parameter to the command /// - [Parameter(Position = 0, ParameterSetName = propertyPSObjectPathSet, + [Parameter(Position = 0, ParameterSetName = propertyPSObjectPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] - [Parameter(Position = 0, ParameterSetName = propertyValuePathSet, + [Parameter(Position = 0, ParameterSetName = propertyValuePathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Path { @@ -73,24 +74,24 @@ namespace Microsoft.PowerShell.Commands /// This value type is determined by the InvokeProvider. /// /// - [Parameter(Position=1, ParameterSetName = propertyValuePathSet, - Mandatory=true, ValueFromPipelineByPropertyName = true)] - [Parameter(Position=1, ParameterSetName = propertyValueLiteralPathSet, - Mandatory=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ParameterSetName = propertyValuePathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ParameterSetName = propertyValueLiteralPathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] [Alias("PSProperty")] public string Name { get { - return property; + return _property; } // get set { - property = value; + _property = value; } } // Property - + /// /// The value of the property to set. @@ -100,21 +101,21 @@ namespace Microsoft.PowerShell.Commands /// This value type is determined by the InvokeProvider. /// /// - [Parameter(Position=2, ParameterSetName = propertyValuePathSet, - Mandatory=true, ValueFromPipelineByPropertyName = true)] - [Parameter(Position=2, ParameterSetName = propertyValueLiteralPathSet, - Mandatory=true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 2, ParameterSetName = propertyValuePathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 2, ParameterSetName = propertyValueLiteralPathSet, + Mandatory = true, ValueFromPipelineByPropertyName = true)] [AllowNull] public object Value { get { - return content; + return _content; } // get set { - content = value; + _content = value; } } // Value @@ -136,12 +137,12 @@ namespace Microsoft.PowerShell.Commands { get { - return propertyTable; + return _propertyTable; } //get set { - propertyTable = value; + _propertyTable = value; } // set } // PropertyTable #endregion Shell Object set @@ -169,7 +170,7 @@ namespace Microsoft.PowerShell.Commands { case propertyValuePathSet: case propertyValueLiteralPathSet: - if (! String.IsNullOrEmpty(Name)) + if (!String.IsNullOrEmpty(Name)) { mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty(Name, Value)); @@ -187,25 +188,25 @@ namespace Microsoft.PowerShell.Commands } return InvokeProvider.Property.SetPropertyDynamicParameters(".", mshObject, context); } // GetDynamicParameters - + #endregion Parameters #region parameter data - + /// /// The value of the property to be set. /// - private object content; + private object _content; /// /// The name of the property to be set. /// - private string property = String.Empty; + private string _property = String.Empty; /// /// The properties to be set contained within a PSObject /// - private PSObject propertyTable; + private PSObject _propertyTable; #endregion parameter data @@ -214,7 +215,7 @@ namespace Microsoft.PowerShell.Commands /// /// Sets the content of the item at the specified path /// - protected override void ProcessRecord () + protected override void ProcessRecord() { // Default to the CmdletProviderContext that will direct output to // the pipeline. @@ -287,5 +288,4 @@ namespace Microsoft.PowerShell.Commands } // SetItemPropertyCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs index f43d604c7..baca835c8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; using System.Management; @@ -30,8 +31,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "object")] public ManagementObject InputObject { - get { return this.inputObject; } - set { this.inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } /// /// The WMI Path to use @@ -39,8 +40,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "path", Mandatory = true)] public string Path { - get { return this.path; } - set { this.path = value; } + get { return _path; } + set { _path = value; } } /// /// The WMI class to use @@ -48,8 +49,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = true, ParameterSetName = "class")] public string Class { - get { return this.className; } - set { this.className = value; } + get { return _className; } + set { _className = value; } } /// /// The property name /value pair @@ -61,28 +62,28 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable Arguments { - get { return this.propertyBag; } - set { this.propertyBag = value; } + get { return _propertyBag; } + set { _propertyBag = value; } } /// /// The Flag to use /// [Parameter] - public PutType PutType + public PutType PutType { - get { return this.putType; } - set { this.putType = value; flagSpecified = true;} + get { return _putType; } + set { _putType = value; flagSpecified = true; } } #endregion Parameters #region parameter data internal bool flagSpecified = false; - private string path = null; - private string className = null; - private ManagementObject inputObject = null; - private Hashtable propertyBag = null; - private PutType putType = PutType.None; + private string _path = null; + private string _className = null; + private ManagementObject _inputObject = null; + private Hashtable _propertyBag = null; + private PutType _putType = PutType.None; #endregion parameter data @@ -92,12 +93,12 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if( this.AsJob ) + if (this.AsJob) { RunAsJob("Set-WMIInstance"); return; } - if (inputObject != null) + if (_inputObject != null) { object result = null; ManagementObject mObj = null; @@ -105,10 +106,10 @@ namespace Microsoft.PowerShell.Commands { PutOptions pOptions = new PutOptions(); mObj = SetWmiInstanceGetPipelineObject(); - pOptions.Type = putType; - if( mObj != null) + pOptions.Type = _putType; + if (mObj != null) { - if (!ShouldProcess(mObj.Path.Path.ToString()) ) + if (!ShouldProcess(mObj.Path.Path.ToString())) { return; } @@ -139,7 +140,7 @@ namespace Microsoft.PowerShell.Commands //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 != null) { if (!(mPath.Server == "." && serverNameSpecified)) { @@ -155,12 +156,12 @@ namespace Microsoft.PowerShell.Commands result = null; try { - mObject = this.SetWmiInstanceGetObject(mPath,name); + mObject = this.SetWmiInstanceGetObject(mPath, name); PutOptions pOptions = new PutOptions(); - pOptions.Type = putType; - if( mObject != null) + pOptions.Type = _putType; + if (mObject != null) { - if (!ShouldProcess(mObject.Path.Path.ToString()) ) + if (!ShouldProcess(mObject.Path.Path.ToString())) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs index 3754775dc..3a074935d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; @@ -23,22 +24,22 @@ namespace Microsoft.PowerShell.Commands { get { - return (int) timeout.TotalMinutes; + 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); + if (value == 0) + _timeout = TimeSpan.FromTicks(1); else - timeout = TimeSpan.FromMinutes(value); - - timeoutSpecified = true; + _timeout = TimeSpan.FromMinutes(value); + + _timeoutSpecified = true; } } - bool timeoutSpecified = false; - private TimeSpan timeout = TimeSpan.MinValue; + private bool _timeoutSpecified = false; + private TimeSpan _timeout = TimeSpan.MinValue; /// /// Gets or sets the flag to determine if this transaction can @@ -47,10 +48,10 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter Independent { - get { return independent; } - set { independent = value; } + get { return _independent; } + set { _independent = value; } } - private SwitchParameter independent; + private SwitchParameter _independent; /// /// Gets or sets the rollback preference for this transaction. @@ -58,48 +59,46 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public RollbackSeverity RollbackPreference { - get { return rollbackPreference; } - set { rollbackPreference = value; } + get { return _rollbackPreference; } + set { _rollbackPreference = value; } } - private RollbackSeverity rollbackPreference = RollbackSeverity.Error; - + private RollbackSeverity _rollbackPreference = RollbackSeverity.Error; + /// /// Creates a new transaction. /// - protected override void EndProcessing () + protected override void EndProcessing() { - if(ShouldProcess( + if (ShouldProcess( NavigationResources.TransactionResource, NavigationResources.CreateAction)) { // Set the default timeout - if(! timeoutSpecified) + 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) + if (MyInvocation.CommandOrigin == CommandOrigin.Runspace) { - timeout = TimeSpan.MaxValue; + _timeout = TimeSpan.MaxValue; } else { - timeout = TimeSpan.FromMinutes(30); + _timeout = TimeSpan.FromMinutes(30); } } - + // Create the new transaction - if(independent) + if (_independent) { - this.Context.TransactionManager.CreateNew(rollbackPreference, timeout); + this.Context.TransactionManager.CreateNew(_rollbackPreference, _timeout); } else { - this.Context.TransactionManager.CreateOrJoin(rollbackPreference, timeout); + this.Context.TransactionManager.CreateOrJoin(_rollbackPreference, _timeout); } } } - } // StartTransactionCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs index a15be18f7..cdbee0782 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands [Alias("gtz")] public class GetTimeZoneCommand : PSCmdlet { - #region Parameters +#region Parameters /// /// A list of the local time zone ids that the cmdlet should look up. @@ -42,7 +42,7 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get; set; } - #endregion Parameters +#endregion Parameters /// /// Implementation of the ProcessRecord method for Get-TimeZone @@ -131,18 +131,18 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Set, "TimeZone", SupportsShouldProcess = true, - DefaultParameterSetName = "Name", + DefaultParameterSetName = "Name", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=799469")] [Alias("stz")] public class SetTimeZoneCommand : PSCmdlet { - #region string constants +#region string constants private const string TimeZoneTarget = "Local System"; - #endregion string constants +#endregion string constants - #region Parameters +#region Parameters /// /// The name of the local time zone that the system should use. @@ -168,7 +168,7 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter PassThru { get; set; } - #endregion Parameters +#endregion Parameters /// /// Implementation of the ProcessRecord method for Get-TimeZone @@ -357,7 +357,7 @@ namespace Microsoft.PowerShell.Commands } } - #region Helper functions +#region Helper functions /// /// True if the current process has access to change the time zone setting. @@ -461,9 +461,9 @@ namespace Microsoft.PowerShell.Commands throw new Win32Exception(error); } - #endregion Helper functions +#endregion Helper functions - #region Win32 interop helper +#region Win32 interop helper internal class NativeMethods { @@ -474,7 +474,7 @@ namespace Microsoft.PowerShell.Commands { } - #region Native DLL locations +#region Native DLL locations #if CORECLR private const string SetDynamicTimeZoneApiDllName = "api-ms-win-core-timezone-l1-1-0.dll"; @@ -498,9 +498,9 @@ namespace Microsoft.PowerShell.Commands private const string SendMessageTimeoutApiDllName = "user32.dll"; #endif - #endregion Native DLL locations +#endregion Native DLL locations - #region Win32 SetDynamicTimeZoneInformation imports +#region Win32 SetDynamicTimeZoneInformation imports /// /// Used to marshal win32 SystemTime structure to managed code layer @@ -653,9 +653,9 @@ namespace Microsoft.PowerShell.Commands [DllImport(GetTimeZoneInformationForYearApiDllName, SetLastError = true)] public static extern bool GetTimeZoneInformationForYear([In] ushort wYear, [In] ref DYNAMIC_TIME_ZONE_INFORMATION pdtzi, ref TIME_ZONE_INFORMATION ptzi); - #endregion Win32 SetDynamicTimeZoneInformation imports +#endregion Win32 SetDynamicTimeZoneInformation imports - #region Win32 AdjustTokenPrivilege imports +#region Win32 AdjustTokenPrivilege imports /// /// Definition of TOKEN_QUERY constant from Win32 API @@ -765,9 +765,9 @@ namespace Microsoft.PowerShell.Commands public int Attributes; } - #endregion Win32 AdjustTokenPrivilege imports +#endregion Win32 AdjustTokenPrivilege imports - #region Win32 SendMessage imports +#region Win32 SendMessage imports /// /// Definition of WM_SETTINGCHANGE constant from Win32 API @@ -798,10 +798,10 @@ namespace Microsoft.PowerShell.Commands [DllImport(SendMessageTimeoutApiDllName, SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, string lParam, int fuFlags, int uTimeout, ref int lpdwResult); - #endregion Win32 SendMessage imports +#endregion Win32 SendMessage imports } - #endregion Win32 interop helper +#endregion Win32 interop helper } @@ -810,14 +810,14 @@ namespace Microsoft.PowerShell.Commands /// internal static class TimeZoneHelper { - #region Error Ids +#region Error Ids internal const string TimeZoneNotFoundError = "TimeZoneNotFound"; internal const string MultipleMatchingTimeZonesError = "MultipleMatchingTimeZones"; internal const string InsufficientPermissionsError = "InsufficientPermissions"; internal const string SetTimeZoneFailedError = "SetTimeZoneFailed"; - #endregion Error Ids +#endregion Error Ids /// /// Clear the cached TimeZoneInfo data. Note that since TimeZoneInfo.ClearCachedData diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs index b0b105dc0..84d9b1fc0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -24,35 +25,35 @@ namespace Microsoft.PowerShell.Commands { get { - return transactedScript; + return _transactedScript; } set { - transactedScript = value; + _transactedScript = value; } } - private ScriptBlock transactedScript; + private ScriptBlock _transactedScript; /// /// Commits the current transaction /// - protected override void EndProcessing () + protected override void EndProcessing() { - using(CurrentPSTransaction) + using (CurrentPSTransaction) { try { var emptyArray = Utils.EmptyArray(); - transactedScript.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: null, - input: emptyArray, - scriptThis: AutomationNull.Value, - args: emptyArray); + _transactedScript.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: null, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); } - catch(Exception e) + catch (Exception e) { // Catch-all OK. This is a third-party call-out. CommandProcessorBase.CheckForSevereException(e); @@ -63,9 +64,9 @@ namespace Microsoft.PowerShell.Commands // exceedingly obtuse. We clarify things here. bool isTimeoutException = false; Exception tempException = e; - while(tempException != null) + while (tempException != null) { - if(tempException is System.TimeoutException) + if (tempException is System.TimeoutException) { isTimeoutException = true; break; @@ -74,7 +75,7 @@ namespace Microsoft.PowerShell.Commands tempException = tempException.InnerException; } - if(isTimeoutException) + if (isTimeoutException) { errorRecord = new ErrorRecord( new InvalidOperationException( @@ -88,8 +89,6 @@ namespace Microsoft.PowerShell.Commands } } } - } // CommitTransactionCommand - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index 21f4c6e7d..e65710c78 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Globalization; using System.Management.Automation; @@ -21,7 +22,7 @@ using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { -#region Helper Classes + #region Helper Classes /// /// Base class for all WMI helper classes. This is an abstract class @@ -41,8 +42,7 @@ namespace Microsoft.PowerShell.Commands } } protected Exception internalException = null; - - } + } /// /// This class is responsible for creating WMI connection for getting objects and notifications @@ -58,13 +58,13 @@ namespace Microsoft.PowerShell.Commands /// 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) + internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results) { - this.wmiObject = wmiObject; - this.computerName = computerName; - this.results = results; + _wmiObject = wmiObject; + _computerName = computerName; + _results = results; this.State = WmiState.NotStarted; - this.Job = childJob; + _job = childJob; } /// @@ -79,46 +79,46 @@ namespace Microsoft.PowerShell.Commands internal WmiAsyncCmdletHelper(PSWmiChildJob childJob, Cmdlet wmiObject, string computerName, ManagementOperationObserver results, int count) : this(childJob, wmiObject, computerName, results) { - this.cmdCount = count; + _cmdCount = count; } - private string computerName; + private string _computerName; internal event EventHandler WmiOperationState; internal event EventHandler ShutdownComplete; - private ManagementOperationObserver results; - private int cmdCount = 1; - private PSWmiChildJob Job; + private ManagementOperationObserver _results; + private int _cmdCount = 1; + private PSWmiChildJob _job; /// /// current operation state /// internal WmiState State { - get { return state; } - set { state = value; } + get { return _state; } + set { _state = value; } } - - private WmiState state ; + + private WmiState _state; /// /// Cancel WMI connection /// internal override void StopOperation() { - this.results.Cancel(); - state = WmiState.Stopped; + _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)this.wmiObject; + 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)) + if (!String.IsNullOrEmpty(getObject.Filter)) { returnValue.Append(" where "); returnValue.Append(getObject.Filter); @@ -132,27 +132,27 @@ namespace Microsoft.PowerShell.Commands internal override void StartOperation() { Thread thread; - if( this.wmiObject.GetType() == typeof(GetWmiObjectCommand)) + if (_wmiObject.GetType() == typeof(GetWmiObjectCommand)) { - thread = new Thread (new ThreadStart(ConnectGetWMI)); + thread = new Thread(new ThreadStart(ConnectGetWMI)); } - else if( this.wmiObject.GetType() == typeof(RemoveWmiObject) ) + else if (_wmiObject.GetType() == typeof(RemoveWmiObject)) { - thread = new Thread( new ThreadStart(ConnectRemoveWmi)); + thread = new Thread(new ThreadStart(ConnectRemoveWmi)); } - else if( this.wmiObject.GetType() == typeof(InvokeWmiMethod) ) + else if (_wmiObject.GetType() == typeof(InvokeWmiMethod)) { - thread = new Thread( new ThreadStart(ConnectInvokeWmi)); + thread = new Thread(new ThreadStart(ConnectInvokeWmi)); } - else if( this.wmiObject.GetType() == typeof(SetWmiInstance) ) + else if (_wmiObject.GetType() == typeof(SetWmiInstance)) { - thread = new Thread( new ThreadStart(ConnectSetWmi)); + thread = new Thread(new ThreadStart(ConnectSetWmi)); } else { - InvalidOperationException exception = new InvalidOperationException ( "This operation is not supported for this cmdlet." ); + InvalidOperationException exception = new InvalidOperationException("This operation is not supported for this cmdlet."); internalException = exception; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -160,24 +160,22 @@ namespace Microsoft.PowerShell.Commands //thread.SetApartmentState( ApartmentState.STA); thread.Start(); } - + /// /// /// internal override event EventHandler OperationComplete; - - private Cmdlet wmiObject; + + 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); - } // RaiseOperationCompleteEvent /// @@ -186,7 +184,7 @@ namespace Microsoft.PowerShell.Commands internal void RaiseWmiOperationState(EventArgs baseEventArgs, WmiState state) { WmiJobStateEventArgs wmiJobStateEventArgs = new WmiJobStateEventArgs(); - wmiJobStateEventArgs.WmiState= state; + wmiJobStateEventArgs.WmiState = state; WmiOperationState.SafeInvoke(this, wmiJobStateEventArgs); } @@ -195,9 +193,9 @@ namespace Microsoft.PowerShell.Commands /// private void ConnectSetWmi() { - SetWmiInstance setObject = (SetWmiInstance) this.wmiObject; - state = WmiState.Running; - RaiseWmiOperationState(null,WmiState.Running); + SetWmiInstance setObject = (SetWmiInstance)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); if (setObject.InputObject != null) { ManagementObject mObj = null; @@ -208,11 +206,11 @@ namespace Microsoft.PowerShell.Commands if (setObject.InputObject.GetType() == typeof(ManagementClass)) { //Check if Flag specified is CreateOnly or not - if( setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException e = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -222,13 +220,13 @@ namespace Microsoft.PowerShell.Commands else { //Check if Flag specified is Updateonly or UpdateOrCreateOnly or not - if( setObject.flagSpecified ) + if (setObject.flagSpecified) { - if( !(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) + if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) { InvalidOperationException e = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -237,7 +235,7 @@ namespace Microsoft.PowerShell.Commands { setObject.PutType = PutType.UpdateOrCreate; } - + mObj = (ManagementObject)setObject.InputObject.Clone(); } if (setObject.Arguments != null) @@ -249,34 +247,34 @@ namespace Microsoft.PowerShell.Commands } } pOptions.Type = setObject.PutType; - if( mObj != null) + if (mObj != null) { - mObj.Put(this.results,pOptions); + mObj.Put(_results, pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } @@ -284,13 +282,13 @@ namespace Microsoft.PowerShell.Commands { ManagementPath mPath = null; //If Class is specified only CreateOnly flag is supported - if( setObject.Class != null) + if (setObject.Class != null) { - if( setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -307,7 +305,7 @@ namespace Microsoft.PowerShell.Commands { InvalidOperationException exp = new InvalidOperationException("NamespaceSpecifiedWithPath"); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -316,17 +314,17 @@ namespace Microsoft.PowerShell.Commands { InvalidOperationException exp = new InvalidOperationException("ComputerNameSpecifiedWithPath"); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } - if( mPath.IsClass) + if (mPath.IsClass) { - if( setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) + if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { InvalidOperationException exp = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -334,13 +332,13 @@ namespace Microsoft.PowerShell.Commands } else { - if( setObject.flagSpecified ) + if (setObject.flagSpecified) { - if( !(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) + if (!(setObject.PutType == PutType.UpdateOnly || setObject.PutType == PutType.UpdateOrCreate)) { InvalidOperationException exp = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } @@ -352,20 +350,20 @@ namespace Microsoft.PowerShell.Commands } } //If server name is specified loop through it. - if( mPath != null) + if (mPath != null) { if (!(mPath.Server == "." && setObject.serverNameSpecified)) { - computerName = mPath.Server; + _computerName = mPath.Server; } } ConnectionOptions options = setObject.GetConnectionOption(); ManagementObject mObject = null; try { - if (setObject.Path != null) + if (setObject.Path != null) { - mPath.Server = computerName; + mPath.Server = _computerName; ManagementScope mScope = new ManagementScope(mPath, options); if (mPath.IsClass) { @@ -387,28 +385,28 @@ namespace Microsoft.PowerShell.Commands if (e.ErrorCode != ManagementStatus.NotFound) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } int namespaceIndex = setObject.Path.IndexOf(':'); - if( namespaceIndex == -1 ) + if (namespaceIndex == -1) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); - if( classIndex == -1 ) + if (classIndex == -1) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } //Get class object and create instance. - string newPath = setObject.Path.Substring(0,classIndex+namespaceIndex); + string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); ManagementPath classPath = new ManagementPath(newPath); ManagementClass mClass = new ManagementClass(classPath); mClass.Scope = mScope; @@ -419,7 +417,7 @@ namespace Microsoft.PowerShell.Commands } else { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(computerName, setObject.Namespace), options); + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, setObject.Namespace), options); ManagementClass mClass = new ManagementClass(setObject.Class); mClass.Scope = scope; mObject = mClass.CreateInstance(); @@ -431,58 +429,58 @@ namespace Microsoft.PowerShell.Commands { mObject[en.Key as string] = en.Value; } - } + } PutOptions pOptions = new PutOptions(); pOptions.Type = setObject.PutType; - if(mObject != null) + if (mObject != null) { - mObject.Put(this.results, pOptions); + mObject.Put(_results, pOptions); } else { InvalidOperationException exp = new InvalidOperationException(); internalException = exp; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } } - + /// /// Do the actual connection to remote machine for Invokd-WMIMethod cmdlet and raise operation complete event. /// private void ConnectInvokeWmi() { - InvokeWmiMethod invokeObject = (InvokeWmiMethod)this.wmiObject; - state = WmiState.Running; - RaiseWmiOperationState(null,WmiState.Running); + InvokeWmiMethod invokeObject = (InvokeWmiMethod)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); if (invokeObject.InputObject != null) { - ManagementBaseObject inputParameters =null ; + ManagementBaseObject inputParameters = null; try { inputParameters = invokeObject.InputObject.GetMethodParameters(invokeObject.Name); - if(invokeObject.ArgumentList != null ) + if (invokeObject.ArgumentList != null) { int inParamCount = invokeObject.ArgumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -493,24 +491,24 @@ namespace Microsoft.PowerShell.Commands inParamCount--; } } - invokeObject.InputObject.InvokeMethod(this.results, invokeObject.Name, inputParameters,null); + invokeObject.InputObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; @@ -520,34 +518,34 @@ namespace Microsoft.PowerShell.Commands ConnectionOptions options = invokeObject.GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; - if( invokeObject.Path != null) + if (invokeObject.Path != null) { mPath = new ManagementPath(invokeObject.Path); - if(String.IsNullOrEmpty(mPath.NamespacePath)) + if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = invokeObject.Namespace; } - else if( invokeObject.namespaceSpecified ) + else if (invokeObject.namespaceSpecified) { InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } - - if( mPath.Server != "." && invokeObject.serverNameSpecified ) + + if (mPath.Server != "." && invokeObject.serverNameSpecified) { InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } //If server name is specified loop through it. - if ( !(mPath.Server == "." && invokeObject.serverNameSpecified)) + if (!(mPath.Server == "." && invokeObject.serverNameSpecified)) { - computerName = mPath.Server ; + _computerName = mPath.Server; } } @@ -555,26 +553,26 @@ namespace Microsoft.PowerShell.Commands PlatformInvokes.TOKEN_PRIVILEGE currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); try { - needToEnablePrivilege = NeedToEnablePrivilege(computerName, invokeObject.Name, ref isLocal); + 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, + 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; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } - if( invokeObject.Path != null ) + if (invokeObject.Path != null) { - mPath.Server = computerName; + mPath.Server = _computerName; if (mPath.IsClass) { ManagementClass mClass = new ManagementClass(mPath); @@ -590,14 +588,14 @@ namespace Microsoft.PowerShell.Commands } else { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(computerName, invokeObject.Namespace), options); + 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 ) + ManagementBaseObject inputParameters = mObject.GetMethodParameters(invokeObject.Name); + if (invokeObject.ArgumentList != null) { int inParamCount = invokeObject.ArgumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -608,7 +606,7 @@ namespace Microsoft.PowerShell.Commands inParamCount--; } } - + if (needToEnablePrivilege) { ManagementBaseObject result = mObject.InvokeMethod(invokeObject.Name, inputParameters, null); @@ -618,7 +616,7 @@ namespace Microsoft.PowerShell.Commands { var e = new Win32Exception(returnCode); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else @@ -628,25 +626,25 @@ namespace Microsoft.PowerShell.Commands } else { - mObject.InvokeMethod(this.results, invokeObject.Name, inputParameters, null); + mObject.InvokeMethod(_results, invokeObject.Name, inputParameters, null); } } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } finally @@ -690,38 +688,37 @@ namespace Microsoft.PowerShell.Commands return result; } - + /// /// Do the actual connection to remote machine for Remove-WMIObject cmdlet and raise operation complete event. /// private void ConnectRemoveWmi() { - RemoveWmiObject removeObject = (RemoveWmiObject)this.wmiObject; - state = WmiState.Running; - RaiseWmiOperationState(null,WmiState.Running); + RemoveWmiObject removeObject = (RemoveWmiObject)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); if (removeObject.InputObject != null) { try { - removeObject.InputObject.Delete(this.results); - + removeObject.InputObject.Delete(_results); } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; @@ -734,37 +731,37 @@ namespace Microsoft.PowerShell.Commands if (removeObject.Path != null) { mPath = new ManagementPath(removeObject.Path); - if(String.IsNullOrEmpty(mPath.NamespacePath)) + if (String.IsNullOrEmpty(mPath.NamespacePath)) { mPath.NamespacePath = removeObject.Namespace; } - else if( removeObject.namespaceSpecified) + else if (removeObject.namespaceSpecified) { InvalidOperationException e = new InvalidOperationException("NamespaceSpecifiedWithPath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } - if( mPath.Server != "." && removeObject.serverNameSpecified) + if (mPath.Server != "." && removeObject.serverNameSpecified) { InvalidOperationException e = new InvalidOperationException("ComputerNameSpecifiedWithPath"); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } if (!(mPath.Server == "." && removeObject.serverNameSpecified)) { - computerName = mPath.Server; + _computerName = mPath.Server; } } try { - if( removeObject.Path != null ) + if (removeObject.Path != null) { - mPath.Server = computerName; + mPath.Server = _computerName; if (mPath.IsClass) { ManagementClass mClass = new ManagementClass(mPath); @@ -780,46 +777,46 @@ namespace Microsoft.PowerShell.Commands } else { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(computerName, removeObject.Namespace), options); + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, removeObject.Namespace), options); ManagementClass mClass = new ManagementClass(removeObject.Class); mObject = mClass; mObject.Scope = scope; } - mObject.Delete(this.results); + mObject.Delete(_results); } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _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)this.wmiObject; - state = WmiState.Running; - RaiseWmiOperationState(null,WmiState.Running); + GetWmiObjectCommand getObject = (GetWmiObjectCommand)_wmiObject; + _state = WmiState.Running; + RaiseWmiOperationState(null, WmiState.Running); ConnectionOptions options = getObject.GetConnectionOption(); if (getObject.List.IsPresent) { - if(!getObject.ValidateClassFormat( ) ) + if (!getObject.ValidateClassFormat()) { ArgumentException e = new ArgumentException( String.Format( @@ -827,13 +824,13 @@ namespace Microsoft.PowerShell.Commands "Class", getObject.Class)); internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } try { - if( getObject.Recurse.IsPresent) + if (getObject.Recurse.IsPresent) { ArrayList namespaceArray = new ArrayList(); ArrayList sinkArray = new ArrayList(); @@ -841,54 +838,54 @@ namespace Microsoft.PowerShell.Commands int currentNamesapceCount = 0; namespaceArray.Add(getObject.Namespace); bool topNamespace = true; - while(currentNamesapceCount < namespaceArray.Count) + while (currentNamesapceCount < namespaceArray.Count) { string connectNamespace = (string)namespaceArray[currentNamesapceCount]; - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, connectNamespace), options); + 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() ) + ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); + foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) { - if( !getObject.IsLocalizedNamespace( (string)obj["Name"]) ) + if (!getObject.IsLocalizedNamespace((string)obj["Name"])) { namespaceArray.Add(connectNamespace + "\\" + obj["Name"]); } } - if( topNamespace) + if (topNamespace) { - topNamespace = false; - sinkArray.Add(this.results); + topNamespace = false; + sinkArray.Add(_results); } else { - sinkArray.Add(Job.GetNewSink()); + sinkArray.Add(_job.GetNewSink()); } - connectArray.Add(scope); + connectArray.Add(scope); currentNamesapceCount++; } - - if( (sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception + + if ((sinkArray.Count != namespaceArray.Count) || (connectArray.Count != namespaceArray.Count)) // not expected throw exception { internalException = new InvalidOperationException(); - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } currentNamesapceCount = 0; - while(currentNamesapceCount < namespaceArray.Count ) + while (currentNamesapceCount < namespaceArray.Count) { string connectNamespace = (string)namespaceArray[currentNamesapceCount]; - ManagementObjectSearcher searcher = getObject.GetObjectList( (ManagementScope)connectArray[currentNamesapceCount]); - if( searcher == null ) + ManagementObjectSearcher searcher = getObject.GetObjectList((ManagementScope)connectArray[currentNamesapceCount]); + if (searcher == null) { currentNamesapceCount++; continue; } - if( topNamespace ) + if (topNamespace) { topNamespace = false; - searcher.Get(this.results); + searcher.Get(_results); } else { @@ -896,35 +893,33 @@ namespace Microsoft.PowerShell.Commands } currentNamesapceCount++; } - } else { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getObject.Namespace), options); + ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(_computerName, getObject.Namespace), options); scope.Connect(); ManagementObjectSearcher searcher = getObject.GetObjectList(scope); - if( searcher == null) + if (searcher == null) throw new ManagementException(); - searcher.Get(this.results); + searcher.Get(_results); } - } catch (ManagementException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.Runtime.InteropServices.COMException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (System.UnauthorizedAccessException e) { internalException = e; - state = WmiState.Failed; + _state = WmiState.Failed; RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; @@ -933,34 +928,34 @@ namespace Microsoft.PowerShell.Commands ObjectQuery query = new ObjectQuery(queryString.ToString()); try { - ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getObject.Namespace), options); + 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 - internal sealed class WmiJobStateEventArgs:EventArgs + internal sealed class WmiJobStateEventArgs : EventArgs { /// /// WMI state /// internal WmiState WmiState { - get {return wmiState; } - set{ wmiState = value;} + get { return _wmiState; } + set { _wmiState = value; } } - private WmiState wmiState; + private WmiState _wmiState; } - /// + /// /// Enumerated type defining the state of the WMI operation /// public enum WmiState @@ -1029,48 +1024,48 @@ namespace Microsoft.PowerShell.Commands #endregion Helper Classes - /// + /// /// A class to set WMI connection options /// - public class WmiBaseCmdlet:Cmdlet + public class WmiBaseCmdlet : Cmdlet { #region Parameters - /// + /// /// Perform Async operation /// [Parameter] public SwitchParameter AsJob { - get { return this.async; } - set { this.async = value; } + get { return _async; } + set { _async = value; } } - + /// /// The Impersonation level to use /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] public ImpersonationLevel Impersonation { - get { return this.impersonationLevel; } - set { this.impersonationLevel = value; } + get { return _impersonationLevel; } + set { _impersonationLevel = value; } } /// /// The Authentication level to use /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] public AuthenticationLevel Authentication { - get { return this.authenticationLevel; } - set { this.authenticationLevel = value; } + get { return _authenticationLevel; } + set { _authenticationLevel = value; } } /// @@ -1078,26 +1073,26 @@ namespace Microsoft.PowerShell.Commands /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] public string Locale { - get { return this.locale; } - set { this.locale = value; } + get { return _locale; } + set { _locale = value; } } /// /// If all Privileges are enabled /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] public SwitchParameter EnableAllPrivileges { - get { return enableAllPrivileges; } - set { enableAllPrivileges = value; } + get { return _enableAllPrivileges; } + set { _enableAllPrivileges = value; } } /// @@ -1105,27 +1100,27 @@ namespace Microsoft.PowerShell.Commands /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] public string Authority { - get { return authority; } - set { authority = value; } + get { return _authority; } + set { _authority = value; } } /// /// The credential to use /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] [Credential()] public PSCredential Credential { - get { return this.credential; } - set { this.credential = value; } + get { return _credential; } + set { _credential = value; } } /// /// The credential to use @@ -1133,51 +1128,51 @@ namespace Microsoft.PowerShell.Commands [Parameter] public Int32 ThrottleLimit { - get { return this.throttleLimit; } - set { this.throttleLimit = value; } + get { return _throttleLimit; } + set { _throttleLimit = value; } } /// /// The ComputerName in which to query /// [Parameter(ParameterSetName = "path")] [Parameter(ParameterSetName = "class")] - [Parameter(ParameterSetName ="WQLQuery")] - [Parameter(ParameterSetName ="query")] - [Parameter(ParameterSetName ="list")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] [ValidateNotNullOrEmpty] [Alias("Cn")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ComputerName { - get { return this.computerName; } - set { this.computerName = value; serverNameSpecified = true; } + 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")] + [Parameter(ParameterSetName = "WQLQuery")] + [Parameter(ParameterSetName = "query")] + [Parameter(ParameterSetName = "list")] [Alias("NS")] public string Namespace { - get { return this.nameSpace; } - set { this.nameSpace = value; namespaceSpecified = true;} + get { return _nameSpace; } + set { _nameSpace = value; namespaceSpecified = true; } } #endregion Parameters - + #region parameter data /// /// The computer to query. /// - private string[] computerName = new string[] { "localhost" }; - /// + private string[] _computerName = new string[] { "localhost" }; + /// /// WMI namespace /// - private string nameSpace = "root\\cimv2"; - /// + private string _nameSpace = "root\\cimv2"; + /// /// Specify if namespace was specified or not. /// internal bool namespaceSpecified = false; @@ -1188,36 +1183,36 @@ namespace Microsoft.PowerShell.Commands /// /// The credential to use /// - private PSCredential credential; + private PSCredential _credential; /// /// The Impersonation level to use /// - private ImpersonationLevel impersonationLevel = ImpersonationLevel.Impersonate; + private ImpersonationLevel _impersonationLevel = ImpersonationLevel.Impersonate; /// /// The Authentication level to use /// - private AuthenticationLevel authenticationLevel = AuthenticationLevel.PacketPrivacy; + private AuthenticationLevel _authenticationLevel = AuthenticationLevel.PacketPrivacy; /// /// The Locale to use /// - private string locale = null; + private string _locale = null; /// /// If all Privileges are enabled /// - private SwitchParameter enableAllPrivileges; + private SwitchParameter _enableAllPrivileges; /// /// The Authority to use /// - private string authority = null; + private string _authority = null; /// /// To perform async operation /// - private SwitchParameter async = false; - /// + private SwitchParameter _async = false; + /// /// Set throttle limit /// - private Int32 throttleLimit = DEFAULT_THROTTLE_LIMIT; - private static int DEFAULT_THROTTLE_LIMIT = 32; // maximum number of items to be processed at a time + private Int32 _throttleLimit = s_DEFAULT_THROTTLE_LIMIT; + private static int s_DEFAULT_THROTTLE_LIMIT = 32; // maximum number of items to be processed at a time #endregion parameter data @@ -1236,7 +1231,7 @@ namespace Microsoft.PowerShell.Commands options.Impersonation = this.Impersonation; if (this.Credential != null) { - if( !(this.Credential.UserName == null && this.Credential.Password == null) ) // Empty credential, use implicit credential + if (!(this.Credential.UserName == null && this.Credential.Password == null)) // Empty credential, use implicit credential { options.Username = this.Credential.UserName; options.SecurePassword = this.Credential.Password; @@ -1247,14 +1242,14 @@ namespace Microsoft.PowerShell.Commands /// /// Set wmi instance helper /// - internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath,string serverName) + internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string serverName) { ConnectionOptions options = GetConnectionOption(); ManagementObject mObject = null; - if( this.GetType() == typeof(SetWmiInstance) ) + if (this.GetType() == typeof(SetWmiInstance)) { - SetWmiInstance setObject = (SetWmiInstance)this; - if (setObject.Path != null) + SetWmiInstance setObject = (SetWmiInstance)this; + if (setObject.Path != null) { mPath.Server = serverName; ManagementScope mScope = new ManagementScope(mPath, options); @@ -1280,17 +1275,17 @@ namespace Microsoft.PowerShell.Commands throw; } int namespaceIndex = setObject.Path.IndexOf(':'); - if( namespaceIndex == -1 ) + if (namespaceIndex == -1) { throw; } int classIndex = (setObject.Path.Substring(namespaceIndex)).IndexOf('.'); - if( classIndex == -1 ) + if (classIndex == -1) { throw; } //Get class object and create instance. - string newPath = setObject.Path.Substring(0,classIndex+namespaceIndex); + string newPath = setObject.Path.Substring(0, classIndex + namespaceIndex); ManagementPath classPath = new ManagementPath(newPath); ManagementClass mClass = new ManagementClass(classPath); mClass.Scope = mScope; @@ -1323,20 +1318,20 @@ namespace Microsoft.PowerShell.Commands internal ManagementPath SetWmiInstanceBuildManagementPath() { ManagementPath mPath = null; - if( this.GetType() == typeof(SetWmiInstance) ) - { + if (this.GetType() == typeof(SetWmiInstance)) + { SetWmiInstance wmiInstance = (SetWmiInstance)this; //If Class is specified only CreateOnly flag is supported - if( wmiInstance.Class != null) + if (wmiInstance.Class != null) { - if( wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) { //Throw Terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "CreateOnlyFlagNotSpecifiedWithClassPath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "CreateOnlyFlagNotSpecifiedWithClassPath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); } wmiInstance.PutType = PutType.CreateOnly; } @@ -1366,24 +1361,24 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.InvalidOperation, wmiInstance.ComputerName)); } - if( mPath.IsClass) + if (mPath.IsClass) { - if( wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) { - //Throw Terminating error - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(), - "CreateOnlyFlagNotSpecifiedWithClassPath", - ErrorCategory.InvalidOperation, - wmiInstance.PutType)); + //Throw Terminating error + ThrowTerminatingError(new ErrorRecord( + new InvalidOperationException(), + "CreateOnlyFlagNotSpecifiedWithClassPath", + ErrorCategory.InvalidOperation, + wmiInstance.PutType)); } wmiInstance.PutType = PutType.CreateOnly; } else { - if( wmiInstance.flagSpecified ) + if (wmiInstance.flagSpecified) { - if( !(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) + if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) { //Throw terminating error ThrowTerminatingError(new ErrorRecord( @@ -1410,16 +1405,16 @@ namespace Microsoft.PowerShell.Commands { //Should only be called from Set-WMIInstance cmdlet ManagementObject mObj = null; - if( this.GetType() == typeof(SetWmiInstance) ) + if (this.GetType() == typeof(SetWmiInstance)) { SetWmiInstance wmiInstance = (SetWmiInstance)this; //Extra check - if(wmiInstance.InputObject != null) + 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) + if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) { //Throw terminating error ThrowTerminatingError(new ErrorRecord( @@ -1434,9 +1429,9 @@ namespace Microsoft.PowerShell.Commands else { //Check if Flag specified is Updateonly or UpdateOrCreateOnly or not - if( wmiInstance.flagSpecified ) + if (wmiInstance.flagSpecified) { - if( !(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) + if (!(wmiInstance.PutType == PutType.UpdateOnly || wmiInstance.PutType == PutType.UpdateOrCreate)) { //Throw terminating error ThrowTerminatingError(new ErrorRecord( @@ -1450,7 +1445,7 @@ namespace Microsoft.PowerShell.Commands { wmiInstance.PutType = PutType.UpdateOrCreate; } - + mObj = (ManagementObject)wmiInstance.InputObject.Clone(); } if (wmiInstance.Arguments != null) @@ -1479,11 +1474,11 @@ namespace Microsoft.PowerShell.Commands WriteObject(wmiJob); } // Get the PowerShell execution context if it's available at cmdlet creation time... - System.Management.Automation.ExecutionContext _context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); + private System.Management.Automation.ExecutionContext _context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); #endregion Command code } - /// + /// /// A class to perform async operations for WMI cmdlets /// @@ -1495,13 +1490,13 @@ namespace Microsoft.PowerShell.Commands ///Internal constructor for initializing WMI jobs /// internal PSWmiJob(Cmdlet cmds, string[] computerName, int throttleLimt, string command) - :base(command,null) + : base(command, null) { PSJobTypeName = WMIJobType; - throttleManager.ThrottleLimit = throttleLimt; - for( int i=0; i< computerName.Length ; i++) + _throttleManager.ThrottleLimit = throttleLimt; + for (int i = 0; i < computerName.Length; i++) { - PSWmiChildJob job = new PSWmiChildJob(cmds,computerName[i],throttleManager); + PSWmiChildJob job = new PSWmiChildJob(cmds, computerName[i], _throttleManager); job.StateChanged += new EventHandler(HandleChildJobStateChanged); job.JobUnblocked += new EventHandler(HandleJobUnblocked); ChildJobs.Add(job); @@ -1517,10 +1512,10 @@ namespace Microsoft.PowerShell.Commands : base(command, null) { PSJobTypeName = WMIJobType; - throttleManager.ThrottleLimit = throttleLimit; + _throttleManager.ThrottleLimit = throttleLimit; for (int i = 0; i < computerName.Length; ++i) { - PSWmiChildJob childJob = new PSWmiChildJob(cmds, computerName[i], throttleManager, count); + PSWmiChildJob childJob = new PSWmiChildJob(cmds, computerName[i], _throttleManager, count); childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); childJob.JobUnblocked += new EventHandler(HandleJobUnblocked); ChildJobs.Add(childJob); @@ -1532,13 +1527,13 @@ namespace Microsoft.PowerShell.Commands #endregion internal constructor // Set to true when at least one chil job failed - private bool atleastOneChildJobFailed = false; + private bool _atleastOneChildJobFailed = false; // Count the number of childs which have finished - private int finishedChildJobsCount = 0; + private int _finishedChildJobsCount = 0; // Count of number of child jobs which are blocked - private int blockedChildJobsCount = 0; + private int _blockedChildJobsCount = 0; // WMI Job type name. private const string WMIJobType = "WmiJob"; @@ -1553,9 +1548,9 @@ namespace Microsoft.PowerShell.Commands if (e.JobStateInfo.State == JobState.Blocked) { // increment count of blocked child jobs - lock (syncObject) + lock (_syncObject) { - blockedChildJobsCount++; + _blockedChildJobsCount++; } // if any of the child job is blocked, we set state to blocked SetJobState(JobState.Blocked, null); @@ -1563,23 +1558,23 @@ namespace Microsoft.PowerShell.Commands } //Ignore state changes which are not resulting in state change to finished. - if ( (!IsFinishedState(e.JobStateInfo.State)) || (e.JobStateInfo.State == JobState.NotStarted)) + 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; + _atleastOneChildJobFailed = true; } bool allChildJobsFinished = false; - lock (syncObject) + lock (_syncObject) { - finishedChildJobsCount++; + _finishedChildJobsCount++; //We are done - if (finishedChildJobsCount == ChildJobs.Count) + if (_finishedChildJobsCount == ChildJobs.Count) { allChildJobsFinished = true; } @@ -1589,7 +1584,7 @@ namespace Microsoft.PowerShell.Commands //if any child job failed, set status to failed //If stop was called set, status to stopped //else completed - if (atleastOneChildJobFailed) + if (_atleastOneChildJobFailed) { SetJobState(JobState.Failed); } @@ -1605,7 +1600,7 @@ namespace Microsoft.PowerShell.Commands } private bool _stopIsCalled = false; - private string statusMessage; + private string _statusMessage; /// /// Message indicating status of the job /// @@ -1613,7 +1608,7 @@ namespace Microsoft.PowerShell.Commands { get { - return statusMessage; + return _statusMessage; } } //ISSUE: Implement StatusMessage @@ -1623,11 +1618,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void SetStatusMessage() { - statusMessage = "test"; - + _statusMessage = "test"; } // SetStatusMessage - private bool moreData = false; + private bool _moreData = false; /// /// indicates if more data is available /// @@ -1643,35 +1637,35 @@ namespace Microsoft.PowerShell.Commands //if ( (!moreData)) //{ - bool atleastOneChildHasMoreData = false; + bool atleastOneChildHasMoreData = false; - for (int i = 0; i < ChildJobs.Count; i++) + for (int i = 0; i < ChildJobs.Count; i++) + { + if (ChildJobs[i].HasMoreData) { - if (ChildJobs[i].HasMoreData) - { - atleastOneChildHasMoreData = true; - break; - } + atleastOneChildHasMoreData = true; + break; } + } - moreData = atleastOneChildHasMoreData; + _moreData = atleastOneChildHasMoreData; //} - return moreData; + return _moreData; } - } + } /// /// Computers on which this job is running /// public override string Location { - get + get { return ConstructLocation(); } } - private String ConstructLocation() + private String ConstructLocation() { StringBuilder location = new StringBuilder(); @@ -1695,7 +1689,7 @@ namespace Microsoft.PowerShell.Commands { _stopIsCalled = true; - throttleManager.StopAllOperations(); + _throttleManager.StopAllOperations(); Finished.WaitOne(); } @@ -1710,16 +1704,16 @@ namespace Microsoft.PowerShell.Commands { if (disposing) { - if (!isDisposed) + if (!_isDisposed) { - isDisposed = true; + _isDisposed = true; try { if (!IsFinishedState(JobStateInfo.State)) { StopJob(); } - throttleManager.Dispose(); + _throttleManager.Dispose(); foreach (Job job in ChildJobs) { job.Dispose(); @@ -1729,15 +1723,15 @@ namespace Microsoft.PowerShell.Commands { base.Dispose(disposing); } - } + } } } - - private bool isDisposed = false; + + private bool _isDisposed = false; /// /// Initialization common to both constructors /// - void CommonInit(int throttleLimit) + private void CommonInit(int throttleLimit) { //Since no results are produced by any streams. We should //close all the streams @@ -1747,7 +1741,7 @@ namespace Microsoft.PowerShell.Commands SetJobState(JobState.Running); // submit operations to the throttle manager - throttleManager.EndSubmitOperations(); + _throttleManager.EndSubmitOperations(); } /// /// Handles JobUnblocked event from a child job and decrements @@ -1761,11 +1755,11 @@ namespace Microsoft.PowerShell.Commands { bool unblockjob = false; - lock (syncObject) + lock (_syncObject) { - blockedChildJobsCount--; + _blockedChildJobsCount--; - if (blockedChildJobsCount == 0) + if (_blockedChildJobsCount == 0) { unblockjob = true; } @@ -1778,13 +1772,13 @@ namespace Microsoft.PowerShell.Commands } - - private ThrottleManager throttleManager = new ThrottleManager(); - private new object syncObject = new object(); // sync object + 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 @@ -1795,22 +1789,22 @@ namespace Microsoft.PowerShell.Commands /// Internal constructor for initializing WMI jobs /// internal PSWmiChildJob(Cmdlet cmds, string computerName, ThrottleManager throttleManager) - :base(null,null) + : base(null, null) { UsesResultsCollection = true; - this.computerName = computerName; - this.throttleManager = throttleManager; - wmiSinkArray = new ArrayList(); + _computerName = computerName; + _throttleManager = throttleManager; + _wmiSinkArray = new ArrayList(); ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - wmiSinkArray.Add( wmiSink); - sinkCompleted++; + _wmiSinkArray.Add(wmiSink); + _sinkCompleted++; wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); wmiSink.Completed += new CompletedEventHandler(this.JobDone); - this.helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink); - helper.WmiOperationState += new EventHandler(HandleWMIState); - helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); + _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink); + _helper.WmiOperationState += new EventHandler(HandleWMIState); + _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); SetJobState(JobState.NotStarted); - IThrottleOperation operation = this.helper; + IThrottleOperation operation = _helper; operation.OperationComplete += new EventHandler(HandleOperationComplete); throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); throttleManager.AddOperation(operation); @@ -1824,19 +1818,19 @@ namespace Microsoft.PowerShell.Commands : base(null, null) { UsesResultsCollection = true; - this.computerName = computerName; - this.throttleManager = throttleManager; - wmiSinkArray = new ArrayList(); + _computerName = computerName; + _throttleManager = throttleManager; + _wmiSinkArray = new ArrayList(); ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - wmiSinkArray.Add(wmiSink); - sinkCompleted += count; + _wmiSinkArray.Add(wmiSink); + _sinkCompleted += count; wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); wmiSink.Completed += new CompletedEventHandler(this.JobDone); - this.helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count); - helper.WmiOperationState += new EventHandler(HandleWMIState); - helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); + _helper = new WmiAsyncCmdletHelper(this, cmds, computerName, wmiSink, count); + _helper.WmiOperationState += new EventHandler(HandleWMIState); + _helper.ShutdownComplete += new EventHandler(JobDoneForWin32Shutdown); SetJobState(JobState.NotStarted); - IThrottleOperation operation = this.helper; + IThrottleOperation operation = _helper; operation.OperationComplete += new EventHandler(HandleOperationComplete); throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); throttleManager.AddOperation(operation); @@ -1844,29 +1838,29 @@ namespace Microsoft.PowerShell.Commands #endregion internal constructor - private string computerName; - private WmiAsyncCmdletHelper helper; + private string _computerName; + private WmiAsyncCmdletHelper _helper; //bool _bFinished; - private ThrottleManager throttleManager; - private new object syncObject = new object(); // sync object - private int sinkCompleted; - private bool bJobFailed; - private bool bAtLeastOneObject; - + private ThrottleManager _throttleManager; + private object _syncObject = new object(); // sync object + private int _sinkCompleted; + private bool _bJobFailed; + private bool _bAtLeastOneObject; - private ArrayList wmiSinkArray; + + 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")] + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal void UnblockJob() { SetJobState(JobState.Running, null); @@ -1875,42 +1869,42 @@ namespace Microsoft.PowerShell.Commands internal ManagementOperationObserver GetNewSink() { ManagementOperationObserver wmiSink = new ManagementOperationObserver(); - wmiSinkArray.Add( wmiSink); - lock (syncObject) + _wmiSinkArray.Add(wmiSink); + lock (_syncObject) { - sinkCompleted++; + _sinkCompleted++; } wmiSink.ObjectReady += new ObjectReadyEventHandler(this.NewObject); wmiSink.Completed += new CompletedEventHandler(this.JobDone); - return wmiSink; + return wmiSink; } - + /// /// it recieves Management objects /// private void NewObject(object sender, ObjectReadyEventArgs obj) { - if( !bAtLeastOneObject) + if (!_bAtLeastOneObject) { - bAtLeastOneObject = true; + _bAtLeastOneObject = true; } this.WriteObject(obj.NewObject); } - + /// /// It is called when WMI job is done. /// private void JobDone(object sender, CompletedEventArgs obj) { - lock (syncObject) + lock (_syncObject) { - sinkCompleted--; + _sinkCompleted--; } - if( obj.Status != ManagementStatus.NoError) + if (obj.Status != ManagementStatus.NoError) { - bJobFailed = true; + _bJobFailed = true; } - if( sinkCompleted == 0 ) + if (_sinkCompleted == 0) { //Notify throttle manager and change the state to complete //Two cases where _bFinished should be set to false. @@ -1918,19 +1912,18 @@ namespace Microsoft.PowerShell.Commands // 2) We could not get any instance for the class. /*if(bAtLeastOneObject ) _bFinished = true;*/ - helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); - if( !bJobFailed ) + _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); + if (!_bJobFailed) { - helper.State = WmiState.Completed; + _helper.State = WmiState.Completed; SetJobState(JobState.Completed); } else { - helper.State = WmiState.Failed; + _helper.State = WmiState.Failed; SetJobState(JobState.Failed); } } - } /// @@ -1938,19 +1931,19 @@ namespace Microsoft.PowerShell.Commands /// private void JobDoneForWin32Shutdown(object sender, EventArgs arg) { - lock (syncObject) + lock (_syncObject) { - sinkCompleted--; + _sinkCompleted--; } - if (sinkCompleted == 0) + if (_sinkCompleted == 0) { - helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); - helper.State = WmiState.Completed; + _helper.RaiseOperationCompleteEvent(null, OperationState.StopComplete); + _helper.State = WmiState.Completed; SetJobState(JobState.Completed); } } - private string statusMessage = "test"; + private string _statusMessage = "test"; /// /// Message indicating status of the job /// @@ -1958,7 +1951,7 @@ namespace Microsoft.PowerShell.Commands { get { - return statusMessage; + return _statusMessage; } } @@ -1981,19 +1974,19 @@ namespace Microsoft.PowerShell.Commands /// public override string Location { - get + get { - return computerName; + return _computerName; } } - + /// /// Stops the job /// public override void StopJob() { AssertNotDisposed(); - throttleManager.StopOperation(helper); + _throttleManager.StopOperation(_helper); // if IgnoreStop is set, then StopOperation will // return immediately, but StopJob should only @@ -2011,74 +2004,73 @@ namespace Microsoft.PowerShell.Commands /// protected override void Dispose(bool disposing) { - if (disposing) { - if (!isDisposed) + if (!_isDisposed) { - isDisposed = true; + _isDisposed = true; base.Dispose(disposing); } } } - bool isDisposed; + private bool _isDisposed; /// /// Handles operation complete event /// private void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) { - WmiAsyncCmdletHelper helper = (WmiAsyncCmdletHelper) sender; - + WmiAsyncCmdletHelper helper = (WmiAsyncCmdletHelper)sender; + if (helper.State == WmiState.NotStarted) { //This is a case WMI operation was not started. - SetJobState(JobState.Stopped,helper.InternalException); + SetJobState(JobState.Stopped, helper.InternalException); } else if (helper.State == WmiState.Running) { - SetJobState(JobState.Running,helper.InternalException); + SetJobState(JobState.Running, helper.InternalException); } else if (helper.State == WmiState.Completed) { - SetJobState(JobState.Completed,helper.InternalException); + SetJobState(JobState.Completed, helper.InternalException); } - else if(helper.State == WmiState.Failed) + else if (helper.State == WmiState.Failed) { - SetJobState(JobState.Failed,helper.InternalException); + SetJobState(JobState.Failed, helper.InternalException); } else { - SetJobState(JobState.Stopped,helper.InternalException); + SetJobState(JobState.Stopped, helper.InternalException); } } /// /// Handles WMI state changed /// - private void HandleWMIState(object sender ,WmiJobStateEventArgs stateEventArgs) + private void HandleWMIState(object sender, WmiJobStateEventArgs stateEventArgs) { - if(stateEventArgs.WmiState == WmiState.Running) + if (stateEventArgs.WmiState == WmiState.Running) { - SetJobState(JobState.Running, helper.InternalException); + SetJobState(JobState.Running, _helper.InternalException); } - else if(stateEventArgs.WmiState == WmiState.NotStarted) + else if (stateEventArgs.WmiState == WmiState.NotStarted) { - SetJobState(JobState.NotStarted, helper.InternalException); + SetJobState(JobState.NotStarted, _helper.InternalException); } - else if(stateEventArgs.WmiState == WmiState.Completed) + else if (stateEventArgs.WmiState == WmiState.Completed) { SetJobState(JobState.Completed); } - else if(stateEventArgs.WmiState == WmiState.Failed) + else if (stateEventArgs.WmiState == WmiState.Failed) { - SetJobState(JobState.Failed,helper.InternalException); + SetJobState(JobState.Failed, _helper.InternalException); } else { - SetJobState(JobState.Stopped,helper.InternalException); + SetJobState(JobState.Stopped, _helper.InternalException); } } - + /// /// Handle a throttle complete event /// @@ -2086,26 +2078,26 @@ namespace Microsoft.PowerShell.Commands /// not used in this method private void HandleThrottleComplete(object sender, EventArgs eventArgs) { - if (helper.State == WmiState.NotStarted) + if (_helper.State == WmiState.NotStarted) { //This is a case WMI operation was not started. - SetJobState(JobState.Stopped,helper.InternalException); + SetJobState(JobState.Stopped, _helper.InternalException); } - else if (helper.State == WmiState.Running) + else if (_helper.State == WmiState.Running) { - SetJobState(JobState.Running,helper.InternalException); + SetJobState(JobState.Running, _helper.InternalException); } - else if (helper.State == WmiState.Completed) + else if (_helper.State == WmiState.Completed) { - SetJobState(JobState.Completed,helper.InternalException); + SetJobState(JobState.Completed, _helper.InternalException); } - else if(helper.State == WmiState.Failed) + else if (_helper.State == WmiState.Failed) { - SetJobState(JobState.Failed,helper.InternalException); + SetJobState(JobState.Failed, _helper.InternalException); } else { - SetJobState(JobState.Stopped,helper.InternalException); + SetJobState(JobState.Stopped, _helper.InternalException); } //Do Nothing } // HandleThrottleComplete diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 3f300bea7..fdc78bc11 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -25,12 +25,11 @@ using Dbg = System.Management.Automation; using System.Runtime.InteropServices; using System.Resources; using Microsoft.Win32; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; namespace Microsoft.PowerShell.Commands { - #region New-WebServiceProxy /// @@ -129,23 +128,23 @@ namespace Microsoft.PowerShell.Commands /// /// Cache for storing URIs. /// - private static Dictionary UriCache = new Dictionary(); + private static Dictionary s_uriCache = new Dictionary(); /// /// Cache for storing sourcecodehashes. /// - private static Dictionary srccodeCache = new Dictionary(); + private static Dictionary s_srccodeCache = new Dictionary(); /// /// holds the hash code of the source generated. /// - private int sourceHash; + private int _sourceHash; /// /// Random class /// - private object cachelock = new object(); - private static Random rnd = new Random(); + private object _cachelock = new object(); + private static Random s_rnd = new Random(); /// /// BeginProcessing code /// @@ -169,16 +168,16 @@ namespace Microsoft.PowerShell.Commands er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported); ThrowTerminatingError(er); } - + int sourceCache = 0; - lock (UriCache) + lock (s_uriCache) { - if (UriCache.ContainsKey(_uri)) + if (s_uriCache.ContainsKey(_uri)) { //if uri is present in the cache string ns; - UriCache.TryGetValue(_uri, out ns); + s_uriCache.TryGetValue(_uri, out ns); string[] data = ns.Split('|'); if (string.IsNullOrEmpty(_namespace)) { @@ -230,25 +229,25 @@ namespace Microsoft.PowerShell.Commands //disposing the entries in a cache //Adding to Cache - lock (UriCache) + lock (s_uriCache) { - UriCache.Remove(_uri); + s_uriCache.Remove(_uri); } if (sourceCache > 0) { - lock (cachelock) + lock (_cachelock) { - srccodeCache.Remove(sourceCache); + s_srccodeCache.Remove(sourceCache); } } - string key = string.Join("|", new string[] { _namespace, _class, sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) }); - lock (UriCache) + string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) }); + lock (s_uriCache) { - UriCache.Add(_uri, key); + s_uriCache.Add(_uri, key); } - lock (cachelock) + lock (_cachelock) { - srccodeCache.Add(sourceHash, instance); + s_srccodeCache.Add(_sourceHash, instance); } WriteObject(instance, true); @@ -258,8 +257,8 @@ namespace Microsoft.PowerShell.Commands #region private - private static ulong sequenceNumber = 1; - private static object sequenceNumberLock = new object(); + private static ulong s_sequenceNumber = 1; + private static object s_sequenceNumberLock = new object(); /// /// Generates a random name @@ -267,7 +266,6 @@ namespace Microsoft.PowerShell.Commands /// string private string GenerateRandomName() { - string rndname = null; string givenuri = _uri.ToString(); for (int i = 0; i < givenuri.Length; i++) @@ -284,9 +282,9 @@ namespace Microsoft.PowerShell.Commands } string sequenceString; - lock (sequenceNumberLock) + lock (s_sequenceNumberLock) { - sequenceString = (sequenceNumber++).ToString(CultureInfo.InvariantCulture); + sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture); } if (rndname.Length > 30) @@ -294,7 +292,6 @@ namespace Microsoft.PowerShell.Commands return (sequenceString + rndname.Substring(rndname.Length - 30)); } return (sequenceString + rndname); - } /// @@ -380,14 +377,14 @@ namespace Microsoft.PowerShell.Commands WriteError(er); } //generate the hashcode of the CodeCompileUnit - sourceHash = codegenerator.ToString().GetHashCode(); + _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 (srccodeCache.ContainsKey(sourceHash)) + if (s_srccodeCache.ContainsKey(_sourceHash)) { object obj; - srccodeCache.TryGetValue(sourceHash, out obj); + s_srccodeCache.TryGetValue(_sourceHash, out obj); WriteObject(obj, true); return null; } @@ -421,7 +418,6 @@ namespace Microsoft.PowerShell.Commands } return results.CompiledAssembly; - } /// @@ -458,22 +454,20 @@ namespace Microsoft.PowerShell.Commands Object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); if (obj.Length > 0) { - proxyType = type; - break; - } + proxyType = type; + break; + } if (proxyType != null) break; } System.Management.Automation.Diagnostics.Assert( - proxyType != null, + 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 - }//end class #endregion - }//Microsoft.Powershell.commands diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index bdce65f11..2463ef376 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -17,7 +18,7 @@ namespace Microsoft.PowerShell.Commands public class WriteContentCommandBase : PassThroughContentCommandBase { #region Parameters - + /// /// The value of the content to set. /// @@ -26,30 +27,30 @@ namespace Microsoft.PowerShell.Commands /// This value type is determined by the InvokeProvider. /// /// - [Parameter (Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [AllowNull] [AllowEmptyCollection] public object[] Value { get { - return content; + return _content; } // get set { - content = value; + _content = value; } } // Value #endregion Parameters #region parameter data - + /// /// The value of the content to be set. /// - private object[] content; + private object[] _content; #endregion parameter data @@ -60,7 +61,7 @@ namespace Microsoft.PowerShell.Commands /// parameter was specified on the command line or via the pipeline. /// /// - bool pipingPaths; + private bool _pipingPaths; /// /// True if the content writers have been open. @@ -68,7 +69,7 @@ namespace Microsoft.PowerShell.Commands /// to determine if the content writers need to /// be closed each time ProgressRecord is called. /// - bool contentWritersOpen; + private bool _contentWritersOpen; #endregion private Data @@ -82,41 +83,41 @@ namespace Microsoft.PowerShell.Commands { if (Path != null && Path.Length > 0) { - pipingPaths = false; + _pipingPaths = false; } else { - pipingPaths = true; + _pipingPaths = true; } } /// /// Appends the content to the specified item. /// - protected override void ProcessRecord () + protected override void ProcessRecord() { CmdletProviderContext currentContext = GetCurrentContext(); // Initialize the content - - if (content == null) + + if (_content == null) { - content = new object[0]; + _content = new object[0]; } - if (pipingPaths) + if (_pipingPaths) { // Make sure to clean up the content writers that are already there if (contentStreams != null && contentStreams.Count > 0) { CloseContent(contentStreams, false); - contentWritersOpen = false; + _contentWritersOpen = false; contentStreams = new List(); } } - if (!contentWritersOpen) + if (!_contentWritersOpen) { // Since the paths are being pipelined in, we have // to get new content writers for the new paths @@ -129,7 +130,7 @@ namespace Microsoft.PowerShell.Commands SeekContentPosition(contentStreams); } - contentWritersOpen = true; + _contentWritersOpen = true; } // Now write the content to the item @@ -142,7 +143,7 @@ namespace Microsoft.PowerShell.Commands IList result = null; try { - result = holder.Writer.Write(content); + result = holder.Writer.Write(_content); } catch (Exception e) // Catch-all OK. 3rd party callout { @@ -177,14 +178,14 @@ namespace Microsoft.PowerShell.Commands } } } - finally + finally { // Need to close all the writers if the paths are being pipelined - if (pipingPaths) + if (_pipingPaths) { CloseContent(contentStreams, false); - contentWritersOpen = false; + _contentWritersOpen = false; contentStreams = new List(); } } @@ -355,11 +356,9 @@ namespace Microsoft.PowerShell.Commands } } - return (string[]) paths.ToArray(typeof(String)); + return (string[])paths.ToArray(typeof(String)); } - + #endregion protected members - } // WriteContentCommandBase - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/AssemblyInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/AssemblyInfo.cs index 8be322935..dd4e8f282 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/AssemblyInfo.cs @@ -1,8 +1,8 @@ using System.Reflection; using System.Resources; -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersionAttribute("3.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 1cca46746..c3cf76565 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; @@ -21,13 +22,13 @@ namespace Microsoft.PowerShell.Commands HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113280", RemotingCapability = RemotingCapability.None)] public class AddMemberCommand : PSCmdlet { - private static object notSpecified = new object(); + private static object s_notSpecified = new object(); private static bool HasBeenSpecified(object obj) { - return !System.Object.ReferenceEquals(obj, notSpecified); + return !System.Object.ReferenceEquals(obj, s_notSpecified); } - private PSObject inputObject; + private PSObject _inputObject; /// /// The object to add a member to /// @@ -37,11 +38,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = NotePropertyMultiMemberSet)] public PSObject InputObject { - set { inputObject = value; } - get { return inputObject; } + set { _inputObject = value; } + get { return _inputObject; } } - - PSMemberTypes memberType; + + private PSMemberTypes _memberType; /// /// The member type of to be added /// @@ -49,22 +50,22 @@ namespace Microsoft.PowerShell.Commands [Alias("Type")] public PSMemberTypes MemberType { - set { memberType = value; } - get { return memberType; } + set { _memberType = value; } + get { return _memberType; } } - string memberName; + private string _memberName; /// /// The name of the new member /// [Parameter(Mandatory = true, Position = 1, ParameterSetName = "MemberSet")] public string Name { - set { memberName = value; } - get { return memberName; } + set { _memberName = value; } + get { return _memberName; } } - private object value1 = notSpecified; + private object _value1 = s_notSpecified; /// /// First value of the new member. The meaning of this value /// changes according to the member type. @@ -72,11 +73,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 2, ParameterSetName = "MemberSet")] public object Value { - set { value1 = value; } - get { return value1; } + set { _value1 = value; } + get { return _value1; } } - private object value2 = notSpecified; + private object _value2 = s_notSpecified; /// /// Second value of the new member. The meaning of this value /// changes according to the member type. @@ -84,11 +85,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 3, ParameterSetName = "MemberSet")] public object SecondValue { - set { value2 = value; } - get { return value2; } + set { _value2 = value; } + get { return _value2; } } - private string typeName; + private string _typeName; /// /// Add new type name to the specified object for TypeNameSet /// @@ -99,11 +100,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string TypeName { - set { typeName = value; } - get { return typeName; } + set { _typeName = value; } + get { return _typeName; } } - private bool force; + private bool _force; /// /// True if we should overwrite a possibly existing member /// @@ -112,11 +113,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NotePropertyMultiMemberSet)] public SwitchParameter Force { - set { force = value; } - get { return force; } + set { _force = value; } + get { return _force; } } - private bool passThru /* = false */; + private bool _passThru /* = false */; /// /// Gets or sets the parameter -passThru which states output from /// the command should be placed in the pipeline. @@ -127,8 +128,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NotePropertyMultiMemberSet)] public SwitchParameter PassThru { - set { passThru = value; } - get { return passThru; } + set { _passThru = value; } + get { return _passThru; } } @@ -187,49 +188,49 @@ namespace Microsoft.PowerShell.Commands private void EnsureValue1AndValue2AreNotBothNull() { - if (value1 == null && - (value2 == null || !HasBeenSpecified(value2))) + if (_value1 == null && + (_value2 == null || !HasBeenSpecified(_value2))) { - ThrowTerminatingError(NewError("Value1AndValue2AreNotBothNull", "Value1AndValue2AreNotBothNull", null, this.memberType)); + ThrowTerminatingError(NewError("Value1AndValue2AreNotBothNull", "Value1AndValue2AreNotBothNull", null, _memberType)); } } private void EnsureValue1IsNotNull() { - if (value1 == null) + if (_value1 == null) { - ThrowTerminatingError(NewError("Value1ShouldNotBeNull", "Value1ShouldNotBeNull", null, this.memberType)); + ThrowTerminatingError(NewError("Value1ShouldNotBeNull", "Value1ShouldNotBeNull", null, _memberType)); } } private void EnsureValue2IsNotNull() { - if (value2 == null) + if (_value2 == null) { - ThrowTerminatingError(NewError("Value2ShouldNotBeNull", "Value2ShouldNotBeNull", null, this.memberType)); + ThrowTerminatingError(NewError("Value2ShouldNotBeNull", "Value2ShouldNotBeNull", null, _memberType)); } } private void EnsureValue1HasBeenSpecified() { - if (!HasBeenSpecified(this.value1)) + if (!HasBeenSpecified(_value1)) { Collection fdc = new Collection(); fdc.Add(new FieldDescription("Value")); - string prompt = StringUtil.Format(AddMember.Value1Prompt, this.memberType); + string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType); Dictionary result = this.Host.UI.Prompt(prompt, null, fdc); if (result != null) { - this.value1 = result["Value"].BaseObject; + _value1 = result["Value"].BaseObject; } } } private void EnsureValue2HasNotBeenSpecified() { - if (HasBeenSpecified(this.value2)) + if (HasBeenSpecified(_value2)) { - ThrowTerminatingError(NewError("Value2ShouldNotBeSpecified", "Value2ShouldNotBeSpecified", null, this.memberType)); + ThrowTerminatingError(NewError("Value2ShouldNotBeSpecified", "Value2ShouldNotBeSpecified", null, _memberType)); } } @@ -238,14 +239,14 @@ namespace Microsoft.PowerShell.Commands EnsureValue1HasBeenSpecified(); EnsureValue1IsNotNull(); - string value1Str = (string)GetParameterType(value1, typeof(string)); - if (HasBeenSpecified(this.value2)) + string value1Str = (string)GetParameterType(_value1, typeof(string)); + if (HasBeenSpecified(_value2)) { EnsureValue2IsNotNull(); - Type value2Type = (Type)GetParameterType(value2, typeof(Type)); - return new PSAliasProperty(this.memberName, value1Str, value2Type); + Type value2Type = (Type)GetParameterType(_value2, typeof(Type)); + return new PSAliasProperty(_memberName, value1Str, value2Type); } - return new PSAliasProperty(this.memberName, value1Str); + return new PSAliasProperty(_memberName, value1Str); } private PSMemberInfo GetCodeMethod() @@ -253,8 +254,8 @@ namespace Microsoft.PowerShell.Commands EnsureValue1HasBeenSpecified(); EnsureValue1IsNotNull(); EnsureValue2HasNotBeenSpecified(); - MethodInfo value1MethodInfo = (MethodInfo)GetParameterType(value1, typeof(MethodInfo)); - return new PSCodeMethod(this.memberName, value1MethodInfo); + MethodInfo value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo)); + return new PSCodeMethod(_memberName, value1MethodInfo); } private PSMemberInfo GetCodeProperty() @@ -263,35 +264,35 @@ namespace Microsoft.PowerShell.Commands EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1MethodInfo = null; - if (HasBeenSpecified(this.value1)) + if (HasBeenSpecified(_value1)) { - value1MethodInfo = (MethodInfo)GetParameterType(value1, typeof(MethodInfo)); + value1MethodInfo = (MethodInfo)GetParameterType(_value1, typeof(MethodInfo)); } MethodInfo value2MethodInfo = null; - if (HasBeenSpecified(this.value2)) + if (HasBeenSpecified(_value2)) { - value2MethodInfo = (MethodInfo)GetParameterType(value2, typeof(MethodInfo)); + value2MethodInfo = (MethodInfo)GetParameterType(_value2, typeof(MethodInfo)); } - return new PSCodeProperty(this.memberName, value1MethodInfo, value2MethodInfo); + return new PSCodeProperty(_memberName, value1MethodInfo, value2MethodInfo); } private PSMemberInfo GetMemberSet() { EnsureValue2HasNotBeenSpecified(); - if (value1 == null || !HasBeenSpecified(this.value1)) + if (_value1 == null || !HasBeenSpecified(_value1)) { - return new PSMemberSet(this.memberName); + return new PSMemberSet(_memberName); } - Collection value1Collection = - (Collection)GetParameterType(value1, typeof(Collection)); - return new PSMemberSet(this.memberName, value1Collection); + Collection value1Collection = + (Collection)GetParameterType(_value1, typeof(Collection)); + return new PSMemberSet(_memberName, value1Collection); } private PSMemberInfo GetNoteProperty() { EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); - return new PSNoteProperty(this.memberName, this.value1); + return new PSNoteProperty(_memberName, _value1); } private PSMemberInfo GetPropertySet() @@ -299,19 +300,18 @@ namespace Microsoft.PowerShell.Commands EnsureValue2HasNotBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1IsNotNull(); - Collection value1Collection = - (Collection)GetParameterType(value1, typeof(Collection)); - return new PSPropertySet(this.memberName, value1Collection); + Collection value1Collection = + (Collection)GetParameterType(_value1, typeof(Collection)); + return new PSPropertySet(_memberName, value1Collection); } private PSMemberInfo GetScriptMethod() { EnsureValue2HasNotBeenSpecified(); EnsureValue1HasBeenSpecified(); - EnsureValue1IsNotNull(); - ScriptBlock value1ScriptBlock = (ScriptBlock)GetParameterType(value1, typeof(ScriptBlock)); - return new PSScriptMethod(this.memberName, value1ScriptBlock); - + EnsureValue1IsNotNull(); + ScriptBlock value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock)); + return new PSScriptMethod(_memberName, value1ScriptBlock); } private PSMemberInfo GetScriptProperty() @@ -320,16 +320,16 @@ namespace Microsoft.PowerShell.Commands EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; - if (HasBeenSpecified(this.value1)) + if (HasBeenSpecified(_value1)) { - value1ScriptBlock = (ScriptBlock)GetParameterType(value1, typeof(ScriptBlock)); + value1ScriptBlock = (ScriptBlock)GetParameterType(_value1, typeof(ScriptBlock)); } ScriptBlock value2ScriptBlock = null; - if (HasBeenSpecified(this.value2)) + if (HasBeenSpecified(_value2)) { - value2ScriptBlock = (ScriptBlock)GetParameterType(value2, typeof(ScriptBlock)); + value2ScriptBlock = (ScriptBlock)GetParameterType(_value2, typeof(ScriptBlock)); } - return new PSScriptProperty(this.memberName, value1ScriptBlock, value2ScriptBlock); + return new PSScriptProperty(_memberName, value1ScriptBlock, value2ScriptBlock); } /// @@ -337,18 +337,18 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (this.typeName != null && string.IsNullOrWhiteSpace(this.typeName)) + if (_typeName != null && string.IsNullOrWhiteSpace(_typeName)) { - ThrowTerminatingError(NewError("TypeNameShouldNotBeEmpty", "TypeNameShouldNotBeEmpty", this.typeName)); + ThrowTerminatingError(NewError("TypeNameShouldNotBeEmpty", "TypeNameShouldNotBeEmpty", _typeName)); } - if(ParameterSetName == "TypeNameSet") + if (ParameterSetName == "TypeNameSet") { UpdateTypeNames(); - if (this.passThru) + if (_passThru) { - WriteObject(this.inputObject); + WriteObject(_inputObject); } return; } @@ -366,7 +366,7 @@ namespace Microsoft.PowerShell.Commands } else { - int memberCountHelper = (int)memberType; + int memberCountHelper = (int)_memberType; int memberCount = 0; while (memberCountHelper != 0) { @@ -378,11 +378,11 @@ namespace Microsoft.PowerShell.Commands } if (memberCount != 1) { - ThrowTerminatingError(NewError("WrongMemberCount", "WrongMemberCount", null, memberType.ToString())); + ThrowTerminatingError(NewError("WrongMemberCount", "WrongMemberCount", null, _memberType.ToString())); return; } - switch (memberType) + switch (_memberType) { case PSMemberTypes.AliasProperty: member = GetAliasProperty(); @@ -409,11 +409,11 @@ namespace Microsoft.PowerShell.Commands member = GetScriptProperty(); break; default: - ThrowTerminatingError(NewError("CannotAddMemberType", "CannotAddMemberType", null, memberType.ToString())); + ThrowTerminatingError(NewError("CannotAddMemberType", "CannotAddMemberType", null, _memberType.ToString())); break; } } - + if (member == null) { return; @@ -421,15 +421,15 @@ namespace Microsoft.PowerShell.Commands if (!AddMemberToTarget(member)) return; - - if(this.typeName != null) + + if (_typeName != null) { UpdateTypeNames(); } - - if (this.passThru) + + if (_passThru) { - WriteObject(this.inputObject); + WriteObject(_inputObject); } } @@ -440,32 +440,32 @@ namespace Microsoft.PowerShell.Commands /// private bool AddMemberToTarget(PSMemberInfo member) { - PSMemberInfo previousMember = this.inputObject.Members[member.Name]; + PSMemberInfo previousMember = _inputObject.Members[member.Name]; if (previousMember != null) { - if (!this.force) + if (!_force) { WriteError(NewError("MemberAlreadyExists", "MemberAlreadyExists", - this.inputObject, member.Name)); + _inputObject, member.Name)); return false; } else { if (previousMember.IsInstance) { - this.inputObject.Members.Remove(member.Name); + _inputObject.Members.Remove(member.Name); } else { WriteError(NewError("CannotRemoveTypeDataMember", "CannotRemoveTypeDataMember", - this.inputObject, member.Name, previousMember.MemberType)); + _inputObject, member.Name, previousMember.MemberType)); return false; } } } - this.inputObject.Members.Add(member); + _inputObject.Members.Add(member); return true; } @@ -482,7 +482,7 @@ namespace Microsoft.PowerShell.Commands if (string.IsNullOrEmpty(noteName)) { - WriteError(NewError("NotePropertyNameShouldNotBeNull", + WriteError(NewError("NotePropertyNameShouldNotBeNull", "NotePropertyNameShouldNotBeNull", noteName)); continue; } @@ -492,13 +492,13 @@ namespace Microsoft.PowerShell.Commands result = true; } - if (result && this.typeName != null) + if (result && _typeName != null) { UpdateTypeNames(); } - if (result && this.passThru) + if (result && _passThru) { - WriteObject(this.inputObject); + WriteObject(_inputObject); } } @@ -506,9 +506,9 @@ namespace Microsoft.PowerShell.Commands { // Respect the type shortcut Type type; - string typeNameInUse = this.typeName; - if (LanguagePrimitives.TryConvertTo(this.typeName, out type)) { typeNameInUse = type.FullName; } - this.inputObject.TypeNames.Insert(0, typeNameInUse); + string typeNameInUse = _typeName; + if (LanguagePrimitives.TryConvertTo(_typeName, out type)) { typeNameInUse = type.FullName; } + _inputObject.TypeNames.Insert(0, typeNameInUse); } private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) @@ -579,6 +579,6 @@ namespace Microsoft.PowerShell.Commands return inputData; } } - } + } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 51528a5f3..dfb4ddc68 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -178,14 +178,14 @@ namespace Microsoft.PowerShell.Commands { get { - return typename; + return _typename; } set { - typename = value; + _typename = value; } } - private string typename; + private string _typename; /// /// The source code of this method / member @@ -248,14 +248,14 @@ namespace Microsoft.PowerShell.Commands { get { - return usingNamespace; + return _usingNamespace; } set { - usingNamespace = value; + _usingNamespace = value; } } - private string[] usingNamespace = Utils.EmptyArray(); + private string[] _usingNamespace = Utils.EmptyArray(); @@ -489,7 +489,7 @@ namespace Microsoft.PowerShell.Commands } internal bool referencedAssembliesSpecified = false; internal string[] referencedAssemblies = Utils.EmptyArray(); - + /// /// The path to the output assembly /// @@ -698,7 +698,6 @@ namespace Microsoft.PowerShell.Commands " {{\n" + " {1}\n" + " }}\n"; - } return null; } @@ -939,7 +938,7 @@ namespace Microsoft.PowerShell.Commands } #if CORECLR - + /// /// Adds a new type to the Application Domain. /// This version is based on CodeAnalysis (Roslyn). @@ -948,8 +947,8 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(Type))] public sealed class AddTypeCommand : AddTypeCommandBase { - private static Dictionary sourceCache = new Dictionary(); - + private static Dictionary s_sourceCache = new Dictionary(); + /// /// Generate the type(s) /// @@ -1025,9 +1024,9 @@ namespace Microsoft.PowerShell.Commands { foreach (var type in assembly.GetTypes()) { - if (sourceCache.ContainsKey(type.FullName)) + if (s_sourceCache.ContainsKey(type.FullName)) { - if (sourceCache[type.FullName] != sourceCode.GetHashCode()) + if (s_sourceCache[type.FullName] != sourceCode.GetHashCode()) { ErrorRecord errorRecord = new ErrorRecord( new Exception( @@ -1042,12 +1041,12 @@ namespace Microsoft.PowerShell.Commands } else { - sourceCache[type.FullName] = sourceCode.GetHashCode(); + s_sourceCache[type.FullName] = sourceCode.GetHashCode(); } } } - private static string FrameworkFolder = System.IO.Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location); + private static string s_frameworkFolder = System.IO.Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location); // there are two different assemblies: framework contract and framework implementation. // Version 1.1.1 of Microsoft.CodeAnalysis doesn't provide a good way to handle contract separetely from implementation. @@ -1056,40 +1055,40 @@ namespace Microsoft.PowerShell.Commands // (i.e. System.Management.Automation), so we need the contract one. // 2) We have to provide implementation assembly explicitly, Roslyn doesn't have a way to figure out implementation by itself. // So we are adding both. - private static PortableExecutableReference ObjectImplementationAssemblyReference = + private static PortableExecutableReference s_objectImplementationAssemblyReference = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); - private static PortableExecutableReference MscorlibAssemblyReference = - MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location); + private static PortableExecutableReference s_mscorlibAssemblyReference = + MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location); // This assembly should be System.Runtime.dll - private static PortableExecutableReference SystemRuntimeAssemblyReference = + private static PortableExecutableReference s_systemRuntimeAssemblyReference = MetadataReference.CreateFromFile(ClrFacade.GetAssemblies(typeof(object).FullName).First().Location); // SecureString is defined in a separate assembly. // This fact is an implementation detail and should not require the user to specify one more assembly, // if they want to use SecureString in Add-Type -TypeDefinition. // So this assembly should be in the default assemblies list to provide the best experience. - private static PortableExecutableReference SecureStringAssemblyReference = + private static PortableExecutableReference s_secureStringAssemblyReference = MetadataReference.CreateFromFile(typeof(System.Security.SecureString).GetTypeInfo().Assembly.Location); // These assemlbies are always automatically added to ReferencedAssemblies. - private static PortableExecutableReference[] autoReferencedAssemblies = new PortableExecutableReference[] + private static PortableExecutableReference[] s_autoReferencedAssemblies = new PortableExecutableReference[] { - MscorlibAssemblyReference, - SystemRuntimeAssemblyReference, - SecureStringAssemblyReference, - ObjectImplementationAssemblyReference + s_mscorlibAssemblyReference, + s_systemRuntimeAssemblyReference, + s_secureStringAssemblyReference, + s_objectImplementationAssemblyReference }; // These assemlbies are used, when ReferencedAssemblies parameter is not specified. - private static PortableExecutableReference[] defaultAssemblies = new PortableExecutableReference[] + private static PortableExecutableReference[] s_defaultAssemblies = new PortableExecutableReference[] { - MscorlibAssemblyReference, - SystemRuntimeAssemblyReference, - SecureStringAssemblyReference, - ObjectImplementationAssemblyReference, + s_mscorlibAssemblyReference, + s_systemRuntimeAssemblyReference, + s_secureStringAssemblyReference, + s_objectImplementationAssemblyReference, MetadataReference.CreateFromFile(typeof(PSObject).GetTypeInfo().Assembly.Location) }; @@ -1126,7 +1125,7 @@ namespace Microsoft.PowerShell.Commands } // lookup in framework folders and the current folder - string frameworkPossiblePath = System.IO.Path.Combine(FrameworkFolder, referencedAssembly); + string frameworkPossiblePath = System.IO.Path.Combine(s_frameworkFolder, referencedAssembly); if (File.Exists(frameworkPossiblePath)) { return frameworkPossiblePath; @@ -1227,11 +1226,11 @@ namespace Microsoft.PowerShell.Commands } SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions); - var references = defaultAssemblies; + var references = s_defaultAssemblies; if (referencedAssembliesSpecified) { var tempReferences = ReferencedAssemblies.Select(a => MetadataReference.CreateFromFile(ResolveReferencedAssembly(a))).ToList(); - tempReferences.AddRange(autoReferencedAssemblies); + tempReferences.AddRange(s_autoReferencedAssemblies); references = tempReferences.ToArray(); } @@ -1447,7 +1446,7 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "FromMember")] [Parameter(ParameterSetName = "FromPath")] [Parameter(ParameterSetName = "FromLiteralPath")] - [Alias("CP")] + [Alias("CP")] public CompilerParameters CompilerParameters { get @@ -1469,7 +1468,7 @@ namespace Microsoft.PowerShell.Commands base.EndProcessing(); // Generate an error if they've specified a language AND a CodeDomProvider - if(providerSpecified && languageSpecified) + if (providerSpecified && languageSpecified) { ErrorRecord errorRecord = new ErrorRecord( new Exception( @@ -1552,11 +1551,11 @@ namespace Microsoft.PowerShell.Commands return; } } - + List generatedTypes = new List(); // We want to compile from a source representation - if(! loadAssembly) + if (!loadAssembly) { CompileAssemblyFromSource(generatedTypes); } @@ -1567,7 +1566,7 @@ namespace Microsoft.PowerShell.Commands } // Pass the type along if they supplied the PassThru parameter - if(PassThru) + if (PassThru) { WriteObject(generatedTypes, true); } @@ -1584,12 +1583,12 @@ namespace Microsoft.PowerShell.Commands } // Load the source if they want to load from a file - if(String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) || + if (String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) || String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase) ) { sourceCode = ""; - foreach(string file in paths) + foreach (string file in paths) { sourceCode += System.IO.File.ReadAllText(file) + "\n"; } @@ -1659,14 +1658,13 @@ namespace Microsoft.PowerShell.Commands { compilerParameters = new CompilerParameters(); - // Turn off debug information and turn on compiler optimizations by default. + // Turn off debug information and turn on compiler optimizations by default. compilerParameters.IncludeDebugInformation = false; - if (Language == Language.CSharp || Language == Language.VisualBasic || Language==Language.CSharpVersion2 || Language==Language.CSharpVersion3) + if (Language == Language.CSharp || Language == Language.VisualBasic || Language == Language.CSharpVersion2 || Language == Language.CSharpVersion3) { - compilerParameters.CompilerOptions = "/optimize+"; } - + compilerParameters.ReferencedAssemblies.AddRange(defaultAssemblies.ToArray()); foreach (string referencedAssembly in referencedAssemblies) @@ -1709,7 +1707,7 @@ namespace Microsoft.PowerShell.Commands } } - compilerParameters.TreatWarningsAsErrors = !((bool) ignoreWarnings); + compilerParameters.TreatWarningsAsErrors = !((bool)ignoreWarnings); if (String.IsNullOrEmpty(outputAssembly)) { @@ -1753,8 +1751,8 @@ namespace Microsoft.PowerShell.Commands { compilerResults = provider.CompileAssemblyFromFile(compilerParameters, paths); } - // Otherwise, this is code generated. Use the - // source code + // Otherwise, this is code generated. Use the + // source code else { compilerResults = provider.CompileAssemblyFromSource(compilerParameters, sourceCode); @@ -1794,7 +1792,7 @@ namespace Microsoft.PowerShell.Commands HandleCompilerErrors(GetErrors(compilerResults.Errors)); return; } - + // Only return / load the types if they aren't // storing it to disk. PassThru overrides this. if (PassThru || String.IsNullOrEmpty(outputAssembly)) @@ -1876,7 +1874,7 @@ namespace Microsoft.PowerShell.Commands // Suppress the "defines no public members" for // cmdlets as they are so common - if (typeof (System.Management.Automation.Cmdlet).IsAssignableFrom(generatedType)) + if (typeof(System.Management.Automation.Cmdlet).IsAssignableFrom(generatedType)) { foundPublicMember = true; continue; @@ -1934,7 +1932,7 @@ namespace Microsoft.PowerShell.Commands return result.ToArray(); } - [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId="System.Reflection.Assembly.LoadFrom")] + [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] private void LoadAssemblyFromPathOrName(List generatedTypes) { // Load the source if they want to load from a file @@ -1942,13 +1940,13 @@ namespace Microsoft.PowerShell.Commands String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase) ) { - foreach(string path in paths) + foreach (string path in paths) { generatedTypes.AddRange(ClrFacade.LoadFrom(path).GetTypes()); } } // Load the assembly by name - else if(String.Equals(ParameterSetName, "FromAssemblyName", StringComparison.OrdinalIgnoreCase)) + else if (String.Equals(ParameterSetName, "FromAssemblyName", StringComparison.OrdinalIgnoreCase)) { bool caughtError = false; @@ -2005,26 +2003,26 @@ namespace Microsoft.PowerShell.Commands // to use it. So here, we do it all through reflection. // Go through the constructors - foreach(ConstructorInfo constructor in typeof(CSharpCodeProvider).GetConstructors()) + foreach (ConstructorInfo constructor in typeof(CSharpCodeProvider).GetConstructors()) { // Look for the one that takes a single parameter ParameterInfo[] constructorParameters = constructor.GetParameters(); - if(constructorParameters.Length == 1) + if (constructorParameters.Length == 1) { // Ensure this is the one that takes a dictionary - Dictionary providerParameters = new Dictionary(); + Dictionary providerParameters = new Dictionary(); providerParameters["CompilerVersion"] = "v3.5"; - if(constructorParameters[0].ParameterType.IsAssignableFrom(providerParameters.GetType())) + if (constructorParameters[0].ParameterType.IsAssignableFrom(providerParameters.GetType())) { // If so, create the compiler and break - csc = (CodeDomProvider) constructor.Invoke(new object[] { providerParameters }); + csc = (CodeDomProvider)constructor.Invoke(new object[] { providerParameters }); break; } } } - if(csc == null) + if (csc == null) { throw new NotSupportedException( string.Format(CultureInfo.InvariantCulture, AddTypeStrings.SpecialNetVersionRequired, Language.CSharpVersion3.ToString(), "3.5")); @@ -2068,7 +2066,7 @@ namespace Microsoft.PowerShell.Commands // So we'll try from the short name. catch (System.IO.FileNotFoundException) { } - if(loadedAssembly != null) + if (loadedAssembly != null) return loadedAssembly; // Next, try an exact match @@ -2087,12 +2085,12 @@ namespace Microsoft.PowerShell.Commands string matchedStrongName = null; WildcardPattern pattern = WildcardPattern.Get(assemblyName, WildcardOptions.IgnoreCase); - foreach(string strongNameShortcut in StrongNames.Value.Keys) + foreach (string strongNameShortcut in StrongNames.Value.Keys) { if (pattern.IsMatch(strongNameShortcut)) { // If we've already found a matching type, throw an error. - if(matchedStrongName != null) + if (matchedStrongName != null) { ErrorRecord errorRecord = new ErrorRecord( new Exception( @@ -2113,7 +2111,7 @@ namespace Microsoft.PowerShell.Commands } // Return NULL if we couldn't find one. The caller generates an error here. - if(matchedStrongName == null) + if (matchedStrongName == null) return null; // Otherwise, load the assembly. @@ -2885,6 +2883,5 @@ namespace Microsoft.PowerShell.Commands } } #endif // if !CORECLR - } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs index 1c880f495..08eda2604 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CSVCommands.cs @@ -78,7 +78,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - + /// /// NoTypeInformation : should the #TYPE line be generated /// @@ -95,7 +95,7 @@ namespace Microsoft.PowerShell.Commands _noTypeInformation = value; } } - bool _noTypeInformation; + private bool _noTypeInformation; #endregion Command Line Parameters @@ -163,11 +163,11 @@ namespace Microsoft.PowerShell.Commands set { _path = value; - specifiedPath = true; + _specifiedPath = true; } } private string _path; - bool specifiedPath = false; + private bool _specifiedPath = false; /// /// The literal path of the mandatory file name to write to @@ -185,13 +185,13 @@ namespace Microsoft.PowerShell.Commands set { _path = value; - isLiteralPath = true; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; + + - - /// /// Property that sets force parameter. /// @@ -218,14 +218,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noclobber; + return _noclobber; } set { - noclobber = value; + _noclobber = value; } } - private bool noclobber; + private bool _noclobber; /// /// Encoding optional flag @@ -250,16 +250,16 @@ namespace Microsoft.PowerShell.Commands /// [Parameter] public SwitchParameter Append { get; set; } - private bool isActuallyAppending; // true if Append=true AND the file written was not empty (or nonexistant) when the cmdlet was invoked + private bool _isActuallyAppending; // true if Append=true AND the file written was not empty (or nonexistant) when the cmdlet was invoked #endregion #region Overrides - private bool shouldProcess; + private bool _shouldProcess; private IList _propertyNames; private IList _preexistingPropertyNames; - private ExportCsvHelper helper; + private ExportCsvHelper _helper; /// /// BeginProcessing override @@ -269,22 +269,22 @@ namespace Microsoft.PowerShell.Commands base.BeginProcessing(); // Validate that they don't provide both Path and LiteralPath, but have provided at least one. - if (!(specifiedPath ^ isLiteralPath)) + if (!(_specifiedPath ^ _isLiteralPath)) { InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } - shouldProcess = ShouldProcess(Path); - if (!shouldProcess) return; + _shouldProcess = ShouldProcess(Path); + if (!_shouldProcess) return; CreateFileStream(); - - helper = new ExportCsvHelper(this, base.Delimiter); + + _helper = new ExportCsvHelper(this, base.Delimiter); } - - + + /// /// Convert the current input object to Csv and write to file/WriteObject /// @@ -297,30 +297,30 @@ namespace Microsoft.PowerShell.Commands return; } - if (!shouldProcess) return; + if (!_shouldProcess) return; //Process first object if (_propertyNames == null) { // figure out the column names (and lock-in their order) - _propertyNames = helper.BuildPropertyNames(InputObject, _propertyNames); - if (this.isActuallyAppending && _preexistingPropertyNames != null) + _propertyNames = _helper.BuildPropertyNames(InputObject, _propertyNames); + if (_isActuallyAppending && _preexistingPropertyNames != null) { this.ReconcilePreexistingPropertyNames(); } // write headers (row1: typename + row2: column names) - if (!this.isActuallyAppending) + if (!_isActuallyAppending) { if (NoTypeInformation == false) { - WriteCsvLine(helper.GetTypeString(InputObject)); + WriteCsvLine(_helper.GetTypeString(InputObject)); } - WriteCsvLine(helper.ConvertPropertyNamesCSV(_propertyNames)); + WriteCsvLine(_helper.ConvertPropertyNamesCSV(_propertyNames)); } } - string csv = helper.ConvertPSObjectToCSV(InputObject, _propertyNames); + string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); WriteCsvLine(csv); _sw.Flush(); } @@ -350,32 +350,32 @@ namespace Microsoft.PowerShell.Commands /// /// handle to file whose read-only attribute should be reset when we are done /// - private FileInfo readOnlyFileInfo = null; + private FileInfo _readOnlyFileInfo = null; private void CreateFileStream() { Dbg.Assert(_path != null, "FileName is mandatory parameter"); - string resolvedFilePath = PathUtils.ResolveFilePath(this.Path, this, isLiteralPath); + string resolvedFilePath = PathUtils.ResolveFilePath(this.Path, this, _isLiteralPath); bool isCsvFileEmpty = true; if (this.Append && File.Exists(resolvedFilePath)) { - using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, this._encodingParameter, isLiteralPath)) + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, _encodingParameter, _isLiteralPath)) { isCsvFileEmpty = streamReader.Peek() == -1 ? true : false; } } // If the csv file is empty then even append is treated as regualr export (i.e., both header & values are added to the CSV file). - this.isActuallyAppending = this.Append && File.Exists(resolvedFilePath) && !isCsvFileEmpty; + _isActuallyAppending = this.Append && File.Exists(resolvedFilePath) && !isCsvFileEmpty; - if (this.isActuallyAppending) + if (_isActuallyAppending) { Encoding encodingObject; - using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, this._encodingParameter, isLiteralPath)) + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, _encodingParameter, _isLiteralPath)) { ImportCsvHelper readingHelper = new ImportCsvHelper( this, this.Delimiter, null /* header */, null /* typeName */, streamReader); @@ -392,31 +392,31 @@ namespace Microsoft.PowerShell.Commands false, // defaultEncoding Append, Force, - NoClobber, + NoClobber, out _fs, out _sw, - out readOnlyFileInfo, - isLiteralPath); + out _readOnlyFileInfo, + _isLiteralPath); } else { PathUtils.MasterStreamOpen( this, this.Path, - this._encodingParameter ?? "ASCII", + _encodingParameter ?? "ASCII", false, // defaultEncoding Append, Force, - NoClobber, + NoClobber, out _fs, out _sw, - out readOnlyFileInfo, - isLiteralPath); + out _readOnlyFileInfo, + _isLiteralPath); } } - private - void + private + void CleanUp() { if (_fs != null) @@ -430,27 +430,27 @@ namespace Microsoft.PowerShell.Commands _fs.Dispose(); _fs = null; // reset the read-only attribute - if (null != readOnlyFileInfo) - readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + if (null != _readOnlyFileInfo) + _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } - if (helper != null) + if (_helper != null) { - helper.Dispose(); + _helper.Dispose(); } } - + private void ReconcilePreexistingPropertyNames() { - Dbg.Assert(this.isActuallyAppending, "This method should only get called when appending"); + Dbg.Assert(_isActuallyAppending, "This method should only get called when appending"); Dbg.Assert(_preexistingPropertyNames != null, "This method should only get called when we have successfully read preexisting property names"); HashSet appendedPropertyNames = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string appendedPropertyName in this._propertyNames) + foreach (string appendedPropertyName in _propertyNames) { appendedPropertyNames.Add(appendedPropertyName); } - foreach (string preexistingPropertyName in this._preexistingPropertyNames) + foreach (string preexistingPropertyName in _preexistingPropertyNames) { if (!appendedPropertyNames.Contains(preexistingPropertyName)) { @@ -488,13 +488,13 @@ namespace Microsoft.PowerShell.Commands _sw.WriteLine(line); } #endregion file - + #region IDisposable Members /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// public dispose method @@ -510,7 +510,6 @@ namespace Microsoft.PowerShell.Commands _disposed = true; } - #endregion IDisposable Members } @@ -561,11 +560,11 @@ namespace Microsoft.PowerShell.Commands set { _paths = value; - specifiedPath = true; + _specifiedPath = true; } } private string[] _paths; - bool specifiedPath = false; + private bool _specifiedPath = false; /// /// The literal path of the mandatory file name to read from @@ -583,10 +582,10 @@ namespace Microsoft.PowerShell.Commands set { _paths = value; - isLiteralPath = true; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Property that sets UseCulture parameter @@ -616,17 +615,17 @@ namespace Microsoft.PowerShell.Commands public string[] Header { get - { - return _header; + { + return _header; } set { - _header = value; - } + _header = value; + } } private string[] _header; - + /// /// Encoding optional flag /// @@ -650,7 +649,7 @@ namespace Microsoft.PowerShell.Commands /// one or more unspecified names /// private bool _alreadyWarnedUnspecifiedNames = false; - + #endregion Command Line Parameters #region Override Methods @@ -668,7 +667,7 @@ namespace Microsoft.PowerShell.Commands protected override void ProcessRecord() { // Validate that they don't provide both Path and LiteralPath, but have provided at least one. - if (!(specifiedPath ^ isLiteralPath)) + if (!(_specifiedPath ^ _isLiteralPath)) { InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); @@ -679,7 +678,7 @@ namespace Microsoft.PowerShell.Commands { foreach (string path in _paths) { - using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, isLiteralPath)) + using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath)) { ImportCsvHelper helper = new ImportCsvHelper(this, _delimiter, _header, null /* typeName */, streamReader); @@ -697,7 +696,7 @@ namespace Microsoft.PowerShell.Commands }//if }////ProcessRecord } - #endregion Override Methods + #endregion Override Methods #endregion Import-CSV Command @@ -716,7 +715,7 @@ namespace Microsoft.PowerShell.Commands /// /// Overrides Base InputObject /// - [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true,Position=0)] + [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] public override PSObject InputObject { get @@ -737,12 +736,12 @@ namespace Microsoft.PowerShell.Commands /// /// Stores Property Names /// - IList _propertyNames; + private IList _propertyNames; /// /// /// - ExportCsvHelper helper; + private ExportCsvHelper _helper; /// /// BeginProcessing override @@ -752,10 +751,10 @@ namespace Microsoft.PowerShell.Commands BeginProcessing() { base.BeginProcessing(); - helper = new ExportCsvHelper(this, base.Delimiter); + _helper = new ExportCsvHelper(this, base.Delimiter); } - + /// /// Convert the current input object to Csv and write to stream/WriteObject @@ -771,25 +770,23 @@ namespace Microsoft.PowerShell.Commands //Process first object if (_propertyNames == null) { - _propertyNames = helper.BuildPropertyNames(InputObject, _propertyNames); + _propertyNames = _helper.BuildPropertyNames(InputObject, _propertyNames); if (NoTypeInformation == false) { - WriteCsvLine(helper.GetTypeString(InputObject)); + WriteCsvLine(_helper.GetTypeString(InputObject)); } //Write property information - string properties = helper.ConvertPropertyNamesCSV(_propertyNames); + string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); if (!properties.Equals("")) WriteCsvLine(properties); } - string csv = helper.ConvertPSObjectToCSV(InputObject, _propertyNames); + string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); //write to the console - if(csv != "") + if (csv != "") WriteCsvLine(csv); - - } - + #endregion Overrides #region CSV conversion @@ -803,10 +800,7 @@ namespace Microsoft.PowerShell.Commands WriteObject(line); } - #endregion CSV conversion - - } #endregion ConvertTo-CSV Command @@ -846,7 +840,7 @@ namespace Microsoft.PowerShell.Commands /// ///Culture switch for csv conversion /// - [Parameter(ParameterSetName = "UseCulture",Mandatory=true)] + [Parameter(ParameterSetName = "UseCulture", Mandatory = true)] [ValidateNotNull] [ValidateNotNullOrEmpty] public SwitchParameter UseCulture @@ -865,14 +859,14 @@ namespace Microsoft.PowerShell.Commands /// /// Input Object which is written in Csv format /// - [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true,Position=0)] + [Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] [ValidateNotNull] [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSObject[] InputObject { get - { + { return _object; } set @@ -888,7 +882,7 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = false)] [ValidateNotNull] [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Header { get @@ -922,12 +916,12 @@ namespace Microsoft.PowerShell.Commands { _delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, _delimiter, _useculture); } - + /// /// Convert the current input object to Csv and write to stream/WriteObject /// - protected override - void + protected override + void ProcessRecord() { foreach (PSObject pObject in _object) @@ -958,7 +952,7 @@ namespace Microsoft.PowerShell.Commands } } } - + #endregion Overrides private string _typeName; @@ -978,27 +972,27 @@ namespace Microsoft.PowerShell.Commands /// /// /// - private PSCmdlet _cmdlet ; + private PSCmdlet _cmdlet; - private char Delimiter; + private char _delimiter; - /// - /// - /// - /// - /// + /// + /// + /// + /// + /// internal ExportCsvHelper(PSCmdlet cmdlet, char delimiter) { if (cmdlet == null) - { + { } _cmdlet = cmdlet; - Delimiter = delimiter; + _delimiter = delimiter; } //Name of properties to be written in CSV format - + /// /// Get the name of properties from source PSObject and @@ -1044,7 +1038,7 @@ namespace Microsoft.PowerShell.Commands else { //changed to delimiter - dest.Append(Delimiter); + dest.Append(_delimiter); } EscapeAndAppendString(dest, propertyName); } @@ -1059,7 +1053,7 @@ namespace Microsoft.PowerShell.Commands /// internal string - ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames ) + ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) { Dbg.Assert(propertyNames != null, "PropertyName collection can be empty here, but it should not be null"); @@ -1074,7 +1068,7 @@ namespace Microsoft.PowerShell.Commands } else { - dest.Append(Delimiter); + dest.Append(_delimiter); } PSPropertyInfo property = mshObject.Properties[propertyName] as PSPropertyInfo; string value = null; @@ -1120,7 +1114,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - internal + internal string GetTypeString(PSObject source) { @@ -1174,14 +1168,13 @@ namespace Microsoft.PowerShell.Commands dest.Append(c); } dest.Append('"'); - } #region IDisposable Members /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// public dispose method @@ -1191,16 +1184,13 @@ namespace Microsoft.PowerShell.Commands Dispose() { if (_disposed == false) - { + { GC.SuppressFinalize(this); } _disposed = true; - } - - #endregion IDisposable Members - + #endregion IDisposable Members } #endregion ExportHelperConversion @@ -1283,7 +1273,7 @@ namespace Microsoft.PowerShell.Commands /// /// This is set to true when end of file is reached /// - private + private bool EOF { get @@ -1366,7 +1356,7 @@ namespace Microsoft.PowerShell.Commands Collection values = ParseNextRecord(false); if (values.Count == 0) break; - + if (values.Count == 1 && String.IsNullOrEmpty(values[0])) { // skip the blank lines @@ -1467,12 +1457,12 @@ namespace Microsoft.PowerShell.Commands StringBuilder current = new StringBuilder(); bool seenBeginQuote = false; - // int i = 0; + // int i = 0; while (!EOF) { //Read the next character char ch = ReadChar(); - + if ((ch == _delimiter)) { @@ -1491,7 +1481,6 @@ namespace Microsoft.PowerShell.Commands result.Add(current.ToString()); current.Remove(0, current.Length); } - } else if (ch == '"') @@ -1509,7 +1498,6 @@ namespace Microsoft.PowerShell.Commands ReadChar(); current.Append('"'); - } else { @@ -1640,7 +1628,7 @@ namespace Microsoft.PowerShell.Commands return result; } - private + private bool IsNewLine(char ch) { @@ -1672,7 +1660,7 @@ namespace Microsoft.PowerShell.Commands /// If this is true, eat the trailing blanks. Note:if there are non /// whitespace characters present, then trailing blanks are not consumed /// - private + private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks) { @@ -1726,7 +1714,7 @@ namespace Microsoft.PowerShell.Commands private PSObject - BuildMshobject(string type, IList names, Collection values,char delimiter) + BuildMshobject(string type, IList names, Collection values, char delimiter) { //string[] namesarray = null; PSObject result = new PSObject(); @@ -1737,13 +1725,12 @@ namespace Microsoft.PowerShell.Commands result.TypeNames.Clear(); result.TypeNames.Add(type); } - for (int i = 0; i <= names.Count-1; i++) + for (int i = 0; i <= names.Count - 1; i++) { - string name = names[i]; string value = null; ////if name is null and delimiter is '"', continue - if (name.Length == 0 && delimiterlocal == '"') + if (name.Length == 0 && delimiterlocal == '"') continue; ////if name is null and delimiter is not '"', use a default property name 'UnspecifiedName' if (string.IsNullOrEmpty(name)) @@ -1781,7 +1768,7 @@ namespace Microsoft.PowerShell.Commands internal const char CSVDelimiter = ','; internal const string CSVTypePrefix = "CSV:"; - internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName,char Delimiter, bool UseCulture) + internal static char SetDelimiter(PSCmdlet Cmdlet, string ParameterSetName, char Delimiter, bool UseCulture) { switch (ParameterSetName) { @@ -1806,7 +1793,6 @@ namespace Microsoft.PowerShell.Commands Delimiter = ImportExportCSVHelper.CSVDelimiter; } break; - } return Delimiter; } @@ -1815,5 +1801,4 @@ namespace Microsoft.PowerShell.Commands #endregion ExportImport Helper #endregion CSV conversion - } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs index da2b8dc0f..a77f9822d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -15,7 +15,7 @@ namespace Microsoft.PowerShell.Commands /// Base class for a variety of commandlets that take color parameters /// /// - + public class ConsoleColorCmdlet : PSCmdlet { @@ -24,7 +24,7 @@ namespace Microsoft.PowerShell.Commands /// public ConsoleColorCmdlet() { - consoleColorEnumType = typeof(ConsoleColor); + _consoleColorEnumType = typeof(ConsoleColor); } /// @@ -41,24 +41,24 @@ namespace Microsoft.PowerShell.Commands { get { - if (!isFgColorSet) + if (!_isFgColorSet) { - fgColor = this.Host.UI.RawUI.ForegroundColor; - isFgColorSet = true; + _fgColor = this.Host.UI.RawUI.ForegroundColor; + _isFgColorSet = true; } - return fgColor; + return _fgColor; } set { - if (value >= (ConsoleColor) 0 && value <= (ConsoleColor) 15) + if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) { - fgColor = value; - isFgColorSet = true; + _fgColor = value; + _isFgColorSet = true; } else { - ThrowTerminatingError(BuildOutOfRangeErrorRecord(value, "SetInvalidForegroundColor")); + ThrowTerminatingError(BuildOutOfRangeErrorRecord(value, "SetInvalidForegroundColor")); } } } @@ -69,7 +69,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - + [Parameter] public ConsoleColor @@ -77,20 +77,20 @@ namespace Microsoft.PowerShell.Commands { get { - if (!isBgColorSet) + if (!_isBgColorSet) { - bgColor = this.Host.UI.RawUI.BackgroundColor; - isBgColorSet = true; + _bgColor = this.Host.UI.RawUI.BackgroundColor; + _isBgColorSet = true; } - return bgColor; + return _bgColor; } set { - if (value >= (ConsoleColor) 0 && value <= (ConsoleColor) 15) + if (value >= (ConsoleColor)0 && value <= (ConsoleColor)15) { - bgColor = value; - isBgColorSet = true; + _bgColor = value; + _isBgColorSet = true; } else { @@ -108,13 +108,13 @@ namespace Microsoft.PowerShell.Commands } #endregion helper - private ConsoleColor fgColor; - private ConsoleColor bgColor; + private ConsoleColor _fgColor; + private ConsoleColor _bgColor; - private bool isFgColorSet = false; - private bool isBgColorSet = false; + private bool _isFgColorSet = false; + private bool _isBgColorSet = false; - private readonly Type consoleColorEnumType; + private readonly Type _consoleColorEnumType; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index 6ae5c3ab6..fe1a2f644 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -70,11 +70,11 @@ namespace Microsoft.PowerShell.Commands string name = s.Substring(0, index); name = name.Trim(); - if(result.ContainsKey(name)) + if (result.ContainsKey(name)) { throw PSTraceSource.NewInvalidOperationException( ConvertFromStringData.DataItemAlreadyDefined, - line, + line, name); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs index 1b6054991..adfddb9b4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.ObjectModel; namespace Microsoft.PowerShell.Commands @@ -12,7 +13,7 @@ namespace Microsoft.PowerShell.Commands { internal CSVHelper(char delimiter) { - this.delimiter = delimiter; + _delimiter = delimiter; } /// @@ -21,9 +22,9 @@ namespace Microsoft.PowerShell.Commands /// internal char Delimiter { - get { return delimiter; } + get { return _delimiter; } } - private char delimiter = ','; + private char _delimiter = ','; /// /// Parse a CSV String. @@ -111,8 +112,6 @@ namespace Microsoft.PowerShell.Commands } return result; } - } - } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index fa2e97e80..1e518ef63 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace System.Management.Automation { using System; @@ -50,7 +51,7 @@ namespace System.Management.Automation /// depth to be used for serialization. If this value is specified, /// depth from types.xml is not used. /// - internal CustomSerialization(XmlWriter writer,bool notypeinformation, int depth) + internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth) { if (writer == null) { @@ -69,14 +70,14 @@ namespace System.Management.Automation /// /// Default depth of serialization /// - private static int mshDefaultSerializationDepth = 1; + private static int s_mshDefaultSerializationDepth = 1; /// /// Default depth of serializaiton /// public static int MshDefaultSerializationDepth { - get { return mshDefaultSerializationDepth; } + get { return s_mshDefaultSerializationDepth; } } /// /// Constructor @@ -96,7 +97,7 @@ namespace System.Management.Automation #region public methods - private bool firstCall = true; + private bool _firstCall = true; /// /// Serialzies passed in object @@ -107,9 +108,9 @@ namespace System.Management.Automation internal void Serialize(object source) { //Write the root element tag before writing first object. - if (firstCall) + if (_firstCall) { - firstCall = false; + _firstCall = false; Start(); } @@ -140,7 +141,7 @@ namespace System.Management.Automation _serializer.WriteOneObject(source, null, _depth); _serializer = null; } - + /// /// Writes the start of root element /// @@ -154,9 +155,9 @@ namespace System.Management.Automation /// internal void Done() { - if (firstCall) + if (_firstCall) { - firstCall = false; + _firstCall = false; Start(); } _writer.WriteEndElement(); @@ -194,12 +195,12 @@ namespace System.Management.Automation /// /// Xml writer to be used /// - XmlWriter _writer; + private XmlWriter _writer; /// /// check first call for every pipeline object to write Object tag else property tag /// - private bool firstcall; + private bool _firstcall; /// /// should the type information to be shown @@ -209,7 +210,7 @@ namespace System.Management.Automation /// /// check object call /// - private bool firstobjectcall = true ; + private bool _firstobjectcall = true; /// /// Constructor @@ -229,26 +230,26 @@ namespace System.Management.Automation _writer = writer; _notypeinformation = notypeinformation; - firstcall = isfirstcallforObject; + _firstcall = isfirstcallforObject; } #endregion #region Stopping - private bool isStopping = false; + private bool _isStopping = false; /// /// Called from a separate thread will stop the serialization process /// internal void Stop() { - this.isStopping = true; + _isStopping = true; } private void CheckIfStopping() { - if (this.isStopping) + if (_isStopping) { throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping); } @@ -317,7 +318,7 @@ namespace System.Management.Automation /// /// true if source is handled, else false. /// - private bool HandlePrimitiveKnownType( object source, string property) + private bool HandlePrimitiveKnownType(object source, string property) { Dbg.Assert(source != null, "caller should validate the parameter"); @@ -340,7 +341,7 @@ namespace System.Management.Automation /// /// true if source is handled, else false. /// - private bool HandlePrimitiveKnownTypePSObject( object source, string property, int depth) + private bool HandlePrimitiveKnownTypePSObject(object source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); @@ -444,7 +445,7 @@ namespace System.Management.Automation /// /// /// - void GetKnownContainerTypeInfo( + private void GetKnownContainerTypeInfo( object source, out ContainerType ct, out IDictionary dictionary, out IEnumerable enumerable) { Dbg.Assert(source != null, "caller should validate the parameter"); @@ -513,7 +514,6 @@ namespace System.Management.Automation ct = ContainerType.Enumerable; } } - } /// @@ -522,7 +522,7 @@ namespace System.Management.Automation /// /// /// - static bool DerivesFromGenericType(Type derived, Type baseType) + private static bool DerivesFromGenericType(Type derived, Type baseType) { Dbg.Assert(derived != null, "caller should validate the parameter"); Dbg.Assert(baseType != null, "caller should validate the parameter"); @@ -559,7 +559,7 @@ namespace System.Management.Automation /// /// /// - private void WritePrimitiveTypePSObjectWithNotes ( + private void WritePrimitiveTypePSObjectWithNotes( PSObject source, object primitive, TypeSerializationInfo pktInfo, @@ -576,7 +576,7 @@ namespace System.Management.Automation { WriteOnePrimitiveKnownType(_writer, null, primitive, pktInfo); } - + //Serialize instanceMembers PSMemberInfoCollection instanceMembers = source.InstanceMembers; if (instanceMembers != null) @@ -607,16 +607,15 @@ namespace System.Management.Automation { object baseObject = source.ImmediateBaseObject; foreach (PSPropertyInfo prop in source.Properties) - { + { WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), prop.Name, depth); } - } else if (isPSObject) { - if (firstobjectcall) + if (_firstobjectcall) { - firstobjectcall = false; + _firstobjectcall = false; WritePSObjectProperties(source, depth); } else @@ -628,7 +627,7 @@ namespace System.Management.Automation { WritePSObjectProperties(source, depth); } - + _writer.WriteEndElement(); } @@ -646,7 +645,7 @@ namespace System.Management.Automation bool writeTNH) { Dbg.Assert(mshObject != null, "caller should validate the parameter"); - + if (property != null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); @@ -654,19 +653,19 @@ namespace System.Management.Automation } else { - if (firstcall) + if (_firstcall) { WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); - firstcall = false; - } + _firstcall = false; + } else { WriteStartElement(_writer, CustomSerializationStrings.Properties); } } - + Object baseObject = mshObject.BaseObject; - if(!_notypeinformation) + if (!_notypeinformation) WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, baseObject.GetType().ToString()); } @@ -678,7 +677,7 @@ namespace System.Management.Automation /// /// /// - bool PSObjectHasNotes(PSObject source) + private bool PSObjectHasNotes(PSObject source) { if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) { @@ -719,7 +718,7 @@ namespace System.Management.Automation } enclosingTagWritten = true; - WriteStartElement(_writer, CustomSerializationStrings.Properties); + WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, info.Name); if (!_notypeinformation) WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, info.GetType().ToString()); @@ -761,7 +760,7 @@ namespace System.Management.Automation SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth); return; } - + foreach (PSPropertyInfo prop in source.Properties) { Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); @@ -787,7 +786,6 @@ namespace System.Management.Automation WriteOneObject(value, prop.Name, depth); } } - } /// @@ -848,7 +846,7 @@ namespace System.Management.Automation private void WriteEnumerable(IEnumerable enumerable, int depth) { Dbg.Assert(enumerable != null, "caller should validate the parameter"); - + IEnumerator enumerator = null; try { @@ -887,7 +885,6 @@ namespace System.Management.Automation WriteOneObject(item, null, depth); } } - } /// @@ -923,7 +920,7 @@ namespace System.Management.Automation #region serialize as string - void HandlePSObjectAsString(PSObject source, string property, int depth) + private void HandlePSObjectAsString(PSObject source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the information"); @@ -940,7 +937,7 @@ namespace System.Management.Automation } else { - WriteOnePrimitiveKnownType(_writer, property,source.BaseObject, pktInfo); + WriteOnePrimitiveKnownType(_writer, property, source.BaseObject, pktInfo); } } else @@ -968,7 +965,7 @@ namespace System.Management.Automation /// /// string value to use for serializing this PSObject. /// - string GetStringFromPSObject(PSObject source) + private string GetStringFromPSObject(PSObject source) { Dbg.Assert(source != null, "caller should have validated the information"); @@ -1014,7 +1011,7 @@ namespace System.Management.Automation /// /// PSObject to be serialized /// true if the object needs to be serialized as a string - static bool SerializeAsString(PSObject source) + private static bool SerializeAsString(PSObject source) { return source.GetSerializationMethod(null) == SerializationMethod.String; } @@ -1027,7 +1024,7 @@ namespace System.Management.Automation /// PSObject whose serialization depth has to be computed /// current depth /// - static int GetDepthOfSerialization(PSObject source, int depth) + private static int GetDepthOfSerialization(PSObject source, int depth) { if (source == null) return depth; @@ -1051,7 +1048,6 @@ namespace System.Management.Automation /// private void WriteNull(string property) { - if (property != null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); @@ -1059,10 +1055,10 @@ namespace System.Management.Automation } else { - if (firstcall) + if (_firstcall) { WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); - firstcall = false; + _firstcall = false; } else { @@ -1076,14 +1072,14 @@ namespace System.Management.Automation #region known type serialization private void WritePropertyWithNullValue( - XmlWriter writer,PSPropertyInfo source, int depth) + XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name.ToString()); if (!_notypeinformation) WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue.ToString()); writer.WriteEndElement(); - } + } private void WriteObjectString( XmlWriter writer, string property, object source, TypeSerializationInfo entry) @@ -1095,10 +1091,10 @@ namespace System.Management.Automation } else { - if (firstcall) + if (_firstcall) { WriteStartElement(writer, CustomSerializationStrings.PSObjectTag); - firstcall = false; + _firstcall = false; } else { @@ -1120,7 +1116,7 @@ namespace System.Management.Automation /// name of property. Pass null for item /// object to be written /// serialization information about source - + private void WriteOnePrimitiveKnownType( XmlWriter writer, string property, object source, TypeSerializationInfo entry) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs index 09fe4636b..2a9316937 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace System.Management.Automation { /// @@ -8,14 +9,14 @@ namespace System.Management.Automation /// internal static class CustomSerializationStrings { - #region element tags + #region element tags + - /// /// Element tag for root node /// internal const string RootElementTag = "Objects"; - + /// /// Element tag for PSObject /// @@ -26,8 +27,8 @@ namespace System.Management.Automation /// internal const string Properties = "Property"; - - #region attribute tags + + #region attribute tags /// /// String for name attribute @@ -38,7 +39,7 @@ namespace System.Management.Automation /// String for type attribute /// internal const string TypeAttribute = "Type"; - + #endregion #region known container tags @@ -55,6 +56,6 @@ namespace System.Management.Automation #endregion - #endregion + #endregion } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 3c595feb2..d17c0f780 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -120,15 +120,15 @@ namespace Microsoft.PowerShell.Commands switch (ParameterSetName) { - case DebugRunspaceCommand.NameParameterSet: + case DebugRunspaceCommand.NameParameterSet: runspaces = GetRunspaceUtils.GetRunspacesByName(new string[] { Name }); break; - case DebugRunspaceCommand.IdParameterSet: + case DebugRunspaceCommand.IdParameterSet: runspaces = GetRunspaceUtils.GetRunspacesById(new int[] { Id }); break; - case DebugRunspaceCommand.InstanceIdParameterSet: + case DebugRunspaceCommand.InstanceIdParameterSet: runspaces = GetRunspaceUtils.GetRunspacesByInstanceId(new Guid[] { InstanceId }); break; } @@ -143,7 +143,7 @@ namespace Microsoft.PowerShell.Commands this) ); } - + if (runspaces.Count == 1) { _runspace = runspaces[0]; @@ -209,7 +209,7 @@ namespace Microsoft.PowerShell.Commands // Blocking call. Send runspace/command output to host UI while debugging and wait for runspace/command completion. WaitAndReceiveRunspaceOutput(); } - finally + finally { RestoreRunspace(_runspace); } @@ -259,7 +259,7 @@ namespace Microsoft.PowerShell.Commands // Make sure host debugger has debugging turned on. _debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); - + // Set up host script debugger to debug the runspace. _debugger.DebugRunspace(_runspace); @@ -338,14 +338,14 @@ namespace Microsoft.PowerShell.Commands _runningPowerShell = _runspace.GetCurrentBasePowerShell(); if (_runningPowerShell != null) { - if (_runningPowerShell.OutputBuffer != null) - { - _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding; - } - if (_runningPowerShell.ErrorBuffer != null) - { - _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding; - } + if (_runningPowerShell.OutputBuffer != null) + { + _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding; + } + if (_runningPowerShell.ErrorBuffer != null) + { + _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding; + } } else { @@ -416,7 +416,7 @@ namespace Microsoft.PowerShell.Commands { _debugBlockingCollection.Complete(); } - else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) && + else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) && ((prevAvailability == RunspaceAvailability.Available) || (prevAvailability == RunspaceAvailability.None))) { _newRunningScriptEvent.Set(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs index 55ae882d9..0b2e00c0b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Management.Automation; namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs index 30d593de4..d4dc25d44 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Diagnostics; using System.Management.Automation; @@ -151,5 +152,4 @@ namespace Microsoft.PowerShell.Commands } } } - } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index 9d2a62f6e..89a6fcf26 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -198,7 +198,7 @@ namespace Microsoft.PowerShell.Commands /// [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] [ValidateNotNullOrEmpty()] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.CommonRunspaceCommandBase.#AppDomainName")] public string[] AppDomainName { @@ -291,7 +291,7 @@ namespace Microsoft.PowerShell.Commands { if (!string.IsNullOrEmpty(currentAppDomainName)) { - if(appDomainNames == null) + if (appDomainNames == null) { appDomainNames = new List(); } @@ -360,7 +360,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if(this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) + if (this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) { SetDebugPreferenceHelper(ProcessName, AppDomainName, true, "EnableRunspaceDebugCommandPersistDebugPreferenceFailure"); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 2623f8e04..c28ce12af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -52,21 +53,21 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { if (value == null) { - path = "."; + _path = "."; } else { - path = value; + _path = value; } } } - private string path = "."; + private string _path = "."; /// /// The literal path of the file to export the aliases to. @@ -78,47 +79,47 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { if (value == null) { - path = "."; + _path = "."; } else { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// The Name parameter for the command /// /// - [Parameter (Position = 1, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] public string[] Name { get { - return names; + return _names; } set { if (value == null) { - names = new string[] { "*" }; + _names = new string[] { "*" }; } else { - names = value; + _names = value; } } } - private string[] names = new string[] { "*" }; + private string[] _names = new string[] { "*" }; /// /// If set to true, the alias that is set is passed to the @@ -130,15 +131,15 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; /// /// Parameter that determines the format of the file created. @@ -149,14 +150,14 @@ namespace Microsoft.PowerShell.Commands { get { - return asFormat; + return _asFormat; } set { - asFormat = value; + _asFormat = value; } } - private ExportAliasFormat asFormat = ExportAliasFormat.Csv; + private ExportAliasFormat _asFormat = ExportAliasFormat.Csv; /// /// Property that sets append parameter. @@ -166,14 +167,14 @@ namespace Microsoft.PowerShell.Commands { get { - return append; + return _append; } set { - append = value; + _append = value; } } - private bool append; + private bool _append; /// /// Property that sets force parameter. @@ -183,14 +184,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Property that prevents file overwrite. @@ -201,14 +202,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noclobber; + return _noclobber; } set { - noclobber = value; + _noclobber = value; } } - private bool noclobber; + private bool _noclobber; /// /// The description that gets added to the file as a comment @@ -219,14 +220,14 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// /// The scope parameter for the command determines @@ -238,15 +239,15 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } set { - scope = value; + _scope = value; } } - private string scope; + private string _scope; #endregion Parameters #region Command code @@ -260,20 +261,20 @@ namespace Microsoft.PowerShell.Commands // First get the alias table (from the proper scope if necessary) IDictionary aliasTable = null; - if (!String.IsNullOrEmpty(scope)) + if (!String.IsNullOrEmpty(_scope)) { // This can throw PSArgumentException and PSArgumentOutOfRangeException // but just let them go as this is terminal for the pipeline and the // exceptions are already properly adorned with an ErrorRecord. - aliasTable = SessionState.Internal.GetAliasTableAtScope(scope); + aliasTable = SessionState.Internal.GetAliasTableAtScope(_scope); } else { aliasTable = SessionState.Internal.GetAliasTable(); } - foreach (string aliasName in names) + foreach (string aliasName in _names) { bool resultFound = false; @@ -298,7 +299,7 @@ namespace Microsoft.PowerShell.Commands if (SessionState.IsVisible(origin, tableEntry.Value)) { resultFound = true; - matchingAliases.Add(tableEntry.Value); + _matchingAliases.Add(tableEntry.Value); } } @@ -342,7 +343,7 @@ namespace Microsoft.PowerShell.Commands // Now write out the aliases - foreach (AliasInfo alias in matchingAliases) + foreach (AliasInfo alias in _matchingAliases) { string line = null; if (this.As == ExportAliasFormat.Csv) @@ -362,7 +363,6 @@ namespace Microsoft.PowerShell.Commands WriteObject(alias); } } - } finally { @@ -377,7 +377,7 @@ namespace Microsoft.PowerShell.Commands /// /// Holds all the matching aliases for writing to the file /// - private Collection matchingAliases = new Collection(); + private Collection _matchingAliases = new Collection(); private static string GetAliasLine(AliasInfo alias, string formatString) { @@ -412,17 +412,17 @@ namespace Microsoft.PowerShell.Commands // Now write the description if there is one - if (description != null) + if (_description != null) { // First we need to break up the description on newlines and add a // # for each line. - description = description.Replace("\n", "\n# "); + _description = _description.Replace("\n", "\n# "); // Now write out the description writer.WriteLine("#"); writer.Write("# "); - writer.WriteLine(description); + writer.WriteLine(_description); } } @@ -464,7 +464,7 @@ namespace Microsoft.PowerShell.Commands out file, out result, out readOnlyFileInfo, - isLiteralPath + _isLiteralPath ); return result; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index 03cd917ed..595859f70 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -33,7 +34,7 @@ namespace Microsoft.PowerShell.Commands internal Type GetValueType(PSObject liveObject, out object columnValue) { columnValue = GetValue(liveObject); - if(columnValue != null && columnValue is IComparable) + if (columnValue != null && columnValue is IComparable) { return columnValue.GetType(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs index 093cd12df..2ae6b5585 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -10,17 +11,17 @@ namespace Microsoft.PowerShell.Commands internal class ExpressionColumnInfo : ColumnInfo { - private MshExpression expression; + private MshExpression _expression; internal ExpressionColumnInfo(string staleObjectPropertyName, string displayName, MshExpression expression) : base(staleObjectPropertyName, displayName) { - this.expression = expression; + _expression = expression; } internal override Object GetValue(PSObject liveObject) { - List resList = expression.GetValues(liveObject); + List resList = _expression.GetValues(liveObject); if (resList.Count == 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index b51748868..0e904588c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -11,11 +12,11 @@ namespace Microsoft.PowerShell.Commands internal class HeaderInfo { - private List columns = new List(); + private List _columns = new List(); internal void AddColumn(ColumnInfo col) { - columns.Add(col); + _columns.Add(col); } internal PSObject AddColumnsToWindow(OutWindowProxy windowProxy, PSObject liveObject) @@ -23,13 +24,13 @@ namespace Microsoft.PowerShell.Commands PSObject staleObject = new PSObject(); // Initiate arrays to be of the same size. - int count = columns.Count; + int count = _columns.Count; string[] propertyNames = new string[count]; string[] displayNames = new string[count]; Type[] types = new Type[count]; count = 0; // Reuse this variabe to count cycles. - foreach(ColumnInfo column in columns) + foreach (ColumnInfo column in _columns) { propertyNames[count] = column.StaleObjectPropertyName(); displayNames[count] = column.DisplayName(); @@ -50,7 +51,7 @@ namespace Microsoft.PowerShell.Commands internal PSObject CreateStalePSObject(PSObject liveObject) { PSObject staleObject = new PSObject(); - foreach(ColumnInfo column in columns) + foreach (ColumnInfo column in _columns) { // Add a property to the stale PSObject. staleObject.Properties.Add(new PSNoteProperty(column.StaleObjectPropertyName(), diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 5e89c754c..f64e272b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -11,22 +12,22 @@ namespace Microsoft.PowerShell.Commands internal class OriginalColumnInfo : ColumnInfo { - private string liveObjectPropertyName; - private OutGridViewCommand parentCmdlet; + private string _liveObjectPropertyName; + private OutGridViewCommand _parentCmdlet; internal OriginalColumnInfo(string staleObjectPropertyName, string displayName, string liveObjectPropertyName, OutGridViewCommand parentCmdlet) : base(staleObjectPropertyName, displayName) { - this.liveObjectPropertyName = liveObjectPropertyName; - this.parentCmdlet = parentCmdlet; + _liveObjectPropertyName = liveObjectPropertyName; + _parentCmdlet = parentCmdlet; } internal override Object GetValue(PSObject liveObject) { try { - PSPropertyInfo propertyInfo = liveObject.Properties[this.liveObjectPropertyName]; - if(propertyInfo == null) + PSPropertyInfo propertyInfo = liveObject.Properties[_liveObjectPropertyName]; + if (propertyInfo == null) { return null; } @@ -36,11 +37,10 @@ namespace Microsoft.PowerShell.Commands ICollection collectionValue = liveObjectValue as ICollection; if (null != collectionValue) { - liveObjectValue = this.parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); + liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { - PSObject psObjectValue = liveObjectValue as PSObject; if (psObjectValue != null) { @@ -52,7 +52,7 @@ namespace Microsoft.PowerShell.Commands else { // Use the String type as default. - liveObjectValue = this.parentCmdlet.ConvertToString(psObjectValue); + liveObjectValue = _parentCmdlet.ConvertToString(psObjectValue); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index bfc3a5396..06cca58ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -37,7 +38,7 @@ namespace Microsoft.PowerShell.Commands /// Multiple } - + /// /// Implementation for the Out-GridView command /// @@ -48,10 +49,10 @@ namespace Microsoft.PowerShell.Commands private const string DataNotQualifiedForGridView = "DataNotQualifiedForGridView"; private const string RemotingNotSupported = "RemotingNotSupported"; - private TypeInfoDataBase typeInfoDataBase; - private MshExpressionFactory expressionFactory; - private OutWindowProxy windowProxy; - private GridHeader gridHeader; + private TypeInfoDataBase _typeInfoDataBase; + private MshExpressionFactory _expressionFactory; + private OutWindowProxy _windowProxy; + private GridHeader _gridHeader; #endregion Properties @@ -71,13 +72,13 @@ namespace Microsoft.PowerShell.Commands /// /// This parameter specifies the current pipeline object /// - [Parameter (ValueFromPipeline = true)] + [Parameter(ValueFromPipeline = true)] public PSObject InputObject { - get { return this.inputObject; } - set { this.inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// /// Gets/sets the title of the Out-GridView window. @@ -86,15 +87,15 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string Title { - get { return title; } + get { return title; } set { title = value; } } internal string title; - - /// + + /// /// Field used for the Block parameter. /// - private SwitchParameter wait; + private SwitchParameter _wait; /// /// Get or sets a value indicating whether the cmdlet should wait for the window to be closed @@ -102,14 +103,14 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "Wait")] public SwitchParameter Wait { - get { return this.wait; } - set { this.wait = value; } + get { return _wait; } + set { _wait = value; } } /// /// Field used for the OutputMode parameter. /// - private OutputModeOption outputMode; + private OutputModeOption _outputMode; /// /// Get or sets a value indicating whether the selected items should be written to the pipeline @@ -118,8 +119,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "OutputMode")] public OutputModeOption OutputMode { - set { this.outputMode = value; } - get { return outputMode; } + set { _outputMode = value; } + get { return _outputMode; } } /// @@ -130,7 +131,7 @@ namespace Microsoft.PowerShell.Commands public SwitchParameter PassThru { set { this.OutputMode = value.IsPresent ? OutputModeOption.Multiple : OutputModeOption.None; } - get { return this.outputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); } + get { return _outputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); } } #endregion Input Parameters @@ -143,21 +144,21 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // Set up the ExpressionFactory - this.expressionFactory = new MshExpressionFactory(); + _expressionFactory = new MshExpressionFactory(); // If the value of the Title parameter is valid, use it as a window's title. - if(this.title != null) + if (this.title != null) { - this.windowProxy = new OutWindowProxy(this.title, this.outputMode, this); + _windowProxy = new OutWindowProxy(this.title, _outputMode, this); } else { // Using the command line as a title. - this.windowProxy = new OutWindowProxy(this.MyInvocation.Line, this.outputMode, this); + _windowProxy = new OutWindowProxy(this.MyInvocation.Line, _outputMode, this); } // Load the Type info database. - this.typeInfoDataBase = this.Context.FormatDBManager.GetTypeInfoDataBase(); + _typeInfoDataBase = this.Context.FormatDBManager.GetTypeInfoDataBase(); } /// @@ -167,7 +168,7 @@ namespace Microsoft.PowerShell.Commands { base.EndProcessing(); - if (this.windowProxy == null) + if (_windowProxy == null) { return; } @@ -176,11 +177,11 @@ namespace Microsoft.PowerShell.Commands // The pipeline will be blocked while we don't return if (this.Wait || this.OutputMode != OutputModeOption.None) { - this.windowProxy.BlockUntillClosed(); + _windowProxy.BlockUntillClosed(); } - + // Output selected items to pipeline. - List selectedItems = this.windowProxy.GetSelectedItems(); + List selectedItems = _windowProxy.GetSelectedItems(); if (this.OutputMode != OutputModeOption.None && selectedItems != null) { foreach (PSObject selectedItem in selectedItems) @@ -206,23 +207,23 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (this.inputObject == null || this.inputObject == AutomationNull.Value) + if (_inputObject == null || _inputObject == AutomationNull.Value) { return; } - IDictionary dictionary = this.inputObject.BaseObject as IDictionary; - if(dictionary != null) + IDictionary dictionary = _inputObject.BaseObject as IDictionary; + if (dictionary != null) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. - foreach(DictionaryEntry entry in dictionary) + foreach (DictionaryEntry entry in dictionary) { ProcessObject(PSObjectHelper.AsPSObject(entry)); } } else { - ProcessObject(this.inputObject); + ProcessObject(_inputObject); } } @@ -233,7 +234,7 @@ namespace Microsoft.PowerShell.Commands { if (this.Wait || this.OutputMode != OutputModeOption.None) { - this.windowProxy.CloseWindow(); + _windowProxy.CloseWindow(); } } @@ -245,10 +246,10 @@ namespace Microsoft.PowerShell.Commands { StringFormatError formatErrorObject = new StringFormatError(); string smartToString = PSObjectHelper.SmartToString(liveObject, - this.expressionFactory, + _expressionFactory, InnerFormatShapeCommand.FormatEnumerationLimit(), formatErrorObject); - if(formatErrorObject.exception != null) + if (formatErrorObject.exception != null) { // There was a formatting error that should be sent to the console. this.WriteError( @@ -273,10 +274,10 @@ namespace Microsoft.PowerShell.Commands private void ProcessObject(PSObject input) { // Make sure the OGV window is not closed. - if (this.windowProxy.IsWindowClosed()) + if (_windowProxy.IsWindowClosed()) { LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline(); - + if (pipeline != null && !pipeline.IsStopping) { // Stop the pipeline cleanly. @@ -303,20 +304,20 @@ namespace Microsoft.PowerShell.Commands this.ThrowTerminatingError(error); } - if(this.gridHeader == null) + if (_gridHeader == null) { // Columns have not been added yet; Start the main window and add columns. - this.windowProxy.ShowWindow(); - this.gridHeader = GridHeader.ConstructGridHeader(input, this); + _windowProxy.ShowWindow(); + _gridHeader = GridHeader.ConstructGridHeader(input, this); } else { - this.gridHeader.ProcessInputObject(input); + _gridHeader.ProcessInputObject(input); } - + // Some thread syncronization needed. - Exception exception = this.windowProxy.GetLastException(); - if(exception != null) + Exception exception = _windowProxy.GetLastException(); + if (exception != null) { ErrorRecord error = new ErrorRecord( exception, @@ -327,7 +328,7 @@ namespace Microsoft.PowerShell.Commands this.ThrowTerminatingError(error); } } - + #endregion Private Methods internal abstract class GridHeader @@ -354,67 +355,67 @@ namespace Microsoft.PowerShell.Commands internal class ScalarTypeHeader : GridHeader { - private Type originalScalarType; + private Type _originalScalarType; internal ScalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { - this.originalScalarType = input.BaseObject.GetType(); + _originalScalarType = input.BaseObject.GetType(); // On scalar types the type name is used as a column name. - this.parentCmd.windowProxy.AddColumnsAndItem(input); + this.parentCmd._windowProxy.AddColumnsAndItem(input); } internal override void ProcessInputObject(PSObject input) { - if(!originalScalarType.Equals(input.BaseObject.GetType())) + if (!_originalScalarType.Equals(input.BaseObject.GetType())) { - parentCmd.gridHeader = new HeteroTypeHeader(base.parentCmd, input); + parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input); } else { // Columns are already added; Add the input PSObject as an item to the underlying Management List. - base.parentCmd.windowProxy.AddItem(input); + base.parentCmd._windowProxy.AddItem(input); } } } internal class NonscalarTypeHeader : GridHeader { - private AppliesTo appliesTo = null; + private AppliesTo _appliesTo = null; internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { // Prepare a table view. TableView tableView = new TableView(); - tableView.Initialize(parentCmd.expressionFactory, parentCmd.typeInfoDataBase); + tableView.Initialize(parentCmd._expressionFactory, parentCmd._typeInfoDataBase); // Request a view definition from the type database. - ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd.expressionFactory, parentCmd.typeInfoDataBase, FormatShape.Table, input.TypeNames, null); - if(viewDefinition != null) + ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd._expressionFactory, parentCmd._typeInfoDataBase, FormatShape.Table, input.TypeNames, null); + if (viewDefinition != null) { // Create a header using a view definition provided by the types database. - parentCmd.windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl); + parentCmd._windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl); // Remember all type names and type groups the current view applies to. - this.appliesTo = viewDefinition.appliesTo; + _appliesTo = viewDefinition.appliesTo; } else { // Create a header using only the input object's properties. - parentCmd.windowProxy.AddColumnsAndItem(input, tableView); - this.appliesTo = new AppliesTo(); + parentCmd._windowProxy.AddColumnsAndItem(input, tableView); + _appliesTo = new AppliesTo(); // Add all type names except for Object and MarshalByRefObject types because they are too generic. // Leave the Object type name if it is the only type name. int index = 0; - foreach(string typeName in input.TypeNames) + foreach (string typeName in input.TypeNames) { - if(index > 0 && (typeName.Equals(typeof(Object).FullName, StringComparison.OrdinalIgnoreCase) || + if (index > 0 && (typeName.Equals(typeof(Object).FullName, StringComparison.OrdinalIgnoreCase) || typeName.Equals(typeof(MarshalByRefObject).FullName, StringComparison.OrdinalIgnoreCase))) { break; } - this.appliesTo.AddAppliesToType(typeName); + _appliesTo.AddAppliesToType(typeName); index++; } } @@ -423,22 +424,22 @@ namespace Microsoft.PowerShell.Commands internal override void ProcessInputObject(PSObject input) { // Find out if the input has matching types in the this.appliesTo collection. - foreach(TypeOrGroupReference typeOrGroupRef in this.appliesTo.referenceList) + foreach (TypeOrGroupReference typeOrGroupRef in _appliesTo.referenceList) { - if(typeOrGroupRef is TypeReference) + if (typeOrGroupRef is TypeReference) { // Add deserialization prefix. string deserializedTypeName = typeOrGroupRef.name; Deserializer.AddDeserializationPrefix(ref deserializedTypeName); - for(int i = 0; i < input.TypeNames.Count; i++) + for (int i = 0; i < input.TypeNames.Count; i++) { - if(typeOrGroupRef.name.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase) + if (typeOrGroupRef.name.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase) || deserializedTypeName.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase)) { // Current view supports the input's Type; // Add the input PSObject as an item to the underlying Management List. - base.parentCmd.windowProxy.AddItem(input); + base.parentCmd._windowProxy.AddItem(input); return; } } @@ -447,26 +448,26 @@ namespace Microsoft.PowerShell.Commands { // Find out if the input's Type belongs to the current TypeGroup. // TypeGroupReference has only a group's name, so use the database to get through all actual TypeGroup's. - List typeGroupList = base.parentCmd.typeInfoDataBase.typeGroupSection.typeGroupDefinitionList; - foreach(TypeGroupDefinition typeGroup in typeGroupList) + List typeGroupList = base.parentCmd._typeInfoDataBase.typeGroupSection.typeGroupDefinitionList; + foreach (TypeGroupDefinition typeGroup in typeGroupList) { - if(typeGroup.name.Equals(typeOrGroupRef.name, StringComparison.OrdinalIgnoreCase)) + if (typeGroup.name.Equals(typeOrGroupRef.name, StringComparison.OrdinalIgnoreCase)) { // A matching TypeGroup is found in the database. // Find out if the input's Type belongs to this TypeGroup. - foreach(TypeReference typeRef in typeGroup.typeReferenceList) + foreach (TypeReference typeRef in typeGroup.typeReferenceList) { // Add deserialization prefix. string deserializedTypeName = typeRef.name; Deserializer.AddDeserializationPrefix(ref deserializedTypeName); - if(input.TypeNames.Count > 0 + if (input.TypeNames.Count > 0 && (typeRef.name.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase) || deserializedTypeName.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase))) { // Current view supports the input's Type; // Add the input PSObject as an item to the underlying Management List. - base.parentCmd.windowProxy.AddItem(input); + base.parentCmd._windowProxy.AddItem(input); return; } } @@ -477,7 +478,7 @@ namespace Microsoft.PowerShell.Commands // The input's Type is not supported by the current view; // Switch to the Hetero Type view. - parentCmd.gridHeader = new HeteroTypeHeader(base.parentCmd, input); + parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input); } } @@ -486,12 +487,12 @@ namespace Microsoft.PowerShell.Commands internal HeteroTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { // Clear all existed columns and add Type and Value columns. - this.parentCmd.windowProxy.AddHeteroViewColumnsAndItem(input); + this.parentCmd._windowProxy.AddHeteroViewColumnsAndItem(input); } internal override void ProcessInputObject(PSObject input) { - this.parentCmd.windowProxy.AddHeteroViewItem(input); + this.parentCmd._windowProxy.AddHeteroViewItem(input); } } @@ -503,10 +504,10 @@ namespace Microsoft.PowerShell.Commands { if (isDisposing) { - if (this.windowProxy != null) + if (_windowProxy != null) { - this.windowProxy.Dispose(); - this.windowProxy = null; + _windowProxy.Dispose(); + _windowProxy = null; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 635af783b..0b89517ee 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -14,42 +15,42 @@ namespace Microsoft.PowerShell.Commands using System.Management.Automation.Runspaces; using Microsoft.PowerShell.Commands.Internal.Format; - - internal class OutWindowProxy: IDisposable + + internal class OutWindowProxy : IDisposable { private const string OutGridViewWindowClassName = "Microsoft.Management.UI.Internal.OutGridViewWindow"; private const string OriginalTypePropertyName = "OriginalType"; internal const string OriginalObjectPropertyName = "OutGridViewOriginalObject"; private const string ToStringValuePropertyName = "ToStringValue"; private const string IndexPropertyName = "IndexValue"; - private int index; + private int _index; + - /// Columns definition of the underlying Management List - private HeaderInfo headerInfo; + private HeaderInfo _headerInfo; - private bool IsWindowStarted; + private bool _isWindowStarted; - private string title; - - private OutputModeOption outputMode; - - private AutoResetEvent closedEvent; + private string _title; - private OutGridViewCommand parentCmdlet; + private OutputModeOption _outputMode; - private GraphicalHostReflectionWrapper graphicalHostReflectionWrapper; + private AutoResetEvent _closedEvent; + + private OutGridViewCommand _parentCmdlet; + + private GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; /// /// Initializes a new instance of the OutWindowProxy class. /// internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCommand parentCmdlet) { - this.title = title; - this.outputMode = outPutMode; - this.parentCmdlet = parentCmdlet; + _title = title; + _outputMode = outPutMode; + _parentCmdlet = parentCmdlet; - this.graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, OutWindowProxy.OutGridViewWindowClassName); + _graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, OutWindowProxy.OutGridViewWindowClassName); } /// @@ -75,18 +76,18 @@ namespace Microsoft.PowerShell.Commands try { - this.graphicalHostReflectionWrapper.CallMethod("AddColumns", propertyNames, displayNames, types); + _graphicalHostReflectionWrapper.CallMethod("AddColumns", propertyNames, displayNames, types); } catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if(fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) { - this.parentCmdlet.ThrowTerminatingError( + _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( StringUtil.Format(FormatAndOut_out_gridview.RestartPowerShell, - parentCmdlet.CommandInfo.Name), ex.InnerException), + _parentCmdlet.CommandInfo.Name), ex.InnerException), "ErrorLoadingAssembly", ErrorCategory.ObjectNotFound, null)); @@ -103,7 +104,7 @@ namespace Microsoft.PowerShell.Commands internal void AddColumnsAndItem(PSObject liveObject, TableView tableView) { // Create a header using only the input object's properties. - this.headerInfo = tableView.GenerateHeaderInfo(liveObject, parentCmdlet); + _headerInfo = tableView.GenerateHeaderInfo(liveObject, _parentCmdlet); AddColumnsAndItemEnd(liveObject); } @@ -111,7 +112,7 @@ namespace Microsoft.PowerShell.Commands // Database defined types. internal void AddColumnsAndItem(PSObject liveObject, TableView tableView, TableControlBody tableBody) { - this.headerInfo = tableView.GenerateHeaderInfo(liveObject, tableBody, parentCmdlet); + _headerInfo = tableView.GenerateHeaderInfo(liveObject, tableBody, _parentCmdlet); AddColumnsAndItemEnd(liveObject); } @@ -119,54 +120,54 @@ namespace Microsoft.PowerShell.Commands // Scalar types. internal void AddColumnsAndItem(PSObject liveObject) { - this.headerInfo = new HeaderInfo(); + _headerInfo = new HeaderInfo(); // On scalar types the type name is used as a column name. - headerInfo.AddColumn(new ScalarTypeColumnInfo(liveObject.BaseObject.GetType())); + _headerInfo.AddColumn(new ScalarTypeColumnInfo(liveObject.BaseObject.GetType())); AddColumnsAndItemEnd(liveObject); } private void AddColumnsAndItemEnd(PSObject liveObject) { // Add columns to the underlying Management list and as a byproduct get a stale PSObject. - PSObject staleObject = headerInfo.AddColumnsToWindow(this, liveObject); + PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. AddExtraProperties(staleObject, liveObject); - + // Add the stale PSObject to the underlying Management list. - this.graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); + _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); } // Hetero types. internal void AddHeteroViewColumnsAndItem(PSObject liveObject) { - this.headerInfo = new HeaderInfo(); + _headerInfo = new HeaderInfo(); - headerInfo.AddColumn(new IndexColumnInfo(OutWindowProxy.IndexPropertyName, - StringUtil.Format(FormatAndOut_out_gridview.IndexColumnName), this.index)); - headerInfo.AddColumn(new ToStringColumnInfo(OutWindowProxy.ToStringValuePropertyName, - StringUtil.Format(FormatAndOut_out_gridview.ValueColumnName), this.parentCmdlet)); - headerInfo.AddColumn(new TypeNameColumnInfo(OutWindowProxy.OriginalTypePropertyName, + _headerInfo.AddColumn(new IndexColumnInfo(OutWindowProxy.IndexPropertyName, + StringUtil.Format(FormatAndOut_out_gridview.IndexColumnName), _index)); + _headerInfo.AddColumn(new ToStringColumnInfo(OutWindowProxy.ToStringValuePropertyName, + StringUtil.Format(FormatAndOut_out_gridview.ValueColumnName), _parentCmdlet)); + _headerInfo.AddColumn(new TypeNameColumnInfo(OutWindowProxy.OriginalTypePropertyName, StringUtil.Format(FormatAndOut_out_gridview.TypeColumnName))); - + // Add columns to the underlying Management list and as a byproduct get a stale PSObject. - PSObject staleObject = headerInfo.AddColumnsToWindow(this, liveObject); - + PSObject staleObject = _headerInfo.AddColumnsToWindow(this, liveObject); + // Add the stale PSObject to the underlying Management list. - this.graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); + _graphicalHostReflectionWrapper.CallMethod("AddItem", staleObject); } private void AddExtraProperties(PSObject staleObject, PSObject liveObject) { // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. - staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.IndexPropertyName, index++)); + staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.IndexPropertyName, _index++)); staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalTypePropertyName, liveObject.BaseObject.GetType().FullName)); staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.OriginalObjectPropertyName, liveObject)); // Convert the LivePSObject to a string preserving PowerShell formatting. staleObject.Properties.Add(new PSNoteProperty(OutWindowProxy.ToStringValuePropertyName, - this.parentCmdlet.ConvertToString(liveObject))); + _parentCmdlet.ConvertToString(liveObject))); } /// @@ -182,17 +183,17 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentNullException("livePSObject"); } - if(this.headerInfo == null) + if (_headerInfo == null) { throw new InvalidOperationException(); } - PSObject stalePSObject = this.headerInfo.CreateStalePSObject(livePSObject); + PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); // Add 3 extra properties, so that the stale PSObject has meaningful info in the Hetero-type header view. AddExtraProperties(stalePSObject, livePSObject); - this.graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); + _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); } /// @@ -208,13 +209,13 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentNullException("livePSObject"); } - if(this.headerInfo == null) + if (_headerInfo == null) { throw new InvalidOperationException(); } - PSObject stalePSObject = this.headerInfo.CreateStalePSObject(livePSObject); - this.graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); + PSObject stalePSObject = _headerInfo.CreateStalePSObject(livePSObject); + _graphicalHostReflectionWrapper.CallMethod("AddItem", stalePSObject); } /// @@ -222,19 +223,19 @@ namespace Microsoft.PowerShell.Commands /// internal void ShowWindow() { - if (!this.IsWindowStarted) + if (!_isWindowStarted) { - this.closedEvent = new AutoResetEvent(false); - this.graphicalHostReflectionWrapper.CallMethod("StartWindow", this.title, this.outputMode.ToString(), this.closedEvent); - this.IsWindowStarted = true; + _closedEvent = new AutoResetEvent(false); + _graphicalHostReflectionWrapper.CallMethod("StartWindow", _title, _outputMode.ToString(), _closedEvent); + _isWindowStarted = true; } } internal void BlockUntillClosed() { - if (this.closedEvent != null) + if (_closedEvent != null) { - this.closedEvent.WaitOne(); + _closedEvent.WaitOne(); } } @@ -246,10 +247,10 @@ namespace Microsoft.PowerShell.Commands { if (isDisposing) { - if (this.closedEvent != null) + if (_closedEvent != null) { - this.closedEvent.Dispose(); - this.closedEvent = null; + _closedEvent.Dispose(); + _closedEvent = null; } } } @@ -270,10 +271,10 @@ namespace Microsoft.PowerShell.Commands /// internal void CloseWindow() { - if (this.IsWindowStarted) + if (_isWindowStarted) { - this.graphicalHostReflectionWrapper.CallMethod("CloseWindow"); - this.IsWindowStarted = false; + _graphicalHostReflectionWrapper.CallMethod("CloseWindow"); + _isWindowStarted = false; } } @@ -285,16 +286,16 @@ namespace Microsoft.PowerShell.Commands /// internal bool IsWindowClosed() { - return (bool)this.graphicalHostReflectionWrapper.CallMethod("GetWindowClosedStatus"); + return (bool)_graphicalHostReflectionWrapper.CallMethod("GetWindowClosedStatus"); } /// Returns any exception that has been thrown by previous method calls. /// The thrown and caught exception. It returns null if no exceptions were thrown by any previous method calls. internal Exception GetLastException() { - return (Exception)this.graphicalHostReflectionWrapper.CallMethod("GetLastException"); + return (Exception)_graphicalHostReflectionWrapper.CallMethod("GetLastException"); } - + /// /// Return the selected item of the OutGridView. /// @@ -303,7 +304,7 @@ namespace Microsoft.PowerShell.Commands /// internal List GetSelectedItems() { - return (List)this.graphicalHostReflectionWrapper.CallMethod("SelectedItems"); + return (List)_graphicalHostReflectionWrapper.CallMethod("SelectedItems"); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index 2ee294cca..872a362c1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System.Management.Automation; @@ -8,19 +9,19 @@ namespace Microsoft.PowerShell.Commands internal class ScalarTypeColumnInfo : ColumnInfo { - private Type type; + private Type _type; internal ScalarTypeColumnInfo(Type type) : base(type.Name, type.Name) { - this.type = type; + _type = type; } internal override Object GetValue(PSObject liveObject) { // Strip a wrapping PSObject. object baseObject = ((PSObject)liveObject).BaseObject; - if(baseObject.GetType().Equals(this.type)) + if (baseObject.GetType().Equals(_type)) { return ColumnInfo.LimitString(baseObject); } @@ -30,10 +31,9 @@ namespace Microsoft.PowerShell.Commands internal class TypeNameColumnInfo : ColumnInfo { - internal TypeNameColumnInfo(string staleObjectPropertyName, string displayName) : base(staleObjectPropertyName, displayName) - {} + { } internal override Object GetValue(PSObject liveObject) { @@ -45,35 +45,35 @@ namespace Microsoft.PowerShell.Commands internal class ToStringColumnInfo : ColumnInfo { - private OutGridViewCommand parentCmdlet; + private OutGridViewCommand _parentCmdlet; internal ToStringColumnInfo(string staleObjectPropertyName, string displayName, OutGridViewCommand parentCmdlet) : base(staleObjectPropertyName, displayName) { - this.parentCmdlet = parentCmdlet; + _parentCmdlet = parentCmdlet; } internal override Object GetValue(PSObject liveObject) { // Convert to a string preserving PowerShell formatting. - return ColumnInfo.LimitString(parentCmdlet.ConvertToString(liveObject)); + return ColumnInfo.LimitString(_parentCmdlet.ConvertToString(liveObject)); } } internal class IndexColumnInfo : ColumnInfo { - private int index = 0; + private int _index = 0; internal IndexColumnInfo(string staleObjectPropertyName, string displayName, int index) : base(staleObjectPropertyName, displayName) { - this.index = index; + _index = index; } internal override Object GetValue(PSObject liveObject) { // Every time this method is called, another raw is added to ML. - return index++; + return _index++; } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 7822caf5c..49b4adddb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + namespace Microsoft.PowerShell.Commands { using System; @@ -13,23 +14,23 @@ namespace Microsoft.PowerShell.Commands internal class TableView { - private MshExpressionFactory expressionFactory; - private TypeInfoDataBase typeInfoDatabase; - private FormatErrorManager errorManager; + private MshExpressionFactory _expressionFactory; + private TypeInfoDataBase _typeInfoDatabase; + private FormatErrorManager _errorManager; internal void Initialize(MshExpressionFactory expressionFactory, TypeInfoDataBase db) { - this.expressionFactory = expressionFactory; - this.typeInfoDatabase = db; + _expressionFactory = expressionFactory; + _typeInfoDatabase = db; // Initialize Format Error Manager. FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); - formatErrorPolicy.ShowErrorsAsMessages = this.typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; - formatErrorPolicy.ShowErrorsInFormattedOutput = this.typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; + formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; + formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; - this.errorManager = new FormatErrorManager(formatErrorPolicy); + _errorManager = new FormatErrorManager(formatErrorPolicy); } internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) @@ -57,7 +58,7 @@ namespace Microsoft.PowerShell.Commands if (colHeader != null && colHeader.label != null) { - displayName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); + displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } FormatToken token = null; @@ -71,19 +72,19 @@ namespace Microsoft.PowerShell.Commands FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { - if(displayName == null) + if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } - if(fpt.expression.isScriptBlock) + if (fpt.expression.isScriptBlock) { - MshExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression); + MshExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); // Using the displayName as a propertyName for a stale PSObject. const string LastWriteTimePropertyName = "LastWriteTime"; // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. - if(fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) + if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) { columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); } @@ -102,12 +103,12 @@ namespace Microsoft.PowerShell.Commands TextToken tt = token as TextToken; if (tt != null) { - displayName = this.typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); - columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); + displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); + columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); } } } - if(columnInfo != null) + if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } @@ -124,7 +125,7 @@ namespace Microsoft.PowerShell.Commands List activeAssociationList; // Get properties from the default property set of the object - activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, this.expressionFactory); + activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, _expressionFactory); if (activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for @@ -148,7 +149,7 @@ namespace Microsoft.PowerShell.Commands else { // We were unable to retrieve any properties, so we leave an empty list - activeAssociationList = new List(); + activeAssociationList = new List(); } } @@ -215,7 +216,7 @@ namespace Microsoft.PowerShell.Commands TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; - TypeMatch match = new TypeMatch(this.expressionFactory, this.typeInfoDatabase, typeNames); + TypeMatch match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { @@ -235,7 +236,7 @@ namespace Microsoft.PowerShell.Commands Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { - match = new TypeMatch(expressionFactory, this.typeInfoDatabase, typesWithoutPrefix); + match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index ac6dfe9c4..890ca59ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Get, "FormatData", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=144303")] [OutputType(typeof(System.Management.Automation.ExtendedTypeDefinition))] - public class GetFormatDataCommand: PSCmdlet + public class GetFormatDataCommand : PSCmdlet { private string[] _typename; private WildcardPattern[] _filter = new WildcardPattern[1]; @@ -30,9 +30,9 @@ namespace Microsoft.PowerShell.Commands /// Get Formatting information only for the specified /// typename /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [ValidateNotNullOrEmpty] - [Parameter(Position=0)] + [Parameter(Position = 0)] public String[] TypeName { get @@ -106,7 +106,7 @@ namespace Microsoft.PowerShell.Commands PowerShellVersion.Build < 11086; TypeInfoDataBase db = this.Context.FormatDBManager.Database; - + List viewdefinitions = db.viewDefinitionsSection.viewDefinitionList; Dictionary> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index fae75ae1e..194a7c231 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// /// type definition to include in export /// - [Parameter(Mandatory = true, ValueFromPipeline=true)] + [Parameter(Mandatory = true, ValueFromPipeline = true)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public ExtendedTypeDefinition[] InputObject { @@ -40,7 +40,7 @@ namespace Microsoft.PowerShell.Commands /// /// Path of the XML file /// - [Parameter(ParameterSetName="ByPath", Mandatory = true)] + [Parameter(ParameterSetName = "ByPath", Mandatory = true)] [Alias("FilePath")] public String Path { @@ -57,7 +57,7 @@ namespace Microsoft.PowerShell.Commands /// /// Literal path of the XML file /// - [Parameter(ParameterSetName="ByLiteralPath", Mandatory = true)] + [Parameter(ParameterSetName = "ByLiteralPath", Mandatory = true)] [Alias("PSPath")] public String LiteralPath { @@ -68,11 +68,11 @@ namespace Microsoft.PowerShell.Commands set { _filepath = value; - isLiteralPath = true; + _isLiteralPath = true; } } - bool isLiteralPath = false; - + private bool _isLiteralPath = false; + private List _typeDefinitions = new List(); private bool _force; @@ -145,7 +145,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - FormatXmlWriter.WriteToPs1Xml(this, _typeDefinitions, _filepath, _force, _noclobber, _includescriptblock, isLiteralPath); + FormatXmlWriter.WriteToPs1Xml(this, _typeDefinitions, _filepath, _force, _noclobber, _includescriptblock, _isLiteralPath); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs index 49b9444e5..19a204652 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Management.Automation; @@ -17,9 +18,9 @@ namespace Microsoft.PowerShell.Commands /// /// constructor to set the inner command /// - public FormatListCommand () + public FormatListCommand() { - this.implementation = new InnerFormatShapeCommand (FormatShape.List); + this.implementation = new InnerFormatShapeCommand(FormatShape.List); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs index 3dc7c0af9..2459882dd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/format-object.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Microsoft.PowerShell.Commands.Internal.Format; @@ -19,7 +20,7 @@ namespace Microsoft.PowerShell.Commands /// public FormatCustomCommand() { - this.implementation = new InnerFormatShapeCommand (FormatShape.Complex); + this.implementation = new InnerFormatShapeCommand(FormatShape.Complex); } @@ -31,63 +32,63 @@ namespace Microsoft.PowerShell.Commands /// The paramater is optional, since the defaults /// will be determined using property sets, etc. /// - [Parameter (Position = 0)] + [Parameter(Position = 0)] public object[] Property { - get { return props; } - set { props = value; } + get { return _props; } + set { _props = value; } } - private object[] props; + private object[] _props; /// /// /// /// - [ValidateRangeAttribute (1, int.MaxValue)] + [ValidateRangeAttribute(1, int.MaxValue)] [Parameter] public int Depth { - get { return depth; } - set { depth = value; } + get { return _depth; } + set { _depth = value; } } - private int depth = ComplexSpecificParameters.maxDepthAllowable; + private int _depth = ComplexSpecificParameters.maxDepthAllowable; #endregion - internal override FormattingCommandLineParameters GetCommandLineParameters () + internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters (); + FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); - if (this.props != null) + if (_props != null) { - ParameterProcessor processor = new ParameterProcessor (new FormatObjectParameterDefinition()); - TerminatingErrorContext invocationContext = new TerminatingErrorContext (this); - parameters.mshParameterList = processor.ProcessParameters (this.props, invocationContext); + ParameterProcessor processor = new ParameterProcessor(new FormatObjectParameterDefinition()); + TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext); } - if (!string.IsNullOrEmpty (this.View)) + if (!string.IsNullOrEmpty(this.View)) { // we have a view command line switch if (parameters.mshParameterList.Count != 0) { - ReportCannotSpecifyViewAndProperty (); + ReportCannotSpecifyViewAndProperty(); } parameters.viewName = this.View; } - parameters.groupByParameter = this.ProcessGroupByParameter (); + parameters.groupByParameter = this.ProcessGroupByParameter(); parameters.forceFormattingAlsoOnOutOfBand = this.Force; if (this.showErrorsAsMessages.HasValue) parameters.showErrorsAsMessages = this.showErrorsAsMessages; if (this.showErrorsInFormattedOutput.HasValue) parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput; - parameters.expansion = ProcessExpandParameter (); + parameters.expansion = ProcessExpandParameter(); - ComplexSpecificParameters csp = new ComplexSpecificParameters (); - csp.maxDepth = this.depth; + ComplexSpecificParameters csp = new ComplexSpecificParameters(); + csp.maxDepth = _depth; parameters.shapeParameters = csp; return parameters; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs index cd7a497f4..2b4eca9e8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index 86c20804d..e38690a43 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -34,14 +34,14 @@ namespace Microsoft.PowerShell.Commands /// The paramater is optional, since the defaults /// will be determined using property sets, etc. /// - [Parameter(Position=0)] + [Parameter(Position = 0)] public object Property { - get { return prop; } - set { prop = value; } + get { return _prop; } + set { _prop = value; } } - private object prop; + private object _prop; /// /// optional, non positional parameter @@ -52,13 +52,13 @@ namespace Microsoft.PowerShell.Commands { get { - if (autosize.HasValue) - return autosize.Value; + if (_autosize.HasValue) + return _autosize.Value; return false; } - set { autosize = value; } + set { _autosize = value; } } - private Nullable autosize = null; + private Nullable _autosize = null; /// @@ -66,79 +66,79 @@ namespace Microsoft.PowerShell.Commands /// /// [Parameter] - [ValidateRangeAttribute (1, int.MaxValue)] + [ValidateRangeAttribute(1, int.MaxValue)] public int Column { get { - if (column.HasValue) - return column.Value; + if (_column.HasValue) + return _column.Value; return -1; } - set { column = value; } + set { _column = value; } } - private Nullable column = null; + private Nullable _column = null; #endregion - internal override FormattingCommandLineParameters GetCommandLineParameters () + internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters (); + FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); - if (this.prop != null) + if (_prop != null) { - ParameterProcessor processor = new ParameterProcessor (new FormatWideParameterDefinition()); - TerminatingErrorContext invocationContext = new TerminatingErrorContext (this); - parameters.mshParameterList = processor.ProcessParameters (new object[] { prop }, invocationContext); + ParameterProcessor processor = new ParameterProcessor(new FormatWideParameterDefinition()); + TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { _prop }, invocationContext); } - if (!string.IsNullOrEmpty (this.View)) + if (!string.IsNullOrEmpty(this.View)) { // we have a view command line switch if (parameters.mshParameterList.Count != 0) { - ReportCannotSpecifyViewAndProperty (); + ReportCannotSpecifyViewAndProperty(); } parameters.viewName = this.View; } // we cannot specify -column and -autosize, they are mutually exclusive - if (this.autosize.HasValue && this.column.HasValue) + if (_autosize.HasValue && _column.HasValue) { - if (this.autosize.Value) + if (_autosize.Value) { // the user specified -autosize:true AND a column number string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyAutosizeAndColumnsError); - - ErrorRecord errorRecord = new ErrorRecord ( - new InvalidDataException (), + + ErrorRecord errorRecord = new ErrorRecord( + new InvalidDataException(), "FormatCannotSpecifyAutosizeAndColumns", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); } } - parameters.groupByParameter = this.ProcessGroupByParameter (); + parameters.groupByParameter = this.ProcessGroupByParameter(); parameters.forceFormattingAlsoOnOutOfBand = this.Force; if (this.showErrorsAsMessages.HasValue) parameters.showErrorsAsMessages = this.showErrorsAsMessages; if (this.showErrorsInFormattedOutput.HasValue) parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput; - parameters.expansion = ProcessExpandParameter (); + parameters.expansion = ProcessExpandParameter(); - if (this.autosize.HasValue) - parameters.autosize = this.autosize.Value; + if (_autosize.HasValue) + parameters.autosize = _autosize.Value; - WideSpecificParameters wideSpecific = new WideSpecificParameters (); + WideSpecificParameters wideSpecific = new WideSpecificParameters(); parameters.shapeParameters = wideSpecific; - if (this.column.HasValue) + if (_column.HasValue) { - wideSpecific.columns = this.column.Value; + wideSpecific.columns = _column.Value; } return parameters; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index d1a07d7b0..1010065bf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -10,10 +10,10 @@ using System.IO; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands -{ +{ internal static class InputFileOpenModeConversion { - internal static FileMode Convert (OpenMode openMode) + internal static FileMode Convert(OpenMode openMode) { return SessionStateUtilities.GetFileModeFromOpenMode(openMode); } @@ -28,9 +28,9 @@ namespace Microsoft.PowerShell.Commands /// /// set inner command /// - public OutFileCommand () + public OutFileCommand() { - this.implementation = new OutputManagerInner (); + this.implementation = new OutputManagerInner(); } #region Command Line Parameters @@ -38,14 +38,14 @@ namespace Microsoft.PowerShell.Commands /// /// mandatory file name to write to /// - [Parameter(Mandatory=true, Position=0, ParameterSetName = "ByPath")] + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] public string FilePath { - get{ return fileName;} - set{ fileName = value;} + get { return _fileName; } + set { _fileName = value; } } - private string fileName; + private string _fileName; /// /// mandatory file name to write to @@ -56,21 +56,21 @@ namespace Microsoft.PowerShell.Commands { get { - return fileName; + return _fileName; } set { - fileName = value; - isLiteralPath = true; + _fileName = value; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Encoding optional flag /// /// - [Parameter(Position=1)] + [Parameter(Position = 1)] [ValidateNotNullOrEmpty] [ValidateSetAttribute(new string[] { EncodingConversion.Unknown, @@ -85,11 +85,11 @@ namespace Microsoft.PowerShell.Commands EncodingConversion.OEM })] public string Encoding { - get{ return encoding;} - set{ encoding = value;} + get { return _encoding; } + set { _encoding = value; } } - private string encoding; + private string _encoding; /// /// Property that sets append parameter. @@ -97,10 +97,10 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter Append { - get { return append; } - set { append = value; } + get { return _append; } + set { _append = value; } } - private bool append; + private bool _append; /// /// Property that sets force parameter. @@ -108,10 +108,10 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter Force { - get { return force; } - set { force = value; } + get { return _force; } + set { _force = value; } } - private bool force; + private bool _force; /// /// Property that prevents file overwrite. @@ -120,23 +120,23 @@ namespace Microsoft.PowerShell.Commands [Alias("NoOverwrite")] public SwitchParameter NoClobber { - get { return noclobber; } - set { noclobber = value; } + get { return _noclobber; } + set { _noclobber = value; } } - private bool noclobber; + private bool _noclobber; /// /// optional, number of columns to use when writing to device /// - [ValidateRangeAttribute(2,int.MaxValue)] + [ValidateRangeAttribute(2, int.MaxValue)] [Parameter] public int Width { - get { return (width != null) ? width.Value : 0; } - set { width = value; } + get { return (_width != null) ? _width.Value : 0; } + set { _width = value; } } - private Nullable width = null; + private Nullable _width = null; /// /// False to add a newline to the end of the output string, true if not. @@ -146,15 +146,15 @@ namespace Microsoft.PowerShell.Commands { get { - return suppressNewline; + return _suppressNewline; } set { - suppressNewline = value; + _suppressNewline = value; } } - private bool suppressNewline = false; + private bool _suppressNewline = false; #endregion @@ -168,18 +168,18 @@ namespace Microsoft.PowerShell.Commands // NOTICE: if any exception is thrown from here to the end of the method, the // cleanup code will be called in IDisposable.Dispose() - outInner.LineOutput = InstantiateLineOutputInterface (); + outInner.LineOutput = InstantiateLineOutputInterface(); - if (null == sw) + if (null == _sw) { return; } // finally call the base class for general hookup - base.BeginProcessing (); + base.BeginProcessing(); } - + /// /// one time initialization: acquire a screen host interface /// by creating one on top of a file @@ -187,23 +187,23 @@ namespace Microsoft.PowerShell.Commands /// available in the CRO. JonN recommends: file name has to be /// a MANDATORY parameter on the command line /// - private LineOutput InstantiateLineOutputInterface () + private LineOutput InstantiateLineOutputInterface() { string action = StringUtil.Format(FormatAndOut_out_xxx.OutFile_Action); - if(ShouldProcess(FilePath, action)) + if (ShouldProcess(FilePath, action)) { PathUtils.MasterStreamOpen( this, FilePath, - encoding, + _encoding, false, // defaultEncoding Append, Force, NoClobber, - out fs, - out sw, - out readOnlyFileInfo, - isLiteralPath + out _fs, + out _sw, + out _readOnlyFileInfo, + _isLiteralPath ); } else @@ -212,10 +212,10 @@ namespace Microsoft.PowerShell.Commands // compute the # of columns available int computedWidth = 120; - if (this.width != null) + if (_width != null) { // use the value from the command line - computedWidth = this.width.Value; + computedWidth = _width.Value; } else { @@ -238,11 +238,10 @@ namespace Microsoft.PowerShell.Commands } // use the stream writer to create and initialize the Line Output writer - TextWriterLineOutput twlo = new TextWriterLineOutput (sw, computedWidth, suppressNewline); + TextWriterLineOutput twlo = new TextWriterLineOutput(_sw, computedWidth, _suppressNewline); // finally have the ILineOutput interface extracted return (LineOutput)twlo; - } /// @@ -250,16 +249,16 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - processRecordExecuted = true; - if (null == sw) + _processRecordExecuted = true; + if (null == _sw) { return; } // NOTICE: if any exception is thrown, the // cleanup code will be called in IDisposable.Dispose() - base.ProcessRecord (); - sw.Flush (); + base.ProcessRecord(); + _sw.Flush(); } /// @@ -273,23 +272,23 @@ namespace Microsoft.PowerShell.Commands // Write-Error error > test.txt // In this case, the EndProcess method should return immediately as if it's // never been called. The cleanup work will be done in IDisposable.Dispose() - if (!processRecordExecuted) + if (!_processRecordExecuted) { return; } - if (null == sw) + if (null == _sw) { return; } // NOTICE: if any exception is thrown, the // cleanup code will be called in IDisposable.Dispose() - base.EndProcessing (); - - sw.Flush (); + base.EndProcessing(); - CleanUp (); + _sw.Flush(); + + CleanUp(); } /// @@ -297,36 +296,35 @@ namespace Microsoft.PowerShell.Commands /// protected override void InternalDispose() { - base.InternalDispose (); - CleanUp (); - + base.InternalDispose(); + CleanUp(); } - private void CleanUp () + private void CleanUp() { - if (this.fs != null) + if (_fs != null) { - this.fs.Dispose(); - this.fs = null; + _fs.Dispose(); + _fs = null; } // reset the read-only attribute - if (null != readOnlyFileInfo) + if (null != _readOnlyFileInfo) { - readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; - this.readOnlyFileInfo = null; + _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + _readOnlyFileInfo = null; } } /// /// handle to file stream /// - FileStream fs; + private FileStream _fs; /// /// stream writer used to write to file /// - private StreamWriter sw = null; + private StreamWriter _sw = null; /// /// indicate whether the ProcessRecord method was executed. @@ -337,12 +335,12 @@ namespace Microsoft.PowerShell.Commands /// In this case, the EndProcess method should return immediately as if it's /// never been called. /// - private bool processRecordExecuted = false; + private bool _processRecordExecuted = false; /// /// FileInfo of file to clear read-only flag when operation is complete /// - private FileInfo readOnlyFileInfo = null; + private FileInfo _readOnlyFileInfo = null; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 018f907f9..9f75b849e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.IO; using System.Text; @@ -15,7 +16,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class PrinterLineOutput : LineOutput { - #region LineOutput implementation /// @@ -26,10 +26,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// do the printing on playback /// - internal override void ExecuteBufferPlayBack (DoPlayBackCall playback) + internal override void ExecuteBufferPlayBack(DoPlayBackCall playback) { - this.playbackCall = playback; - DoPrint (); + _playbackCall = playback; + DoPrint(); } /// @@ -41,7 +41,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format get { CheckStopProcessing(); - return this.deviceColumns; + return _deviceColumns; } } @@ -54,7 +54,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format get { CheckStopProcessing(); - return this.deviceRows; + return _deviceRows; } } @@ -62,13 +62,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// write a line to the output device /// /// line to write - internal override void WriteLine (string s) + internal override void WriteLine(string s) { CheckStopProcessing(); // delegate the action to the helper, // that will properly break the string into // screen lines - this.writeLineHelper.WriteLine (s, this.ColumnNumber); + _writeLineHelper.WriteLine(s, this.ColumnNumber); } #endregion @@ -80,31 +80,31 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // This default must be loaded from a resource file as different // cultures will have different defaults and the localizer would // know the default for different cultures. - DefaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName; + s_defaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName; } /// /// constructor for the class /// /// name of printer, if null use default printer - internal PrinterLineOutput (string printerName) + internal PrinterLineOutput(string printerName) { - this.printerName = printerName; + _printerName = printerName; // instantiate the helper to do the line processing when LineOutput.WriteXXX() is called - WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback (this.OnWriteLine); - WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback (this.OnWrite); + WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine); + WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite); - this.writeLineHelper = new WriteLineHelper (true, wl, w, this.DisplayCells); + _writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells); } /// /// callback to be called when IConsole.WriteLine() is called by WriteLineHelper /// /// string to write - private void OnWriteLine (string s) + private void OnWriteLine(string s) { - this.lines.Enqueue (s); + _lines.Enqueue(s); } /// @@ -113,39 +113,39 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// is the same as the width of the screen buffer /// /// string to write - private void OnWrite (string s) + private void OnWrite(string s) { - this.lines.Enqueue (s); + _lines.Enqueue(s); } /// /// do the printing /// - private void DoPrint () + private void DoPrint() { try { // create a new print document object and set the printer name, if available - PrintDocument pd = new PrintDocument (); + PrintDocument pd = new PrintDocument(); - if (!string.IsNullOrEmpty (this.printerName)) + if (!string.IsNullOrEmpty(_printerName)) { - pd.PrinterSettings.PrinterName = this.printerName; + pd.PrinterSettings.PrinterName = _printerName; } // set up the callaback mechanism - pd.PrintPage += new PrintPageEventHandler (this.pd_PrintPage); + pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); // start printing - pd.Print (); + pd.Print(); } finally { // make sure we do not leak the font - if (this.printFont != null) + if (_printFont != null) { - this.printFont.Dispose (); - this.printFont = null; + _printFont.Dispose(); + _printFont = null; } } } @@ -156,26 +156,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// Else, the a new object is created and verified /// /// GDI+ graphics object needed for verification - private void CreateFont (Graphics g) + private void CreateFont(Graphics g) { - if (this.printFont != null) + if (_printFont != null) return; // create the font - + // do we have a specified font? - if (string.IsNullOrEmpty (this.printFontName)) + if (string.IsNullOrEmpty(_printFontName)) { - this.printFontName = DefaultPrintFontName; + _printFontName = s_defaultPrintFontName; } - if (this.printFontSize <= 0) + if (_printFontSize <= 0) { - this.printFontSize = DefaultPrintFontSize; + _printFontSize = DefaultPrintFontSize; } - this.printFont = new Font (this.printFontName, this.printFontSize); - VerifyFont (g); + _printFont = new Font(_printFontName, _printFontSize); + VerifyFont(g); } /// @@ -183,7 +183,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// it reverts to the default font /// /// GDI+ graphics object needed for verification - private void VerifyFont (Graphics g) + private void VerifyFont(Graphics g) { // check if the font is fixed pitch // HEURISTICS: @@ -191,9 +191,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // one made of "narrow" ones. If they are the same length, we assume that // the font is fixed pitch. string large = "ABCDEF"; - float wLarge = g.MeasureString (large, this.printFont).Width / large.Length; + float wLarge = g.MeasureString(large, _printFont).Width / large.Length; string narrow = ".;'}l|"; - float wNarrow = g.MeasureString (narrow, this.printFont).Width / narrow.Length; + float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length; if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F) { @@ -202,8 +202,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // just get back to the default, since it's not fixed pitch - this.printFont.Dispose (); - this.printFont = new Font (DefaultPrintFontName, DefaultPrintFontSize); + _printFont.Dispose(); + _printFont = new Font(s_defaultPrintFontName, DefaultPrintFontSize); } /// @@ -211,86 +211,86 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// sender, not used /// print page event - private void pd_PrintPage (object sender, PrintPageEventArgs ev) + private void pd_PrintPage(object sender, PrintPageEventArgs ev) { float yPos = 0; // GDI+ coordinate down the page int linesPrinted = 0; // linesPrinted float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; - CreateFont (ev.Graphics); + CreateFont(ev.Graphics); // compute the height of a line of text - float lineHeight = this.printFont.GetHeight (ev.Graphics); + float lineHeight = _printFont.GetHeight(ev.Graphics); // Work out the number of lines per page // Use the MarginBounds on the event to do this - float linesPerPage = ev.MarginBounds.Height / this.printFont.GetHeight (ev.Graphics); + float linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics); - if (!this.printingInitalized) + if (!_printingInitalized) { // on the first page we have to initialize the metrics for LineOutput // work out the number of columns per page assuming fixed pitch font string s = "ABCDEF"; - float w = ev.Graphics.MeasureString (s, printFont).Width / s.Length; + float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length; float columnsPerPage = ev.MarginBounds.Width / w; - this.printingInitalized = true; - this.deviceRows = (int)linesPerPage; - this.deviceColumns = (int)columnsPerPage; + _printingInitalized = true; + _deviceRows = (int)linesPerPage; + _deviceColumns = (int)columnsPerPage; // now that we initialized the column and row count for the LineOutput // interface we can tell the outputter to playback from cache to do the // proper computations of line widths // returning from this call, the string queue on this object is full of // lines of text to print - this.playbackCall (); + _playbackCall(); } // now iterate over the file printing out each line - while ((linesPrinted < linesPerPage) && (this.lines.Count > 0)) + while ((linesPrinted < linesPerPage) && (_lines.Count > 0)) { // get the string to be printed - String line = this.lines.Dequeue (); + String line = _lines.Dequeue(); // compute the Y position where to draw yPos = topMargin + (linesPrinted * lineHeight); // do the actual drawing - ev.Graphics.DrawString (line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat ()); + ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); linesPrinted++; } //If we have more lines then print another page - ev.HasMorePages = this.lines.Count > 0; + ev.HasMorePages = _lines.Count > 0; } - + /// /// flag for one time initialization of the interface (columns, etc.) /// - private bool printingInitalized = false; + private bool _printingInitalized = false; /// /// callback to ask the outputter to playback its cache /// - private DoPlayBackCall playbackCall; + private DoPlayBackCall _playbackCall; /// /// name of the printer to print to. Null means default printer /// - private string printerName = null; + private string _printerName = null; /// /// name of the font to use, if null the default is used /// - private string printFontName = null; + private string _printFontName = null; /// /// font size /// - private int printFontSize = 0; + private int _printFontSize = 0; /// @@ -302,32 +302,31 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// cultures will have different defaults and the localizer would /// know the default for different cultures. /// - private static readonly string DefaultPrintFontName; + private static readonly string s_defaultPrintFontName; /// /// default size for the default font /// - const int DefaultPrintFontSize = 8; + private const int DefaultPrintFontSize = 8; /// /// number of columns on the sheet /// - private int deviceColumns = 80; - + private int _deviceColumns = 80; + // number of rows per sheet - private int deviceRows = 40; + private int _deviceRows = 40; /// /// text lines ready to print (after output cache playback) /// - private Queue lines = new Queue (); + private Queue _lines = new Queue(); /// /// cached font object /// - private Font printFont = null; - - private WriteLineHelper writeLineHelper; - } + private Font _printFont = null; + private WriteLineHelper _writeLineHelper; + } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs index 11c537537..6edd7a7a2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/out-printer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; @@ -16,56 +17,55 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { - - /// + /// /// implementation for the out-printer command /// - [Cmdlet ("Out", "Printer", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113367")] + [Cmdlet("Out", "Printer", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113367")] public class OutPrinterCommand : FrontEndCommandBase { /// /// set inner command /// - public OutPrinterCommand () + public OutPrinterCommand() { - this.implementation = new OutputManagerInner (); + this.implementation = new OutputManagerInner(); } /// /// optional name of the printer to print to /// The alias allows "lp -P printer" /// - [Parameter(Position=0)] + [Parameter(Position = 0)] [Alias("PrinterName")] public string Name { - get { return printerName; } - set { printerName = value; } + get { return _printerName; } + set { _printerName = value; } } - private string printerName; + private string _printerName; /// /// read command line parameters /// - protected override void BeginProcessing () + protected override void BeginProcessing() { // set up the Scree Host interface OutputManagerInner outInner = (OutputManagerInner)this.implementation; - outInner.LineOutput = InstantiateLineOutputInterface (); + outInner.LineOutput = InstantiateLineOutputInterface(); // finally call the base class for general hookup - base.BeginProcessing (); + base.BeginProcessing(); } /// /// one time initialization: acquire a screen host interface /// by creating one on top of a memory buffer /// - private LineOutput InstantiateLineOutputInterface () + private LineOutput InstantiateLineOutputInterface() { - PrinterLineOutput printOutput = new PrinterLineOutput (this.printerName); + PrinterLineOutput printOutput = new PrinterLineOutput(_printerName); return (LineOutput)printOutput; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs index b2616acc8..5cc53c029 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/out-string.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text; using System.Management.Automation; @@ -9,8 +10,6 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { - - /// /// implementation for the out-string command /// @@ -18,8 +17,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(string))] public class OutStringCommand : FrontEndCommandBase { - -#region Command Line Parameters + #region Command Line Parameters /// /// optional, non positional parameter to specify the /// streaming behavior @@ -29,66 +27,66 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Stream { - get { return stream; } - set { stream = value; } + get { return _stream; } + set { _stream = value; } } - private bool stream; + private bool _stream; /// /// optional, number of columns to use when writing to device /// - [ValidateRangeAttribute (2, int.MaxValue)] + [ValidateRangeAttribute(2, int.MaxValue)] [Parameter] public int Width { - get { return (width != null) ? width.Value : 0; } - set { width = value; } + get { return (_width != null) ? _width.Value : 0; } + set { _width = value; } } - private Nullable width = null; -#endregion + private Nullable _width = null; + #endregion /// /// set inner command /// - public OutStringCommand () + public OutStringCommand() { - this.implementation = new OutputManagerInner (); + this.implementation = new OutputManagerInner(); } /// /// read command line parameters /// - protected override void BeginProcessing () + protected override void BeginProcessing() { // set up the LineOutput interface OutputManagerInner outInner = (OutputManagerInner)this.implementation; - outInner.LineOutput = InstantiateLineOutputInterface (); + outInner.LineOutput = InstantiateLineOutputInterface(); // finally call the base class for general hookup - base.BeginProcessing (); + base.BeginProcessing(); } /// /// one time initialization: acquire a screen host interface /// by creating one on top of a stream /// - private LineOutput InstantiateLineOutputInterface () + private LineOutput InstantiateLineOutputInterface() { // set up the streaming text writer - StreamingTextWriter.WriteLineCallback callback = new StreamingTextWriter.WriteLineCallback (this.OnWriteLine); + StreamingTextWriter.WriteLineCallback callback = new StreamingTextWriter.WriteLineCallback(this.OnWriteLine); - this.writer = new StreamingTextWriter (callback, Host.CurrentCulture); + _writer = new StreamingTextWriter(callback, Host.CurrentCulture); // compute the # of columns available int computedWidth = 120; - if (this.width != null) + if (_width != null) { // use the value from the command line - computedWidth = this.width.Value; + computedWidth = _width.Value; } else { @@ -110,7 +108,7 @@ namespace Microsoft.PowerShell.Commands } // use it to create and initialize the Line Output writer - TextWriterLineOutput twlo = new TextWriterLineOutput (this.writer, computedWidth); + TextWriterLineOutput twlo = new TextWriterLineOutput(_writer, computedWidth); // finally have the LineOutput interface extracted return (LineOutput)twlo; @@ -121,48 +119,47 @@ namespace Microsoft.PowerShell.Commands /// the output stream /// /// - private void OnWriteLine (string s) + private void OnWriteLine(string s) { - if (this.stream) - this.WriteObject (s); + if (_stream) + this.WriteObject(s); else - this.buffer.AppendLine (s); + _buffer.AppendLine(s); } /// /// execution entry point /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - base.ProcessRecord (); - this.writer.Flush (); + base.ProcessRecord(); + _writer.Flush(); } /// /// execution entry point /// - protected override void EndProcessing () + protected override void EndProcessing() { - base.EndProcessing (); + base.EndProcessing(); //close the writer - this.writer.Flush (); - this.writer.Dispose(); - - if (!this.stream) - this.WriteObject (this.buffer.ToString ()); + _writer.Flush(); + _writer.Dispose(); + + if (!_stream) + this.WriteObject(_buffer.ToString()); } /// /// writer used by the LineOutput /// - private StreamingTextWriter writer = null; + private StreamingTextWriter _writer = null; /// /// buffer used when buffering until the end /// - private StringBuilder buffer = new StringBuilder (); - + private StringBuilder _buffer = new StringBuilder(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index 947f742a9..e6511e56c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.Management.Automation; @@ -76,7 +77,7 @@ namespace Microsoft.PowerShell.Commands /// /// Variables of the breakpoints to output /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification="It's OK to use arrays for cmdlet parameters")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's OK to use arrays for cmdlet parameters")] [Parameter(ParameterSetName = "Variable", Mandatory = true)] [ValidateNotNull] public string[] Variable @@ -152,9 +153,9 @@ namespace Microsoft.PowerShell.Commands breakpoints = Filter( breakpoints, _id, - delegate(Breakpoint breakpoint, int id) + delegate (Breakpoint breakpoint, int id) { - return breakpoint.Id == id; + return breakpoint.Id == id; } ); } @@ -163,7 +164,7 @@ namespace Microsoft.PowerShell.Commands breakpoints = Filter( breakpoints, _command, - delegate(Breakpoint breakpoint, string command) + delegate (Breakpoint breakpoint, string command) { CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint; @@ -180,7 +181,7 @@ namespace Microsoft.PowerShell.Commands breakpoints = Filter( breakpoints, _variable, - delegate(Breakpoint breakpoint, string variable) + delegate (Breakpoint breakpoint, string variable) { VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint; @@ -197,7 +198,7 @@ namespace Microsoft.PowerShell.Commands breakpoints = Filter( breakpoints, _type, - delegate(Breakpoint breakpoint, BreakpointType type) + delegate (Breakpoint breakpoint, BreakpointType type) { switch (type) { @@ -239,7 +240,7 @@ namespace Microsoft.PowerShell.Commands breakpoints = Filter( breakpoints, _script, - delegate(Breakpoint breakpoint, string script) + delegate (Breakpoint breakpoint, string script) { if (breakpoint.Script == null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index bd65665c2..ab2f292b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -29,21 +30,21 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { if (value == null) { - names = new string[] { "*" }; + _names = new string[] { "*" }; } else { - names = value; + _names = value; } } } - private string[] names = new string[] { "*" }; + private string[] _names = new string[] { "*" }; /// /// The Exclude parameter for the command @@ -54,21 +55,21 @@ namespace Microsoft.PowerShell.Commands { get { - return excludes; + return _excludes; } set { if (value == null) { - excludes = new string[0]; + _excludes = new string[0]; } else { - excludes = value; + _excludes = value; } } } - private string[] excludes = new string[0]; + private string[] _excludes = new string[0]; /// /// The scope parameter for the command determines @@ -80,15 +81,15 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } set { - scope = value; + _scope = value; } } - private string scope; + private string _scope; /// /// Parameter definition to retrieve aliases based on their definitions. @@ -123,7 +124,7 @@ namespace Microsoft.PowerShell.Commands } else { - foreach (string aliasName in names) + foreach (string aliasName in _names) { WriteMatches(aliasName, "Default"); } @@ -133,20 +134,19 @@ namespace Microsoft.PowerShell.Commands private void WriteMatches(string value, string parametersetname) { - // First get the alias table (from the proper scope if necessary) IDictionary aliasTable = null; //get the command origin CommandOrigin origin = MyInvocation.CommandOrigin; string displayString = "name"; - if (!String.IsNullOrEmpty(scope)) + if (!String.IsNullOrEmpty(_scope)) { // This can throw PSArgumentException and PSArgumentOutOfRangeException // but just let them go as this is terminal for the pipeline and the // exceptions are already properly adorned with an ErrorRecord. - aliasTable = SessionState.Internal.GetAliasTableAtScope(scope); + aliasTable = SessionState.Internal.GetAliasTableAtScope(_scope); } else { @@ -162,7 +162,7 @@ namespace Microsoft.PowerShell.Commands // exlucing patter for Default paramset. Collection excludePatterns = SessionStateUtilities.CreateWildcardsFromStrings( - excludes, + _excludes, WildcardOptions.IgnoreCase); List results = new List(); @@ -179,7 +179,6 @@ namespace Microsoft.PowerShell.Commands { continue; } - } else { @@ -192,7 +191,6 @@ namespace Microsoft.PowerShell.Commands { continue; } - } if (ContainsWildcard) { @@ -225,11 +223,10 @@ namespace Microsoft.PowerShell.Commands continue; } } - } results.Sort( - delegate(AliasInfo left, AliasInfo right) + delegate (AliasInfo left, AliasInfo right) { return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name); }); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs index 4e904565a..bf7ccaaae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands /// /// Returns the thread's current culture. /// - [Cmdlet( VerbsCommon.Get, "Culture", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113312")] + [Cmdlet(VerbsCommon.Get, "Culture", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113312")] [OutputType(typeof(System.Globalization.CultureInfo))] public sealed class GetCultureCommand : PSCmdlet { @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - WriteObject( Host.CurrentCulture ); + WriteObject(Host.CurrentCulture); } // EndProcessing } // GetCultureCommand } // Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 77a68d2e7..acd5699d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Globalization; using System.Text; @@ -14,7 +15,7 @@ namespace Microsoft.PowerShell.Commands /// /// implementation for the get-date command /// - [Cmdlet( VerbsCommon.Get, "Date", DefaultParameterSetName = "net", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113313" )] + [Cmdlet(VerbsCommon.Get, "Date", DefaultParameterSetName = "net", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113313")] [OutputType(typeof(string), ParameterSetName = new string[] { "UFormat", "net" })] [OutputType(typeof(DateTime), ParameterSetName = new string[] { "net" })] public sealed class GetDateCommand : Cmdlet @@ -30,162 +31,162 @@ namespace Microsoft.PowerShell.Commands { get { - return date; + return _date; } set { - date = value; - dateSpecified = true; + _date = value; + _dateSpecified = true; } } - private DateTime date; - private bool dateSpecified; + private DateTime _date; + private bool _dateSpecified; /// /// Allows the user to override the year /// [Parameter] - [ValidateRangeAttribute( 1, 9999 )] + [ValidateRangeAttribute(1, 9999)] public int Year { get { - return year; + return _year; } set { - year = value; - yearSpecified = true; + _year = value; + _yearSpecified = true; } } - private int year; - private bool yearSpecified; + private int _year; + private bool _yearSpecified; /// /// Allows the user to override the month /// [Parameter] - [ValidateRangeAttribute( 1, 12 )] + [ValidateRangeAttribute(1, 12)] public int Month { get { - return month; + return _month; } set { - month = value; - monthSpecified = true; + _month = value; + _monthSpecified = true; } } - private int month; - private bool monthSpecified; + private int _month; + private bool _monthSpecified; /// /// Allows the user to override the day /// [Parameter] - [ValidateRangeAttribute( 1, 31 )] + [ValidateRangeAttribute(1, 31)] public int Day { get { - return day; + return _day; } set { - day = value; - daySpecified = true; + _day = value; + _daySpecified = true; } } - private int day; - private bool daySpecified; + private int _day; + private bool _daySpecified; /// /// Allows the user to override the hour /// [Parameter] - [ValidateRangeAttribute( 0, 23 )] + [ValidateRangeAttribute(0, 23)] public int Hour { get { - return hour; + return _hour; } set { - hour = value; - hourSpecified = true; + _hour = value; + _hourSpecified = true; } } - private int hour; - private bool hourSpecified; + private int _hour; + private bool _hourSpecified; /// /// Allows the user to override the minute /// [Parameter] - [ValidateRangeAttribute( 0, 59 )] + [ValidateRangeAttribute(0, 59)] public int Minute { get { - return minute; + return _minute; } set { - minute = value; - minuteSpecified = true; + _minute = value; + _minuteSpecified = true; } } - private int minute; - private bool minuteSpecified; + private int _minute; + private bool _minuteSpecified; /// /// Allows the user to override the second /// [Parameter] - [ValidateRangeAttribute( 0, 59 )] + [ValidateRangeAttribute(0, 59)] public int Second { get { - return second; + return _second; } set { - second = value; - secondSpecified = true; + _second = value; + _secondSpecified = true; } } - private int second; - private bool secondSpecified; + private int _second; + private bool _secondSpecified; /// /// Allows the user to override the millisecond /// [Parameter] - [ValidateRangeAttribute( 0, 999 )] + [ValidateRangeAttribute(0, 999)] public int Millisecond { get { - return millisecond; + return _millisecond; } set { - millisecond = value; - millisecondSpecified = true; + _millisecond = value; + _millisecondSpecified = true; } } - private int millisecond; - private bool millisecondSpecified; + private int _millisecond; + private bool _millisecondSpecified; /// /// This option determines the default output format used to display the object get-date emits @@ -195,50 +196,50 @@ namespace Microsoft.PowerShell.Commands { get { - return displayHint; + return _displayHint; } set { - displayHint = value; + _displayHint = value; } } - private DisplayHintType displayHint = DisplayHintType.DateTime; + private DisplayHintType _displayHint = DisplayHintType.DateTime; /// /// Unix format string /// - [Parameter( ParameterSetName = "UFormat" )] + [Parameter(ParameterSetName = "UFormat")] public string UFormat { get { - return uFormat; + return _uFormat; } set { - uFormat = value; + _uFormat = value; } } - private string uFormat; + private string _uFormat; /// /// Unix format string /// - [Parameter( ParameterSetName = "net" )] + [Parameter(ParameterSetName = "net")] public string Format { get { - return format; + return _format; } set { - format = value; + _format = value; } } - private string format; + private string _format; #endregion @@ -253,67 +254,67 @@ namespace Microsoft.PowerShell.Commands int offset; // use passed date object if specified - if ( dateSpecified ) + if (_dateSpecified) { dateToUse = Date; } //use passed year if specified - if ( yearSpecified ) + if (_yearSpecified) { offset = Year - dateToUse.Year; - dateToUse = dateToUse.AddYears( offset ); + dateToUse = dateToUse.AddYears(offset); } //use passed month if specified - if ( monthSpecified ) + if (_monthSpecified) { offset = Month - dateToUse.Month; - dateToUse = dateToUse.AddMonths( offset ); + dateToUse = dateToUse.AddMonths(offset); } //use passed day if specified - if ( daySpecified ) + if (_daySpecified) { offset = Day - dateToUse.Day; - dateToUse = dateToUse.AddDays( offset ); + dateToUse = dateToUse.AddDays(offset); } //use passed hour if specified - if ( hourSpecified ) + if (_hourSpecified) { offset = Hour - dateToUse.Hour; - dateToUse = dateToUse.AddHours( offset ); + dateToUse = dateToUse.AddHours(offset); } //use passed minute if specified - if ( minuteSpecified ) + if (_minuteSpecified) { offset = Minute - dateToUse.Minute; - dateToUse = dateToUse.AddMinutes( offset ); + dateToUse = dateToUse.AddMinutes(offset); } //use passed second if specified - if ( secondSpecified ) + if (_secondSpecified) { offset = Second - dateToUse.Second; - dateToUse = dateToUse.AddSeconds( offset ); + dateToUse = dateToUse.AddSeconds(offset); } //use passed millisecond if specified - if ( millisecondSpecified ) + if (_millisecondSpecified) { offset = Millisecond - dateToUse.Millisecond; dateToUse = dateToUse.AddMilliseconds(offset); dateToUse = dateToUse.Subtract(TimeSpan.FromTicks(dateToUse.Ticks % 10000)); } - if ( UFormat != null ) + if (UFormat != null) { //format according to UFormat string - WriteObject( UFormatDateString( dateToUse ) ); + WriteObject(UFormatDateString(dateToUse)); } - else if ( Format != null ) + else if (Format != null) { //format according to Format string @@ -340,16 +341,16 @@ namespace Microsoft.PowerShell.Commands Format = "yyyyMMddTHHmmssffffZ"; } - WriteObject( dateToUse.ToString( Format, CultureInfo.CurrentCulture ) ); + WriteObject(dateToUse.ToString(Format, CultureInfo.CurrentCulture)); } else { //output DateTime object wrapped in an PSObject with DisplayHint attached - PSObject outputObj = new PSObject( dateToUse ); - PSNoteProperty note = new PSNoteProperty( "DisplayHint", DisplayHint ); - outputObj.Properties.Add( note ); + PSObject outputObj = new PSObject(dateToUse); + PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); + outputObj.Properties.Add(note); - WriteObject( outputObj ); + WriteObject(outputObj); } } // EndProcessing @@ -357,43 +358,43 @@ namespace Microsoft.PowerShell.Commands /// /// This is more an implementation of the UNIX strftime /// - private string UFormatDateString( DateTime dateTime ) + private string UFormatDateString(DateTime dateTime) { - DateTime epoch = DateTime.Parse("January 1, 1970", System.Globalization.CultureInfo.InvariantCulture); + DateTime epoch = DateTime.Parse("January 1, 1970", System.Globalization.CultureInfo.InvariantCulture); int offset = 0; StringBuilder sb = new StringBuilder(); // folks may include the "+" as part of the format string - if ( UFormat[0] == '+' ) + if (UFormat[0] == '+') { offset++; } - for ( int i = offset; i < UFormat.Length; i++ ) + for (int i = offset; i < UFormat.Length; i++) { - if ( UFormat[i] == '%' ) + if (UFormat[i] == '%') { i++; - switch ( UFormat[i] ) + switch (UFormat[i]) { case 'A': - sb.Append( "{0:dddd}" ); + sb.Append("{0:dddd}"); break; case 'a': - sb.Append( "{0:ddd}" ); + sb.Append("{0:ddd}"); break; case 'B': - sb.Append( "{0:MMMM}" ); + sb.Append("{0:MMMM}"); break; case 'b': - sb.Append( "{0:MMM}" ); + sb.Append("{0:MMM}"); break; case 'h': - sb.Append( "{0:MMM}" ); + sb.Append("{0:MMM}"); break; case 'C': @@ -401,145 +402,144 @@ namespace Microsoft.PowerShell.Commands break; case 'c': - sb.Append( "{0:ddd} {0:MMM} " ); - sb.Append( StringUtil.Format( "{0,2} ", dateTime.Day ) ); - sb.Append( "{0:HH}:{0:mm}:{0:ss} {0:yyyy}" ); + sb.Append("{0:ddd} {0:MMM} "); + sb.Append(StringUtil.Format("{0,2} ", dateTime.Day)); + sb.Append("{0:HH}:{0:mm}:{0:ss} {0:yyyy}"); break; case 'D': - sb.Append( "{0:MM/dd/yy}" ); + sb.Append("{0:MM/dd/yy}"); break; case 'd': - sb.Append( "{0:dd}" ); + sb.Append("{0:dd}"); break; case 'e': - sb.Append( StringUtil.Format( "{0,2}", dateTime.Day ) ); + sb.Append(StringUtil.Format("{0,2}", dateTime.Day)); break; case 'H': - sb.Append( "{0:HH}" ); + sb.Append("{0:HH}"); break; case 'I': - sb.Append( "{0:hh}" ); + sb.Append("{0:hh}"); break; case 'j': - sb.Append( dateTime.DayOfYear ); + sb.Append(dateTime.DayOfYear); break; case 'k': - sb.Append( "{0:HH}" ); + sb.Append("{0:HH}"); break; case 'l': - sb.Append( "{0:hh}" ); + sb.Append("{0:hh}"); break; case 'M': - sb.Append( "{0:mm}" ); + sb.Append("{0:mm}"); break; case 'm': - sb.Append( "{0:MM}" ); + sb.Append("{0:MM}"); break; case 'n': - sb.Append( "\n" ); + sb.Append("\n"); break; case 'p': - sb.Append( "{0:tt}" ); + sb.Append("{0:tt}"); break; case 'R': - sb.Append( "{0:HH:mm}" ); + sb.Append("{0:HH:mm}"); break; case 'r': - sb.Append( "{0:hh:mm:ss tt}" ); + sb.Append("{0:hh:mm:ss tt}"); break; case 'S': - sb.Append( "{0:ss}" ); + sb.Append("{0:ss}"); break; case 's': - sb.Append(dateTime.Subtract( epoch ).TotalSeconds ); + sb.Append(dateTime.Subtract(epoch).TotalSeconds); break; case 'T': - sb.Append( "{0:HH:mm:ss}" ); + sb.Append("{0:HH:mm:ss}"); break; case 'X': - sb.Append( "{0:HH:mm:ss}" ); + sb.Append("{0:HH:mm:ss}"); break; case 't': - sb.Append( "\t" ); + sb.Append("\t"); break; case 'u': - sb.Append( (int) dateTime.DayOfWeek ); + sb.Append((int)dateTime.DayOfWeek); break; case 'U': - sb.Append( dateTime.DayOfYear / 7 ); + sb.Append(dateTime.DayOfYear / 7); break; case 'V': - sb.Append( ( dateTime.DayOfYear / 7 ) + 1 ); + sb.Append((dateTime.DayOfYear / 7) + 1); break; case 'G': - sb.Append( "{0:yyyy}" ); + sb.Append("{0:yyyy}"); break; case 'g': - sb.Append( "{0:yy}" ); + sb.Append("{0:yy}"); break; case 'W': - sb.Append( dateTime.DayOfYear / 7 ); + sb.Append(dateTime.DayOfYear / 7); break; case 'w': - sb.Append( (int) dateTime.DayOfWeek ); + sb.Append((int)dateTime.DayOfWeek); break; case 'x': - sb.Append( "{0:MM/dd/yy}" ); + sb.Append("{0:MM/dd/yy}"); break; case 'y': - sb.Append( "{0:yy}" ); + sb.Append("{0:yy}"); break; case 'Y': - sb.Append( "{0:yyyy}" ); + sb.Append("{0:yyyy}"); break; case 'Z': - sb.Append( "{0:zz}" ); + sb.Append("{0:zz}"); break; default: - sb.Append( UFormat[i] ); + sb.Append(UFormat[i]); break; - } } else { // It's not a known format specifier, so just append it - sb.Append( UFormat[i] ); + sb.Append(UFormat[i]); } } - return StringUtil.Format( sb.ToString(), dateTime ); + return StringUtil.Format(sb.ToString(), dateTime); } // UFormatDateString #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index 8995ab0ba..bf84b6833 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.Management.Automation; @@ -24,19 +25,19 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; - if(value != null) + if (value != null) { - matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// An identifier for this event subscription @@ -47,19 +48,19 @@ namespace Microsoft.PowerShell.Commands { get { - return eventId; + return _eventId; } set { - eventId = value; + _eventId = value; } } - private int eventId = -1; - + private int _eventId = -1; + #endregion parameters - WildcardPattern matchPattern; + private WildcardPattern _matchPattern; /// /// Get the requested events @@ -76,47 +77,47 @@ namespace Microsoft.PowerShell.Commands eventArgsCollection = new List(Events.ReceivedEvents); } - foreach(PSEventArgs eventArg in eventArgsCollection) + foreach (PSEventArgs eventArg in eventArgsCollection) { // If they specified a event identifier and we don't match, continue - if((sourceIdentifier != null) && - (! matchPattern.IsMatch(eventArg.SourceIdentifier))) + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(eventArg.SourceIdentifier))) { continue; } // If they specified an event identifier and we don't match, continue - if((eventId >= 0) && - (eventArg.EventIdentifier != eventId)) + if ((_eventId >= 0) && + (eventArg.EventIdentifier != _eventId)) { continue; } - + WriteObject(eventArg); foundMatch = true; } // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if(! foundMatch) + if (!foundMatch) { - bool lookingForSource = (sourceIdentifier != null) && - (! WildcardPattern.ContainsWildcardCharacters(sourceIdentifier)); - bool lookingForId = (eventId >= 0); - - if(lookingForSource || lookingForId) + bool lookingForSource = (_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); + bool lookingForId = (_eventId >= 0); + + if (lookingForSource || lookingForId) { object identifier = null; string error = null; - if(lookingForSource) + if (lookingForSource) { - identifier = sourceIdentifier; + identifier = _sourceIdentifier; error = EventingStrings.SourceIdentifierNotFound; } - else if(lookingForId) + else if (lookingForId) { - identifier = eventId; + identifier = _eventId; error = EventingStrings.EventIdentifierNotFound; } @@ -128,7 +129,7 @@ namespace Microsoft.PowerShell.Commands WriteError(errorRecord); } - } + } } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index 73080021d..515d3f991 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.Management.Automation; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.Commands /// /// Lists all event subscribers. /// - [Cmdlet(VerbsCommon.Get, "EventSubscriber", DefaultParameterSetName="BySource", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135155")] + [Cmdlet(VerbsCommon.Get, "EventSubscriber", DefaultParameterSetName = "BySource", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135155")] [OutputType(typeof(PSEventSubscriber))] public class GetEventSubscriberCommand : PSCmdlet { @@ -24,19 +25,19 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; - if(value != null) + if (value != null) { - matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// An identifier for this event subscription @@ -47,14 +48,14 @@ namespace Microsoft.PowerShell.Commands { get { - return subscriptionId; + return _subscriptionId; } set { - subscriptionId = value; + _subscriptionId = value; } } - private int subscriptionId = -1; + private int _subscriptionId = -1; /// @@ -65,18 +66,18 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; #endregion parameters - WildcardPattern matchPattern; + private WildcardPattern _matchPattern; /// /// Get the subscribers @@ -88,18 +89,18 @@ namespace Microsoft.PowerShell.Commands // Go through all the received events and write them to the output // pipeline List subscribers = new List(Events.Subscribers); - foreach(PSEventSubscriber subscriber in subscribers) + foreach (PSEventSubscriber subscriber in subscribers) { // If they specified a event identifier and we don't match, continue - if((sourceIdentifier != null) && - (! matchPattern.IsMatch(subscriber.SourceIdentifier))) + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(subscriber.SourceIdentifier))) { continue; } // If they specified a subscription identifier and we don't match, continue - if((subscriptionId >= 0) && - (subscriber.SubscriptionId != subscriptionId)) + if ((_subscriptionId >= 0) && + (subscriber.SubscriptionId != _subscriptionId)) { continue; } @@ -109,35 +110,35 @@ namespace Microsoft.PowerShell.Commands { continue; } - + WriteObject(subscriber); foundMatch = true; } // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if(! foundMatch) + if (!foundMatch) { - bool lookingForSource = (sourceIdentifier != null) && - (! WildcardPattern.ContainsWildcardCharacters(sourceIdentifier)); - bool lookingForId = (subscriptionId >= 0); - - if(lookingForSource || lookingForId) + bool lookingForSource = (_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); + bool lookingForId = (_subscriptionId >= 0); + + if (lookingForSource || lookingForId) { object identifier = null; string error = null; - if(lookingForSource) + if (lookingForSource) { - identifier = sourceIdentifier; + identifier = _sourceIdentifier; error = EventingStrings.EventSubscriptionSourceNotFound; } - else if(lookingForId) + else if (lookingForId) { - identifier = subscriptionId; + identifier = _subscriptionId; error = EventingStrings.EventSubscriptionNotFound; } - + ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)), "INVALID_SOURCE_IDENTIFIER", @@ -146,7 +147,7 @@ namespace Microsoft.PowerShell.Commands WriteError(errorRecord); } - } + } } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index a9acf3322..ddfa5ea73 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -11,8 +12,6 @@ using System.Text; namespace Microsoft.PowerShell.Commands { - - /// /// Class with member information that this cmdlet writes to the pipeline /// @@ -23,39 +22,39 @@ namespace Microsoft.PowerShell.Commands /// public override string ToString() { - return this.definition; + return _definition; } /// /// Initializes a new instance of this class /// public MemberDefinition(string typeName, string name, PSMemberTypes memberType, string definition) { - this.name = name; - this.definition = definition; - this.memberType = memberType; - this.typeName = typeName; + _name = name; + _definition = definition; + _memberType = memberType; + _typeName = typeName; } - private string name; - private string typeName; - private string definition; - private PSMemberTypes memberType; + private string _name; + private string _typeName; + private string _definition; + private PSMemberTypes _memberType; /// /// type name /// - public string TypeName { get { return this.typeName; } } + public string TypeName { get { return _typeName; } } /// /// member name /// - public string Name { get {return this.name;} } + public string Name { get { return _name; } } /// /// member type /// - public PSMemberTypes MemberType { get {return this.memberType;} } + public PSMemberTypes MemberType { get { return _memberType; } } /// /// member definition /// - public string Definition { get {return this.definition;} } + public string Definition { get { return _definition; } } } /// @@ -65,7 +64,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(MemberDefinition))] public class GetMemberCommand : PSCmdlet { - private PSObject inputObject; + private PSObject _inputObject; /// /// The object to retrieve properties from @@ -73,12 +72,12 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true)] public PSObject InputObject { - set { inputObject = value; } - get { return inputObject; } + set { _inputObject = value; } + get { return _inputObject; } } - string[] name = new string[] { "*" }; + private string[] _name = new string[] { "*" }; /// /// The member names to be retrieved /// @@ -86,12 +85,12 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string[] Name { - set { name = value; } - get { return name; } + set { _name = value; } + get { return _name; } } - PSMemberTypes memberType = PSMemberTypes.All; + private PSMemberTypes _memberType = PSMemberTypes.All; /// /// The member types to be retrieved /// @@ -99,33 +98,33 @@ namespace Microsoft.PowerShell.Commands [Alias("Type")] public PSMemberTypes MemberType { - set { memberType = value; } - get { return memberType; } + set { _memberType = value; } + get { return _memberType; } } - - + + /// /// View from which the members are retrieved. /// [Parameter] public PSMemberViewTypes View { - get { return view; } - set { view = value; } + get { return _view; } + set { _view = value; } } - private PSMemberViewTypes view = PSMemberViewTypes.Adapted | PSMemberViewTypes.Extended; + private PSMemberViewTypes _view = PSMemberViewTypes.Adapted | PSMemberViewTypes.Extended; - bool staticParameter = false; + private bool _staticParameter = false; /// /// True if we should return static members /// [Parameter] public SwitchParameter Static { - set { staticParameter = value; } - get { return staticParameter; } + set { _staticParameter = value; } + get { return _staticParameter; } } - + /// /// Gets or sets the force property /// @@ -139,26 +138,26 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Force { - get - { - return (matchOptions == MshMemberMatchOptions.IncludeHidden); + get + { + return (_matchOptions == MshMemberMatchOptions.IncludeHidden); } - set + set { if (value) { // Include hidden members if force parameter is set - matchOptions = MshMemberMatchOptions.IncludeHidden; + _matchOptions = MshMemberMatchOptions.IncludeHidden; } else { - matchOptions = MshMemberMatchOptions.None; + _matchOptions = MshMemberMatchOptions.None; } } } - private MshMemberMatchOptions matchOptions = MshMemberMatchOptions.None; + private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; - private HybridDictionary typesAlreadyDisplayed = new HybridDictionary(); + private HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); /// /// This method implements the ProcessRecord method for get-member command @@ -199,19 +198,19 @@ namespace Microsoft.PowerShell.Commands } } - if (typesAlreadyDisplayed.Contains(typeName)) + if (_typesAlreadyDisplayed.Contains(typeName)) { return; } else { - typesAlreadyDisplayed.Add(typeName, ""); + _typesAlreadyDisplayed.Add(typeName, ""); } - PSMemberTypes memberTypeToSearch = memberType; - PSMemberViewTypes viewToSearch = view; + PSMemberTypes memberTypeToSearch = _memberType; + PSMemberViewTypes viewToSearch = _view; - if (((view & PSMemberViewTypes.Extended) == 0) && + if (((_view & PSMemberViewTypes.Extended) == 0) && (!typeof(PSMemberSet).ToString().Equals(typeName, StringComparison.OrdinalIgnoreCase))) { // PSMemberSet is an internal memberset and its properties/methods are populated differently. @@ -226,13 +225,13 @@ namespace Microsoft.PowerShell.Commands | PSMemberTypes.ScriptProperty); } - if (((view & PSMemberViewTypes.Adapted) == 0) && (view & PSMemberViewTypes.Base) == 0) + if (((_view & PSMemberViewTypes.Adapted) == 0) && (_view & PSMemberViewTypes.Base) == 0) { // base and adapted are not mentioned in the view so ignore respective properties memberTypeToSearch ^= (PSMemberTypes.Property | PSMemberTypes.ParameterizedProperty | PSMemberTypes.Method); } - if (((view & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) && + if (((_view & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) && (InputObject.InternalBaseDotNetAdapter == null)) { // the input object don't have a custom adapter.. @@ -254,8 +253,8 @@ namespace Microsoft.PowerShell.Commands foreach (string nameElement in this.Name) { ReadOnlyPSMemberInfoCollection readOnlyMembers; - readOnlyMembers = membersToSearch.Match(nameElement, memberTypeToSearch, matchOptions); - + readOnlyMembers = membersToSearch.Match(nameElement, memberTypeToSearch, _matchOptions); + MemberDefinition[] members = new MemberDefinition[readOnlyMembers.Count]; int resultCount = 0; foreach (PSMemberInfo member in readOnlyMembers) @@ -272,19 +271,19 @@ namespace Microsoft.PowerShell.Commands resultCount++; } Array.Sort(members, 0, resultCount, new MemberComparer()); - for(int index = 0; index < resultCount; index++) + for (int index = 0; index < resultCount; index++) { this.WriteObject(members[index]); } } } - class MemberComparer : System.Collections.Generic.IComparer + private class MemberComparer : System.Collections.Generic.IComparer { public int Compare(MemberDefinition first, MemberDefinition second) { int result = String.Compare(first.MemberType.ToString(), second.MemberType.ToString(), - StringComparison.OrdinalIgnoreCase); + StringComparison.OrdinalIgnoreCase); if (result != 0) { return result; @@ -299,7 +298,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (typesAlreadyDisplayed.Count == 0) + if (_typesAlreadyDisplayed.Count == 0) { ErrorDetails details = new ErrorDetails(this.GetType().GetTypeInfo().Assembly, "GetMember", "NoObjectSpecified"); ErrorRecord errorRecord = new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 67c42dcda..bc053499a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -35,33 +36,33 @@ namespace Microsoft.PowerShell.Commands RandomListItem } - private MyParameterSet effectiveParameterSet; + private MyParameterSet _effectiveParameterSet; private MyParameterSet EffectiveParameterSet { get { // cache MyParameterSet enum instead of doing string comparison every time - if (this.effectiveParameterSet == MyParameterSet.Unknown) + if (_effectiveParameterSet == MyParameterSet.Unknown) { if ((this.MyInvocation.ExpectingInput) && (this.Maximum == null) && (this.Minimum == null)) { - this.effectiveParameterSet = MyParameterSet.RandomListItem; + _effectiveParameterSet = MyParameterSet.RandomListItem; } else if (ParameterSetName.Equals(GetRandomCommand.RandomListItemParameterSet, StringComparison.OrdinalIgnoreCase)) { - this.effectiveParameterSet = MyParameterSet.RandomListItem; + _effectiveParameterSet = MyParameterSet.RandomListItem; } else if (this.ParameterSetName.Equals(GetRandomCommand.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) { if ((this.Maximum != null) && (this.Maximum.GetType().IsArray)) { this.InputObject = (object[])this.Maximum; - this.effectiveParameterSet = MyParameterSet.RandomListItem; + _effectiveParameterSet = MyParameterSet.RandomListItem; } else { - this.effectiveParameterSet = MyParameterSet.RandomNumber; + _effectiveParameterSet = MyParameterSet.RandomNumber; } } else @@ -70,7 +71,7 @@ namespace Microsoft.PowerShell.Commands } } - return this.effectiveParameterSet; + return _effectiveParameterSet; } } @@ -104,10 +105,10 @@ namespace Microsoft.PowerShell.Commands #region Random generator state - static private ReaderWriterLockSlim runspaceGeneratorMapLock = new ReaderWriterLockSlim(); + static private ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim(); // 1-to-1 mapping of runspaces and random number generators - static private Dictionary RunspaceGeneratorMap = new Dictionary(); + static private Dictionary s_runspaceGeneratorMap = new Dictionary(); static private void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { @@ -117,18 +118,18 @@ namespace Microsoft.PowerShell.Commands case RunspaceState.Closed: try { - GetRandomCommand.runspaceGeneratorMapLock.EnterWriteLock(); - GetRandomCommand.RunspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); + GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); + GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); } finally { - GetRandomCommand.runspaceGeneratorMapLock.ExitWriteLock(); + GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } break; } } - private PolymorphicRandomNumberGenerator generator; + private PolymorphicRandomNumberGenerator _generator; /// /// Gets and sets generator associated with the current runspace @@ -137,19 +138,19 @@ namespace Microsoft.PowerShell.Commands { get { - if (this.generator == null) + if (_generator == null) { Guid runspaceId = this.Context.CurrentRunspace.InstanceId; bool needToInitialize = false; try { - GetRandomCommand.runspaceGeneratorMapLock.EnterReadLock(); - needToInitialize = !GetRandomCommand.RunspaceGeneratorMap.TryGetValue(runspaceId, out this.generator); + GetRandomCommand.s_runspaceGeneratorMapLock.EnterReadLock(); + needToInitialize = !GetRandomCommand.s_runspaceGeneratorMap.TryGetValue(runspaceId, out _generator); } finally { - GetRandomCommand.runspaceGeneratorMapLock.ExitReadLock(); + GetRandomCommand.s_runspaceGeneratorMapLock.ExitReadLock(); } if (needToInitialize) @@ -158,26 +159,26 @@ namespace Microsoft.PowerShell.Commands } } - return this.generator; + return _generator; } - set - { - this.generator = value; + set + { + _generator = value; Runspace myRunspace = this.Context.CurrentRunspace; try { - GetRandomCommand.runspaceGeneratorMapLock.EnterWriteLock(); - if (!GetRandomCommand.RunspaceGeneratorMap.ContainsKey(myRunspace.InstanceId)) + GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); + if (!GetRandomCommand.s_runspaceGeneratorMap.ContainsKey(myRunspace.InstanceId)) { // make sure we won't leave the generator around after runspace exits myRunspace.StateChanged += CurrentRunspace_StateChanged; } - GetRandomCommand.RunspaceGeneratorMap[myRunspace.InstanceId] = this.generator; + GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator; } finally { - GetRandomCommand.runspaceGeneratorMapLock.ExitWriteLock(); + GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } } } @@ -186,7 +187,7 @@ namespace Microsoft.PowerShell.Commands #region Common parameters - private int? setSeed; + private int? _setSeed; /// /// Seed used to reinitialize random numbers generator @@ -195,15 +196,15 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public int? SetSeed { - get { return this.setSeed; } - set { this.setSeed = value; } + get { return _setSeed; } + set { _setSeed = value; } } #endregion Common parameters #region Parameters for RandomNumberParameterSet - private object maximum; + private object _maximum; /// /// Maximum number to generate @@ -211,11 +212,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] public object Maximum { - get { return this.maximum; } - set { this.maximum = value; } + get { return _maximum; } + set { _maximum = value; } } - private object minimum; + private object _minimum; /// /// Minimum number to generate @@ -223,8 +224,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = RandomNumberParameterSet)] public object Minimum { - get { return this.minimum; } - set { this.minimum = value; } + get { return _minimum; } + set { _minimum = value; } } private bool IsInt(object o) @@ -280,24 +281,24 @@ namespace Microsoft.PowerShell.Commands #region Parameters and variables for RandomListItemParameterSet - private List chosenListItems; - private int numberOfProcessedListItems; + private List _chosenListItems; + private int _numberOfProcessedListItems; - private object[] inputObject; + private object[] _inputObject; /// /// List from which random elements are chosen /// [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] InputObject { - get { return this.inputObject; } - set { this.inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } - private int count; + private int _count; /// /// Number of items to output (number of list items or of numbers) @@ -306,8 +307,8 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(1, int.MaxValue)] public int Count { - get { return this.count; } - set { this.count = value; } + get { return _count; } + set { _count = value; } } #endregion @@ -363,7 +364,7 @@ namespace Microsoft.PowerShell.Commands UInt64 randomUint64; BigInteger bigIntegerDiff = (BigInteger)max - (BigInteger)min; - + // When the difference is less than int.MaxValue, use Random.Next(int, int) if (bigIntegerDiff <= int.MaxValue) { @@ -372,7 +373,7 @@ namespace Microsoft.PowerShell.Commands } // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. - UInt64 uint64Diff = (UInt64) bigIntegerDiff; + UInt64 uint64Diff = (UInt64)bigIntegerDiff; // Calculate the number of bits to represent the diff in type UInt64 int bitsToRepresentDiff = 0; @@ -392,7 +393,7 @@ namespace Microsoft.PowerShell.Commands randomUint64 &= mask; } while (uint64Diff <= randomUint64); - double result = min*1.0 + randomUint64*1.0; + double result = min * 1.0 + randomUint64 * 1.0; return (Int64)result; } @@ -462,8 +463,8 @@ namespace Microsoft.PowerShell.Commands } else if (this.EffectiveParameterSet == MyParameterSet.RandomListItem) { - this.chosenListItems = new List(); - this.numberOfProcessedListItems = 0; + _chosenListItems = new List(); + _numberOfProcessedListItems = 0; if (this.Count == 0) // -Count not specified { @@ -512,22 +513,22 @@ namespace Microsoft.PowerShell.Commands { foreach (object item in this.InputObject) { - if (this.numberOfProcessedListItems < this.Count) // (3) + if (_numberOfProcessedListItems < this.Count) // (3) { - Debug.Assert(this.chosenListItems.Count == this.numberOfProcessedListItems, "Initial K elements should all be included in this.chosenListItems"); - this.chosenListItems.Add(item); + Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in this.chosenListItems"); + _chosenListItems.Add(item); } else { - Debug.Assert(this.chosenListItems.Count == this.Count, "After processing K initial elements, the length of this.chosenItems should stay equal to K"); - if (this.Generator.Next(this.numberOfProcessedListItems + 1) < this.Count) // (1) + Debug.Assert(_chosenListItems.Count == this.Count, "After processing K initial elements, the length of this.chosenItems should stay equal to K"); + if (this.Generator.Next(_numberOfProcessedListItems + 1) < this.Count) // (1) { - int indexToReplace = this.Generator.Next(this.chosenListItems.Count); // (2) - this.chosenListItems[indexToReplace] = item; + int indexToReplace = this.Generator.Next(_chosenListItems.Count); // (2) + _chosenListItems[indexToReplace] = item; } } - this.numberOfProcessedListItems++; + _numberOfProcessedListItems++; } } } @@ -542,7 +543,7 @@ namespace Microsoft.PowerShell.Commands // make sure the order is truly random // (all permutations with the same probability) // O(n) time - int n = this.chosenListItems.Count; + int n = _chosenListItems.Count; for (int i = 0; i < n; i++) { // randomly choose an item to go into the i-th position @@ -551,14 +552,14 @@ namespace Microsoft.PowerShell.Commands // swap j-th item into i-th position if (i != j) { - object tmp = this.chosenListItems[i]; - this.chosenListItems[i] = this.chosenListItems[j]; - this.chosenListItems[j] = tmp; + object tmp = _chosenListItems[i]; + _chosenListItems[i] = _chosenListItems[j]; + _chosenListItems[j] = tmp; } } // output all items - foreach (object chosenItem in this.chosenListItems) + foreach (object chosenItem in _chosenListItems) { this.WriteObject(chosenItem); } @@ -581,18 +582,18 @@ namespace Microsoft.PowerShell.Commands /// public PolymorphicRandomNumberGenerator() { - cryptographicGenerator = RandomNumberGenerator.Create(); - pseudoGenerator = null; + _cryptographicGenerator = RandomNumberGenerator.Create(); + _pseudoGenerator = null; } internal PolymorphicRandomNumberGenerator(int seed) { - cryptographicGenerator = null; - pseudoGenerator = new Random(seed); + _cryptographicGenerator = null; + _pseudoGenerator = new Random(seed); } - Random pseudoGenerator = null; - RandomNumberGenerator cryptographicGenerator = null; + private Random _pseudoGenerator = null; + private RandomNumberGenerator _cryptographicGenerator = null; /// /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. @@ -622,7 +623,7 @@ namespace Microsoft.PowerShell.Commands } while (result == Int32.MaxValue); - if(result < 0) + if (result < 0) { result += Int32.MaxValue; } @@ -653,19 +654,19 @@ namespace Microsoft.PowerShell.Commands /// public int Next(int minValue, int maxValue) { - if(minValue > maxValue) + if (minValue > maxValue) { throw new ArgumentOutOfRangeException("minValue", GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); } - long range = (long) maxValue - (long) minValue; - if(range <= int.MaxValue) + long range = (long)maxValue - (long)minValue; + if (range <= int.MaxValue) { return ((int)(NextDouble() * range) + minValue); } else { - double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint) Int32.MaxValue))); + double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)Int32.MaxValue))); int result = (int)((long)(largeSample * range) + minValue); return result; @@ -678,13 +679,13 @@ namespace Microsoft.PowerShell.Commands /// The array to be filled internal void NextBytes(byte[] buffer) { - if(cryptographicGenerator != null) + if (_cryptographicGenerator != null) { - cryptographicGenerator.GetBytes(buffer); + _cryptographicGenerator.GetBytes(buffer); } else { - pseudoGenerator.NextBytes(buffer); + _pseudoGenerator.NextBytes(buffer); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs index 8953bbcb3..759fd0608 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - WriteObject( Host.CurrentUICulture ); + WriteObject(Host.CurrentUICulture); } // EndProcessing } // GetUICultureCommand } // Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index d65f5c01e..5143b3dea 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - [Parameter (ValueFromPipeline = true)] + [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set { _inputObject = value; } @@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Commands /// strings and the strings should be compared. /// /// - [Parameter (ParameterSetName = "AsString")] + [Parameter(ParameterSetName = "AsString")] public SwitchParameter AsString { get { return _asString; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 670e09f97..d8693795d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -57,15 +57,15 @@ namespace Microsoft.PowerShell.Commands { get { - return moduleName; + return _moduleName; } set { - moduleName = value; + _moduleName = value; } } - private string moduleName; + private string _moduleName; /// /// Property that sets force parameter. @@ -75,14 +75,14 @@ namespace Microsoft.PowerShell.Commands { get { - return new SwitchParameter(force); + return new SwitchParameter(_force); } set { - force = value.IsPresent; + _force = value.IsPresent; } } - private bool force; + private bool _force; /// /// Encoding optional flag @@ -93,14 +93,14 @@ namespace Microsoft.PowerShell.Commands { get { - return encoding.GetType().Name; + return _encoding.GetType().Name; } set { - encoding = EncodingConversion.Convert(this, value); + _encoding = EncodingConversion.Convert(this, value); } } - private Encoding encoding = System.Text.Encoding.UTF8; + private Encoding _encoding = System.Text.Encoding.UTF8; #endregion Parameters @@ -139,8 +139,8 @@ namespace Microsoft.PowerShell.Commands string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); - } - + } + DirectoryInfo directory = PathUtils.CreateModuleDirectory(this, this.OutputModule, this.Force.IsPresent); // Creating a temporary directory where files will be created. @@ -155,17 +155,17 @@ namespace Microsoft.PowerShell.Commands List generatedFiles = GenerateProxyModule( tempDirectory, Path.GetFileName(directory.FullName), - this.encoding, - this.force, + _encoding, + _force, listOfCommandMetadata, alias2resolvedCommandName, listOfFormatData ); ScriptBlock script = this.Context.Engine.ParseScriptBlock(copyItemScript, false); - script.Invoke(new object[] { tempDirectory, directory}); + script.Invoke(new object[] { tempDirectory, directory }); - this.DisplayDirectory(new List {directory.FullName}); + this.DisplayDirectory(new List { directory.FullName }); } #endregion Methods @@ -249,7 +249,7 @@ namespace Microsoft.PowerShell.Commands private PSModuleInfo CreateModule(string manifestFile) { ScriptBlock script = this.Context.Engine.ParseScriptBlock(importModuleScript, false); - Collection results = script.Invoke(manifestFile, this.Session, this.Prefix, this.disableNameChecking); + Collection results = script.Invoke(manifestFile, this.Session, this.Prefix, _disableNameChecking); Dbg.Assert(results != null, "Import-Module should always succeed"); Dbg.Assert(results.Count == 1, "Import-Module should always succeed"); Dbg.Assert(results[0].BaseObject is PSModuleInfo, "Import-Module should always succeed"); @@ -279,11 +279,11 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter DisableNameChecking { - get { return this.disableNameChecking; } - set { this.disableNameChecking = value; } + get { return _disableNameChecking; } + set { _disableNameChecking = value; } } - private bool disableNameChecking; + private bool _disableNameChecking; #endregion @@ -347,10 +347,10 @@ namespace Microsoft.PowerShell.Commands internal ImplicitRemotingCommandBase() { this.CommandName = new string[] { "*" }; - this.commandParameterSpecified = false; + _commandParameterSpecified = false; this.FormatTypeName = new string[] { "*" }; - this.formatTypeNamesSpecified = false; + _formatTypeNamesSpecified = false; } #endregion @@ -369,19 +369,19 @@ namespace Microsoft.PowerShell.Commands { get { - return this.commandNameParameter; + return _commandNameParameter; } set { - this.commandNameParameter = value; - this.commandParameterSpecified = true; - this.commandNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( - this.commandNameParameter, + _commandNameParameter = value; + _commandParameterSpecified = true; + _commandNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( + _commandNameParameter, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } - private string[] commandNameParameter; - private Collection commandNamePatterns; // initialized to default value in the constructor + private string[] _commandNameParameter; + private Collection _commandNamePatterns; // initialized to default value in the constructor /// /// Allows shadowing and/or overwriting of existing local/client commands @@ -391,14 +391,14 @@ namespace Microsoft.PowerShell.Commands { get { - return this.allowClobber; + return _allowClobber; } set { - this.allowClobber = value; + _allowClobber = value; } } - private SwitchParameter allowClobber = new SwitchParameter(false); // no clobber by default + private SwitchParameter _allowClobber = new SwitchParameter(false); // no clobber by default /// /// The parameter that all additional arguments get bound to. These arguments are used @@ -413,15 +413,15 @@ namespace Microsoft.PowerShell.Commands { get { - return commandArgs; + return _commandArgs; } set { - this.commandArgs = value; - this.commandParameterSpecified = true; + _commandArgs = value; + _commandParameterSpecified = true; } } - private object[] commandArgs; + private object[] _commandArgs; /// /// Gets or sets the type of the command to get @@ -432,16 +432,16 @@ namespace Microsoft.PowerShell.Commands { get { - return commandType; + return _commandType; } set { - this.commandType = value; - this.commandParameterSpecified = true; + _commandType = value; + _commandParameterSpecified = true; } } - private CommandTypes commandType = CommandTypes.All & (~(CommandTypes.Application | CommandTypes.Script | CommandTypes.ExternalScript)); + private CommandTypes _commandType = CommandTypes.All & (~(CommandTypes.Application | CommandTypes.Script | CommandTypes.ExternalScript)); /// /// Gets or sets the PSSnapin parameter to the cmdlet @@ -455,7 +455,7 @@ namespace Microsoft.PowerShell.Commands { get { - return PSSnapins; + return _PSSnapins; } set @@ -464,12 +464,12 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - this.PSSnapins = value; - this.commandParameterSpecified = true; + _PSSnapins = value; + _commandParameterSpecified = true; IsModuleSpecified = true; } } - private string[] PSSnapins = new string[0]; + private string[] _PSSnapins = new string[0]; internal bool IsModuleSpecified = false; /// /// Gets or sets the FullyQualifiedModule parameter to the cmdlet @@ -488,16 +488,16 @@ namespace Microsoft.PowerShell.Commands { if (value != null) { - this._moduleSpecifications = value; + _moduleSpecifications = value; } - this.commandParameterSpecified = true; + _commandParameterSpecified = true; IsFullyQualifiedModuleSpecified = true; } } private ModuleSpecification[] _moduleSpecifications = new ModuleSpecification[0]; internal bool IsFullyQualifiedModuleSpecified = false; - private bool commandParameterSpecified; // initialized to default value in the constructor + private bool _commandParameterSpecified; // initialized to default value in the constructor #endregion related to Get-Command @@ -512,20 +512,20 @@ namespace Microsoft.PowerShell.Commands { get { - return this.formatTypeNameParameter; + return _formatTypeNameParameter; } set { - this.formatTypeNameParameter = value; - this.formatTypeNamesSpecified = true; - this.formatTypeNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( - this.formatTypeNameParameter, + _formatTypeNameParameter = value; + _formatTypeNamesSpecified = true; + _formatTypeNamePatterns = SessionStateUtilities.CreateWildcardsFromStrings( + _formatTypeNameParameter, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } - private string[] formatTypeNameParameter; // initialized to default value in the constructor - private Collection formatTypeNamePatterns; - private bool formatTypeNamesSpecified; // initialized to default value in the constructor + private string[] _formatTypeNameParameter; // initialized to default value in the constructor + private Collection _formatTypeNamePatterns; + private bool _formatTypeNamesSpecified; // initialized to default value in the constructor #endregion @@ -536,11 +536,11 @@ namespace Microsoft.PowerShell.Commands /// internal string Prefix { - set { prefix = value; } - get { return prefix; } + set { _prefix = value; } + get { return _prefix; } } - private string prefix = string.Empty; + private string _prefix = string.Empty; /// /// Gets or sets the certificate with which to sign the format file and psm1 file. @@ -550,15 +550,15 @@ namespace Microsoft.PowerShell.Commands { get { - return certificate; + return _certificate; } set { - certificate = value; + _certificate = value; } } - private X509Certificate2 certificate; + private X509Certificate2 _certificate; #endregion @@ -573,14 +573,14 @@ namespace Microsoft.PowerShell.Commands { get { - return remoteRunspaceInfo; + return _remoteRunspaceInfo; } set { - remoteRunspaceInfo = value; + _remoteRunspaceInfo = value; } } - private PSSession remoteRunspaceInfo; + private PSSession _remoteRunspaceInfo; #endregion Parameters @@ -846,12 +846,12 @@ namespace Microsoft.PowerShell.Commands return errorRecord; } - private List commandsSkippedBecauseOfShadowing = new List(); + private List _commandsSkippedBecauseOfShadowing = new List(); private void ReportSkippedCommands() { - if (this.commandsSkippedBecauseOfShadowing.Count != 0) + if (_commandsSkippedBecauseOfShadowing.Count != 0) { - string skippedCommands = string.Join(", ", this.commandsSkippedBecauseOfShadowing.ToArray()); + string skippedCommands = string.Join(", ", _commandsSkippedBecauseOfShadowing.ToArray()); ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands.ToString()); this.WriteWarning(errorRecord.ErrorDetails.Message); } @@ -863,7 +863,7 @@ namespace Microsoft.PowerShell.Commands private bool IsCommandNameMatchingParameters(string commandName) { - if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, this.commandNamePatterns, false)) + if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, _commandNamePatterns, false)) { return true; } @@ -871,20 +871,20 @@ namespace Microsoft.PowerShell.Commands string nameWithoutExtension = Path.GetFileNameWithoutExtension(commandName); if (!nameWithoutExtension.Equals(commandName, StringComparison.OrdinalIgnoreCase)) { - return SessionStateUtilities.MatchesAnyWildcardPattern(nameWithoutExtension, this.commandNamePatterns, false); + return SessionStateUtilities.MatchesAnyWildcardPattern(nameWithoutExtension, _commandNamePatterns, false); } return false; } - private Dictionary existingCommands; + private Dictionary _existingCommands; private Dictionary ExistingCommands { get { - if (existingCommands == null) + if (_existingCommands == null) { - existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); + _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); CommandSearcher searcher = new CommandSearcher( "*", SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, @@ -892,10 +892,10 @@ namespace Microsoft.PowerShell.Commands this.Context); foreach (CommandInfo commandInfo in searcher) { - existingCommands[commandInfo.Name] = null; + _existingCommands[commandInfo.Name] = null; } } - return existingCommands; + return _existingCommands; } } @@ -934,7 +934,7 @@ namespace Microsoft.PowerShell.Commands if (IsShadowingExistingCommands(commandName)) { - this.commandsSkippedBecauseOfShadowing.Add(commandName); + _commandsSkippedBecauseOfShadowing.Add(commandName); return false; } else @@ -952,7 +952,7 @@ namespace Microsoft.PowerShell.Commands get { // try to get the list from server's application private data - if (commandSkipListFromServer == null) + if (_commandSkipListFromServer == null) { string[] serverDeclaredListOfCommandsToSkip; if (PSPrimitiveDictionary.TryPathGet( @@ -961,36 +961,36 @@ namespace Microsoft.PowerShell.Commands ImplicitRemotingKey, ImplicitRemotingCommandsToSkipKey)) { - commandSkipListFromServer = new List(); + _commandSkipListFromServer = new List(); if (serverDeclaredListOfCommandsToSkip != null) { - commandSkipListFromServer.AddRange(serverDeclaredListOfCommandsToSkip); + _commandSkipListFromServer.AddRange(serverDeclaredListOfCommandsToSkip); } } } // fallback to the default list that hardcodes ... - if (commandSkipListFromServer == null) + if (_commandSkipListFromServer == null) { - commandSkipListFromServer = new List(); + _commandSkipListFromServer = new List(); // ... A) 5 commands used (some required some not) by implicit remoting - commandSkipListFromServer.Add("Get-Command"); - commandSkipListFromServer.Add("Get-FormatData"); - commandSkipListFromServer.Add("Get-Help"); - commandSkipListFromServer.Add("Select-Object"); - commandSkipListFromServer.Add("Measure-Object"); + _commandSkipListFromServer.Add("Get-Command"); + _commandSkipListFromServer.Add("Get-FormatData"); + _commandSkipListFromServer.Add("Get-Help"); + _commandSkipListFromServer.Add("Select-Object"); + _commandSkipListFromServer.Add("Measure-Object"); // ... B) 2 commands required for 1:1 remoting - commandSkipListFromServer.Add("Exit-PSSession"); - commandSkipListFromServer.Add("Out-Default"); + _commandSkipListFromServer.Add("Exit-PSSession"); + _commandSkipListFromServer.Add("Out-Default"); } - return commandSkipListFromServer; + return _commandSkipListFromServer; } } - private List commandSkipListFromServer; + private List _commandSkipListFromServer; private bool IsCommandSkippedByServerDeclaration(string commandName) { @@ -1082,7 +1082,7 @@ namespace Microsoft.PowerShell.Commands { if (itemRehydrator == null) { - itemRehydrator = delegate(PSObject pso) { return ConvertTo(commandName, pso); }; + itemRehydrator = delegate (PSObject pso) { return ConvertTo(commandName, pso); }; } List result = null; @@ -1109,7 +1109,7 @@ namespace Microsoft.PowerShell.Commands if (valueRehydrator == null) { - valueRehydrator = delegate(PSObject pso) { return ConvertTo(commandName, pso); }; + valueRehydrator = delegate (PSObject pso) { return ConvertTo(commandName, pso); }; } Dictionary result = new Dictionary(); @@ -1491,7 +1491,7 @@ namespace Microsoft.PowerShell.Commands private bool IsTypeNameMatchingParameters(string name) { - return SessionStateUtilities.MatchesAnyWildcardPattern(name, this.formatTypeNamePatterns, false); + return SessionStateUtilities.MatchesAnyWildcardPattern(name, _formatTypeNamePatterns, false); } private bool IsSafeTypeDefinition(ExtendedTypeDefinition typeDefinition) @@ -1523,11 +1523,11 @@ namespace Microsoft.PowerShell.Commands #region Helpers for executing remote commands - private bool assumeMeasureObjectIsAvailable = true; + private bool _assumeMeasureObjectIsAvailable = true; private int CountRemoteObjects(PowerShell powerShell) { - if (!assumeMeasureObjectIsAvailable) + if (!_assumeMeasureObjectIsAvailable) { return -1; } @@ -1544,14 +1544,14 @@ namespace Microsoft.PowerShell.Commands if ((measurements == null) || (measurements.Count != 1)) { - assumeMeasureObjectIsAvailable = false; + _assumeMeasureObjectIsAvailable = false; return -1; } PSPropertyInfo countProperty = measurements[0].Properties["Count"]; if (countProperty == null) { - assumeMeasureObjectIsAvailable = false; + _assumeMeasureObjectIsAvailable = false; return -1; } @@ -1562,14 +1562,14 @@ namespace Microsoft.PowerShell.Commands } else { - assumeMeasureObjectIsAvailable = false; + _assumeMeasureObjectIsAvailable = false; return -1; } } catch (RuntimeException) { // just return -1 if remote Measure-Object invocation fails for any reason - assumeMeasureObjectIsAvailable = false; + _assumeMeasureObjectIsAvailable = false; return -1; } } @@ -1614,14 +1614,14 @@ namespace Microsoft.PowerShell.Commands powerShell.AddParameter("TypeName", this.FormatTypeName); // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter - RemoteRunspace remoteRunspace = this.remoteRunspaceInfo.Runspace as RemoteRunspace; + RemoteRunspace remoteRunspace = _remoteRunspaceInfo.Runspace as RemoteRunspace; if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && - (remoteRunspace.ServerVersion >= new Version(5,1))) + (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); } - powerShell.Runspace = this.remoteRunspaceInfo.Runspace; + powerShell.Runspace = _remoteRunspaceInfo.Runspace; return powerShell; } @@ -1633,7 +1633,7 @@ namespace Microsoft.PowerShell.Commands internal List GetRemoteFormatData() { if ((this.FormatTypeName == null) || (this.FormatTypeName.Length == 0) || - (this.commandParameterSpecified && !this.formatTypeNamesSpecified)) + (_commandParameterSpecified && !_formatTypeNamesSpecified)) { return new List(); } @@ -1671,7 +1671,7 @@ namespace Microsoft.PowerShell.Commands this.DuplicatePowerShellStreams(powerShell); powerShell.EndInvoke(asyncResult); - if ((numberOfReceivedObjects == 0) && (this.formatTypeNamesSpecified)) + if ((numberOfReceivedObjects == 0) && (_formatTypeNamesSpecified)) { this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-FormatData")); } @@ -1711,7 +1711,7 @@ namespace Microsoft.PowerShell.Commands } powerShell.AddParameter("ArgumentList", this.ArgumentList); - powerShell.Runspace = this.remoteRunspaceInfo.Runspace; + powerShell.Runspace = _remoteRunspaceInfo.Runspace; powerShell.RemotePowerShell.HostCallReceived += new EventHandler>(HandleHostCallReceived); return powerShell; } @@ -1737,7 +1737,7 @@ namespace Microsoft.PowerShell.Commands alias2resolvedCommandName = new Dictionary(StringComparer.OrdinalIgnoreCase); if ((this.CommandName == null) || (this.CommandName.Length == 0) || - (!this.commandParameterSpecified && this.formatTypeNamesSpecified)) + (!_commandParameterSpecified && _formatTypeNamesSpecified)) { return new List(); } @@ -1794,7 +1794,7 @@ namespace Microsoft.PowerShell.Commands this.DuplicatePowerShellStreams(powerShell); powerShell.EndInvoke(asyncResult); - if ((numberOfReceivedObjects == 0) && (this.commandParameterSpecified)) + if ((numberOfReceivedObjects == 0) && (_commandParameterSpecified)) { this.ThrowTerminatingError(this.GetErrorNoResultsFromRemoteEnd("Get-Command")); } @@ -1817,7 +1817,7 @@ namespace Microsoft.PowerShell.Commands #region Reporting progress - private DateTime lastTimeProgressWasWritten = DateTime.UtcNow; + private DateTime _lastTimeProgressWasWritten = DateTime.UtcNow; private void WriteProgress(string statusDescription, int? percentComplete, int? secondsRemaining) { @@ -1834,13 +1834,13 @@ namespace Microsoft.PowerShell.Commands if (recordType == ProgressRecordType.Processing) { - TimeSpan timeSinceProgressWasWrittenLast = DateTime.UtcNow - lastTimeProgressWasWritten; + TimeSpan timeSinceProgressWasWrittenLast = DateTime.UtcNow - _lastTimeProgressWasWritten; if (timeSinceProgressWasWrittenLast < TimeSpan.FromMilliseconds(200)) { return; } } - lastTimeProgressWasWritten = DateTime.UtcNow; + _lastTimeProgressWasWritten = DateTime.UtcNow; string activityDescription = StringUtil.Format(ImplicitRemotingStrings.ProgressActivity); ProgressRecord progressRecord = new ProgressRecord( @@ -1885,13 +1885,13 @@ namespace Microsoft.PowerShell.Commands #region Generating a proxy module - private Guid moduleGuid = Guid.NewGuid(); + private Guid _moduleGuid = Guid.NewGuid(); internal Guid ModuleGuid { get { - return moduleGuid; + return _moduleGuid; } } @@ -1915,7 +1915,7 @@ namespace Microsoft.PowerShell.Commands Dictionary alias2resolvedCommandName, List listOfFormatData) { - if (this.commandsSkippedBecauseOfShadowing.Count != 0) + if (_commandsSkippedBecauseOfShadowing.Count != 0) { this.ReportSkippedCommands(); @@ -1955,9 +1955,9 @@ namespace Microsoft.PowerShell.Commands #region Constructor and shared private data - private PSSession remoteRunspaceInfo; - private Guid moduleGuid; - private InvocationInfo invocationInfo; + private PSSession _remoteRunspaceInfo; + private Guid _moduleGuid; + private InvocationInfo _invocationInfo; internal ImplicitRemotingCodeGenerator( PSSession remoteRunspaceInfo, @@ -1968,9 +1968,9 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(moduleGuid != null, "Caller should validate moduleGuid != null"); Dbg.Assert(invocationInfo != null, "Caller should validate invocationInfo != null"); - this.remoteRunspaceInfo = remoteRunspaceInfo; - this.moduleGuid = moduleGuid; - this.invocationInfo = invocationInfo; + _remoteRunspaceInfo = remoteRunspaceInfo; + _moduleGuid = moduleGuid; + _invocationInfo = invocationInfo; } #endregion @@ -1983,20 +1983,20 @@ namespace Microsoft.PowerShell.Commands /// Connection URI associated with the remote runspace private string GetConnectionString() { - WSManConnectionInfo connectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (connectionInfo != null) { return connectionInfo.ConnectionUri.ToString(); } - - VMConnectionInfo vmConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; + + VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) { return vmConnectionInfo.ComputerName; } - ContainerConnectionInfo containerConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; + if (containerConnectionInfo != null) { return containerConnectionInfo.ComputerName; } @@ -2008,7 +2008,7 @@ namespace Microsoft.PowerShell.Commands Uri.IsWellFormedUriString(connectionString, UriKind.Absolute), "GetConnectionString() should return only well formed uri strings"); */ - return null; + return null; } private string EscapeFunctionNameForRemoteHelp(string name) @@ -2070,7 +2070,7 @@ namespace Microsoft.PowerShell.Commands writer.Write( ManifestTemplate, - CodeGeneration.EscapeSingleQuotedStringContent(this.moduleGuid.ToString()), + CodeGeneration.EscapeSingleQuotedStringContent(_moduleGuid.ToString()), CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyModuleDescription, this.GetConnectionString())), CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(psm1fileName)), CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName))); @@ -2095,8 +2095,8 @@ namespace Microsoft.PowerShell.Commands TopCommentTemplate, CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderTitle)), CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderDate, DateTime.Now.ToString(CultureInfo.CurrentCulture))), - CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommand, this.invocationInfo.MyCommand.Name)), - CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommandLine, this.invocationInfo.Line))); + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommand, _invocationInfo.MyCommand.Name)), + CodeGeneration.EscapeBlockCommentContent(StringUtil.Format(ImplicitRemotingStrings.ModuleHeaderCommandLine, _invocationInfo.Line))); } private const string HeaderTemplate = @" @@ -2267,7 +2267,7 @@ function Get-PSImplicitRemotingSessionOption private PSPrimitiveDictionary GetApplicationArguments() { - RemoteRunspace remoteRunspace = remoteRunspaceInfo.Runspace as RemoteRunspace; + RemoteRunspace remoteRunspace = _remoteRunspaceInfo.Runspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "PSSessionInfo should refer to a *remote* runspace"); Dbg.Assert(remoteRunspace.RunspacePool != null, "All remote runspaces are implemented using a runspace pool"); @@ -2280,7 +2280,7 @@ function Get-PSImplicitRemotingSessionOption { StringBuilder result = new StringBuilder("& $script:NewPSSessionOption "); - RunspaceConnectionInfo runspaceConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; + RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; if (runspaceConnectionInfo != null) { result.AppendFormat(null, "-Culture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())); @@ -2292,7 +2292,7 @@ function Get-PSImplicitRemotingSessionOption result.AppendFormat(null, "-OperationTimeOut {0} ", runspaceConnectionInfo.OperationTimeout); } - WSManConnectionInfo wsmanConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } @@ -2368,7 +2368,7 @@ function Get-PSImplicitRemotingSessionOption /* 0 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestTitle)), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyCredentialRequestBody, this.GetConnectionString())), /* 2 */ CodeGeneration.EscapeSingleQuotedStringContent(wsmanConnectionInfo.ProxyCredential.UserName), - /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(this.remoteRunspaceInfo.ComputerName + @"\httpproxy")); + /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ComputerName + @"\httpproxy")); } } @@ -2446,7 +2446,7 @@ function Get-PSImplicitRemotingSession string hashString; PSPrimitiveDictionary.TryPathGet( - this.remoteRunspaceInfo.ApplicationPrivateData, + _remoteRunspaceInfo.ApplicationPrivateData, out hashString, ImplicitRemotingCommandBase.ImplicitRemotingKey, ImplicitRemotingCommandBase.ImplicitRemotingHashKey); @@ -2454,7 +2454,7 @@ function Get-PSImplicitRemotingSession writer.Write( HelperFunctionsGetImplicitRunspaceTemplate, - /* 0 */ this.remoteRunspaceInfo.InstanceId, + /* 0 */ _remoteRunspaceInfo.InstanceId, /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CreateNewRunspaceMessageTemplate)), /* 2 */ this.GenerateNewRunspaceExpression(), /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ErrorNoRunspaceForThisModule)), @@ -2476,9 +2476,9 @@ function Get-PSImplicitRemotingSession { StringBuilder result = new StringBuilder(); - if (this.invocationInfo.BoundParameters.ContainsKey("Module")) + if (_invocationInfo.BoundParameters.ContainsKey("Module")) { - string[] moduleNames = (string[]) this.invocationInfo.BoundParameters["Module"]; + string[] moduleNames = (string[])_invocationInfo.BoundParameters["Module"]; foreach (string moduleName in moduleNames) { result.AppendFormat( @@ -2540,7 +2540,7 @@ function Get-PSImplicitRemotingSession private string GenerateNewRunspaceExpression() { - VMConnectionInfo vmConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; + VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; @@ -2553,7 +2553,7 @@ function Get-PSImplicitRemotingSession } else { - ContainerConnectionInfo containerConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; + ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; if (containerConnectionInfo != null) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; @@ -2570,7 +2570,7 @@ function Get-PSImplicitRemotingSession CultureInfo.InvariantCulture, NewRunspaceTemplate, /* 0 */ this.GenerateConnectionStringForNewRunspace(), - /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(this.remoteRunspaceInfo.ConfigurationName), + /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ConfigurationName), /* 2 */ this.GenerateCredentialParameter(), /* 3 */ this.GenerateCertificateThumbprintParameter(), /* 4 */ this.GenerateAuthenticationMechanismParameter(), @@ -2583,7 +2583,7 @@ function Get-PSImplicitRemotingSession -ApplicationName '{1}' {2} {3} "; private const string VMIdParameterTemplate = @"-VMId '{0}' "; private const string ContainerIdParameterTemplate = @"-ContainerId '{0}' "; - + /// /// This is needed to work with Default Port DCR change from WSMan. See BUG /// 542726. If http/https is specified in the connectionURI and no port is @@ -2597,10 +2597,10 @@ function Get-PSImplicitRemotingSession { string connectionString = null; - WSManConnectionInfo connectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (null == connectionInfo) { - VMConnectionInfo vmConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; + VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) { return string.Format(CultureInfo.InvariantCulture, @@ -2608,7 +2608,7 @@ function Get-PSImplicitRemotingSession CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); } - ContainerConnectionInfo containerConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; + ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; if (containerConnectionInfo != null) { return string.Format(CultureInfo.InvariantCulture, @@ -2643,7 +2643,7 @@ function Get-PSImplicitRemotingSession private string GenerateAllowRedirectionParameter() { - WSManConnectionInfo wsmanConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo == null) { return string.Empty; @@ -2665,12 +2665,12 @@ function Get-PSImplicitRemotingSession { // comment in newrunspacecommand.cs says that -CertificateThumbprint // and AuthenticationMechanism are mutually exclusive - if (this.remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint != null) { return string.Empty; } - WSManConnectionInfo wsmanConnectionInfo = this.remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo == null) { return string.Empty; @@ -2691,7 +2691,7 @@ function Get-PSImplicitRemotingSession private string GenerateCredentialParameter() { - if (this.remoteRunspaceInfo.Runspace.ConnectionInfo.Credential == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential == null) { return string.Empty; } @@ -2702,8 +2702,8 @@ function Get-PSImplicitRemotingSession CredentialParameterTemplate, /* 0 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestTitle)), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.CredentialRequestBody, this.GetConnectionString())), - /* 2 */ CodeGeneration.EscapeSingleQuotedStringContent(this.remoteRunspaceInfo.Runspace.ConnectionInfo.Credential.UserName), - /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(this.remoteRunspaceInfo.ComputerName)); + /* 2 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential.UserName), + /* 3 */ CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.ComputerName)); } } @@ -2711,7 +2711,7 @@ function Get-PSImplicitRemotingSession private string GenerateCertificateThumbprintParameter() { - if (this.remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint == null) { return string.Empty; } @@ -2720,7 +2720,7 @@ function Get-PSImplicitRemotingSession return string.Format( CultureInfo.InvariantCulture, CertificateThumbprintParameterTemplate, - CodeGeneration.EscapeSingleQuotedStringContent(this.remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint)); + CodeGeneration.EscapeSingleQuotedStringContent(_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint)); } } @@ -3051,7 +3051,7 @@ function Get-PSImplicitRemotingClientSideParameters X509Certificate2 certificate) { List result = new List(); - + Dbg.Assert(moduleRootDirectory != null, "Caller should validate moduleRootDirectory != null"); Dbg.Assert(Directory.Exists(moduleRootDirectory.FullName), "Caller should validate moduleRootDirectory exists"); Dbg.Assert(encoding != null, "Caller should validate encoding != null"); @@ -3122,7 +3122,7 @@ function Get-PSImplicitRemotingClientSideParameters string message = StringUtil.Format(ImplicitRemotingStrings.InvalidSigningOperation, currentFile); throw new PSInvalidOperationException(message, e); } - } + } } result.Add(baseName + ".psd1"); @@ -3143,7 +3143,7 @@ function Get-PSImplicitRemotingClientSideParameters { string applicationArgumentsFile = Path.Combine(moduleRootDirectory.FullName, "ApplicationArguments.xml"); result.Add(applicationArgumentsFile); - + using (XmlWriter xw = XmlTextWriter.Create(applicationArgumentsFile)) { Serializer serializer = new Serializer(xw); @@ -3155,5 +3155,4 @@ function Get-PSImplicitRemotingClientSideParameters return result; } } - } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index c2c65f557..a1d067404 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Globalization; using System.IO; @@ -112,12 +113,12 @@ namespace Microsoft.PowerShell.Commands } set { - setSupportedCommand = true; + _setSupportedCommand = true; _commandsAllowed = value; } } private string[] _commandsAllowed = new string[] { "ConvertFrom-StringData" }; - private bool setSupportedCommand = false; + private bool _setSupportedCommand = false; #endregion Parameters @@ -149,7 +150,7 @@ namespace Microsoft.PowerShell.Commands // Prevent additional commands in ConstrainedLanguage mode if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if (setSupportedCommand) + if (_setSupportedCommand) { NotSupportedException nse = PSTraceSource.NewNotSupportedException( @@ -276,8 +277,8 @@ namespace Microsoft.PowerShell.Commands fileName = Path.GetFileNameWithoutExtension(fileName); - CultureInfo culture = null; - if(_uiculture == null) + CultureInfo culture = null; + if (_uiculture == null) { culture = CultureInfo.CurrentUICulture; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 508e04bc0..05b95f039 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -31,20 +32,20 @@ namespace Microsoft.PowerShell.Commands /// The path from which to import the aliases /// /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string Path { get { - return path; + return _path; } set { - path = value; + _path = value; } } - private string path; + private string _path; /// /// The literal path from which to import the aliases @@ -56,12 +57,12 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; + _path = value; } } @@ -75,15 +76,15 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } set { - scope = value; + _scope = value; } } - private string scope; + private string _scope; /// /// If set to true, the alias that is set is passed to the @@ -95,15 +96,15 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; /// /// If set to true and an existing alias of the same name exists @@ -115,15 +116,15 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; #endregion Parameters @@ -254,14 +255,14 @@ namespace Microsoft.PowerShell.Commands } } // ProcessRecord - private Dictionary existingCommands; + private Dictionary _existingCommands; private Dictionary ExistingCommands { get { - if (existingCommands == null) + if (_existingCommands == null) { - existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); + _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); CommandSearcher searcher = new CommandSearcher( "*", SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, @@ -270,19 +271,19 @@ namespace Microsoft.PowerShell.Commands foreach (CommandInfo commandInfo in searcher) { - existingCommands[commandInfo.Name] = commandInfo.CommandType; + _existingCommands[commandInfo.Name] = commandInfo.CommandType; } // Also add commands from the analysis cache foreach (CommandInfo commandInfo in System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands("*", this.Context, this.MyInvocation.CommandOrigin)) { - if (!existingCommands.ContainsKey(commandInfo.Name)) + if (!_existingCommands.ContainsKey(commandInfo.Name)) { - existingCommands[commandInfo.Name] = commandInfo.CommandType; + _existingCommands[commandInfo.Name] = commandInfo.CommandType; } } } - return existingCommands; + return _existingCommands; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeCommandCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeCommandCmdlet.cs index 6ba1f039d..38ff82fcc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeCommandCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeCommandCmdlet.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet("Invoke", "Expression", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113343")] public sealed - class + class InvokeExpressionCommand : PSCmdlet { #region parameters @@ -33,7 +33,7 @@ namespace Microsoft.PowerShell.Commands { Diagnostics.Assert(null != Command, "Command is null"); - ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock( Command); + ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command); // If the runspace has ever been in ConstrainedLanguage, lock down this // invocation as well - it is too easy for the command to be negatively influenced @@ -45,13 +45,13 @@ namespace Microsoft.PowerShell.Commands var emptyArray = Utils.EmptyArray(); myScriptBlock.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, + contextCmdlet: this, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: emptyArray, - scriptThis: AutomationNull.Value, - args: emptyArray); + dollarUnder: AutomationNull.Value, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); } } } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 2bf94a400..57a2561e2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text.RegularExpressions; using System.IO; @@ -35,10 +36,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] PreContext { - get { return preContext; } - set { preContext = value; } + get { return _preContext; } + set { _preContext = value; } } - private string[] preContext; + private string[] _preContext; /// /// Lines found after a match. @@ -47,10 +48,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] PostContext { - get { return postContext; } - set { postContext = value; } + get { return _postContext; } + set { _postContext = value; } } - private string[] postContext; + private string[] _postContext; /// /// Lines found before a match. Does not include @@ -61,10 +62,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] DisplayPreContext { - get { return displayPreContext; } - set { displayPreContext = value; } + get { return _displayPreContext; } + set { _displayPreContext = value; } } - private string[] displayPreContext; + private string[] _displayPreContext; /// /// Lines found after a match. Does not include @@ -75,10 +76,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] DisplayPostContext { - get { return displayPostContext; } - set { displayPostContext = value; } + get { return _displayPostContext; } + set { _displayPostContext = value; } } - private string[] displayPostContext; + private string[] _displayPostContext; /// /// Produce a deep copy of this object. @@ -86,10 +87,10 @@ namespace Microsoft.PowerShell.Commands public object Clone() { MatchInfoContext clone = new MatchInfoContext(); - clone.PreContext = (clone.PreContext != null) ? (string[]) PreContext.Clone() : null; - clone.PostContext = (clone.PostContext != null) ? (string[]) PostContext.Clone() : null; - clone.DisplayPreContext = (clone.DisplayPreContext != null) ? (string[]) DisplayPreContext.Clone() : null; - clone.DisplayPostContext = (clone.DisplayPostContext != null) ? (string[]) DisplayPostContext.Clone() : null; + clone.PreContext = (clone.PreContext != null) ? (string[])PreContext.Clone() : null; + clone.PostContext = (clone.PostContext != null) ? (string[])PostContext.Clone() : null; + clone.DisplayPreContext = (clone.DisplayPreContext != null) ? (string[])DisplayPreContext.Clone() : null; + clone.DisplayPostContext = (clone.DisplayPostContext != null) ? (string[])DisplayPostContext.Clone() : null; return clone; } } @@ -99,7 +100,7 @@ namespace Microsoft.PowerShell.Commands /// public class MatchInfo { - private static string inputStream = "InputStream"; + private static string s_inputStream = "InputStream"; /// /// Indicates if the match was done ignoring case. @@ -109,14 +110,14 @@ namespace Microsoft.PowerShell.Commands { get { - return ignoreCase; + return _ignoreCase; } set { - ignoreCase = value; + _ignoreCase = value; } } - private bool ignoreCase; + private bool _ignoreCase; /// /// Returns the number of the matching line. @@ -126,14 +127,14 @@ namespace Microsoft.PowerShell.Commands { get { - return lineNumber; + return _lineNumber; } set { - lineNumber = value; + _lineNumber = value; } } - private int lineNumber; + private int _lineNumber; /// /// Returns the text of the matching line. @@ -143,14 +144,14 @@ namespace Microsoft.PowerShell.Commands { get { - return line; + return _line; } set { - line = value; + _line = value; } } - private string line = ""; + private string _line = ""; /// /// Returns the base name of the file containing the matching line. @@ -164,14 +165,14 @@ namespace Microsoft.PowerShell.Commands { get { - if (!pathSet) - return inputStream; - if (filename == null) - filename = System.IO.Path.GetFileName(path); - return filename; + if (!_pathSet) + return s_inputStream; + if (_filename == null) + _filename = System.IO.Path.GetFileName(_path); + return _filename; } } - private string filename; + private string _filename; /// @@ -185,18 +186,18 @@ namespace Microsoft.PowerShell.Commands { get { - if (!pathSet) - return inputStream; - return path; + if (!_pathSet) + return s_inputStream; + return _path; } set { - path = value; - pathSet = true; + _path = value; + _pathSet = true; } } - private string path = inputStream; - private bool pathSet; + private string _path = s_inputStream; + private bool _pathSet; /// /// Returns the pattern that was used in the match. @@ -206,14 +207,14 @@ namespace Microsoft.PowerShell.Commands { get { - return pattern; + return _pattern; } set { - pattern = value; + _pattern = value; } } - private string pattern; + private string _pattern; /// /// The context for the match, or null if -context was not @@ -223,14 +224,14 @@ namespace Microsoft.PowerShell.Commands { get { - return context; + return _context; } set { - context = value; + _context = value; } } - private MatchInfoContext context; + private MatchInfoContext _context; /// /// Returns the path of the matching file truncated relative to the parameter. @@ -243,10 +244,10 @@ namespace Microsoft.PowerShell.Commands /// The relative path that was produced. public string RelativePath(string directory) { - if (!this.pathSet) + if (!_pathSet) return this.Path; - string relPath = this.path; + string relPath = _path; if (!String.IsNullOrEmpty(directory)) { if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase)) @@ -297,13 +298,13 @@ namespace Microsoft.PowerShell.Commands /// The string representation of the match object public string ToString(string directory) { - string displayPath = (directory != null) ? RelativePath(directory) : this.path; + string displayPath = (directory != null) ? RelativePath(directory) : _path; // Just return a single line if the user didn't // enable context-tracking. if (Context == null) { - return FormatLine(this.line, this.LineNumber, displayPath, EmptyPrefix); + return FormatLine(_line, this.LineNumber, displayPath, EmptyPrefix); } // Otherwise, render the full context. @@ -315,7 +316,7 @@ namespace Microsoft.PowerShell.Commands lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix)); } - lines.Add(FormatLine(this.line, displayLineNumber++, displayPath, MatchPrefix)); + lines.Add(FormatLine(_line, displayLineNumber++, displayPath, MatchPrefix)); foreach (string contextLine in Context.DisplayPostContext) { @@ -335,7 +336,7 @@ namespace Microsoft.PowerShell.Commands /// The formatted line as a string. private string FormatLine(string lineStr, int displayLineNumber, string displayPath, string prefix) { - if (pathSet) + if (_pathSet) return StringUtil.Format(MatchFormat, prefix, displayPath, displayLineNumber, lineStr); else return StringUtil.Format(SimpleFormat, prefix, lineStr); @@ -349,14 +350,14 @@ namespace Microsoft.PowerShell.Commands { get { - return matches; + return _matches; } set { - matches = value; + _matches = value; } } - private Match[] matches = new Match[]{}; + private Match[] _matches = new Match[] { }; /// /// Create a deep copy of this MatchInfo instance. @@ -365,16 +366,16 @@ namespace Microsoft.PowerShell.Commands { // Just do a shallow copy and then deep-copy the // fields that need it. - MatchInfo clone = (MatchInfo) this.MemberwiseClone(); + MatchInfo clone = (MatchInfo)this.MemberwiseClone(); if (clone.Context != null) { - clone.Context = (MatchInfoContext) clone.Context.Clone(); + clone.Context = (MatchInfoContext)clone.Context.Clone(); } // Regex match objects are immutable, so we can get away // with just copying the array. - clone.Matches = (Match[]) clone.Matches.Clone(); + clone.Matches = (Match[])clone.Matches.Clone(); return clone; } @@ -393,13 +394,13 @@ namespace Microsoft.PowerShell.Commands private class CircularBuffer : ICollection { // Ring of items - private T[] items; + private T[] _items; // Current length, as opposed to the total capacity - private int length; + private int _length; // Current start of the list. Starts at 0, but may // move forwards or wrap around back to 0 due to // rotation. - private int firstIndex; + private int _firstIndex; /// /// Construct a new buffer of the specified capacity. @@ -411,7 +412,7 @@ namespace Microsoft.PowerShell.Commands if (capacity < 0) throw new ArgumentOutOfRangeException("capacity"); - items = new T[capacity]; + _items = new T[capacity]; Clear(); } @@ -425,7 +426,7 @@ namespace Microsoft.PowerShell.Commands { get { - return items.Length; + return _items.Length; } } @@ -436,10 +437,10 @@ namespace Microsoft.PowerShell.Commands { get { - return length == Capacity; + return _length == Capacity; } } - + /// /// Convert from a 0-based index to a buffer index which /// has been properly offset and wrapped. @@ -457,15 +458,15 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentOutOfRangeException("zeroBasedIndex"); } - return (zeroBasedIndex + firstIndex) % Capacity; + return (zeroBasedIndex + _firstIndex) % Capacity; } - + #region IEnumerable implementation. public IEnumerator GetEnumerator() { - for (int i = 0; i < length; i++) + for (int i = 0; i < _length; i++) { - yield return items[WrapIndex(i)]; + yield return _items[WrapIndex(i)]; } } @@ -480,7 +481,7 @@ namespace Microsoft.PowerShell.Commands { get { - return length; + return _length; } } @@ -509,22 +510,22 @@ namespace Microsoft.PowerShell.Commands if (IsFull) { - itemIndex = firstIndex; - firstIndex = (firstIndex + 1) % Capacity; + itemIndex = _firstIndex; + _firstIndex = (_firstIndex + 1) % Capacity; } else { - itemIndex = firstIndex + length; - length++; + itemIndex = _firstIndex + _length; + _length++; } - items[itemIndex] = item; + _items[itemIndex] = item; } public void Clear() { - firstIndex = 0; - length = 0; + _firstIndex = 0; + _length = 0; } public bool Contains(T item) @@ -542,9 +543,9 @@ namespace Microsoft.PowerShell.Commands if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex"); - if (length > (array.Length - arrayIndex)) + if (_length > (array.Length - arrayIndex)) throw new ArgumentException("arrayIndex"); - + // Iterate through the buffer in correct order. foreach (T item in this) { @@ -585,7 +586,7 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentOutOfRangeException("index"); } - return items[WrapIndex(index)]; + return _items[WrapIndex(index)]; } } } @@ -633,20 +634,20 @@ namespace Microsoft.PowerShell.Commands CollectPost, } - private ContextState contextState = ContextState.InitialState; - private int preContext = 0; - private int postContext = 0; + private ContextState _contextState = ContextState.InitialState; + private int _preContext = 0; + private int _postContext = 0; // The context leading up to the match. - private CircularBuffer collectedPreContext = null; + private CircularBuffer _collectedPreContext = null; // The context after the match. - private List collectedPostContext = null; + private List _collectedPostContext = null; // Current match info we are tracking postcontext for. // At any given time, if set, this value will not be // in the emitQueue but will be the next to be added. - private MatchInfo matchInfo = null; + private MatchInfo _matchInfo = null; /// /// Constructor for DisplayContextTracker. @@ -655,12 +656,12 @@ namespace Microsoft.PowerShell.Commands /// How much precontext to collect at most. public DisplayContextTracker(int preContext, int postContext) { - this.preContext = preContext; - this.postContext = postContext; + _preContext = preContext; + _postContext = postContext; - collectedPreContext = new CircularBuffer(preContext); - collectedPostContext = new List(postContext); - emitQueue = new List(); + _collectedPreContext = new CircularBuffer(preContext); + _collectedPostContext = new List(postContext); + _emitQueue = new List(); Reset(); } @@ -669,26 +670,26 @@ namespace Microsoft.PowerShell.Commands { get { - return emitQueue; + return _emitQueue; } } - private List emitQueue = null; + private List _emitQueue = null; // Track non-matching line public void TrackLine(string line) { - switch (contextState) + switch (_contextState) { case ContextState.InitialState: break; case ContextState.CollectPre: - collectedPreContext.Add(line); + _collectedPreContext.Add(line); break; case ContextState.CollectPost: // We're not done collecting post-context. - collectedPostContext.Add(line); + _collectedPostContext.Add(line); - if (collectedPostContext.Count >= postContext) + if (_collectedPostContext.Count >= _postContext) { // Now we're done. UpdateQueue(); @@ -702,22 +703,22 @@ namespace Microsoft.PowerShell.Commands { // Update the queue in case we were in the middle // of collecting postcontext for an older match... - if (contextState == ContextState.CollectPost) + if (_contextState == ContextState.CollectPost) UpdateQueue(); // Update the current matchInfo. - matchInfo = match; + _matchInfo = match; // If postContext is set, then we need to hold // onto the match for a while and gather context. // Otherwise, immediately move the match onto the queue // and let UpdateQueue update our state instead. - if (postContext > 0) - contextState = ContextState.CollectPost; + if (_postContext > 0) + _contextState = ContextState.CollectPost; else UpdateQueue(); } - + // Track having reached the end of the file. public void TrackEOF() { @@ -725,7 +726,7 @@ namespace Microsoft.PowerShell.Commands // already have a match and it's okay to queue it up // early since there are no more lines to track context // for. - if (contextState == ContextState.CollectPost) + if (_contextState == ContextState.CollectPost) UpdateQueue(); } #endregion @@ -736,14 +737,14 @@ namespace Microsoft.PowerShell.Commands /// private void UpdateQueue() { - if (matchInfo != null) + if (_matchInfo != null) { - emitQueue.Add(matchInfo); + _emitQueue.Add(_matchInfo); - if (matchInfo.Context != null) + if (_matchInfo.Context != null) { - matchInfo.Context.DisplayPreContext = collectedPreContext.ToArray(); - matchInfo.Context.DisplayPostContext = collectedPostContext.ToArray(); + _matchInfo.Context.DisplayPreContext = _collectedPreContext.ToArray(); + _matchInfo.Context.DisplayPostContext = _collectedPostContext.ToArray(); } Reset(); } @@ -752,12 +753,12 @@ namespace Microsoft.PowerShell.Commands // Reset tracking state. Does not reset the emit queue. private void Reset() { - contextState = (preContext > 0) + _contextState = (_preContext > 0) ? ContextState.CollectPre : ContextState.InitialState; - collectedPreContext.Clear(); - collectedPostContext.Clear(); - matchInfo = null; + _collectedPreContext.Clear(); + _collectedPostContext.Clear(); + _matchInfo = null; } } @@ -806,10 +807,10 @@ namespace Microsoft.PowerShell.Commands // while still filling up the context buffer // have been added to the emit queue. // Used by UpdateQueue. - private bool hasProcessedPreEntries = false; + private bool _hasProcessedPreEntries = false; - private int preContext; - private int postContext; + private int _preContext; + private int _postContext; // A circular buffer tracking both precontext and postcontext. // // Essentially, the buffer is separated into regions: @@ -823,7 +824,7 @@ namespace Microsoft.PowerShell.Commands // enough context to populate the Context properties of the // match. At that point, we will add the match object // to the emit queue. - private CircularBuffer collectedContext = null; + private CircularBuffer _collectedContext = null; /// /// Constructor for LogicalContextTracker. @@ -832,10 +833,10 @@ namespace Microsoft.PowerShell.Commands /// How much postcontext to collect at most. public LogicalContextTracker(int preContext, int postContext) { - this.preContext = preContext; - this.postContext = postContext; - collectedContext = new CircularBuffer(preContext + postContext + 1); - emitQueue = new List(); + _preContext = preContext; + _postContext = postContext; + _collectedContext = new CircularBuffer(preContext + postContext + 1); + _emitQueue = new List(); } #region IContextTracker implementation @@ -843,22 +844,22 @@ namespace Microsoft.PowerShell.Commands { get { - return emitQueue; + return _emitQueue; } } - private List emitQueue = null; + private List _emitQueue = null; public void TrackLine(string line) { ContextEntry entry = new ContextEntry(line); - collectedContext.Add(entry); + _collectedContext.Add(entry); UpdateQueue(); } public void TrackMatch(MatchInfo match) { ContextEntry entry = new ContextEntry(match); - collectedContext.Add(entry); + _collectedContext.Add(entry); UpdateQueue(); } @@ -875,8 +876,8 @@ namespace Microsoft.PowerShell.Commands // ever been emitted and everything is still waiting // on postcontext. So process the whole buffer. - int startIndex = (collectedContext.IsFull) ? preContext + 1 : 0; - EmitAllInRange(startIndex, collectedContext.Count - 1); + int startIndex = (_collectedContext.IsFull) ? _preContext + 1 : 0; + EmitAllInRange(startIndex, _collectedContext.Count - 1); } #endregion @@ -895,11 +896,11 @@ namespace Microsoft.PowerShell.Commands { for (int i = startIndex; i <= endIndex; i++) { - MatchInfo match = collectedContext[i].Match; + MatchInfo match = _collectedContext[i].Match; if (match != null) { - int preStart = Math.Max(i - preContext, 0); - int postLength = Math.Min(postContext, collectedContext.Count - i - 1); + int preStart = Math.Max(i - _preContext, 0); + int postLength = Math.Min(_postContext, _collectedContext.Count - i - 1); Emit(match, preStart, i - preStart, i + 1, postLength); } } @@ -922,20 +923,20 @@ namespace Microsoft.PowerShell.Commands // have entries that never collected enough // precontext. Otherwise, we should just look at the // middle region. - if (collectedContext.IsFull) + if (_collectedContext.IsFull) { - if (hasProcessedPreEntries) + if (_hasProcessedPreEntries) { // Only process a potential match with exactly // enough pre and post-context. - EmitAllInRange(preContext, preContext); + EmitAllInRange(_preContext, _preContext); } else { // Some of our early entries may not // have enough precontext. Process them too. - EmitAllInRange(0, preContext); - hasProcessedPreEntries = true; + EmitAllInRange(0, _preContext); + _hasProcessedPreEntries = true; } } } @@ -962,7 +963,7 @@ namespace Microsoft.PowerShell.Commands match.Context.PostContext = CopyContext(postStartIndex, postLength); } - emitQueue.Add(match); + _emitQueue.Add(match); } /// @@ -979,7 +980,7 @@ namespace Microsoft.PowerShell.Commands for (int i = 0; i < length; i++) { - result[i] = collectedContext[startIndex + i].ToString(); + result[i] = _collectedContext[startIndex + i].ToString(); } return result; @@ -991,8 +992,8 @@ namespace Microsoft.PowerShell.Commands /// private class ContextTracker : IContextTracker { - private IContextTracker displayTracker; - private IContextTracker logicalTracker; + private IContextTracker _displayTracker; + private IContextTracker _logicalTracker; /// /// Constructor for LogicalContextTracker. @@ -1001,9 +1002,9 @@ namespace Microsoft.PowerShell.Commands /// How much postcontext to collect at most. public ContextTracker(int preContext, int postContext) { - displayTracker = new DisplayContextTracker(preContext, postContext); - logicalTracker = new LogicalContextTracker(preContext, postContext); - emitQueue = new List(); + _displayTracker = new DisplayContextTracker(preContext, postContext); + _logicalTracker = new LogicalContextTracker(preContext, postContext); + _emitQueue = new List(); } #region IContextTracker implementation @@ -1011,29 +1012,29 @@ namespace Microsoft.PowerShell.Commands { get { - return emitQueue; + return _emitQueue; } } - private IList emitQueue; + private IList _emitQueue; public void TrackLine(string line) { - displayTracker.TrackLine(line); - logicalTracker.TrackLine(line); + _displayTracker.TrackLine(line); + _logicalTracker.TrackLine(line); UpdateQueue(); } public void TrackMatch(MatchInfo match) { - displayTracker.TrackMatch(match); - logicalTracker.TrackMatch(match); + _displayTracker.TrackMatch(match); + _logicalTracker.TrackMatch(match); UpdateQueue(); } public void TrackEOF() { - displayTracker.TrackEOF(); - logicalTracker.TrackEOF(); + _displayTracker.TrackEOF(); + _logicalTracker.TrackEOF(); UpdateQueue(); } #endregion @@ -1053,13 +1054,13 @@ namespace Microsoft.PowerShell.Commands // be sure the matches will have both logical // and display context already populated. - foreach (MatchInfo match in logicalTracker.EmitQueue) + foreach (MatchInfo match in _logicalTracker.EmitQueue) { - emitQueue.Add(match); + _emitQueue.Add(match); } - logicalTracker.EmitQueue.Clear(); - displayTracker.EmitQueue.Clear(); + _logicalTracker.EmitQueue.Clear(); + _displayTracker.EmitQueue.Clear(); } } @@ -1071,15 +1072,16 @@ namespace Microsoft.PowerShell.Commands [AllowEmptyString] public PSObject InputObject { - get { - return inputObject; + get + { + return _inputObject; } set { - inputObject = LanguagePrimitives.IsNull(value) ? PSObject.AsPSObject("") : value; + _inputObject = LanguagePrimitives.IsNull(value) ? PSObject.AsPSObject("") : value; } } - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// /// String index to start from the beginning. @@ -1091,15 +1093,17 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, Position = 0)] public string[] Pattern { - get { - return pattern; + get + { + return _pattern; } - set { - pattern = value; + set + { + _pattern = value; } } - private string[] pattern; - private Regex[] regexPattern; + private string[] _pattern; + private Regex[] _regexPattern; /// /// file to read from @@ -1109,14 +1113,16 @@ namespace Microsoft.PowerShell.Commands [FileinfoToString] public string[] Path { - get { - return fullName; + get + { + return _fullName; } - set { - fullName = value; + set + { + _fullName = value; } } - private string[] fullName; + private string[] _fullName; /// /// Literal file to read from @@ -1130,15 +1136,15 @@ namespace Microsoft.PowerShell.Commands { get { - return fullName; + return _fullName; } set { - fullName = value; - isLiteralPath = true; + _fullName = value; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; /// If set, match pattern string literally. /// If not (default) search using pattern as a Regular Expression @@ -1146,14 +1152,16 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter SimpleMatch { - get { - return simpleMatch; + get + { + return _simpleMatch; } - set { - simpleMatch = value; + set + { + _simpleMatch = value; } } - private bool simpleMatch; + private bool _simpleMatch; /// /// If true, then do case-sensitive searches... @@ -1161,14 +1169,16 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter CaseSensitive { - get { - return caseSensitive; + get + { + return _caseSensitive; } - set { - caseSensitive = value; + set + { + _caseSensitive = value; } } - private bool caseSensitive; + private bool _caseSensitive; /// /// If true the cmdlet will stop processing at the first successful match and @@ -1179,14 +1189,14 @@ namespace Microsoft.PowerShell.Commands { get { - return quiet; + return _quiet; } set { - quiet = value; + _quiet = value; } } - private bool quiet; + private bool _quiet; /// /// list files where a match is found @@ -1199,14 +1209,14 @@ namespace Microsoft.PowerShell.Commands { get { - return list; + return _list; } set - { - list = value; + { + _list = value; } } - private bool list; + private bool _list; /// /// Lets you include particular files. Files not matching @@ -1284,14 +1294,14 @@ namespace Microsoft.PowerShell.Commands { get { - return notMatch; + return _notMatch; } set - { - notMatch = value; + { + _notMatch = value; } } - private bool notMatch; + private bool _notMatch; /// /// If set, sets the Matches property of MatchInfo to the result @@ -1305,14 +1315,14 @@ namespace Microsoft.PowerShell.Commands { get { - return allMatches; + return _allMatches; } set - { - allMatches = value; + { + _allMatches = value; } } - private bool allMatches; + private bool _allMatches; /// /// The text encoding to process each file as. @@ -1332,15 +1342,15 @@ namespace Microsoft.PowerShell.Commands { get { - return encoding; + return _encoding; } set { - encoding = value; + _encoding = value; } } - private string encoding; - private System.Text.Encoding textEncoding; + private string _encoding; + private System.Text.Encoding _textEncoding; /// /// The number of context lines to collect. If set to a @@ -1358,7 +1368,7 @@ namespace Microsoft.PowerShell.Commands { get { - return context; + return _context; } set { @@ -1369,23 +1379,23 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("value"); } - context = value; + _context = value; - if (context.Length == 1) + if (_context.Length == 1) { - preContext = context[0]; - postContext = context[0]; + _preContext = _context[0]; + _postContext = _context[0]; } - else if (context.Length >= 2) + else if (_context.Length >= 2) { - preContext = context[0]; - postContext = context[1]; + _preContext = _context[0]; + _postContext = _context[1]; } } } - private int[] context; - private int preContext = 0; - private int postContext = 0; + private int[] _context; + private int _preContext = 0; + private int _postContext = 0; // This context tracker is only used for strings which are piped // directly into the cmdlet. File processing doesn't need @@ -1394,15 +1404,15 @@ namespace Microsoft.PowerShell.Commands // use a single global tracker for both is that in the case of // a mixed list of strings and FileInfo, the context tracker // would get reset after each file. - private ContextTracker globalContextTracker = null; + private ContextTracker _globalContextTracker = null; /// /// This is used to handle the case were we're done processing input objects. /// If true, process record will just return. /// - private bool doneProcessing; + private bool _doneProcessing; - private int inputRecordNumber; + private int _inputRecordNumber; /// /// Read command line parameters. @@ -1410,34 +1420,34 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // Process encoding switch. - if (encoding != null) + if (_encoding != null) { - textEncoding = EncodingConversion.Convert (this, encoding); + _textEncoding = EncodingConversion.Convert(this, _encoding); } else { - textEncoding = new System.Text.UTF8Encoding(); + _textEncoding = new System.Text.UTF8Encoding(); } - if (!simpleMatch) + if (!_simpleMatch) { - RegexOptions regexOptions = (caseSensitive) ? RegexOptions.None : RegexOptions.IgnoreCase; - regexPattern = new Regex[pattern.Length]; - for (int i = 0; i < pattern.Length; i++) + RegexOptions regexOptions = (_caseSensitive) ? RegexOptions.None : RegexOptions.IgnoreCase; + _regexPattern = new Regex[_pattern.Length]; + for (int i = 0; i < _pattern.Length; i++) { try { - regexPattern[i] = new Regex(pattern[i], regexOptions); + _regexPattern[i] = new Regex(_pattern[i], regexOptions); } catch (Exception e) { - this.ThrowTerminatingError(BuildErrorRecord(MatchStringStrings.InvalidRegex, pattern[i], e.Message, "InvalidRegex", e)); + this.ThrowTerminatingError(BuildErrorRecord(MatchStringStrings.InvalidRegex, _pattern[i], e.Message, "InvalidRegex", e)); throw; } } } - globalContextTracker = new ContextTracker(preContext, postContext); + _globalContextTracker = new ContextTracker(_preContext, _postContext); } /// @@ -1451,19 +1461,19 @@ namespace Microsoft.PowerShell.Commands /// A file cannot be found. protected override void ProcessRecord() { - if (doneProcessing) + if (_doneProcessing) return; List expandedPaths = null; - if (fullName != null) + if (_fullName != null) { - expandedPaths = ResolveFilePaths(fullName, isLiteralPath); + expandedPaths = ResolveFilePaths(_fullName, _isLiteralPath); if (expandedPaths == null) return; } else { - FileInfo fileInfo = inputObject.BaseObject as FileInfo; + FileInfo fileInfo = _inputObject.BaseObject as FileInfo; if (fileInfo != null) { expandedPaths = new List(); @@ -1476,14 +1486,14 @@ namespace Microsoft.PowerShell.Commands foreach (string filename in expandedPaths) { bool foundMatch = ProcessFile(filename); - if (quiet && foundMatch) + if (_quiet && foundMatch) return; } // No results in any files. - if (quiet) + if (_quiet) { - if (list) + if (_list) WriteObject(null); else WriteObject(false); @@ -1492,20 +1502,20 @@ namespace Microsoft.PowerShell.Commands else { // Set the line number in the matched object to be the record number - inputRecordNumber++; + _inputRecordNumber++; bool matched; MatchInfo result; MatchInfo matchInfo = null; - var line = inputObject.BaseObject as string; + var line = _inputObject.BaseObject as string; if (line != null) { matched = doMatch(line, out result); } else { - matchInfo = inputObject.BaseObject as MatchInfo; - object objectToCheck = matchInfo ?? (object) inputObject; + matchInfo = _inputObject.BaseObject as MatchInfo; + object objectToCheck = matchInfo ?? (object)_inputObject; matched = doMatch(objectToCheck, out result, out line); } @@ -1514,23 +1524,23 @@ namespace Microsoft.PowerShell.Commands // Don't re-write the line number if it was already set... if (matchInfo == null) { - result.LineNumber = inputRecordNumber; + result.LineNumber = _inputRecordNumber; } // doMatch will have already set the pattern and line text... - globalContextTracker.TrackMatch(result); + _globalContextTracker.TrackMatch(result); } else { - globalContextTracker.TrackLine(line); + _globalContextTracker.TrackLine(line); } // Emit any queued up objects... - if (FlushTrackerQueue(globalContextTracker)) + if (FlushTrackerQueue(_globalContextTracker)) { // If we're in quiet mode, go ahead and stop processing // now. - if (quiet) - doneProcessing = true; + if (_quiet) + _doneProcessing = true; } } } @@ -1543,7 +1553,7 @@ namespace Microsoft.PowerShell.Commands /// True if a match was found; otherwise false. private bool ProcessFile(string filename) { - ContextTracker contextTracker = new ContextTracker(preContext, postContext); + ContextTracker contextTracker = new ContextTracker(_preContext, _postContext); bool foundMatch = false; @@ -1556,7 +1566,7 @@ namespace Microsoft.PowerShell.Commands using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - using (StreamReader sr = new StreamReader(fs, textEncoding)) + using (StreamReader sr = new StreamReader(fs, _textEncoding)) { String line; int lineNo = 0; @@ -1591,7 +1601,7 @@ namespace Microsoft.PowerShell.Commands // the result so the downstream cmdlet can actually manipulate the file // that was found. - if (quiet || list) + if (_quiet || _list) { break; } @@ -1631,7 +1641,7 @@ namespace Microsoft.PowerShell.Commands return foundMatch; } - + /// /// Emit any objects which have been queued up, and clear /// the queue. @@ -1645,11 +1655,11 @@ namespace Microsoft.PowerShell.Commands return false; // If -quiet is specified but not -list return true on first match - if (quiet && !list) + if (_quiet && !_list) { WriteObject(true); } - else if (list) + else if (_list) { WriteObject(contextTracker.EmitQueue[0]); } @@ -1672,9 +1682,9 @@ namespace Microsoft.PowerShell.Commands protected override void EndProcessing() { // Check for a leftover match that was still tracking context. - globalContextTracker.TrackEOF(); - if (!doneProcessing) - FlushTrackerQueue(globalContextTracker); + _globalContextTracker.TrackEOF(); + if (!_doneProcessing) + FlushTrackerQueue(_globalContextTracker); } private bool doMatch(string operandString, out MatchInfo matchResult) @@ -1696,11 +1706,11 @@ namespace Microsoft.PowerShell.Commands // objects to use the new settings. operandString = matchInfo.Line; - if (preContext > 0 || postContext > 0) + if (_preContext > 0 || _postContext > 0) { - preContext = 0; - postContext = 0; - globalContextTracker = new ContextTracker(preContext, postContext); + _preContext = 0; + _postContext = 0; + _globalContextTracker = new ContextTracker(_preContext, _postContext); WarnFilterContext(); } } @@ -1730,16 +1740,16 @@ namespace Microsoft.PowerShell.Commands int patternIndex = 0; matchResult = null; - if (!simpleMatch) + if (!_simpleMatch) { - while (patternIndex < pattern.Length) + while (patternIndex < _pattern.Length) { - Regex r = regexPattern[patternIndex]; - + Regex r = _regexPattern[patternIndex]; + // Only honor allMatches if notMatch is not set, // since it's a fairly expensive operation and // notMatch takes precedent over allMatch. - if (allMatches && !notMatch) + if (_allMatches && !_notMatch) { MatchCollection mc = r.Matches(operandString); if (mc.Count > 0) @@ -1748,7 +1758,9 @@ namespace Microsoft.PowerShell.Commands ((ICollection)mc).CopyTo(matches, 0); gotMatch = true; } - } else { + } + else + { Match match = r.Match(operandString); gotMatch = match.Success; @@ -1766,11 +1778,11 @@ namespace Microsoft.PowerShell.Commands } else { - StringComparison compareOption = caseSensitive ? + StringComparison compareOption = _caseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; - while (patternIndex < pattern.Length) + while (patternIndex < _pattern.Length) { - string pat = pattern[patternIndex]; + string pat = _pattern[patternIndex]; if (operandString.IndexOf(pat, compareOption) >= 0) { @@ -1782,7 +1794,7 @@ namespace Microsoft.PowerShell.Commands } } - if (notMatch) + if (_notMatch) { gotMatch = !gotMatch; // If notMatch was specified with multiple @@ -1808,9 +1820,11 @@ namespace Microsoft.PowerShell.Commands if (matchInfo.Context != null) { matchResult = matchInfo.Clone(); - matchResult.Context.DisplayPreContext = new string[] {}; - matchResult.Context.DisplayPostContext = new string[] {}; - } else { + matchResult.Context.DisplayPreContext = new string[] { }; + matchResult.Context.DisplayPostContext = new string[] { }; + } + else + { // Otherwise, just pass the object as is. matchResult = matchInfo; } @@ -1820,18 +1834,18 @@ namespace Microsoft.PowerShell.Commands // otherwise construct and populate a new MatchInfo object matchResult = new MatchInfo(); - matchResult.IgnoreCase = !this.caseSensitive; + matchResult.IgnoreCase = !_caseSensitive; matchResult.Line = operandString; - matchResult.Pattern = pattern[patternIndex]; + matchResult.Pattern = _pattern[patternIndex]; - if (preContext > 0 || postContext > 0) + if (_preContext > 0 || _postContext > 0) { matchResult.Context = new MatchInfoContext(); } // Matches should be an empty list, rather than null, // in the cases of notMatch and simpleMatch. - matchResult.Matches = (matches != null) ? matches : new Match[] {}; + matchResult.Matches = (matches != null) ? matches : new Match[] { }; return true; } @@ -1873,12 +1887,12 @@ namespace Microsoft.PowerShell.Commands private static ErrorRecord BuildErrorRecord(string messageId, string argument, string errorId, Exception innerException) { - return BuildErrorRecord(messageId, new object[] {argument}, errorId, innerException); + return BuildErrorRecord(messageId, new object[] { argument }, errorId, innerException); } private static ErrorRecord BuildErrorRecord(string messageId, string arg0, string arg1, string errorId, Exception innerException) { - return BuildErrorRecord(messageId, new object[] {arg0, arg1}, errorId, innerException); + return BuildErrorRecord(messageId, new object[] { arg0, arg1 }, errorId, innerException); } private static ErrorRecord BuildErrorRecord(string messageId, object[] arguments, string errorId, Exception innerException) @@ -1887,7 +1901,7 @@ namespace Microsoft.PowerShell.Commands ArgumentException e = new ArgumentException(fmtedMsg, innerException); return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); } - + private void WarnFilterContext() { string msg = MatchStringStrings.FilterContextWarning; @@ -1919,7 +1933,7 @@ namespace Microsoft.PowerShell.Commands { object element = argList[i]; - mso = element as PSObject; + mso = element as PSObject; if (mso != null) element = mso.BaseObject; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 7bc100225..d64346831 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -24,10 +24,10 @@ namespace Microsoft.PowerShell.Commands /// public string Property { - get { return property; } - set { property = value; } + get { return _property; } + set { _property = value; } } - private string property = null; + private string _property = null; } /// @@ -40,7 +40,7 @@ namespace Microsoft.PowerShell.Commands /// public GenericMeasureInfo() { - average = sum = max = min = null; + _average = _sum = _max = _min = null; } /// @@ -50,10 +50,10 @@ namespace Microsoft.PowerShell.Commands /// public int Count { - get { return count; } - set { count = value; } + get { return _count; } + set { _count = value; } } - private int count; + private int _count; /// /// @@ -62,10 +62,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Average { - get { return average; } - set { average = value; } + get { return _average; } + set { _average = value; } } - private double? average; + private double? _average; /// /// @@ -74,10 +74,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Sum { - get { return sum; } - set { sum = value; } + get { return _sum; } + set { _sum = value; } } - private double? sum; + private double? _sum; /// /// @@ -86,10 +86,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Maximum { - get { return max; } - set { max = value; } + get { return _max; } + set { _max = value; } } - private double? max; + private double? _max; /// /// @@ -98,11 +98,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Minimum { - get { return min; } - set { min = value; } + get { return _min; } + set { _min = value; } } - private double? min; - + private double? _min; } /// @@ -122,8 +121,8 @@ namespace Microsoft.PowerShell.Commands /// public GenericObjectMeasureInfo() { - average = sum = null; - max = min = null; + _average = _sum = null; + _max = _min = null; } /// @@ -133,10 +132,10 @@ namespace Microsoft.PowerShell.Commands /// public int Count { - get { return count; } - set { count = value; } + get { return _count; } + set { _count = value; } } - private int count; + private int _count; /// /// @@ -145,10 +144,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Average { - get { return average; } - set { average = value; } + get { return _average; } + set { _average = value; } } - private double? average; + private double? _average; /// /// @@ -157,10 +156,10 @@ namespace Microsoft.PowerShell.Commands /// public double? Sum { - get { return sum; } - set { sum = value; } + get { return _sum; } + set { _sum = value; } } - private double? sum; + private double? _sum; /// /// @@ -169,10 +168,10 @@ namespace Microsoft.PowerShell.Commands /// public object Maximum { - get { return max; } - set { max = value; } + get { return _max; } + set { _max = value; } } - private object max; + private object _max; /// /// @@ -181,10 +180,10 @@ namespace Microsoft.PowerShell.Commands /// public object Minimum { - get { return min; } - set { min = value; } + get { return _min; } + set { _min = value; } } - private object min; + private object _min; } @@ -198,7 +197,7 @@ namespace Microsoft.PowerShell.Commands /// public TextMeasureInfo() { - lines = words = characters = null; + _lines = _words = _characters = null; } /// @@ -208,10 +207,10 @@ namespace Microsoft.PowerShell.Commands /// public int? Lines { - get { return lines; } - set { lines = value; } + get { return _lines; } + set { _lines = value; } } - private int? lines; + private int? _lines; /// /// @@ -220,10 +219,10 @@ namespace Microsoft.PowerShell.Commands /// public int? Words { - get { return words; } - set { words = value; } + get { return _words; } + set { _words = value; } } - private int? words; + private int? _words; /// /// @@ -232,11 +231,10 @@ namespace Microsoft.PowerShell.Commands /// public int? Characters { - get { return characters; } - set { characters = value; } + get { return _characters; } + set { _characters = value; } } - private int? characters; - + private int? _characters; } /// @@ -327,10 +325,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true)] public PSObject InputObject { - set { inputObject = value; } - get { return inputObject; } + set { _inputObject = value; } + get { return _inputObject; } } - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// /// Properties to be examined @@ -342,14 +340,14 @@ namespace Microsoft.PowerShell.Commands { get { - return property; + return _property; } set { - property = value; + _property = value; } } - private string[] property = null; + private string[] _property = null; #endregion Common parameters in both sets /// @@ -361,14 +359,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureSum; + return _measureSum; } set { - measureSum = value; + _measureSum = value; } } - private bool measureSum; + private bool _measureSum; /// /// Set to true is Average is to be returned @@ -379,14 +377,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureAverage; + return _measureAverage; } set { - measureAverage = value; + _measureAverage = value; } } - private bool measureAverage; + private bool _measureAverage; /// /// Set to true is Max is to be returned @@ -397,14 +395,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureMax; + return _measureMax; } set { - measureMax = value; + _measureMax = value; } } - private bool measureMax; + private bool _measureMax; /// /// Set to true is Min is to be returned @@ -415,14 +413,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureMin; + return _measureMin; } set { - measureMin = value; + _measureMin = value; } } - private bool measureMin; + private bool _measureMin; #region TextMeasure ParameterSet /// @@ -434,14 +432,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureLines; + return _measureLines; } set { - measureLines = value; + _measureLines = value; } } - private bool measureLines = false; + private bool _measureLines = false; /// /// @@ -452,14 +450,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureWords; + return _measureWords; } set { - measureWords = value; + _measureWords = value; } } - private bool measureWords = false; + private bool _measureWords = false; /// /// @@ -470,14 +468,14 @@ namespace Microsoft.PowerShell.Commands { get { - return measureCharacters; + return _measureCharacters; } set { - measureCharacters = value; + _measureCharacters = value; } } - private bool measureCharacters = false; + private bool _measureCharacters = false; /// /// @@ -488,14 +486,14 @@ namespace Microsoft.PowerShell.Commands { get { - return ignoreWhiteSpace; + return _ignoreWhiteSpace; } set { - ignoreWhiteSpace = value; + _ignoreWhiteSpace = value; } } - private bool ignoreWhiteSpace; + private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet #endregion Command Line Switches @@ -518,17 +516,17 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (inputObject == null || inputObject == AutomationNull.Value) + if (_inputObject == null || _inputObject == AutomationNull.Value) { return; } - totalRecordCount++; + _totalRecordCount++; if (Property == null) - AnalyzeValue(null, inputObject.BaseObject); + AnalyzeValue(null, _inputObject.BaseObject); else - AnalyzeObjectProperties(inputObject); + AnalyzeObjectProperties(_inputObject); } /// @@ -557,7 +555,7 @@ namespace Microsoft.PowerShell.Commands if (!expression.HasWildCardCharacters) { string propertyName = expression.ToString(); - statistics.EnsureEntry(propertyName); + _statistics.EnsureEntry(propertyName); } continue; @@ -604,23 +602,23 @@ namespace Microsoft.PowerShell.Commands if (propertyName == null) propertyName = thisObject; - Statistics stat = statistics.EnsureEntry(propertyName); + Statistics stat = _statistics.EnsureEntry(propertyName); // Update common properties. stat.count++; - if (measureCharacters || measureWords || measureLines) + if (_measureCharacters || _measureWords || _measureLines) { string strValue = (objValue == null) ? "" : objValue.ToString(); AnalyzeString(strValue, stat); } - if (measureAverage || measureSum) + if (_measureAverage || _measureSum) { double numValue = 0.0; if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { - nonNumericError = true; + _nonNumericError = true; ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", @@ -628,18 +626,18 @@ namespace Microsoft.PowerShell.Commands objValue); WriteError(errorRecord); return; - } + } - AnalyzeNumber(numValue, stat); + AnalyzeNumber(numValue, stat); } // Win8:343911 Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo - if (measureMin) + if (_measureMin) { stat.min = Compare(objValue, stat.min, true); } - if (measureMax) + if (_measureMax) { stat.max = Compare(objValue, stat.max, false); } @@ -659,7 +657,7 @@ namespace Microsoft.PowerShell.Commands /// If true is passed in then the minimum of the two values would be returned. /// If false is passed in then maximum of the two values will be returned. /// - private object Compare(object objValue , object statMinOrMaxValue, bool isMin) + private object Compare(object objValue, object statMinOrMaxValue, bool isMin) { object currentValue = objValue; object statValue = statMinOrMaxValue; @@ -675,7 +673,7 @@ namespace Microsoft.PowerShell.Commands statValue = PSObject.AsPSObject(statValue).ToString(); } - if ((statValue == null) || + if ((statValue == null) || ((LanguagePrimitives.Compare(statValue, currentValue, false, CultureInfo.CurrentCulture) * factor) > 0)) { return objValue; @@ -715,7 +713,7 @@ namespace Microsoft.PowerShell.Commands } return len; } - + /// /// count words in inStr /// @@ -783,11 +781,11 @@ namespace Microsoft.PowerShell.Commands /// private void AnalyzeString(string strValue, Statistics stat) { - if (measureCharacters) - stat.characters += TextCountUtilities.CountChar(strValue, ignoreWhiteSpace); - if (measureWords) + if (_measureCharacters) + stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); + if (_measureWords) stat.words += TextCountUtilities.CountWord(strValue); - if (measureLines) + if (_measureLines) stat.lines += TextCountUtilities.CountLine(strValue); } @@ -798,8 +796,8 @@ namespace Microsoft.PowerShell.Commands /// private void AnalyzeNumber(double numValue, Statistics stat) { - if (measureSum || measureAverage) - stat.sum += numValue; + if (_measureSum || _measureAverage) + stat.sum += numValue; } /// @@ -809,7 +807,7 @@ namespace Microsoft.PowerShell.Commands /// The error ID to write. private void WritePropertyNotFoundError(string propertyName, string errorId) { - Diagnostics.Assert(property != null, "no property and no InputObject should have been addressed"); + Diagnostics.Assert(_property != null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Property"), errorId, @@ -829,14 +827,14 @@ namespace Microsoft.PowerShell.Commands // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. - if (totalRecordCount == 0 && Property == null) + if (_totalRecordCount == 0 && Property == null) { - statistics.EnsureEntry(thisObject); + _statistics.EnsureEntry(thisObject); } - foreach (string propertyName in statistics.Keys) + foreach (string propertyName in _statistics.Keys) { - Statistics stat = statistics[propertyName]; + Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { // Why are there two different ids for this error? @@ -861,7 +859,7 @@ namespace Microsoft.PowerShell.Commands } else mi = CreateTextMeasureInfo(stat); - + // Set common properties. if (Property != null) mi.Property = propertyName; @@ -882,16 +880,16 @@ namespace Microsoft.PowerShell.Commands double? average = null; object max = null; object min = null; - - if (!nonNumericError) + + if (!_nonNumericError) { - if (measureSum) + if (_measureSum) sum = stat.sum; - if (measureAverage && stat.count > 0) + if (_measureAverage && stat.count > 0) average = stat.sum / stat.count; } - - if (measureMax) + + if (_measureMax) { if (shouldUseGenericMeasureInfo && (stat.max != null)) { @@ -905,7 +903,7 @@ namespace Microsoft.PowerShell.Commands } } - if (measureMin) + if (_measureMin) { if (shouldUseGenericMeasureInfo && (stat.min != null)) { @@ -927,11 +925,11 @@ namespace Microsoft.PowerShell.Commands gmi.Average = average; if (null != max) { - gmi.Maximum = (double) max; + gmi.Maximum = (double)max; } if (null != min) { - gmi.Minimum = (double) min; + gmi.Minimum = (double)min; } return gmi; @@ -947,7 +945,7 @@ namespace Microsoft.PowerShell.Commands return gomi; } - } + } /// /// Create a MeasureInfo object for text stats. @@ -958,34 +956,34 @@ namespace Microsoft.PowerShell.Commands { TextMeasureInfo tmi = new TextMeasureInfo(); - if (measureCharacters) + if (_measureCharacters) tmi.Characters = stat.characters; - if (measureWords) + if (_measureWords) tmi.Words = stat.words; - if (measureLines) + if (_measureLines) tmi.Lines = stat.lines; return tmi; - } + } /// /// The observed statistics keyed by property name. If /// Property is not set, then the key used will be the /// value of thisObject. /// - private MeasureObjectDictionary statistics = new MeasureObjectDictionary(); + private MeasureObjectDictionary _statistics = new MeasureObjectDictionary(); /// /// Whether or not a numeric conversion error occurred. /// If true, then average/sum will not be output. /// - private bool nonNumericError = false; + private bool _nonNumericError = false; /// /// The total number of records encountered. /// - private int totalRecordCount = 0; - + private int _totalRecordCount = 0; + /// /// Parameter set name for measuring objects. /// @@ -1000,7 +998,6 @@ namespace Microsoft.PowerShell.Commands /// Key that statistics are stored under when Property is not set. /// private const string thisObject = "$_"; - } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs index 45a32388e..3e0bd0a4b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs index cc2b927a0..0682e759c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -1,14 +1,13 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { - - /// /// implementation for the new-timespan command /// @@ -29,16 +28,16 @@ namespace Microsoft.PowerShell.Commands { get { - return start; + return _start; } set { - start = value; - startSpecified = true; + _start = value; + _startSpecified = true; } } - private DateTime start; - private bool startSpecified; + private DateTime _start; + private bool _startSpecified; /// @@ -46,24 +45,24 @@ namespace Microsoft.PowerShell.Commands /// times are being compared. If one of the times is not specified, /// the current system time is used. /// - [Parameter(Position = 1,ValueFromPipelineByPropertyName = true,ParameterSetName = "Date" )] + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "Date")] public DateTime End { get { - return end; + return _end; } set { - end = value; - endSpecified = true; + _end = value; + _endSpecified = true; } } - private DateTime end; - private bool endSpecified = false; + private DateTime _end; + private bool _endSpecified = false; - /// + /// /// Allows the user to override the day /// [Parameter(ParameterSetName = "Time")] @@ -71,14 +70,14 @@ namespace Microsoft.PowerShell.Commands { get { - return days; + return _days; } set { - days = value; + _days = value; } } - private int days = 0; + private int _days = 0; /// @@ -89,14 +88,14 @@ namespace Microsoft.PowerShell.Commands { get { - return hours; + return _hours; } set { - hours = value; + _hours = value; } } - private int hours = 0; + private int _hours = 0; /// @@ -107,14 +106,14 @@ namespace Microsoft.PowerShell.Commands { get { - return minutes; + return _minutes; } set { - minutes = value; + _minutes = value; } } - private int minutes = 0; + private int _minutes = 0; /// @@ -125,14 +124,14 @@ namespace Microsoft.PowerShell.Commands { get { - return seconds; + return _seconds; } set { - seconds = value; + _seconds = value; } } - private int seconds = 0; + private int _seconds = 0; #endregion @@ -148,36 +147,35 @@ namespace Microsoft.PowerShell.Commands DateTime endTime = startTime; TimeSpan result; - switch ( ParameterSetName ) + switch (ParameterSetName) { case "Date": - if ( startSpecified ) + if (_startSpecified) { startTime = Start; } - if ( endSpecified ) + if (_endSpecified) { endTime = End; } - result = endTime.Subtract( startTime ); + result = endTime.Subtract(startTime); break; case "Time": - result = new TimeSpan( Days, Hours, Minutes, Seconds ); + result = new TimeSpan(Days, Hours, Minutes, Seconds); break; default: - Dbg.Diagnostics.Assert(false,"Only one of the specified parameter sets should be called." ); + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); return; } - WriteObject( result ); + WriteObject(result); } // EndProcessing #endregion } // NewTimeSpanCommand - - } // namespace Microsoft.PowerShell.Commands +} // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index bfb65c336..cf7910c6b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -26,8 +26,8 @@ namespace Microsoft.PowerShell.Commands internal ObjectCommandPropertyValue(object propVal) { - propertyValue = propVal; - isExistingProperty = true; + _propertyValue = propVal; + _isExistingProperty = true; } /// @@ -39,7 +39,7 @@ namespace Microsoft.PowerShell.Commands internal ObjectCommandPropertyValue(object propVal, bool isCaseSensitive, CultureInfo cultureInfo) : this(propVal) { - this.caseSensitive = isCaseSensitive; + _caseSensitive = isCaseSensitive; this.cultureInfo = cultureInfo; } @@ -48,14 +48,14 @@ namespace Microsoft.PowerShell.Commands { get { - return propertyValue; + return _propertyValue; } } internal bool IsExistingProperty { get { - return isExistingProperty; + return _isExistingProperty; } } @@ -64,7 +64,7 @@ namespace Microsoft.PowerShell.Commands /// internal SwitchParameter CaseSensitive { - get { return caseSensitive; } + get { return _caseSensitive; } } /// @@ -78,11 +78,11 @@ namespace Microsoft.PowerShell.Commands } } - private object propertyValue; - private bool isExistingProperty; + private object _propertyValue; + private bool _isExistingProperty; internal readonly static ObjectCommandPropertyValue NonExistingProperty = new ObjectCommandPropertyValue(); internal readonly static ObjectCommandPropertyValue ExistingNullProperty = new ObjectCommandPropertyValue(null); - private bool caseSensitive; + private bool _caseSensitive; internal CultureInfo cultureInfo = null; /// @@ -96,7 +96,7 @@ namespace Microsoft.PowerShell.Commands if (objectCommandPropertyValueObject == null) return false; - object baseObject = PSObject.Base(propertyValue); + object baseObject = PSObject.Base(_propertyValue); object inComingbaseObjectPropertyValue = PSObject.Base(objectCommandPropertyValueObject.PropertyValue); IComparable baseObjectComparable = baseObject as IComparable; @@ -127,10 +127,10 @@ namespace Microsoft.PowerShell.Commands /// Hashcode in the form of an integer. public override int GetHashCode() { - if (propertyValue == null) + if (_propertyValue == null) return 0; - object baseObject = PSObject.Base(propertyValue); + object baseObject = PSObject.Base(_propertyValue); IComparable baseObjectComparable = baseObject as IComparable; if (baseObjectComparable != null) @@ -156,9 +156,9 @@ namespace Microsoft.PowerShell.Commands /// internal ObjectCommandComparer(bool ascending, CultureInfo cultureInfo, bool caseSensitive) { - this.ascendingOrder = ascending; - this.cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; - this.caseSensitive = caseSensitive; + _ascendingOrder = ascending; + _cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; + _caseSensitive = caseSensitive; } private static bool IsValueNull(object value) @@ -224,7 +224,7 @@ namespace Microsoft.PowerShell.Commands try { - return LanguagePrimitives.Compare(first, second, !caseSensitive, cultureInfo) * (ascendingOrder ? 1 : -1); + return LanguagePrimitives.Compare(first, second, !_caseSensitive, _cultureInfo) * (_ascendingOrder ? 1 : -1); } catch (InvalidCastException) { @@ -240,15 +240,14 @@ namespace Microsoft.PowerShell.Commands string firstString = PSObject.AsPSObject(first).ToString(); string secondString = PSObject.AsPSObject(second).ToString(); - return cultureInfo.CompareInfo.Compare(firstString, secondString, caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase) * (ascendingOrder ? 1 : -1); + return _cultureInfo.CompareInfo.Compare(firstString, secondString, _caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase) * (_ascendingOrder ? 1 : -1); } - private CultureInfo cultureInfo = null; + private CultureInfo _cultureInfo = null; - private bool ascendingOrder = true; - - private bool caseSensitive = false; + private bool _ascendingOrder = true; + private bool _caseSensitive = false; } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index 7b6ba4eae..82b0fc196 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -133,10 +133,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] Property { - get { return expr; } - set { expr = value; } + get { return _expr; } + set { _expr = value; } } - private object[] expr; + private object[] _expr; #endregion Parameters } @@ -153,16 +153,16 @@ namespace Microsoft.PowerShell.Commands /// internal SwitchParameter DescendingOrder { - get { return !ascending; } - set { ascending = !value; } + get { return !_ascending; } + set { _ascending = !value; } } - private bool ascending = true; + private bool _ascending = true; internal List InputObjects { get { - return inputObjects; + return _inputObjects; } } @@ -188,15 +188,14 @@ namespace Microsoft.PowerShell.Commands { if (InputObject != null && InputObject != AutomationNull.Value) { - inputObjects.Add(InputObject); + _inputObjects.Add(InputObject); } } /// /// list of incoming objects to compare /// - private List inputObjects = new List(); - + private List _inputObjects = new List(); } internal sealed class OrderByProperty @@ -206,7 +205,7 @@ namespace Microsoft.PowerShell.Commands { get { - return orderMatrix; + return _orderMatrix; } } @@ -214,7 +213,7 @@ namespace Microsoft.PowerShell.Commands { get { - return comparer; + return _comparer; } } internal List MshParameterList @@ -245,7 +244,7 @@ namespace Microsoft.PowerShell.Commands TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? - new ParameterProcessor(new SortObjectExpressionParameterDefinition()): + new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr == null && inputObjects != null && inputObjects.Count > 0) @@ -268,16 +267,16 @@ namespace Microsoft.PowerShell.Commands TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? - new ParameterProcessor(new SortObjectExpressionParameterDefinition()): + new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr != null) { - if (unexpandedParameterList == null) + if (_unexpandedParameterList == null) { - unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); + _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); - foreach (MshParameter unexpandedParameter in unexpandedParameterList) + foreach (MshParameter unexpandedParameter in _unexpandedParameterList) { MshExpression mshExpression = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings @@ -286,12 +285,12 @@ namespace Microsoft.PowerShell.Commands } else { - if (unExpandedParametersWithWildCardPattern == null) + if (_unExpandedParametersWithWildCardPattern == null) { - unExpandedParametersWithWildCardPattern = new List(); + _unExpandedParametersWithWildCardPattern = new List(); } - unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); + _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); } } } @@ -383,13 +382,13 @@ namespace Microsoft.PowerShell.Commands internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) { PSMemberSet standardNames = mshObj.PSStandardMembers; - if(standardNames == null) + if (standardNames == null) { return null; } PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet; - if(defaultKeys == null) + if (defaultKeys == null) { return null; } @@ -463,7 +462,7 @@ namespace Microsoft.PowerShell.Commands ascendingOverrides[k] = null; } else if (isAscendingDefined && isDescendingDefined && - (bool) ascendingVal == (bool) descendingVal ) + (bool)ascendingVal == (bool)descendingVal) { // if both ascending and descending defined but their values conflict // they are ignored. @@ -475,7 +474,7 @@ namespace Microsoft.PowerShell.Commands } else { - ascendingOverrides[k] = ! (bool)descendingVal; + ascendingOverrides[k] = !(bool)descendingVal; } } } @@ -498,8 +497,8 @@ namespace Microsoft.PowerShell.Commands Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList); - orderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); - comparer = CreateComparer(orderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive); + _orderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); + _comparer = CreateComparer(_orderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive); } /// @@ -508,7 +507,7 @@ namespace Microsoft.PowerShell.Commands internal OrderByProperty() { _mshParameterList = new List(); - orderMatrix = new List(); + _orderMatrix = new List(); } /// @@ -527,9 +526,9 @@ namespace Microsoft.PowerShell.Commands { Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); - if (unExpandedParametersWithWildCardPattern != null) + if (_unExpandedParametersWithWildCardPattern != null) { - ExpandExpressions(inputObject, unExpandedParametersWithWildCardPattern, _mshParameterList); + ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); } List evaluationErrors = new List(); @@ -553,21 +552,21 @@ namespace Microsoft.PowerShell.Commands /// /// comparer for orderMatrix /// - private OrderByPropertyComparer comparer = null; + private OrderByPropertyComparer _comparer = null; /// /// a logical matrix where each row is an input object and its property values specified by Properties /// - private List orderMatrix = null; + private List _orderMatrix = null; // list of processed parameters obtained from the Expression array private List _mshParameterList = null; // list of unprocessed parameters obtained from the Expression array. - private List unexpandedParameterList = null; + private List _unexpandedParameterList = null; // list of unprocessed parameters with wild card patterns. - private List unExpandedParametersWithWildCardPattern = null; + private List _unExpandedParametersWithWildCardPattern = null; } internal static class OrderByPropertyEntryEvaluationHelper @@ -655,10 +654,10 @@ namespace Microsoft.PowerShell.Commands { internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive) { - this.propertyComparers = new ObjectCommandComparer[ascending.Length]; + _propertyComparers = new ObjectCommandComparer[ascending.Length]; for (int k = 0; k < ascending.Length; k++) { - this.propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive); + _propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive); } } @@ -667,13 +666,13 @@ namespace Microsoft.PowerShell.Commands // we have to take into consideration that some vectors // might be shorter than others int order = 0; - for (int k = 0; k < propertyComparers.Length; k++) + for (int k = 0; k < _propertyComparers.Length; k++) { ObjectCommandPropertyValue firstValue = (k < firstEntry.orderValues.Count) ? firstEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; ObjectCommandPropertyValue secondValue = (k < secondEntry.orderValues.Count) ? secondEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; - order = propertyComparers[k].Compare(firstValue, secondValue); + order = _propertyComparers[k].Compare(firstValue, secondValue); if (order != 0) return order; @@ -715,8 +714,7 @@ namespace Microsoft.PowerShell.Commands return new OrderByPropertyComparer(ascending, cultureInfo, caseSensitive); } - ObjectCommandComparer[] propertyComparers = null; + private ObjectCommandComparer[] _propertyComparers = null; } - } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index 78c9f8f1d..692a65212 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -13,172 +13,168 @@ using System.Security; using System.Text; namespace Microsoft.PowerShell.Commands -{ - -/// -/// -/// Retrieves input from the host virtual console and writes it to the pipeline output. -/// -/// - -[Cmdlet("Read", "Host", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113371")] -[OutputType(typeof(String), typeof(SecureString))] -public sealed class ReadHostCommand : PSCmdlet { /// /// - /// Constructs a new instance. - /// - /// - - public - ReadHostCommand() - { - // empty, provided per design guidelines. - } - - #region Parameters - - /// - /// - /// The objects to display on the host before collecting input. - /// - /// - - [Parameter(Position=0,ValueFromRemainingArguments =true)] - [AllowNull] - public - object - Prompt - { - get - { - return prompt; - } - - set - { - prompt = value; - } - } - - /// - /// - /// Set to no echo the input as is is typed. + /// Retrieves input from the host virtual console and writes it to the pipeline output. /// /// - [Parameter] - public - SwitchParameter - AsSecureString + [Cmdlet("Read", "Host", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113371")] + [OutputType(typeof(String), typeof(SecureString))] + public sealed class ReadHostCommand : PSCmdlet { - get + /// + /// + /// Constructs a new instance. + /// + /// + + public + ReadHostCommand() { - return safe; + // empty, provided per design guidelines. } - set + #region Parameters + + /// + /// + /// The objects to display on the host before collecting input. + /// + /// + + [Parameter(Position = 0, ValueFromRemainingArguments = true)] + [AllowNull] + public + object + Prompt { - safe = value; - } - } - #endregion Parameters - - - #region Cmdlet Overrides - - /// - /// - /// Write the prompt, then collect a line of input from the host, then - /// output it to the output stream. - /// - /// - protected override void BeginProcessing() - { - PSHostUserInterface ui = Host.UI; - string promptString; - - if (prompt != null) - { - IEnumerator e = LanguagePrimitives.GetEnumerator(prompt); - if (e != null) + get { - StringBuilder sb = new StringBuilder(); + return _prompt; + } - while (e.MoveNext()) + set + { + _prompt = value; + } + } + + /// + /// + /// Set to no echo the input as is is typed. + /// + /// + + [Parameter] + public + SwitchParameter + AsSecureString + { + get + { + return _safe; + } + + set + { + _safe = value; + } + } + #endregion Parameters + + + #region Cmdlet Overrides + + /// + /// + /// Write the prompt, then collect a line of input from the host, then + /// output it to the output stream. + /// + /// + protected override void BeginProcessing() + { + PSHostUserInterface ui = Host.UI; + string promptString; + + if (_prompt != null) + { + IEnumerator e = LanguagePrimitives.GetEnumerator(_prompt); + if (e != null) { - // The current object might itself be a collection, like a string array, as in read/console "foo","bar","baz" - // If it is, then the PSObject ToString() will take care of it. We could go on unwrapping collections - // forever, but it's a pretty common use case to see a varags confused with an array. + StringBuilder sb = new StringBuilder(); - string element = (string)LanguagePrimitives.ConvertTo(e.Current, typeof(string), CultureInfo.InvariantCulture); - - if (! String.IsNullOrEmpty(element)) + while (e.MoveNext()) { - // Prepend a space if the stringbuilder isn't empty... - // We could consider using $OFS here but that's probably more - // effort than is really needed... - if (sb.Length > 0) - sb.Append(' '); - sb.Append(element); + // The current object might itself be a collection, like a string array, as in read/console "foo","bar","baz" + // If it is, then the PSObject ToString() will take care of it. We could go on unwrapping collections + // forever, but it's a pretty common use case to see a varags confused with an array. + + string element = (string)LanguagePrimitives.ConvertTo(e.Current, typeof(string), CultureInfo.InvariantCulture); + + if (!String.IsNullOrEmpty(element)) + { + // Prepend a space if the stringbuilder isn't empty... + // We could consider using $OFS here but that's probably more + // effort than is really needed... + if (sb.Length > 0) + sb.Append(' '); + sb.Append(element); + } + } + promptString = sb.ToString(); + } + else + { + promptString = (string)LanguagePrimitives.ConvertTo(_prompt, typeof(string), CultureInfo.InvariantCulture); + } + + FieldDescription fd = new FieldDescription(promptString); + if (AsSecureString) + { + fd.SetParameterType(typeof(System.Security.SecureString)); + } + else + { + fd.SetParameterType(typeof(String)); + } + + Collection fdc = new Collection(); + fdc.Add(fd); + + Dictionary result = Host.UI.Prompt("", "", fdc); + // Result can be null depending on the host implementation. One typical + // example of a null return is for a canceled dialog. + if (result != null) + { + foreach (PSObject o in result.Values) + { + WriteObject(o); } } - promptString = sb.ToString(); } else { - promptString = (string)LanguagePrimitives.ConvertTo(prompt, typeof(string), CultureInfo.InvariantCulture); - } - - FieldDescription fd = new FieldDescription(promptString); - if (AsSecureString) - { - fd.SetParameterType(typeof(System.Security.SecureString)); - } - else - { - fd.SetParameterType(typeof(String)); - } - - Collection fdc = new Collection(); - fdc.Add(fd); - - Dictionary result = Host.UI.Prompt("", "", fdc); - // Result can be null depending on the host implementation. One typical - // example of a null return is for a canceled dialog. - if (result != null) - { - foreach (PSObject o in result.Values) + object result; + if (AsSecureString) { - WriteObject(o); + result = Host.UI.ReadLineAsSecureString(); } + else + { + result = Host.UI.ReadLine(); + } + WriteObject(result); } } - else - { - object result; - if (AsSecureString) - { - result = Host.UI.ReadLineAsSecureString(); - } - else - { - result = Host.UI.ReadLine(); - } - WriteObject(result); - } + + #endregion Cmdlet Overrides + + + + private object _prompt = null; + private Boolean _safe = false; } - - #endregion Cmdlet Overrides - - - - private object prompt = null; - private Boolean safe = false; -} - - - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs index 835d84938..4dfff1643 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; @@ -23,14 +24,14 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; } } - private PSObject inputObject = null; + private PSObject _inputObject = null; /// /// The event name to subscribe @@ -40,14 +41,14 @@ namespace Microsoft.PowerShell.Commands { get { - return eventName; + return _eventName; } set { - eventName = value; + _eventName = value; } } - private string eventName = null; + private string _eventName = null; #endregion parameters @@ -56,7 +57,7 @@ namespace Microsoft.PowerShell.Commands /// protected override Object GetSourceObject() { - return inputObject; + return _inputObject; } /// @@ -64,7 +65,7 @@ namespace Microsoft.PowerShell.Commands /// protected override String GetSourceObjectEventName() { - return eventName; + return _eventName; } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs index 519db4801..d02cab776 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; @@ -36,9 +37,9 @@ namespace Microsoft.PowerShell.Commands { // If it's not a forwarded event, the user must specify // an action - if( + if ( (Action == null) && - (! (bool) Forward) + (!(bool)Forward) ) { ErrorRecord errorRecord = new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs index 8aad4e163..b6f45279d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Management.Automation; namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs index 3cdb81a4d..10fa22827 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; @@ -17,45 +18,45 @@ namespace Microsoft.PowerShell.Commands /// /// A source identifier for this event subscription /// - [Parameter(Mandatory = true, Position = 0, ParameterSetName="BySource")] + [Parameter(Mandatory = true, Position = 0, ParameterSetName = "BySource")] public string SourceIdentifier { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; - if(value != null) + if (value != null) { - matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// An identifier for this event subscription /// - [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName="ByIdentifier")] + [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByIdentifier")] public int EventIdentifier { get { - return eventIdentifier; + return _eventIdentifier; } set { - eventIdentifier = value; + _eventIdentifier = value; } } - private int eventIdentifier = -1; + private int _eventIdentifier = -1; #endregion parameters - WildcardPattern matchPattern; + private WildcardPattern _matchPattern; /// /// Remove the event from the queue @@ -66,32 +67,32 @@ namespace Microsoft.PowerShell.Commands // pipeline bool foundMatch = false; - lock(Events.ReceivedEvents.SyncRoot) + lock (Events.ReceivedEvents.SyncRoot) { PSEventArgsCollection currentEvents = Events.ReceivedEvents; - for(int eventCounter = currentEvents.Count; eventCounter > 0; eventCounter--) + for (int eventCounter = currentEvents.Count; eventCounter > 0; eventCounter--) { PSEventArgs currentEvent = currentEvents[eventCounter - 1]; // If they specified a event identifier and we don't match, continue - if((sourceIdentifier != null) && - (! matchPattern.IsMatch(currentEvent.SourceIdentifier))) + if ((_sourceIdentifier != null) && + (!_matchPattern.IsMatch(currentEvent.SourceIdentifier))) { continue; } // If they specified a TimeGenerated and we don't match, continue - if ((eventIdentifier >= 0) && - (currentEvent.EventIdentifier != eventIdentifier)) + if ((_eventIdentifier >= 0) && + (currentEvent.EventIdentifier != _eventIdentifier)) { continue; } foundMatch = true; - if(ShouldProcess( + if (ShouldProcess( String.Format( - System.Globalization.CultureInfo.CurrentCulture, + System.Globalization.CultureInfo.CurrentCulture, EventingStrings.EventResource, currentEvent.SourceIdentifier), EventingStrings.Remove)) @@ -103,28 +104,28 @@ namespace Microsoft.PowerShell.Commands // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if((sourceIdentifier != null) && - (! WildcardPattern.ContainsWildcardCharacters(sourceIdentifier)) && - (! foundMatch)) + if ((_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && + (!foundMatch)) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( System.Globalization.CultureInfo.CurrentCulture, - EventingStrings.SourceIdentifierNotFound, sourceIdentifier)), + EventingStrings.SourceIdentifierNotFound, _sourceIdentifier)), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); } - else if((eventIdentifier >= 0) && (! foundMatch)) + else if ((_eventIdentifier >= 0) && (!foundMatch)) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( System.Globalization.CultureInfo.CurrentCulture, - EventingStrings.EventIdentifierNotFound, eventIdentifier)), + EventingStrings.EventIdentifierNotFound, _eventIdentifier)), "INVALID_EVENT_IDENTIFIER", ErrorCategory.InvalidArgument, null); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 6584be9c6..33cb4e151 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -41,13 +41,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Attachments { - get { return attachments; } + get { return _attachments; } set { - attachments = value; + _attachments = value; } } - private String[] attachments; + private String[] _attachments; /// /// Specifies the address collection that contains the @@ -58,13 +58,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Bcc { - get { return bcc; } + get { return _bcc; } set { - bcc = value; + _bcc = value; } } - private String[] bcc; + private String[] _bcc; /// /// Specifies the body (content) of the message @@ -73,13 +73,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public String Body { - get { return body; } + get { return _body; } set { - body = value; + _body = value; } } - private String body; + private String _body; /// /// Specifies a value indicating whether the mail message body is in Html. @@ -88,13 +88,13 @@ namespace Microsoft.PowerShell.Commands [Alias("BAH")] public SwitchParameter BodyAsHtml { - get { return bodyashtml; } + get { return _bodyashtml; } set { - bodyashtml = value; + _bodyashtml = value; } } - private SwitchParameter bodyashtml; + private SwitchParameter _bodyashtml; /// /// Specifies the encoding used for the content of the body and also the subject. @@ -105,13 +105,13 @@ namespace Microsoft.PowerShell.Commands [ArgumentToEncodingNameTransformationAttribute()] public Encoding Encoding { - get { return encoding; } + get { return _encoding; } set { - encoding = value; + _encoding = value; } } - private Encoding encoding = new ASCIIEncoding(); + private Encoding _encoding = new ASCIIEncoding(); /// /// Specifies the address collection that contains the @@ -123,13 +123,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Cc { - get { return cc; } + get { return _cc; } set { - cc = value; + _cc = value; } } - private String[] cc; + private String[] _cc; /// /// Specifies the delivery notifications options for the e-mail message. The various @@ -140,13 +140,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public DeliveryNotificationOptions DeliveryNotificationOption { - get { return deliverynotification; } + get { return _deliverynotification; } set { - deliverynotification = value; + _deliverynotification = value; } } - private DeliveryNotificationOptions deliverynotification; + private DeliveryNotificationOptions _deliverynotification; /// /// Specifies the from address for this e-mail message. The default value for @@ -156,13 +156,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public String From { - get { return from; } + get { return _from; } set { - from = value; + _from = value; } } - private String from; + private String _from; /// /// Specifies the name of the Host used to send the email. This host name will be assigned @@ -174,13 +174,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public String SmtpServer { - get { return smtpserver; } + get { return _smtpserver; } set { - smtpserver = value; + _smtpserver = value; } } - private String smtpserver; + private String _smtpserver; /// /// Specifies the priority of the email message. The valid values for this are Normal, High and Low @@ -189,13 +189,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public MailPriority Priority { - get { return priority; } + get { return _priority; } set { - priority = value; + _priority = value; } } - private MailPriority priority; + private MailPriority _priority; /// /// Specifies the subject of the email message. @@ -205,13 +205,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public String Subject { - get { return subject; } + get { return _subject; } set { - subject = value; + _subject = value; } } - private String subject; + private String _subject; /// @@ -222,13 +222,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] To { - get { return to; } + get { return _to; } set { - to = value; + _to = value; } } - private String[] to; + private String[] _to; /// /// Specifies the credential for this e-mail message. @@ -238,13 +238,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public PSCredential Credential { - get { return credential; } + get { return _credential; } set { - credential = value; + _credential = value; } } - private PSCredential credential; + private PSCredential _credential; /// /// Specifies if Secured layer is required or not @@ -252,13 +252,13 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter UseSsl { - get { return usessl; } + get { return _usessl; } set { - usessl = value; + _usessl = value; } } - private SwitchParameter usessl; + private SwitchParameter _usessl; /// /// Specifies the Port to be used on the server. @@ -270,10 +270,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public int Port { - get { return port; } - set { port = value; } + get { return _port; } + set { _port = value; } } - private int port = 0; + private int _port = 0; #endregion @@ -282,9 +282,9 @@ namespace Microsoft.PowerShell.Commands // Instantiate a new instance of MailMessage - private MailMessage mMailMessage = new MailMessage(); + private MailMessage _mMailMessage = new MailMessage(); - private SmtpClient mSmtpClient = null; + private SmtpClient _mSmtpClient = null; /// /// Add the input addresses which are either string or hashtable to the MailMessage @@ -302,20 +302,19 @@ namespace Microsoft.PowerShell.Commands { switch (param) { - case "to": { - mMailMessage.To.Add(new MailAddress(strEmailAddress)); + _mMailMessage.To.Add(new MailAddress(strEmailAddress)); break; } case "cc": { - mMailMessage.CC.Add(new MailAddress(strEmailAddress)); + _mMailMessage.CC.Add(new MailAddress(strEmailAddress)); break; } case "bcc": { - mMailMessage.Bcc.Add(new MailAddress(strEmailAddress)); + _mMailMessage.Bcc.Add(new MailAddress(strEmailAddress)); break; } } @@ -343,97 +342,89 @@ namespace Microsoft.PowerShell.Commands try { // Set the sender address of the mail message - mMailMessage.From = new MailAddress(from); + _mMailMessage.From = new MailAddress(_from); } catch (FormatException e) { - ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, from); + ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, _from); ThrowTerminatingError(er); // return; } // Set the recepient address of the mail message - AddAddressesToMailMessage(to, "to"); + AddAddressesToMailMessage(_to, "to"); // Set the BCC address of the mail message - if (bcc != null) + if (_bcc != null) { - AddAddressesToMailMessage(bcc, "bcc"); - + AddAddressesToMailMessage(_bcc, "bcc"); } // Set the CC address of the mail message - if (cc != null) + if (_cc != null) { - AddAddressesToMailMessage(cc, "cc"); - + AddAddressesToMailMessage(_cc, "cc"); } //set the delivery notification - mMailMessage.DeliveryNotificationOptions = deliverynotification; + _mMailMessage.DeliveryNotificationOptions = _deliverynotification; // Set the subject of the mail message - mMailMessage.Subject = subject; + _mMailMessage.Subject = _subject; // Set the body of the mail message - mMailMessage.Body = body; + _mMailMessage.Body = _body; //set the subject and body encoding - mMailMessage.SubjectEncoding = encoding; - mMailMessage.BodyEncoding = encoding; + _mMailMessage.SubjectEncoding = _encoding; + _mMailMessage.BodyEncoding = _encoding; // Set the format of the mail message body as HTML - mMailMessage.IsBodyHtml = bodyashtml; + _mMailMessage.IsBodyHtml = _bodyashtml; // Set the priority of the mail message to normal - mMailMessage.Priority = priority; + _mMailMessage.Priority = _priority; //get the PowerShell environment variable //globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer); - if (smtpserver == null && globalEmailServer != null) + if (_smtpserver == null && globalEmailServer != null) { - smtpserver = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); + _smtpserver = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); } - if (string.IsNullOrEmpty(smtpserver)) + if (string.IsNullOrEmpty(_smtpserver)) { ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null); this.ThrowTerminatingError(er); } - if (0 == port) + if (0 == _port) { - mSmtpClient = new SmtpClient(smtpserver); + _mSmtpClient = new SmtpClient(_smtpserver); } else { - mSmtpClient = new SmtpClient(smtpserver, port); + _mSmtpClient = new SmtpClient(_smtpserver, _port); } - if (usessl) + if (_usessl) { - mSmtpClient.EnableSsl = true; + _mSmtpClient.EnableSsl = true; } - if (credential != null) + if (_credential != null) { - - mSmtpClient.UseDefaultCredentials = false; - mSmtpClient.Credentials = credential.GetNetworkCredential(); + _mSmtpClient.UseDefaultCredentials = false; + _mSmtpClient.Credentials = _credential.GetNetworkCredential(); } - else if (!usessl) + else if (!_usessl) { - mSmtpClient.UseDefaultCredentials = true; + _mSmtpClient.UseDefaultCredentials = true; } - - - - - } /// @@ -442,10 +433,10 @@ namespace Microsoft.PowerShell.Commands protected override void ProcessRecord() { //add the attachments - if (attachments != null) + if (_attachments != null) { string filepath = string.Empty; - foreach (string attachFile in attachments) + foreach (string attachFile in _attachments) { try { @@ -457,7 +448,7 @@ namespace Microsoft.PowerShell.Commands PathUtils.ReportFileOpenFailure(this, filepath, e); } Attachment mailAttachment = new Attachment(filepath); - mMailMessage.Attachments.Add(mailAttachment); + _mMailMessage.Attachments.Add(mailAttachment); } } } @@ -470,49 +461,42 @@ namespace Microsoft.PowerShell.Commands try { // Send the mail message - mSmtpClient.Send(mMailMessage); - + _mSmtpClient.Send(_mMailMessage); } catch (SmtpFailedRecipientsException ex) { - ErrorRecord er = new ErrorRecord(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, mSmtpClient); + ErrorRecord er = new ErrorRecord(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (SmtpException ex) { - if (ex.InnerException != null) { - ErrorRecord er = new ErrorRecord(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, mSmtpClient); + ErrorRecord er = new ErrorRecord(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } else { - ErrorRecord er = new ErrorRecord(ex, "SmtpException", ErrorCategory.InvalidOperation, mSmtpClient); + ErrorRecord er = new ErrorRecord(ex, "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } - } catch (InvalidOperationException ex) { - ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, mSmtpClient); + ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (System.Security.Authentication.AuthenticationException ex) { - ErrorRecord er = new ErrorRecord(ex, "AuthenticationException", ErrorCategory.InvalidOperation, mSmtpClient); + ErrorRecord er = new ErrorRecord(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } //if we don't dispose the attachments, the sender can't modify or use the files sent. - mMailMessage.Attachments.Dispose(); - + _mMailMessage.Attachments.Dispose(); } - - #endregion - } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs index 8d7dd9a46..c40fe300b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.ObjectModel; using System.Diagnostics; @@ -22,9 +23,9 @@ namespace Microsoft.PowerShell.Commands /// /// the action to take when hitting this breakpoint /// - [Parameter(ParameterSetName="Command")] - [Parameter(ParameterSetName="Line")] - [Parameter(ParameterSetName="Variable")] + [Parameter(ParameterSetName = "Command")] + [Parameter(ParameterSetName = "Line")] + [Parameter(ParameterSetName = "Variable")] public ScriptBlock Action { get @@ -41,7 +42,7 @@ namespace Microsoft.PowerShell.Commands /// /// The column to set the breakpoint on /// - [Parameter(Position=2, ParameterSetName="Line")] + [Parameter(Position = 2, ParameterSetName = "Line")] [ValidateRange(1, int.MaxValue)] public int Column { @@ -143,7 +144,7 @@ namespace Microsoft.PowerShell.Commands set { _accessMode = value; } } - VariableAccessMode _accessMode = VariableAccessMode.Write; + private VariableAccessMode _accessMode = VariableAccessMode.Write; #endregion parameters @@ -175,7 +176,7 @@ namespace Microsoft.PowerShell.Commands // script block. So debugging is supported in Constrained language mode only if // the system is also in lock down mode. if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && - (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() != + (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() != System.Management.Automation.Security.SystemEnforcementMode.Enforce)) { ThrowTerminatingError( @@ -251,7 +252,7 @@ namespace Microsoft.PowerShell.Commands WriteObject( Context.Debugger.NewCommandBreakpoint(path.ToString(), Command[i], Action)); } - } + } else { WriteObject( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs index d10106629..d3843c7c9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index cf5868ce2..7332f9e41 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -12,7 +12,6 @@ using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { - /// /// implementation for the set-date command /// @@ -30,33 +29,33 @@ namespace Microsoft.PowerShell.Commands { get { - return to; + return _to; } set { - to = value; + _to = value; } } - private DateTime to; + private DateTime _to; /// /// Allows a use to specify a timespan with which to apply to the current time /// - [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Adjust", ValueFromPipelineByPropertyName = true )] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Adjust", ValueFromPipelineByPropertyName = true)] [AllowNull] public TimeSpan Adjust { get { - return adjust; + return _adjust; } set { - adjust = value; + _adjust = value; } } - private TimeSpan adjust; + private TimeSpan _adjust; /// @@ -67,14 +66,14 @@ namespace Microsoft.PowerShell.Commands { get { - return displayHint; + return _displayHint; } set { - displayHint = value; + _displayHint = value; } } - private DisplayHintType displayHint = DisplayHintType.DateTime; + private DisplayHintType _displayHint = DisplayHintType.DateTime; #endregion @@ -88,18 +87,18 @@ namespace Microsoft.PowerShell.Commands { DateTime dateToUse; - switch ( ParameterSetName ) + switch (ParameterSetName) { case "Date": dateToUse = Date; break; case "Adjust": - dateToUse = DateTime.Now.Add( Adjust ); + dateToUse = DateTime.Now.Add(Adjust); break; default: - Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called." ); + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); goto case "Date"; } @@ -107,19 +106,19 @@ namespace Microsoft.PowerShell.Commands // build up the SystemTime struct to pass to SetSystemTime NativeMethods.SystemTime systemTime = new NativeMethods.SystemTime(); - systemTime.Year = (UInt16) dateToUse.Year; - systemTime.Month = (UInt16) dateToUse.Month; - systemTime.Day = (UInt16) dateToUse.Day; - systemTime.Hour = (UInt16) dateToUse.Hour; - systemTime.Minute = (UInt16) dateToUse.Minute; - systemTime.Second = (UInt16) dateToUse.Second; - systemTime.Milliseconds = (UInt16) dateToUse.Millisecond; + systemTime.Year = (UInt16)dateToUse.Year; + systemTime.Month = (UInt16)dateToUse.Month; + systemTime.Day = (UInt16)dateToUse.Day; + systemTime.Hour = (UInt16)dateToUse.Hour; + systemTime.Minute = (UInt16)dateToUse.Minute; + systemTime.Second = (UInt16)dateToUse.Second; + systemTime.Milliseconds = (UInt16)dateToUse.Millisecond; - if ( ShouldProcess( dateToUse.ToString() ) ) + if (ShouldProcess(dateToUse.ToString())) { if (Platform.IsWindows) { - #pragma warning disable 56523 +#pragma warning disable 56523 if (!NativeMethods.SetLocalTime(ref systemTime)) { @@ -133,7 +132,7 @@ namespace Microsoft.PowerShell.Commands throw new Win32Exception(Marshal.GetLastWin32Error()); } - #pragma warning restore 56523 +#pragma warning restore 56523 } else { @@ -142,11 +141,11 @@ namespace Microsoft.PowerShell.Commands } //output DateTime object wrapped in an PSObject with DisplayHint attached - PSObject outputObj = new PSObject( dateToUse ); - PSNoteProperty note = new PSNoteProperty( "DisplayHint", DisplayHint ); - outputObj.Properties.Add( note ); + PSObject outputObj = new PSObject(dateToUse); + PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); + outputObj.Properties.Add(note); - WriteObject( outputObj ); + WriteObject(outputObj); } // EndProcessing #endregion @@ -167,15 +166,12 @@ namespace Microsoft.PowerShell.Commands public UInt16 Milliseconds; } - [DllImport(PinvokeDllNames.SetLocalTimeDllName, SetLastError = true )] - public static extern bool SetLocalTime( ref SystemTime systime ); - + [DllImport(PinvokeDllNames.SetLocalTimeDllName, SetLastError = true)] + public static extern bool SetLocalTime(ref SystemTime systime); } // NativeMethods #endregion } // SetDateCommand - - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 2614de1d0..447749110 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands { using System; @@ -16,7 +16,7 @@ namespace Microsoft.PowerShell.Commands using System.Text; using System.Threading; using Microsoft.PowerShell.Commands.ShowCommandExtension; - + /// /// Show-Command displays a GUI for a cmdlet, or for all cmdlets if no specific cmdlet is specified. /// @@ -27,62 +27,62 @@ namespace Microsoft.PowerShell.Commands /// /// Set to true when ProcessRecord is reached, since it will allways open a window /// - private bool hasOpenedWindow; + private bool _hasOpenedWindow; /// /// Determines if the command should be sent to the pipeline as a string instead of run. /// - private bool passThrough; + private bool _passThrough; /// /// Uses ShowCommandProxy to invoke WPF GUI object. /// - private ShowCommandProxy showCommandProxy; + private ShowCommandProxy _showCommandProxy; /// /// Data container for all cmdlets. This is populated when show-command is called with no command name. /// - private List commands; + private List _commands; /// /// List of modules that have been loaded indexed by module name /// - private Dictionary importedModules; + private Dictionary _importedModules; /// /// Record the EndProcessing error. /// - private PSDataCollection errors = new PSDataCollection(); + private PSDataCollection _errors = new PSDataCollection(); /// /// Field used for the CommandName parameter. /// - private string commandName; + private string _commandName; /// /// Field used for the Height parameter. /// - private double height; + private double _height; /// /// Field used for the Width parameter. /// - private double width; + private double _width; /// /// Field used for the NoCommonParameter parameter. /// - private SwitchParameter noCommonParameter; + private SwitchParameter _noCommonParameter; /// /// A value indicating errors should not cause a message window to be displayed /// - private SwitchParameter errorPopup; + private SwitchParameter _errorPopup; /// /// Object used for ShowCommand with a command name that holds the view model created for the command /// - private object commandViewModelObj; + private object _commandViewModelObj; #endregion /// @@ -101,8 +101,8 @@ namespace Microsoft.PowerShell.Commands [Alias("CommandName")] public string Name { - get { return this.commandName; } - set { this.commandName = value; } + get { return _commandName; } + set { _commandName = value; } } /// @@ -112,8 +112,8 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(300, Int32.MaxValue)] public double Height { - get { return this.height; } - set { this.height = value; } + get { return _height; } + set { _height = value; } } /// @@ -123,8 +123,8 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(300, Int32.MaxValue)] public double Width { - get { return this.width; } - set { this.width = value; } + get { return _width; } + set { _width = value; } } /// @@ -133,8 +133,8 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter NoCommonParameter { - get { return this.noCommonParameter; } - set { this.noCommonParameter = value; } + get { return _noCommonParameter; } + set { _noCommonParameter = value; } } /// @@ -143,8 +143,8 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter ErrorPopup { - get { return this.errorPopup; } - set { this.errorPopup = value; } + get { return _errorPopup; } + set { _errorPopup = value; } } /// @@ -155,12 +155,12 @@ namespace Microsoft.PowerShell.Commands { get { - return this.passThrough; + return _passThrough; } set { - this.passThrough = value; + _passThrough = value; } } // PassThru #endregion @@ -172,26 +172,26 @@ namespace Microsoft.PowerShell.Commands /// Script to execute public void RunScript(string script) { - if (this.showCommandProxy == null || string.IsNullOrEmpty(script)) + if (_showCommandProxy == null || string.IsNullOrEmpty(script)) { return; } - if (this.passThrough) + if (_passThrough) { this.WriteObject(script); return; } - if (this.errorPopup) + if (_errorPopup) { this.RunScriptSilentlyAndWithErrorHookup(script); return; } - if (this.showCommandProxy.HasHostWindow) + if (_showCommandProxy.HasHostWindow) { - if (!this.showCommandProxy.SetPendingISECommand(script)) + if (!_showCommandProxy.SetPendingISECommand(script)) { this.RunScriptSilentlyAndWithErrorHookup(script); } @@ -220,22 +220,22 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - this.showCommandProxy = new ShowCommandProxy(this); + _showCommandProxy = new ShowCommandProxy(this); - if (this.showCommandProxy.ScreenHeight < this.Height) + if (_showCommandProxy.ScreenHeight < this.Height) { ErrorRecord error = new ErrorRecord( - new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", this.showCommandProxy.ScreenHeight)), + new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(error); } - if (this.showCommandProxy.ScreenWidth < this.Width) + if (_showCommandProxy.ScreenWidth < this.Width) { ErrorRecord error = new ErrorRecord( - new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", this.showCommandProxy.ScreenWidth)), + new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, null); @@ -248,13 +248,13 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (this.commandName == null) + if (_commandName == null) { - this.hasOpenedWindow = this.CanProcessRecordForAllCommands(); + _hasOpenedWindow = this.CanProcessRecordForAllCommands(); } else { - this.hasOpenedWindow = this.CanProcessRecordForOneCommand(); + _hasOpenedWindow = this.CanProcessRecordForOneCommand(); } } @@ -263,7 +263,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (!this.hasOpenedWindow) + if (!_hasOpenedWindow) { return; } @@ -272,31 +272,31 @@ namespace Microsoft.PowerShell.Commands // to work arround the console window gaining activation somewhere // in the end of ProcessRecord, which causes the keyboard focus // (and use oif tab key to focus controls) to go away from the window - this.showCommandProxy.WindowLoaded.WaitOne(); - this.showCommandProxy.ActivateWindow(); + _showCommandProxy.WindowLoaded.WaitOne(); + _showCommandProxy.ActivateWindow(); this.WaitForWindowClosedOrHelpNeeded(); - this.RunScript(this.showCommandProxy.GetScript()); + this.RunScript(_showCommandProxy.GetScript()); - if (this.errors.Count == 0 || !this.errorPopup) + if (_errors.Count == 0 || !_errorPopup) { return; } StringBuilder errorString = new StringBuilder(); - for (int i = 0; i < this.errors.Count; i++) + for (int i = 0; i < _errors.Count; i++) { if (i != 0) { errorString.AppendLine(); } - ErrorRecord error = this.errors[i]; + ErrorRecord error = _errors[i]; errorString.Append(error.Exception.Message); } - this.showCommandProxy.ShowErrorString(errorString.ToString()); + _showCommandProxy.ShowErrorString(errorString.ToString()); } /// @@ -304,7 +304,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - this.showCommandProxy.CloseWindow(); + _showCommandProxy.CloseWindow(); } #endregion @@ -321,10 +321,10 @@ namespace Microsoft.PowerShell.Commands PSDataCollection output = new PSDataCollection(); output.DataAdded += new EventHandler(this.Output_DataAdded); - this.errors.DataAdded += new EventHandler(this.Error_DataAdded); + _errors.DataAdded += new EventHandler(this.Error_DataAdded); PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace); - ps.Streams.Error = this.errors; + ps.Streams.Error = _errors; ps.Commands.AddScript(script); @@ -340,8 +340,8 @@ namespace Microsoft.PowerShell.Commands String.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.CommandNotFound, - this.commandName)); - this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, this.commandName)); + _commandName)); + this.ThrowTerminatingError(new ErrorRecord(errorException, "NoCommand", ErrorCategory.InvalidOperation, _commandName)); } /// @@ -353,9 +353,9 @@ namespace Microsoft.PowerShell.Commands String.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.MoreThanOneCommand, - this.commandName, + _commandName, "Show-Command")); - this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, this.commandName)); + this.ThrowTerminatingError(new ErrorRecord(errorException, "MoreThanOneCommand", ErrorCategory.InvalidOperation, _commandName)); } /// @@ -367,7 +367,7 @@ namespace Microsoft.PowerShell.Commands { command = null; modules = null; - string commandText = this.showCommandProxy.GetShowCommandCommand(this.commandName, true); + string commandText = _showCommandProxy.GetShowCommandCommand(_commandName, true); Collection commandResults = this.InvokeCommand.InvokeScript(commandText); @@ -393,7 +393,7 @@ namespace Microsoft.PowerShell.Commands if (command.CommandType == CommandTypes.Alias) { - commandText = this.showCommandProxy.GetShowCommandCommand(command.Definition, false); + commandText = _showCommandProxy.GetShowCommandCommand(command.Definition, false); commandResults = this.InvokeCommand.InvokeScript(commandText); if (commandResults == null || commandResults.Count != 1) { @@ -404,7 +404,7 @@ namespace Microsoft.PowerShell.Commands command = (CommandInfo)commandResults[0].BaseObject; } - modules = this.showCommandProxy.GetImportedModulesDictionary(moduleObjects); + modules = _showCommandProxy.GetImportedModulesDictionary(moduleObjects); } /// @@ -414,17 +414,17 @@ namespace Microsoft.PowerShell.Commands private bool CanProcessRecordForOneCommand() { CommandInfo commandInfo; - this.GetCommandInfoAndModules(out commandInfo, out this.importedModules); + this.GetCommandInfoAndModules(out commandInfo, out _importedModules); Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a termninating error/exception"); try { - this.commandViewModelObj = this.showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), this.noCommonParameter.ToBool(), this.importedModules, this.Name.IndexOf('\\') != -1); - this.showCommandProxy.ShowCommandWindow(this.commandViewModelObj, this.passThrough); + _commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1); + _showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough); } catch (TargetInvocationException ti) { - this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, this.commandName)); + this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForOneCommand", ErrorCategory.InvalidOperation, _commandName)); return false; } @@ -437,18 +437,18 @@ namespace Microsoft.PowerShell.Commands /// true if there was no exception processing this record private bool CanProcessRecordForAllCommands() { - Collection rawCommands = this.InvokeCommand.InvokeScript(this.showCommandProxy.GetShowAllModulesCommand()); - - this.commands = this.showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); - this.importedModules = this.showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); + Collection rawCommands = this.InvokeCommand.InvokeScript(_showCommandProxy.GetShowAllModulesCommand()); + + _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); + _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); try { - this.showCommandProxy.ShowAllModulesWindow(this.importedModules, this.commands, this.noCommonParameter.ToBool(), this.passThrough); + _showCommandProxy.ShowAllModulesWindow(_importedModules, _commands, _noCommonParameter.ToBool(), _passThrough); } catch (TargetInvocationException ti) { - this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, this.commandName)); + this.WriteError(new ErrorRecord(ti.InnerException, "CannotProcessRecordForAllCommands", ErrorCategory.InvalidOperation, _commandName)); return false; } @@ -462,7 +462,7 @@ namespace Microsoft.PowerShell.Commands { do { - int which = WaitHandle.WaitAny(new WaitHandle[] { this.showCommandProxy.WindowClosed, this.showCommandProxy.HelpNeeded, this.showCommandProxy.ImportModuleNeeded }); + int which = WaitHandle.WaitAny(new WaitHandle[] { _showCommandProxy.WindowClosed, _showCommandProxy.HelpNeeded, _showCommandProxy.ImportModuleNeeded }); if (which == 0) { @@ -471,13 +471,13 @@ namespace Microsoft.PowerShell.Commands if (which == 1) { - Collection helpResults = this.InvokeCommand.InvokeScript(this.showCommandProxy.GetHelpCommand(this.showCommandProxy.CommandNeedingHelp)); - this.showCommandProxy.DisplayHelp(helpResults); + Collection helpResults = this.InvokeCommand.InvokeScript(_showCommandProxy.GetHelpCommand(_showCommandProxy.CommandNeedingHelp)); + _showCommandProxy.DisplayHelp(helpResults); continue; } Diagnostics.Assert(which == 2, "which is 0,1 or 2 and 0 and 1 have been eliminated in the ifs above"); - string commandToRun = this.showCommandProxy.GetImportModuleCommand(this.showCommandProxy.ParentModuleNeedingImportModule); + string commandToRun = _showCommandProxy.GetImportModuleCommand(_showCommandProxy.ParentModuleNeedingImportModule); Collection rawCommands; try { @@ -485,15 +485,15 @@ namespace Microsoft.PowerShell.Commands } catch (RuntimeException e) { - this.showCommandProxy.ImportModuleFailed(e); + _showCommandProxy.ImportModuleFailed(e); continue; } - this.commands = this.showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); - this.importedModules = this.showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); - this.showCommandProxy.ImportModuleDone(this.importedModules, this.commands); + _commands = _showCommandProxy.GetCommandList((object[])rawCommands[0].BaseObject); + _importedModules = _showCommandProxy.GetImportedModulesDictionary((object[])rawCommands[1].BaseObject); + _showCommandProxy.ImportModuleDone(_importedModules, _commands); continue; - } + } while (true); } @@ -525,10 +525,10 @@ namespace Microsoft.PowerShell.Commands { if (isDisposing) { - if (this.errors != null) + if (_errors != null) { - this.errors.Dispose(); - this.errors = null; + _errors.Dispose(); + _errors = null; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index 577d805f9..a8e54ebe9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands.ShowCommandExtension { using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index 81dd4e572..6c13d206f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands.ShowCommandExtension { using System; @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension using System.Globalization; using System.Linq; using System.Management.Automation; - + /// /// Implements a facade around PSModuleInfo and its deserialized counterpart /// @@ -32,10 +32,10 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension { throw new ArgumentNullException("other"); } - + this.Name = other.Name; } - + /// /// Creates an instance of the ShowCommandModuleInfo class based on a PSObject object /// @@ -49,10 +49,10 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension { throw new ArgumentNullException("other"); } - + this.Name = other.Members["Name"].Value as string; } - + /// /// Gets the name of this module /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 50961f1c0..c7ef23dbc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands.ShowCommandExtension { using System; @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension using System.Linq; using System.Management.Automation; - + /// /// Implements a facade around ShowCommandParameterInfo and its deserialized counterpart /// @@ -40,14 +40,14 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension this.ParameterType = new ShowCommandParameterType(other.ParameterType); this.Position = other.Position; - var validateSetAttribute = other.Attributes.Where(x=>typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); - if(validateSetAttribute != null) + var validateSetAttribute = other.Attributes.Where(x => typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); + if (validateSetAttribute != null) { this.HasParameterSet = true; this.ValidParamSetValues = validateSetAttribute.ValidValues; } } - + /// /// Creates an instance of the ShowCommandParameterInfo class based on a PSObject object /// @@ -73,37 +73,37 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension this.ValidParamSetValues = ShowCommandCommandInfo.GetObjectEnumerable((other.Members["ValidParamSetValues"].Value as PSObject).BaseObject as System.Collections.ArrayList).Cast().ToList(); } } - + /// /// Gets the name of the parameter. /// public string Name { get; private set; } - + /// /// True if the parameter is dynamic, or false otherwise. /// public bool IsMandatory { get; private set; } - + /// /// Gets whether the parameter can take values from the incoming pipeline object. /// public bool ValueFromPipeline { get; private set; } - + /// /// Gets the type of the parameter. /// public ShowCommandParameterType ParameterType { get; private set; } - + /// /// The possible values of this parameter /// public IList ValidParamSetValues { get; private set; } - + /// /// Gets whether the parameter has a parameter set. /// public bool HasParameterSet { get; private set; } - + /// /// Gets the position in which the parameter can be specified on the command line /// if not named. If the returned value is int.MinValue then the parameter must be named. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index 4a61dac7b..432c4a2ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands.ShowCommandExtension { using System; @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension using System.Linq; using System.Management.Automation; - + /// /// Implements a facade around CommandParameterSetInfo and its deserialized counterpart /// @@ -33,12 +33,12 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension { throw new ArgumentNullException("other"); } - + this.Name = other.Name; this.IsDefault = other.IsDefault; - this.Parameters = other.Parameters.Select(x=>new ShowCommandParameterInfo(x)).ToArray(); + this.Parameters = other.Parameters.Select(x => new ShowCommandParameterInfo(x)).ToArray(); } - + /// /// Creates an instance of the ShowCommandParameterSetInfo class based on a PSObject object /// @@ -56,9 +56,9 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension this.Name = other.Members["Name"].Value as string; this.IsDefault = (bool)(other.Members["IsDefault"].Value); var parameters = (other.Members["Parameters"].Value as PSObject).BaseObject as System.Collections.ArrayList; - this.Parameters = ShowCommandCommandInfo.GetObjectEnumerable(parameters).Cast().Select(x=>new ShowCommandParameterInfo(x)).ToArray(); + this.Parameters = ShowCommandCommandInfo.GetObjectEnumerable(parameters).Cast().Select(x => new ShowCommandParameterInfo(x)).ToArray(); } - + /// /// Gets the name of the parameter set /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index af40834a2..a0f3bbc72 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -3,6 +3,7 @@ // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands.ShowCommandExtension { using System; @@ -15,12 +16,12 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension using System.Linq; using System.Management.Automation; - + /// /// Implements a facade around ShowCommandParameterInfo and its deserialized counterpart /// public class ShowCommandParameterType - { + { /// /// Creates an instance of the ShowCommandParameterType class based on a Type object /// @@ -34,18 +35,18 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension { throw new ArgumentNullException("other"); } - + this.FullName = other.FullName; - if(other.IsEnum) + if (other.IsEnum) { this.EnumValues = new ArrayList(Enum.GetValues(other)); } - - if(other.IsArray) + + if (other.IsArray) { this.ElementType = new ShowCommandParameterType(other.GetElementType()); } - + object[] attributes = other.GetCustomAttributes(typeof(FlagsAttribute), true); this.HasFlagAttribute = attributes.Length != 0; this.ImplementsDictionary = typeof(IDictionary).IsAssignableFrom(other); @@ -81,27 +82,27 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension this.EnumValues = (other.Members["EnumValues"].Value as PSObject).BaseObject as ArrayList; } } - + /// /// The full name of the outermost type /// - public string FullName { get; private set;} - + public string FullName { get; private set; } + /// /// Whether or not this type is an enum /// - public bool IsEnum { get; private set;} - + public bool IsEnum { get; private set; } + /// /// Whether or not this type is an dictionary /// - public bool ImplementsDictionary { get; private set;} - + public bool ImplementsDictionary { get; private set; } + /// /// Whether or not this enum has a flag attribute /// - public bool HasFlagAttribute { get; private set;} - + public bool HasFlagAttribute { get; private set; } + /// /// Whether or not this type is an array type /// @@ -111,7 +112,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension /// Gets the inner type, if this corresponds to an array type /// public ShowCommandParameterType ElementType { get; private set; } - + /// /// Whether or not this type is a string /// @@ -122,7 +123,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension return String.Equals(this.FullName, "System.String", StringComparison.OrdinalIgnoreCase); } } - + /// /// Whether or not this type is an script block /// @@ -133,7 +134,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension return String.Equals(this.FullName, "System.Management.Automation.ScriptBlock", StringComparison.OrdinalIgnoreCase); } } - + /// /// Whether or not this type is a bool /// @@ -144,7 +145,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension return String.Equals(this.FullName, "System.Management.Automation.ScriptBlock", StringComparison.OrdinalIgnoreCase); } } - + /// /// Whether or not this type is a switch parameter /// @@ -155,7 +156,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandExtension return String.Equals(this.FullName, "System.Management.Automation.SwitchParameter", StringComparison.OrdinalIgnoreCase); } } - + /// /// If this is an enum value, return the list of potential values /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs index 3e5acfa98..c6c440a42 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -1,8 +1,8 @@ //----------------------------------------------------------------------- -// // Copyright © Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- + namespace Microsoft.PowerShell.Commands { using System; @@ -25,76 +25,76 @@ namespace Microsoft.PowerShell.Commands { private const string ShowCommandHelperName = "Microsoft.PowerShell.Commands.ShowCommandInternal.ShowCommandHelper"; - private ShowCommandCommand cmdlet; + private ShowCommandCommand _cmdlet; - private GraphicalHostReflectionWrapper graphicalHostReflectionWrapper; + private GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; internal ShowCommandProxy(ShowCommandCommand cmdlet) { - this.cmdlet = cmdlet; - this.graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(cmdlet, ShowCommandProxy.ShowCommandHelperName); + _cmdlet = cmdlet; + _graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(cmdlet, ShowCommandProxy.ShowCommandHelperName); } internal void ShowAllModulesWindow(Dictionary importedModules, IEnumerable commands, bool noCommonParameter, bool passThrough) { - this.graphicalHostReflectionWrapper.CallMethod("ShowAllModulesWindow", this.cmdlet, importedModules, commands, noCommonParameter, this.cmdlet.Width, this.cmdlet.Height, passThrough); + _graphicalHostReflectionWrapper.CallMethod("ShowAllModulesWindow", _cmdlet, importedModules, commands, noCommonParameter, _cmdlet.Width, _cmdlet.Height, passThrough); } internal void ShowCommandWindow(object commandViewModelObj, bool passThrough) { - this.graphicalHostReflectionWrapper.CallMethod("ShowCommandWindow", this.cmdlet, commandViewModelObj, this.cmdlet.Width, this.cmdlet.Height, passThrough); + _graphicalHostReflectionWrapper.CallMethod("ShowCommandWindow", _cmdlet, commandViewModelObj, _cmdlet.Width, _cmdlet.Height, passThrough); } internal void CloseWindow() { - this.graphicalHostReflectionWrapper.CallMethod("CloseWindow"); + _graphicalHostReflectionWrapper.CallMethod("CloseWindow"); } internal string GetScript() { - return (string)this.graphicalHostReflectionWrapper.CallMethod("GetScript"); + return (string)_graphicalHostReflectionWrapper.CallMethod("GetScript"); } internal void ShowErrorString(string error) { - this.graphicalHostReflectionWrapper.CallMethod("ShowErrorString", error); + _graphicalHostReflectionWrapper.CallMethod("ShowErrorString", error); } internal bool SetPendingISECommand(string command) { - return (bool)this.graphicalHostReflectionWrapper.CallMethod("SetPendingISECommand", command); + return (bool)_graphicalHostReflectionWrapper.CallMethod("SetPendingISECommand", command); } internal object GetCommandViewModel(ShowCommandCommandInfo command, bool noCommonParameter, Dictionary importedModules, bool moduleQualify) { - return this.graphicalHostReflectionWrapper.CallStaticMethod("GetCommandViewModel", command, noCommonParameter, importedModules, moduleQualify); + return _graphicalHostReflectionWrapper.CallStaticMethod("GetCommandViewModel", command, noCommonParameter, importedModules, moduleQualify); } internal string GetShowCommandCommand(string commandName, bool includeAliasAndModules) { - return (string)this.graphicalHostReflectionWrapper.CallStaticMethod("GetShowCommandCommand", commandName, includeAliasAndModules); + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetShowCommandCommand", commandName, includeAliasAndModules); } internal string GetShowAllModulesCommand() { - return (string)this.graphicalHostReflectionWrapper.CallStaticMethod("GetShowAllModulesCommand", false, true); + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetShowAllModulesCommand", false, true); } internal Dictionary GetImportedModulesDictionary(object[] moduleObjects) { - return (Dictionary)this.graphicalHostReflectionWrapper.CallStaticMethod("GetImportedModulesDictionary", new object[] { moduleObjects }); + return (Dictionary)_graphicalHostReflectionWrapper.CallStaticMethod("GetImportedModulesDictionary", new object[] { moduleObjects }); } internal List GetCommandList(object[] commandObjects) { - return (List)this.graphicalHostReflectionWrapper.CallStaticMethod("GetCommandList", new object[] { commandObjects }); + return (List)_graphicalHostReflectionWrapper.CallStaticMethod("GetCommandList", new object[] { commandObjects }); } internal bool HasHostWindow { get { - return (bool)this.graphicalHostReflectionWrapper.GetPropertyValue("HasHostWindow"); + return (bool)_graphicalHostReflectionWrapper.GetPropertyValue("HasHostWindow"); } } @@ -102,7 +102,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (AutoResetEvent)this.graphicalHostReflectionWrapper.GetPropertyValue("WindowClosed"); + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("WindowClosed"); } } @@ -110,7 +110,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (AutoResetEvent)this.graphicalHostReflectionWrapper.GetPropertyValue("HelpNeeded"); + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("HelpNeeded"); } } @@ -118,7 +118,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (AutoResetEvent)this.graphicalHostReflectionWrapper.GetPropertyValue("ImportModuleNeeded"); + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("ImportModuleNeeded"); } } @@ -126,7 +126,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (AutoResetEvent)this.graphicalHostReflectionWrapper.GetPropertyValue("WindowLoaded"); + return (AutoResetEvent)_graphicalHostReflectionWrapper.GetPropertyValue("WindowLoaded"); } } @@ -135,7 +135,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (string)this.graphicalHostReflectionWrapper.GetPropertyValue("CommandNeedingHelp"); + return (string)_graphicalHostReflectionWrapper.GetPropertyValue("CommandNeedingHelp"); } } @@ -143,46 +143,46 @@ namespace Microsoft.PowerShell.Commands { get { - return (string)this.graphicalHostReflectionWrapper.GetPropertyValue("ParentModuleNeedingImportModule"); + return (string)_graphicalHostReflectionWrapper.GetPropertyValue("ParentModuleNeedingImportModule"); } } internal void DisplayHelp(Collection helpResults) { - this.graphicalHostReflectionWrapper.CallMethod("DisplayHelp", helpResults); + _graphicalHostReflectionWrapper.CallMethod("DisplayHelp", helpResults); } internal string GetImportModuleCommand(string module) { - return (string)this.graphicalHostReflectionWrapper.CallStaticMethod("GetImportModuleCommand", module, false, true); + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetImportModuleCommand", module, false, true); } internal string GetHelpCommand(string command) { - return (string)this.graphicalHostReflectionWrapper.CallStaticMethod("GetHelpCommand", command); + return (string)_graphicalHostReflectionWrapper.CallStaticMethod("GetHelpCommand", command); } internal void ImportModuleDone(Dictionary importedModules, IEnumerable commands) { - this.graphicalHostReflectionWrapper.CallMethod("ImportModuleDone", importedModules, commands); + _graphicalHostReflectionWrapper.CallMethod("ImportModuleDone", importedModules, commands); } internal void ImportModuleFailed(Exception reason) { - this.graphicalHostReflectionWrapper.CallMethod("ImportModuleFailed", reason); + _graphicalHostReflectionWrapper.CallMethod("ImportModuleFailed", reason); } internal void ActivateWindow() { - this.graphicalHostReflectionWrapper.CallMethod("ActivateWindow"); + _graphicalHostReflectionWrapper.CallMethod("ActivateWindow"); } internal double ScreenWidth { get { - return (double)this.graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenWidth"); + return (double)_graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenWidth"); } } @@ -190,7 +190,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (double)this.graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenHeight"); + return (double)_graphicalHostReflectionWrapper.GetStaticPropertyValue("ScreenHeight"); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index bef853455..396efc0ef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Threading; @@ -11,10 +12,10 @@ namespace Microsoft.PowerShell.Commands /// /// Suspend shell, script, or runspace activity for the specified period of time. /// - [Cmdlet(VerbsLifecycle.Start, "Sleep", DefaultParameterSetName = "Seconds", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113407" )] + [Cmdlet(VerbsLifecycle.Start, "Sleep", DefaultParameterSetName = "Seconds", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113407")] public sealed class StartSleepCommand : PSCmdlet, IDisposable { - private bool disposed = false; + private bool _disposed = false; #region IDisposable /// @@ -22,14 +23,14 @@ namespace Microsoft.PowerShell.Commands /// public void Dispose() { - if (disposed == false) + if (_disposed == false) { - if (waitHandle != null) + if (_waitHandle != null) { - waitHandle.Dispose(); - waitHandle = null; + _waitHandle.Dispose(); + _waitHandle = null; } - disposed = true; + _disposed = true; } } @@ -42,74 +43,74 @@ namespace Microsoft.PowerShell.Commands /// /// Allows sleep time to be specified in seconds /// - [Parameter(Position = 0,Mandatory = true,ParameterSetName = "Seconds",ValueFromPipeline=true, - ValueFromPipelineByPropertyName = true )] - [ValidateRangeAttribute( 0, int.MaxValue/1000 )] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Seconds", ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] + [ValidateRangeAttribute(0, int.MaxValue / 1000)] public int Seconds { get { - return seconds; + return _seconds; } set { - seconds = value; + _seconds = value; } } - private int seconds; + private int _seconds; /// /// Allows sleep time to be specified in milliseconds /// - [Parameter(Mandatory=true,ParameterSetName = "Milliseconds", ValueFromPipelineByPropertyName=true)] - [ValidateRangeAttribute( 0, int.MaxValue )] + [Parameter(Mandatory = true, ParameterSetName = "Milliseconds", ValueFromPipelineByPropertyName = true)] + [ValidateRangeAttribute(0, int.MaxValue)] public int Milliseconds { get { - return milliseconds; + return _milliseconds; } set { - milliseconds = value; + _milliseconds = value; } } - private int milliseconds; + private int _milliseconds; #endregion #region methods //Wait handle which is used by thread to sleep. - ManualResetEvent waitHandle; + private ManualResetEvent _waitHandle; //object used for synchornizes pipeline thread and stop thread //access to waitHandle - object syncObject = new object(); + private object _syncObject = new object(); //this is set to true by stopProcessing - bool stopping = false; + private bool _stopping = false; /// /// This method causes calling thread to sleep for /// specified milliseconds /// - void Sleep(int milliSecondsToSleep) + private void Sleep(int milliSecondsToSleep) { - lock (syncObject) + lock (_syncObject) { - if (stopping == false) + if (_stopping == false) { - waitHandle = new ManualResetEvent(false); + _waitHandle = new ManualResetEvent(false); } } - if (waitHandle != null) + if (_waitHandle != null) { #if CORECLR //TODO:CORECLR bool WaitOne(int millisecondsTimeout,bool exitContext) is not available on CLR yet - waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep)); + _waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep)); #else - waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep), true); + _waitHandle.WaitOne(new TimeSpan(0, 0, 0, 0, milliSecondsToSleep), true); #endif } } @@ -121,7 +122,7 @@ namespace Microsoft.PowerShell.Commands { int sleepTime = 0; - switch ( ParameterSetName ) + switch (ParameterSetName) { case "Seconds": sleepTime = Seconds * 1000; @@ -132,7 +133,7 @@ namespace Microsoft.PowerShell.Commands break; default: - Dbg.Diagnostics.Assert(false,"Only one of the specified parameter sets should be called." ); + Dbg.Diagnostics.Assert(false, "Only one of the specified parameter sets should be called."); break; } @@ -142,21 +143,20 @@ namespace Microsoft.PowerShell.Commands /// /// stopprocessing override /// - protected override - void + protected override + void StopProcessing() { - lock (syncObject) + lock (_syncObject) { - stopping = true; - if (waitHandle != null) + _stopping = true; + if (_waitHandle != null) { - waitHandle.Set(); + _waitHandle.Set(); } } } - #endregion } // StartSleepCommand } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs index 1932bc03d..9208d1982 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs @@ -25,19 +25,19 @@ namespace Microsoft.PowerShell.Commands /// /// This parameter specifies the current pipeline object /// - [Parameter( ValueFromPipeline = true )] + [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set { - inputObject = value; + _inputObject = value; } get { - return inputObject; + return _inputObject; } } - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// @@ -48,20 +48,20 @@ namespace Microsoft.PowerShell.Commands { set { - script = value; + _script = value; } get { - return script; + return _script; } } - private ScriptBlock script; + private ScriptBlock _script; #endregion #region private members - private System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); + private System.Diagnostics.Stopwatch _stopWatch = new System.Diagnostics.Stopwatch(); #endregion @@ -73,7 +73,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - WriteObject( stopWatch.Elapsed ); + WriteObject(_stopWatch.Elapsed); } // EndProcessing @@ -85,17 +85,17 @@ namespace Microsoft.PowerShell.Commands { // Only accumulate the time used by this scriptblock... // As results are discarded, write directly to a null pipe instead of accumulating. - stopWatch.Start(); - script.InvokeWithPipe( - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: InputObject, // $_ - input: new object[0], // $input - scriptThis: AutomationNull.Value, - outputPipe: new Pipe { NullPipe = true }, - invocationInfo: null); + _stopWatch.Start(); + _script.InvokeWithPipe( + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, // $_ + input: new object[0], // $input + scriptThis: AutomationNull.Value, + outputPipe: new Pipe { NullPipe = true }, + invocationInfo: null); - stopWatch.Stop(); + _stopWatch.Stop(); } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index da21d5c12..843736484 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -29,11 +29,11 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } @@ -47,15 +47,15 @@ namespace Microsoft.PowerShell.Commands { get { - return paths; + return _paths; } set { - paths = value; + _paths = value; } } - private string[] paths; + private string[] _paths; /// /// Generate the type(s) @@ -67,7 +67,7 @@ namespace Microsoft.PowerShell.Commands if (String.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase)) { - foreach (string path in paths) + foreach (string path in _paths) { string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); @@ -80,7 +80,7 @@ namespace Microsoft.PowerShell.Commands else { // Resolve paths - foreach (string path in paths) + foreach (string path in _paths) { try { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index e06c3c1e8..be4e3c282 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; @@ -22,19 +23,19 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; - if(value != null) + if (value != null) { - matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// An identifier for this event subscription @@ -44,14 +45,14 @@ namespace Microsoft.PowerShell.Commands { get { - return subscriptionId; + return _subscriptionId; } set { - subscriptionId = value; + _subscriptionId = value; } } - private int subscriptionId = -1; + private int _subscriptionId = -1; /// /// Flag that determines if we should include subscriptions used to support @@ -62,19 +63,19 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; #endregion parameters - WildcardPattern matchPattern; - bool foundMatch = false; + private WildcardPattern _matchPattern; + private bool _foundMatch = false; /// /// Unsubscribe from the event @@ -83,24 +84,24 @@ namespace Microsoft.PowerShell.Commands { // Go through all the received events and write them to the output // pipeline - foreach(PSEventSubscriber subscriber in Events.Subscribers) + foreach (PSEventSubscriber subscriber in Events.Subscribers) { // If the event identifier matches, remove the subscription - if( - ((sourceIdentifier != null) && matchPattern.IsMatch(subscriber.SourceIdentifier)) || + if ( + ((_sourceIdentifier != null) && _matchPattern.IsMatch(subscriber.SourceIdentifier)) || ((SubscriptionId >= 0) && (subscriber.SubscriptionId == SubscriptionId)) ) { // If this is a support event but they aren't explicitly // looking for them, continue. - if (subscriber.SupportEvent && (! Force)) + if (subscriber.SupportEvent && (!Force)) { continue; } - foundMatch = true; + _foundMatch = true; - if(ShouldProcess( + if (ShouldProcess( String.Format( System.Globalization.CultureInfo.CurrentCulture, EventingStrings.EventSubscription, @@ -114,23 +115,23 @@ namespace Microsoft.PowerShell.Commands // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if((sourceIdentifier != null) && - (! WildcardPattern.ContainsWildcardCharacters(sourceIdentifier)) && - (! foundMatch)) + if ((_sourceIdentifier != null) && + (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && + (!_foundMatch)) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( System.Globalization.CultureInfo.CurrentCulture, - EventingStrings.EventSubscriptionNotFound, sourceIdentifier)), + EventingStrings.EventSubscriptionNotFound, _sourceIdentifier)), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, null); WriteError(errorRecord); - } - else if((SubscriptionId >= 0) && - (! foundMatch)) + } + else if ((SubscriptionId >= 0) && + (!_foundMatch)) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( @@ -142,7 +143,7 @@ namespace Microsoft.PowerShell.Commands null); WriteError(errorRecord); - } + } } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs index 38d8d469c..dc9316dbe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Collections.ObjectModel; @@ -19,7 +20,7 @@ namespace Microsoft.PowerShell.Commands /// File parameter set name /// protected const string FileParameterSet = "FileSet"; - string[] appendPath = new string[0]; + private string[] _appendPath = new string[0]; /// /// Files to append to the existing set /// @@ -28,11 +29,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public string[] AppendPath { - set { appendPath = value; } - get { return appendPath; } + set { _appendPath = value; } + get { return _appendPath; } } - string[] prependPath = new string[0]; + private string[] _prependPath = new string[0]; /// /// Files to prepend to the existing set /// @@ -40,8 +41,8 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public string[] PrependPath { - set { prependPath = value; } - get { return prependPath; } + set { _prependPath = value; } + get { return _prependPath; } } private static void ReportWrongExtension(string file, string errorId, PSCmdlet cmdlet) @@ -71,7 +72,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - internal static Collection Glob(string []files, string errorId, PSCmdlet cmdlet) + internal static Collection Glob(string[] files, string errorId, PSCmdlet cmdlet) { Collection retValue = new Collection(); foreach (string file in files) @@ -82,7 +83,7 @@ namespace Microsoft.PowerShell.Commands { providerPaths = cmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath(file, out provider); } - catch(SessionStateException e) + catch (SessionStateException e) { cmdlet.WriteError(new ErrorRecord(e, errorId, ErrorCategory.InvalidOperation, file)); continue; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index e37f288db..73c317424 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -28,14 +29,14 @@ namespace Microsoft.PowerShell.Commands private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; - private static object notSpecified = new object(); + private static object s_notSpecified = new object(); private static bool HasBeenSpecified(object obj) { - return !System.Object.ReferenceEquals(obj, notSpecified); + return !System.Object.ReferenceEquals(obj, s_notSpecified); } - - private PSMemberTypes memberType; - private bool isMemberTypeSet = false; + + private PSMemberTypes _memberType; + private bool _isMemberTypeSet = false; /// /// The member type of to be added /// @@ -51,13 +52,13 @@ namespace Microsoft.PowerShell.Commands { set { - memberType = value; - isMemberTypeSet = true; + _memberType = value; + _isMemberTypeSet = true; } - get { return memberType; } + get { return _memberType; } } - string memberName; + private string _memberName; /// /// The name of the new member /// @@ -65,11 +66,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string MemberName { - set { memberName = value; } - get { return memberName; } + set { _memberName = value; } + get { return _memberName; } } - private object value1 = notSpecified; + private object _value1 = s_notSpecified; /// /// First value of the new member. The meaning of this value /// changes according to the member type. @@ -77,11 +78,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = DynamicTypeSet)] public object Value { - set { value1 = value; } - get { return value1; } + set { _value1 = value; } + get { return _value1; } } - private object value2; + private object _value2; /// /// Second value of the new member. The meaning of this value /// changes according to the member type. @@ -90,11 +91,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public object SecondValue { - set { value2 = value; } - get { return value2; } + set { _value2 = value; } + get { return _value2; } } - private Type typeConverter; + private Type _typeConverter; /// /// The type converter to be added /// @@ -102,11 +103,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public Type TypeConverter { - set { typeConverter = value; } - get { return typeConverter; } + set { _typeConverter = value; } + get { return _typeConverter; } } - private Type typeAdapter; + private Type _typeAdapter; /// /// The type adapter to be added /// @@ -114,8 +115,8 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public Type TypeAdapter { - set { typeAdapter = value; } - get { return typeAdapter; } + set { _typeAdapter = value; } + get { return _typeAdapter; } } /// @@ -256,7 +257,7 @@ namespace Microsoft.PowerShell.Commands get { return _typeName; } } - private bool force = false; + private bool _force = false; /// /// True if we should overwrite a possibly existing member /// @@ -264,8 +265,8 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = TypeDataSet)] public SwitchParameter Force { - set { force = value; } - get { return force; } + set { _force = value; } + get { return _force; } } #endregion dynamic type set @@ -342,7 +343,7 @@ namespace Microsoft.PowerShell.Commands TypeData type = item.Copy(); // Set property IsOverride to be true if -Force parameter is specified - if (force) + if (_force) { type.IsOverride = true; } @@ -401,17 +402,17 @@ namespace Microsoft.PowerShell.Commands { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } - TypeData type = new TypeData(_typeName) {IsOverride = force}; + TypeData type = new TypeData(_typeName) { IsOverride = _force }; GetMembers(type.Members); - if(typeConverter != null) + if (_typeConverter != null) { - type.TypeConverter = typeConverter; + type.TypeConverter = _typeConverter; } - if(typeAdapter != null) + if (_typeAdapter != null) { - type.TypeAdapter = typeAdapter; + type.TypeAdapter = _typeAdapter; } if (_serializationMethod != null) @@ -455,7 +456,7 @@ namespace Microsoft.PowerShell.Commands } // If the type contains no members at all, report the error and return - if(!EnsureTypeDataIsNotEmpty(type)) + if (!EnsureTypeDataIsNotEmpty(type)) { return; } @@ -511,11 +512,11 @@ namespace Microsoft.PowerShell.Commands /// private void GetMembers(Dictionary members) { - if(!isMemberTypeSet) + if (!_isMemberTypeSet) { // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters // should not be specified either - if(memberName != null || HasBeenSpecified(value1) || value2 != null) + if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } @@ -549,7 +550,7 @@ namespace Microsoft.PowerShell.Commands members.Add(codeMethod.Name, codeMethod); break; default: - ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, memberType.ToString())); + ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, _memberType.ToString())); break; } } @@ -561,50 +562,50 @@ namespace Microsoft.PowerShell.Commands private void EnsureMemberNameHasBeenSpecified() { - if(String.IsNullOrEmpty(this.memberName)) + if (String.IsNullOrEmpty(_memberName)) { - ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", this.memberType)); + ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", _memberType)); } } private void EnsureValue1HasBeenSpecified() { - if (!HasBeenSpecified(value1)) + if (!HasBeenSpecified(_value1)) { - ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", this.memberType)); + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", _memberType)); } } private void EnsureValue1NotNullOrEmpty() { - if(value1 is string) + if (_value1 is string) { - if(String.IsNullOrEmpty((string)value1)) + if (String.IsNullOrEmpty((string)_value1)) { - ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", this.memberType)); + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } return; } - if (value1 == null) + if (_value1 == null) { - ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", this.memberType)); + ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } } private void EnsureValue2HasNotBeenSpecified() { - if (value2 != null) + if (_value2 != null) { - ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", this.memberType)); + ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); } } private void EnsureValue1AndValue2AreNotBothNull() { - if (value1 == null && value2 == null) + if (_value1 == null && _value2 == null) { - ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, this.memberType)); + ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); } } @@ -615,7 +616,7 @@ namespace Microsoft.PowerShell.Commands /// false if empty, true if not private bool EnsureTypeDataIsNotEmpty(TypeData typeData) { - if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 + if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 && typeData.TypeConverter == null && typeData.TypeAdapter == null && typeData.DefaultDisplayPropertySet == null && typeData.DefaultKeyPropertySet == null @@ -632,7 +633,7 @@ namespace Microsoft.PowerShell.Commands EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); - return new NotePropertyData(memberName, value1); + return new NotePropertyData(_memberName, _value1); } private AliasPropertyData GetAliasProperty() @@ -642,14 +643,14 @@ namespace Microsoft.PowerShell.Commands EnsureValue1NotNullOrEmpty(); AliasPropertyData alias; - string referencedName = GetParameterType(value1); - if(value2 != null) + string referencedName = GetParameterType(_value1); + if (_value2 != null) { - Type type = GetParameterType(value2); - alias = new AliasPropertyData(memberName, referencedName, type); + Type type = GetParameterType(_value2); + alias = new AliasPropertyData(_memberName, referencedName, type); return alias; } - alias = new AliasPropertyData(memberName, referencedName); + alias = new AliasPropertyData(_memberName, referencedName); return alias; } @@ -660,18 +661,18 @@ namespace Microsoft.PowerShell.Commands EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; - if(value1 != null) + if (_value1 != null) { - value1ScriptBlock = GetParameterType(value1); - } - - ScriptBlock value2ScriptBlock = null; - if(value2 != null) - { - value2ScriptBlock = GetParameterType(value2); + value1ScriptBlock = GetParameterType(_value1); } - ScriptPropertyData scriptProperty = new ScriptPropertyData(memberName, value1ScriptBlock, value2ScriptBlock); + ScriptBlock value2ScriptBlock = null; + if (_value2 != null) + { + value2ScriptBlock = GetParameterType(_value2); + } + + ScriptPropertyData scriptProperty = new ScriptPropertyData(_memberName, value1ScriptBlock, value2ScriptBlock); return scriptProperty; } @@ -682,18 +683,18 @@ namespace Microsoft.PowerShell.Commands EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1CodeReference = null; - if(value1 != null) + if (_value1 != null) { - value1CodeReference = GetParameterType(value1); + value1CodeReference = GetParameterType(_value1); } MethodInfo value2CodeReference = null; - if(value2 != null) + if (_value2 != null) { - value2CodeReference = GetParameterType(value2); + value2CodeReference = GetParameterType(_value2); } - CodePropertyData codeProperty = new CodePropertyData(memberName, value1CodeReference, value2CodeReference); + CodePropertyData codeProperty = new CodePropertyData(_memberName, value1CodeReference, value2CodeReference); return codeProperty; } @@ -703,8 +704,8 @@ namespace Microsoft.PowerShell.Commands EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); - ScriptBlock method = GetParameterType(value1); - ScriptMethodData scriptMethod = new ScriptMethodData(memberName, method); + ScriptBlock method = GetParameterType(_value1); + ScriptMethodData scriptMethod = new ScriptMethodData(_memberName, method); return scriptMethod; } @@ -714,8 +715,8 @@ namespace Microsoft.PowerShell.Commands EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); - MethodInfo codeReference = GetParameterType(value1); - CodeMethodData codeMethod = new CodeMethodData(memberName, codeReference); + MethodInfo codeReference = GetParameterType(_value1); + CodeMethodData codeMethod = new CodeMethodData(_memberName, codeReference); return codeMethod; } @@ -748,8 +749,9 @@ namespace Microsoft.PowerShell.Commands Collection appendPathTotal = Glob(this.AppendPath, "TypesAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob - if ((PrependPath.Length > 0 || AppendPath.Length > 0) && - prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } + if ((PrependPath.Length > 0 || AppendPath.Length > 0) && + prependPathTotal.Count == 0 && appendPathTotal.Count == 0) + { return; } string action = UpdateDataStrings.UpdateTypeDataAction; // Load the resource once and format it whenver a new target @@ -825,15 +827,15 @@ namespace Microsoft.PowerShell.Commands newTypes.Add(entry); } } - + foreach (string appendPathTotalItem in appendPathTotal) { - string formattedTarget = string.Format(CultureInfo.InvariantCulture,target, appendPathTotalItem); + string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(appendPathTotalItem, Context) ?? appendPathTotalItem; if (ShouldProcess(formattedTarget, action)) { - if(!fullFileNameHash.Contains(resolvedPath)) + if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); @@ -920,8 +922,9 @@ namespace Microsoft.PowerShell.Commands Collection appendPathTotal = Glob(this.AppendPath, "FormatAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob - if ((PrependPath.Length > 0 || AppendPath.Length > 0) && - prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } + if ((PrependPath.Length > 0 || AppendPath.Length > 0) && + prependPathTotal.Count == 0 && appendPathTotal.Count == 0) + { return; } string action = UpdateDataStrings.UpdateFormatDataAction; @@ -964,7 +967,7 @@ namespace Microsoft.PowerShell.Commands { if (Context.InitialSessionState.DisableFormatUpdates) { - throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); + throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); } // This hashSet is to detect if there are duplicate format files @@ -1038,7 +1041,7 @@ namespace Microsoft.PowerShell.Commands this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); continue; } - else if(ssfe.FormatData != null) + else if (ssfe.FormatData != null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } @@ -1083,7 +1086,7 @@ namespace Microsoft.PowerShell.Commands private const string RemoveFileSet = "RemoveFileSet"; private const string RemoveTypeDataSet = "RemoveTypeDataSet"; - private string typeName; + private string _typeName; /// /// The target type to remove /// @@ -1092,11 +1095,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string TypeName { - get { return typeName; } - set { typeName = value; } + get { return _typeName; } + set { _typeName = value; } } - private string[] typeFiles; + private string[] _typeFiles; /// /// The type xml file to remove from the cache /// @@ -1105,19 +1108,19 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string[] Path { - get { return typeFiles; } - set { typeFiles = value; } + get { return _typeFiles; } + set { _typeFiles = value; } } - private TypeData typeData; + private TypeData _typeData; /// /// The TypeData to remove /// [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = RemoveTypeDataSet)] public TypeData TypeData { - get { return typeData; } - set { typeData = value; } + get { return _typeData; } + set { _typeData = value; } } private static void ConstructFileToIndexMap(string fileName, int index, Dictionary> fileNameToIndexMap) @@ -1129,7 +1132,7 @@ namespace Microsoft.PowerShell.Commands } else { - fileNameToIndexMap[fileName] = new List {index}; + fileNameToIndexMap[fileName] = new List { index }; } } @@ -1138,13 +1141,13 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if(ParameterSetName == RemoveFileSet) + if (ParameterSetName == RemoveFileSet) { // Load the resource strings string removeFileAction = UpdateDataStrings.RemoveTypeFileAction; string removeFileTarget = UpdateDataStrings.UpdateTarget; - Collection typeFileTotal = UpdateData.Glob(typeFiles, "TypePathException", this); + Collection typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); if (typeFileTotal.Count == 0) { return; } // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might @@ -1242,17 +1245,17 @@ namespace Microsoft.PowerShell.Commands string removeTypeTarget = UpdateDataStrings.RemoveTypeDataTarget; string typeNameToRemove = null; - if(ParameterSetName == RemoveTypeDataSet) + if (ParameterSetName == RemoveTypeDataSet) { - typeNameToRemove = typeData.TypeName; + typeNameToRemove = _typeData.TypeName; } else { - if (String.IsNullOrWhiteSpace(typeName)) + if (String.IsNullOrWhiteSpace(_typeName)) { - ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, typeName)); + ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } - typeNameToRemove = typeName; + typeNameToRemove = _typeName; } Dbg.Assert(!String.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index d8c88a7c2..ca46d5d9b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -90,7 +90,6 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal static Encoding GetEncodingFromEnum(TextEncodingType type) { - Encoding encoding = Encoding.ASCII; switch (type) @@ -127,7 +126,6 @@ namespace Microsoft.PowerShell.Commands return encoding; } - } // class UtilityCommon /// /// abc @@ -173,7 +171,6 @@ namespace Microsoft.PowerShell.Commands /// ASCII encoding. /// Ascii, - } /// @@ -229,7 +226,7 @@ namespace Microsoft.PowerShell.Commands public ByteCollection(UInt32 offset, Byte[] value, string path) { this.Offset = offset; - this.initialOffSet = offset; + _initialOffSet = offset; this.Bytes = value; this.Path = path; } @@ -242,7 +239,7 @@ namespace Microsoft.PowerShell.Commands public ByteCollection(UInt32 offset, Byte[] value) { this.Offset = offset; - this.initialOffSet = offset; + _initialOffSet = offset; this.Bytes = value; } @@ -259,7 +256,7 @@ namespace Microsoft.PowerShell.Commands /// The Offset address to be used while displaying the bytes in the collection. /// public UInt32 Offset { get; private set; } - private UInt32 initialOffSet = 0; + private UInt32 _initialOffSet = 0; /// /// Underlying bytes stored in the collection. @@ -288,7 +285,7 @@ namespace Microsoft.PowerShell.Commands // ToString() in invoked thrice by the F&O for the same content. // Hence making sure that Offset is not getting incremented thrice for the same bytes being displayed. - Offset = initialOffSet; + Offset = _initialOffSet; nextLine.AppendFormat("{0:X2} ", CultureInfo.InvariantCulture.TextInfo.ToUpper(Convert.ToString(Offset, 16)).PadLeft(8, '0')); foreach (Byte currentByte in Bytes) @@ -344,6 +341,5 @@ namespace Microsoft.PowerShell.Commands return result.ToString(); } } - } // namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 516080603..836dbd645 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -10,7 +11,6 @@ using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { - /// /// Base class for all variable commands. /// @@ -31,15 +31,15 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } set { - scope = value; + _scope = value; } } - private string scope; + private string _scope; #endregion parameters /// @@ -50,7 +50,7 @@ namespace Microsoft.PowerShell.Commands { get { - return include; + return _include; } set @@ -59,10 +59,10 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - include = value; + _include = value; } } - private string[] include = new string[0]; + private string[] _include = new string[0]; /// /// The Exclude parameter for all the variable commands @@ -72,7 +72,7 @@ namespace Microsoft.PowerShell.Commands { get { - return exclude; + return _exclude; } set @@ -81,10 +81,10 @@ namespace Microsoft.PowerShell.Commands { value = new string[0]; } - exclude = value; + _exclude = value; } } - private string[] exclude = new string[0]; + private string[] _exclude = new string[0]; #region helpers @@ -139,12 +139,12 @@ namespace Microsoft.PowerShell.Commands Collection includeFilters = SessionStateUtilities.CreateWildcardsFromStrings( - include, + _include, WildcardOptions.IgnoreCase); Collection excludeFilters = SessionStateUtilities.CreateWildcardsFromStrings( - exclude, + _exclude, WildcardOptions.IgnoreCase); if (!nameContainsWildcard) @@ -212,7 +212,6 @@ namespace Microsoft.PowerShell.Commands // In quiet mode, don't report private variable accesses unless they are specific matches... if (quiet || nameContainsWildcard) { - wasFiltered = true; continue; } @@ -275,7 +274,7 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set @@ -284,10 +283,10 @@ namespace Microsoft.PowerShell.Commands { value = new string[] { "*" }; } - name = value; + _name = value; } } - private string[] name = new string[] { "*" }; + private string[] _name = new string[] { "*" }; @@ -299,14 +298,14 @@ namespace Microsoft.PowerShell.Commands { get { - return valueOnly; + return _valueOnly; } set { - valueOnly = value; + _valueOnly = value; } } - private bool valueOnly; + private bool _valueOnly; /// @@ -352,14 +351,14 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - foreach (string varName in name) + foreach (string varName in _name) { bool wasFiltered = false; List matchingVariables = GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false); matchingVariables.Sort( - delegate(PSVariable left, PSVariable right) + delegate (PSVariable left, PSVariable right) { return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name); }); @@ -368,7 +367,7 @@ namespace Microsoft.PowerShell.Commands foreach (PSVariable matchingVariable in matchingVariables) { matchFound = true; - if (valueOnly) + if (_valueOnly) { WriteObject(matchingVariable.Value); } @@ -411,15 +410,15 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set { - name = value; + _name = value; } } - private string name; + private string _name; /// /// Value of the PSVariable @@ -433,7 +432,7 @@ namespace Microsoft.PowerShell.Commands } set { - this._value = value; + _value = value; } } private object _value; @@ -446,14 +445,14 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// @@ -466,14 +465,14 @@ namespace Microsoft.PowerShell.Commands { get { - return options; + return _options; } set { - options = value; + _options = value; } } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// /// Specifies the visiblity of the new variable... @@ -501,15 +500,15 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// The variable object should be passed down the pipeline. @@ -519,14 +518,14 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; #endregion parameters @@ -548,19 +547,19 @@ namespace Microsoft.PowerShell.Commands if (String.IsNullOrEmpty(Scope)) { varFound = - SessionState.PSVariable.GetAtScope(name, "local"); + SessionState.PSVariable.GetAtScope(_name, "local"); } else { varFound = - SessionState.PSVariable.GetAtScope(name, Scope); + SessionState.PSVariable.GetAtScope(_name, Scope); } if (varFound != null) { SessionStateException sessionStateException = new SessionStateException( - name, + _name, SessionStateCategory.Variable, "VariableAlreadyExists", SessionStateStrings.VariableAlreadyExists, @@ -583,16 +582,16 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(target, action)) { - PSVariable newVariable = new PSVariable(name, _value, options); + PSVariable newVariable = new PSVariable(_name, _value, _options); if (_visibility != null) { - newVariable.Visibility = (SessionStateEntryVisibility) _visibility; + newVariable.Visibility = (SessionStateEntryVisibility)_visibility; } - if (description != null) + if (_description != null) { - newVariable.Description = description; + newVariable.Description = _description; } try @@ -623,7 +622,7 @@ namespace Microsoft.PowerShell.Commands return; } - if (passThru) + if (_passThru) { WriteObject(newVariable); } @@ -649,15 +648,15 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } - private string[] names; + private string[] _names; /// /// Value of the PSVariable @@ -671,7 +670,7 @@ namespace Microsoft.PowerShell.Commands } set { - this._value = value; + _value = value; } } private object _value = AutomationNull.Value; @@ -720,14 +719,14 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// @@ -740,14 +739,14 @@ namespace Microsoft.PowerShell.Commands { get { - return (ScopedItemOptions)options; + return (ScopedItemOptions)_options; } set { - options = value; + _options = value; } } - private Nullable options; + private Nullable _options; /// /// Force the operation to make the best attempt at setting the variable. @@ -757,15 +756,15 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Sets the visibility of the variable... @@ -794,17 +793,17 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; - private bool nameIsFormalParameter; - private bool valueIsFormalParameter; + private bool _nameIsFormalParameter; + private bool _valueIsFormalParameter; #endregion parameters /// @@ -813,14 +812,14 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - if (names != null && names.Length > 0) + if (_names != null && _names.Length > 0) { - nameIsFormalParameter = true; + _nameIsFormalParameter = true; } if (_value != AutomationNull.Value) { - valueIsFormalParameter = true; + _valueIsFormalParameter = true; } } @@ -836,28 +835,28 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (nameIsFormalParameter && valueIsFormalParameter) + if (_nameIsFormalParameter && _valueIsFormalParameter) { return; } - if (nameIsFormalParameter && !valueIsFormalParameter) + if (_nameIsFormalParameter && !_valueIsFormalParameter) { if (_value != AutomationNull.Value) { - if (valueList == null) + if (_valueList == null) { - valueList = new ArrayList(); + _valueList = new ArrayList(); } - valueList.Add(_value); + _valueList.Add(_value); } } else { - SetVariable(names, _value); + SetVariable(_names, _value); } } - private ArrayList valueList; + private ArrayList _valueList; /// /// Sets the variable if the name was specified as a formal parameter @@ -865,32 +864,32 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (nameIsFormalParameter) + if (_nameIsFormalParameter) { - if (valueIsFormalParameter) + if (_valueIsFormalParameter) { - SetVariable(names, _value); + SetVariable(_names, _value); } else { - if (valueList != null) + if (_valueList != null) { - if (valueList.Count == 1) + if (_valueList.Count == 1) { - SetVariable(names, valueList[0]); + SetVariable(_names, _valueList[0]); } - else if (valueList.Count == 0) + else if (_valueList.Count == 0) { - SetVariable(names, AutomationNull.Value); + SetVariable(_names, AutomationNull.Value); } else { - SetVariable(names, valueList.ToArray()); + SetVariable(_names, _valueList.ToArray()); } } else { - SetVariable(names, AutomationNull.Value); + SetVariable(_names, AutomationNull.Value); } } } @@ -959,9 +958,9 @@ namespace Microsoft.PowerShell.Commands newOptions = ScopedItemOptions.Private; } - if (this.options != null) + if (_options != null) { - newOptions |= (ScopedItemOptions)this.options; + newOptions |= (ScopedItemOptions)_options; } object newVarValue = varValue; @@ -976,9 +975,9 @@ namespace Microsoft.PowerShell.Commands newVarValue, newOptions); - if (description == null) + if (_description == null) { - this.description = String.Empty; + _description = String.Empty; } varToSet.Description = Description; @@ -1007,7 +1006,7 @@ namespace Microsoft.PowerShell.Commands SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin); } - if (passThru && result != null) + if (_passThru && result != null) { WriteObject(result); } @@ -1068,14 +1067,14 @@ namespace Microsoft.PowerShell.Commands } - if (description != null) + if (_description != null) { - matchingVariable.Description = description; + matchingVariable.Description = _description; } - if (options != null) + if (_options != null) { - matchingVariable.Options = (ScopedItemOptions)options; + matchingVariable.Options = (ScopedItemOptions)_options; } else { @@ -1110,7 +1109,7 @@ namespace Microsoft.PowerShell.Commands continue; } - if (passThru && result != null) + if (_passThru && result != null) { WriteObject(result); } @@ -1137,15 +1136,15 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } - private string[] names; + private string[] _names; /// /// The Include parameter for all the variable commands @@ -1192,14 +1191,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; #endregion parameters @@ -1218,7 +1217,7 @@ namespace Microsoft.PowerShell.Commands } - foreach (string varName in names) + foreach (string varName in _names) { // First look for existing variables to set. bool wasFiltered = false; @@ -1260,11 +1259,11 @@ namespace Microsoft.PowerShell.Commands { if (String.IsNullOrEmpty(Scope)) { - SessionState.Internal.RemoveVariable(matchingVariable, force); + SessionState.Internal.RemoveVariable(matchingVariable, _force); } else { - SessionState.Internal.RemoveVariableAtScope(matchingVariable, Scope, force); + SessionState.Internal.RemoveVariableAtScope(matchingVariable, Scope, _force); } } catch (SessionStateException sessionStateException) @@ -1304,15 +1303,15 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } - private string[] names; + private string[] _names; /// /// The Include parameter for all the variable commands @@ -1358,15 +1357,15 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// The variable object should be passed down the pipeline. @@ -1376,14 +1375,14 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; #endregion parameters @@ -1393,7 +1392,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - foreach (string varName in names) + foreach (string varName in _names) { bool wasFiltered = false; @@ -1434,7 +1433,7 @@ namespace Microsoft.PowerShell.Commands try { - if (force && + if (_force && (matchingVariable.Options & ScopedItemOptions.ReadOnly) != 0) { // Remove the ReadOnly bit to set the value and then reapply @@ -1467,7 +1466,7 @@ namespace Microsoft.PowerShell.Commands continue; } - if (passThru) + if (_passThru) { WriteObject(result); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 8ded28128..d434f93a0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; using System.Threading; @@ -24,15 +25,15 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; - matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); + _sourceIdentifier = value; + _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// If timeout is specified, the cmdlet will only wait for this number of seconds. @@ -45,21 +46,21 @@ namespace Microsoft.PowerShell.Commands { get { - return timeoutInSeconds; + return _timeoutInSeconds; } set { - timeoutInSeconds = value; + _timeoutInSeconds = value; } } - int timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. + private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. #endregion parameters - AutoResetEvent eventArrived = new AutoResetEvent(false); - PSEventArgs receivedEvent = null; - Object receivedEventLock = new Object(); - WildcardPattern matchPattern; + private AutoResetEvent _eventArrived = new AutoResetEvent(false); + private PSEventArgs _receivedEvent = null; + private Object _receivedEventLock = new Object(); + private WildcardPattern _matchPattern; /// /// Wait for the event to arrive @@ -67,7 +68,7 @@ namespace Microsoft.PowerShell.Commands protected override void ProcessRecord() { DateTime startTime = DateTime.UtcNow; - + // Subscribe to notification of events received Events.ReceivedEvents.PSEventReceived += ReceivedEvents_PSEventReceived; bool received = false; @@ -76,17 +77,17 @@ namespace Microsoft.PowerShell.Commands ScanEventQueue(); // And wait for our event handler (or Control-C processor) to give us control - PSLocalEventManager eventManager = (PSLocalEventManager) Events; + PSLocalEventManager eventManager = (PSLocalEventManager)Events; while (!received) { - if(timeoutInSeconds >= 0) + if (_timeoutInSeconds >= 0) { - if( (DateTime.UtcNow - startTime).TotalSeconds > timeoutInSeconds) + if ((DateTime.UtcNow - startTime).TotalSeconds > _timeoutInSeconds) break; } - - received = eventArrived.WaitOne(200); + + received = _eventArrived.WaitOne(200); eventManager.ProcessPendingActions(); } @@ -94,9 +95,9 @@ namespace Microsoft.PowerShell.Commands // Unsubscribe, and write the event information we received Events.ReceivedEvents.PSEventReceived -= ReceivedEvents_PSEventReceived; - if(receivedEvent != null) + if (_receivedEvent != null) { - WriteObject(receivedEvent); + WriteObject(_receivedEvent); } } @@ -105,13 +106,13 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - eventArrived.Set(); + _eventArrived.Set(); } private void ReceivedEvents_PSEventReceived(Object sender, PSEventArgs e) { // If they want to wait on just any event - if(sourceIdentifier == null) + if (_sourceIdentifier == null) { NotifyEvent(e); } @@ -127,12 +128,12 @@ namespace Microsoft.PowerShell.Commands // break. private void ScanEventQueue() { - lock(Events.ReceivedEvents.SyncRoot) + lock (Events.ReceivedEvents.SyncRoot) { - foreach(PSEventArgs eventArg in Events.ReceivedEvents) + foreach (PSEventArgs eventArg in Events.ReceivedEvents) { // If they specified a subscription identifier and we don't match, continue - if((matchPattern == null) || (matchPattern.IsMatch(eventArg.SourceIdentifier))) + if ((_matchPattern == null) || (_matchPattern.IsMatch(eventArg.SourceIdentifier))) { NotifyEvent(eventArg); return; @@ -144,14 +145,14 @@ namespace Microsoft.PowerShell.Commands // Notify that an event has arrived private void NotifyEvent(PSEventArgs e) { - if (receivedEvent == null) + if (_receivedEvent == null) { - lock (receivedEventLock) + lock (_receivedEventLock) { - if (receivedEvent == null) + if (_receivedEvent == null) { - receivedEvent = e; - eventArrived.Set(); + _receivedEvent = e; + _eventArrived.Set(); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index f6f3fbc35..328dfbda9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -24,7 +24,7 @@ namespace Microsoft.PowerShell.Commands /// gets or protected sets the Content property /// public new string Content { get; private set; } - + private WebCmdletElementCollection _inputFields; /// @@ -39,7 +39,7 @@ namespace Microsoft.PowerShell.Commands EnsureHtmlParser(); List parsedFields = new List(); - MatchCollection fieldMatch = _inputFieldRegex.Matches(Content); + MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); foreach (Match field in fieldMatch) { parsedFields.Add(CreateHtmlObject(field.Value, "INPUT")); @@ -66,7 +66,7 @@ namespace Microsoft.PowerShell.Commands EnsureHtmlParser(); List parsedLinks = new List(); - MatchCollection linkMatch = _linkRegex.Matches(Content); + MatchCollection linkMatch = s_linkRegex.Matches(Content); foreach (Match link in linkMatch) { parsedLinks.Add(CreateHtmlObject(link.Value, "A")); @@ -93,7 +93,7 @@ namespace Microsoft.PowerShell.Commands EnsureHtmlParser(); List parsedImages = new List(); - MatchCollection imageMatch = _imageRegex.Matches(Content); + MatchCollection imageMatch = s_imageRegex.Matches(Content); foreach (Match image in imageMatch) { parsedImages.Add(CreateHtmlObject(image.Value, "IMG")); @@ -110,12 +110,12 @@ namespace Microsoft.PowerShell.Commands #region Private Fields - private static Regex _tagRegex; - private static Regex _attribsRegex; - private static Regex _attribNameValueRegex; - private static Regex _inputFieldRegex; - private static Regex _linkRegex; - private static Regex _imageRegex; + private static Regex s_tagRegex; + private static Regex s_attribsRegex; + private static Regex s_attribNameValueRegex; + private static Regex s_inputFieldRegex; + private static Regex s_linkRegex; + private static Regex s_imageRegex; #endregion Private Fields @@ -123,40 +123,39 @@ namespace Microsoft.PowerShell.Commands private void EnsureHtmlParser() { - - if (_tagRegex == null) + if (s_tagRegex == null) { - _tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", + s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (_attribsRegex == null) + if (s_attribsRegex == null) { - _attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", + s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (_attribNameValueRegex == null) + if (s_attribNameValueRegex == null) { - _attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", + s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (_inputFieldRegex == null) + if (s_inputFieldRegex == null) { - _inputFieldRegex = new Regex(@"]*(/>|>.*?)", + s_inputFieldRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (_linkRegex == null) + if (s_linkRegex == null) { - _linkRegex = new Regex(@"]*(/>|>.*?)", + s_linkRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (_imageRegex == null) + if (s_imageRegex == null) { - _imageRegex = new Regex(@"]*>", + s_imageRegex = new Regex(@"]*>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } } @@ -172,7 +171,7 @@ namespace Microsoft.PowerShell.Commands return elementObject; } - + private void ParseAttributes(string outerHtml, PSObject elementObject) { // We might get an empty input for a directive from the HTML file @@ -180,16 +179,16 @@ namespace Microsoft.PowerShell.Commands { // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, // including contained HTML elements) - var match = _tagRegex.Match(outerHtml); + var match = s_tagRegex.Match(outerHtml); // Extract all the attribute specifications within the HTML element opening tag - var attribMatches = _attribsRegex.Matches(match.Value); + var attribMatches = s_attribsRegex.Matches(match.Value); foreach (Match attribMatch in attribMatches) { // Extract the name and value for this attribute (allowing for variations like single/double/no // quotes, and no value at all) - var nvMatches = _attribNameValueRegex.Match(attribMatch.Value); + var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); Debug.Assert(nvMatches.Groups.Count == 5); // Name is always captured by group #1 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index a7e20981a..def92d903 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands #region Constants // used to split contentType arguments - private static readonly char[] _contentTypeParamSeparator = { ';' }; + private static readonly char[] s_contentTypeParamSeparator = { ';' }; // default codepage encoding for web content. See RFC 2616. private const string _defaultCodePage = "ISO-8859-1"; @@ -61,7 +61,7 @@ namespace Microsoft.PowerShell.Commands internal static Encoding GetDefaultEncoding() { - return GetEncodingOrDefault((string)null); + return GetEncodingOrDefault((string)null); } #endregion Internal Methods @@ -73,7 +73,7 @@ namespace Microsoft.PowerShell.Commands if (String.IsNullOrEmpty(contentType)) return null; - string sig = contentType.Split(_contentTypeParamSeparator, 2)[0].ToUpperInvariant(); + string sig = contentType.Split(s_contentTypeParamSeparator, 2)[0].ToUpperInvariant(); return (sig); } @@ -99,10 +99,10 @@ namespace Microsoft.PowerShell.Commands { using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { - if (extensionKey != null) + if (extensionKey != null) { - string perceivedType = extensionKey.GetValue("PerceivedType") as string; - isText = (perceivedType == "text"); + string perceivedType = extensionKey.GetValue("PerceivedType") as string; + isText = (perceivedType == "text"); } } } @@ -145,7 +145,7 @@ namespace Microsoft.PowerShell.Commands return (isJson); } - + #endregion Internal Helper Methods } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HtmlWebResponseObject.Common.cs index e07f4477b..e7462ccb8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HtmlWebResponseObject.Common.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Commands /// public partial class HtmlWebResponseObject : WebResponseObject, IDisposable { - #region Properties +#region Properties /// /// gets or protected sets the Content property @@ -50,7 +50,7 @@ namespace Microsoft.PowerShell.Commands // The flag that indicates the html is parsed private bool _htmlParsed = false; - + /// /// gets the ParsedHtml property /// @@ -167,7 +167,7 @@ namespace Microsoft.PowerShell.Commands } private WebCmdletElementCollection _scripts; - + /// /// gets the Scripts property /// @@ -220,18 +220,18 @@ namespace Microsoft.PowerShell.Commands } } - #endregion Properties - - #region Private Fields +#endregion Properties + +#region Private Fields private static Regex _tagRegex; private static Regex _attribsRegex; private static Regex _attribNameValueRegex; - #endregion Private Fields +#endregion Private Fields + +#region Methods - #region Methods - // The "onreadystatechange" event handler private void ReadyStateChanged(IHTMLEventObj obj) { @@ -297,7 +297,7 @@ namespace Microsoft.PowerShell.Commands // The IHTMLDocument events cannot be handled in STA ApartmentState, so we use a worker thread to load the document ThreadPool.QueueUserWorkItem(new WaitCallback(LoadDocumentInMtaThread)); - + // Wait for the worker thread to finish loading the document. In the meantime, we check the Ctrl-C every 500ms bool wait = true; while (wait) @@ -470,7 +470,7 @@ namespace Microsoft.PowerShell.Commands this.Content = string.Empty; } } - #endregion Methods +#endregion Methods /// /// Dispose the the instance of the class. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 899a9a54a..ac5c347f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -99,7 +99,7 @@ namespace Microsoft.PowerShell.Commands return xrs; } - + private bool TryConvertToXml(string xml, out object doc, ref Exception exRef) { try @@ -176,15 +176,15 @@ namespace Microsoft.PowerShell.Commands { internal BufferingStreamReader(Stream baseStream) { - this.baseStream = baseStream; - streamBuffer = new MemoryStream(); - this.length = long.MaxValue; - copyBuffer = new byte[4096]; + _baseStream = baseStream; + _streamBuffer = new MemoryStream(); + _length = long.MaxValue; + _copyBuffer = new byte[4096]; } - private Stream baseStream; - private MemoryStream streamBuffer; - private byte[] copyBuffer; + private Stream _baseStream; + private MemoryStream _streamBuffer; + private byte[] _copyBuffer; public override bool CanRead { @@ -203,19 +203,19 @@ namespace Microsoft.PowerShell.Commands public override void Flush() { - streamBuffer.SetLength(0); + _streamBuffer.SetLength(0); } public override long Length { - get { return this.length; } + get { return _length; } } - private long length; + private long _length; public override long Position { - get { return streamBuffer.Position; } - set { streamBuffer.Position = value; } + get { return _streamBuffer.Position; } + set { _streamBuffer.Position = value; } } public override int Read(byte[] buffer, int offset, int count) @@ -224,24 +224,24 @@ namespace Microsoft.PowerShell.Commands bool consumedStream = false; int totalCount = count; while ((!consumedStream) && - ((Position + totalCount) > streamBuffer.Length)) + ((Position + totalCount) > _streamBuffer.Length)) { // If we don't have enough data to fill this from memory, cache more. // We try to read 4096 bytes from base stream every time, so at most we // may cache 4095 bytes more than what is required by the Read operation. - int bytesRead = baseStream.Read(copyBuffer, 0, copyBuffer.Length); + int bytesRead = _baseStream.Read(_copyBuffer, 0, _copyBuffer.Length); - if (streamBuffer.Position < streamBuffer.Length) + if (_streamBuffer.Position < _streamBuffer.Length) { // Win8: 651902 no need to -1 here as Position refers to the place // where we can start writing from. - streamBuffer.Position = streamBuffer.Length; + _streamBuffer.Position = _streamBuffer.Length; } - streamBuffer.Write(copyBuffer, 0, bytesRead); + _streamBuffer.Write(_copyBuffer, 0, bytesRead); totalCount -= bytesRead; - if (bytesRead < copyBuffer.Length) + if (bytesRead < _copyBuffer.Length) { consumedStream = true; } @@ -249,10 +249,10 @@ namespace Microsoft.PowerShell.Commands // Reset our backing store to its official position, as reading // for the CopyTo updates the position. - streamBuffer.Seek(previousPosition, SeekOrigin.Begin); + _streamBuffer.Seek(previousPosition, SeekOrigin.Begin); // Read from the backing store into the requested buffer. - int read = streamBuffer.Read(buffer, offset, count); + int read = _streamBuffer.Read(buffer, offset, count); if (read < count) { @@ -264,12 +264,12 @@ namespace Microsoft.PowerShell.Commands public override long Seek(long offset, SeekOrigin origin) { - return streamBuffer.Seek(offset, origin); + return _streamBuffer.Seek(offset, origin); } public override void SetLength(long value) { - this.length = value; + _length = value; } public override void Write(byte[] buffer, int offset, int count) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 6b070db23..32e65f868 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -129,10 +129,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public virtual int MaximumRedirection { - get { return maximumRedirection; } - set { maximumRedirection = value; } + get { return _maximumRedirection; } + set { _maximumRedirection = value; } } - private int maximumRedirection = -1; + private int _maximumRedirection = -1; #endregion @@ -144,10 +144,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public virtual WebRequestMethod Method { - get { return method; } - set { method = value; } + get { return _method; } + set { _method = value; } } - private WebRequestMethod method = WebRequestMethod.Default; + private WebRequestMethod _method = WebRequestMethod.Default; #endregion @@ -433,7 +433,7 @@ namespace Microsoft.PowerShell.Commands } } } - + #endregion Virtual Methods #region Helper Properties @@ -559,7 +559,7 @@ namespace Microsoft.PowerShell.Commands return uri; } - + private Uri CheckProtocol(Uri uri) { if (null == uri) { throw new ArgumentNullException("uri"); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index c36acd32b..d01d2bc08 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -18,9 +18,9 @@ namespace Microsoft.PowerShell.Commands /// /// gets or protected sets the Content property /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Content { get; protected set; } - + /// /// gets the StatusCode property /// @@ -41,11 +41,11 @@ namespace Microsoft.PowerShell.Commands /// /// gets the RawContentStream property /// - public MemoryStream RawContentStream + public MemoryStream RawContentStream { get { return (_rawContentStream); } } - + /// /// gets the RawContentLength property /// @@ -60,7 +60,7 @@ namespace Microsoft.PowerShell.Commands public string RawContent { get; protected set; } #endregion Properties - + #region Methods /// @@ -93,7 +93,7 @@ namespace Microsoft.PowerShell.Commands return new string(stringContent); } - + #endregion Methods } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index 5583941ec..7c89579d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -15,7 +15,7 @@ namespace Microsoft.PowerShell.Commands /// This command convert a Json string representation to a JsonObject /// [Cmdlet(VerbsData.ConvertFrom, "Json", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217031", RemotingCapability = RemotingCapability.None)] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public class ConvertFromJsonCommand : Cmdlet { #region parameters @@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands /// /// inputObjectBuffer buffers all InputObjet contents avaliable in the pipeline. /// - private List inputObjectBuffer = new List(); + private List _inputObjectBuffer = new List(); #endregion parameters @@ -64,7 +64,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - inputObjectBuffer.Add(InputObject); + _inputObjectBuffer.Add(InputObject); } /// @@ -75,18 +75,18 @@ namespace Microsoft.PowerShell.Commands // When Input is provided through pipeline, the input can be represented in the following two ways: // 1. Each input to the buffer is a complete Json content. There can be multiple inputs of this format. // 2. The complete buffer input collectively represent a single JSon format. This is typically the majority of the case. - if (inputObjectBuffer.Count > 0) + if (_inputObjectBuffer.Count > 0) { - if (inputObjectBuffer.Count == 1) + if (_inputObjectBuffer.Count == 1) { - ConvertFromJsonHelper(inputObjectBuffer[0]); + ConvertFromJsonHelper(_inputObjectBuffer[0]); } else { bool successfullyConverted = false; try { - successfullyConverted = ConvertFromJsonHelper(inputObjectBuffer[0]); + successfullyConverted = ConvertFromJsonHelper(_inputObjectBuffer[0]); } catch (ArgumentException) { @@ -101,14 +101,14 @@ namespace Microsoft.PowerShell.Commands #endif if (successfullyConverted) { - for (int index = 1; index < inputObjectBuffer.Count; index++) + for (int index = 1; index < _inputObjectBuffer.Count; index++) { - ConvertFromJsonHelper(inputObjectBuffer[index]); + ConvertFromJsonHelper(_inputObjectBuffer[index]); } } else { - ConvertFromJsonHelper(string.Join(System.Environment.NewLine, inputObjectBuffer.ToArray())); + ConvertFromJsonHelper(string.Join(System.Environment.NewLine, _inputObjectBuffer.ToArray())); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 7dca44267..268d65779 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands /// This command convert an object to a Json string representation /// [Cmdlet(VerbsData.ConvertTo, "Json", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217032", RemotingCapability = RemotingCapability.None)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public class ConvertToJsonCommand : PSCmdlet { #region parameters @@ -96,7 +96,7 @@ namespace Microsoft.PowerShell.Commands #endif } - private List inputObjects = new List(); + private List _inputObjects = new List(); /// /// Caching the input objects for the convertto-json command @@ -105,7 +105,7 @@ namespace Microsoft.PowerShell.Commands { if (InputObject != null) { - inputObjects.Add(InputObject); + _inputObjects.Add(InputObject); } } @@ -114,9 +114,9 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (inputObjects.Count > 0) + if (_inputObjects.Count > 0) { - object objectToProcess = (inputObjects.Count > 1) ? (inputObjects.ToArray() as object) : (inputObjects[0]); + object objectToProcess = (_inputObjects.Count > 1) ? (_inputObjects.ToArray() as object) : (_inputObjects[0]); // Pre-process the object so that it serializes the same, except that properties whose // values cannot be evaluated are treated as having the value null. object preprocessedObject = ProcessValue(objectToProcess, 0); @@ -128,7 +128,7 @@ namespace Microsoft.PowerShell.Commands // ProcessValue creates an object to be serialized from 1 to depth. However, the properties of the object at 'depth' should also be serialized, // and from the perspective of the serializer, this means it needs to support serializing depth + 1. For the JavaScriptSerializer to support this, // RecursionLimit needs to be set to depth + 2. - JavaScriptSerializer helper = new JavaScriptSerializer() {RecursionLimit = (maxDepthAllowed + 2)}; + JavaScriptSerializer helper = new JavaScriptSerializer() { RecursionLimit = (maxDepthAllowed + 2) }; helper.MaxJsonLength = Int32.MaxValue; string output = helper.Serialize(preprocessedObject); #endif @@ -373,7 +373,7 @@ namespace Microsoft.PowerShell.Commands /// private void AddIndentations(int numberOfTabsToReturn, StringBuilder result) { - int realNumber = numberOfTabsToReturn*4; + int realNumber = numberOfTabsToReturn * 4; for (int i = 0; i < realNumber; i++) { result.Append(' '); @@ -427,7 +427,7 @@ namespace Microsoft.PowerShell.Commands bool isPurePSObj = false; bool isCustomObj = false; - if ( obj == null + if (obj == null || DBNull.Value.Equals(obj) || obj is string || obj is char @@ -463,7 +463,6 @@ namespace Microsoft.PowerShell.Commands { rv = obj; } - } else { @@ -473,7 +472,7 @@ namespace Microsoft.PowerShell.Commands { // The obj is a pure PSObject, we convet the original PSObject to a string, // instead of its base object in this case - rv = LanguagePrimitives.ConvertTo(pso, typeof (string), + rv = LanguagePrimitives.ConvertTo(pso, typeof(string), CultureInfo.InvariantCulture); isPurePSObj = true; } @@ -531,7 +530,7 @@ namespace Microsoft.PowerShell.Commands /// private object AddPsProperties(object psobj, object obj, int depth, bool isPurePSObj, bool isCustomObj) { - PSObject pso = psobj as PSObject; + PSObject pso = psobj as PSObject; if (pso == null) return obj; @@ -574,7 +573,7 @@ namespace Microsoft.PowerShell.Commands // serialize only Extended and Adapted properties.. PSMemberInfoCollection srcPropertiesToSearch = new PSMemberInfoIntegratingCollection(psobj, - isCustomObject ? PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted) : + isCustomObject ? PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted) : PSObject.GetPropertyCollection(PSMemberViewTypes.Extended)); foreach (PSPropertyInfo prop in srcPropertiesToSearch) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/BasicHtmlWebResponseObject.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/BasicHtmlWebResponseObject.CoreClr.cs index b1f09a5b7..f4b060430 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/BasicHtmlWebResponseObject.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/BasicHtmlWebResponseObject.CoreClr.cs @@ -22,7 +22,8 @@ namespace Microsoft.PowerShell.Commands /// /// public BasicHtmlWebResponseObject(HttpResponseMessage response) - : this(response, null) { } + : this(response, null) + { } /// /// Constructor for HtmlWebResponseObject with memory stream diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HtmlWebResponseObject.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HtmlWebResponseObject.CoreClr.cs index 2b6fc8f97..09879c6e3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HtmlWebResponseObject.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HtmlWebResponseObject.CoreClr.cs @@ -26,7 +26,8 @@ namespace Microsoft.PowerShell.Commands /// /// internal HtmlWebResponseObject(HttpResponseMessage response, ExecutionContext executionContext) - : this(response, null, executionContext) { } + : this(response, null, executionContext) + { } /// /// Constructor for HtmlWebResponseObject with memory stream diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 754e6f47b..4a60e4eae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -81,30 +81,31 @@ namespace Microsoft.PowerShell.Commands #endregion Known_HTTP_Header_Names - private static HashSet _contentHeaderSet = null; + private static HashSet s_contentHeaderSet = null; internal static HashSet ContentHeaders { - get { - if (_contentHeaderSet == null) + get + { + if (s_contentHeaderSet == null) { - _contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); + s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); - _contentHeaderSet.Add(HttpKnownHeaderNames.Allow); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentDisposition); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentEncoding); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentLanguage); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentLength); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentLocation); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentMD5); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentRange); - _contentHeaderSet.Add(HttpKnownHeaderNames.ContentType); - _contentHeaderSet.Add(HttpKnownHeaderNames.Expires); - _contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); + s_contentHeaderSet.Add(HttpKnownHeaderNames.Allow); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentDisposition); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentEncoding); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLanguage); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLength); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentLocation); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentMD5); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentRange); + s_contentHeaderSet.Add(HttpKnownHeaderNames.ContentType); + s_contentHeaderSet.Add(HttpKnownHeaderNames.Expires); + s_contentHeaderSet.Add(HttpKnownHeaderNames.LastModified); } - return _contentHeaderSet; + return s_contentHeaderSet; } } } } -#endif \ No newline at end of file +#endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeRestMethodCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeRestMethodCommand.CoreClr.cs index 679764f79..5158e9398 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeRestMethodCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeRestMethodCommand.CoreClr.cs @@ -82,11 +82,11 @@ namespace Microsoft.PowerShell.Commands } } } - + #endregion Virtual Method Overrides #region Helper Methods - + private RestReturnType CheckReturnType(HttpResponseMessage response) { if (null == response) { throw new ArgumentNullException("response"); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 61393b562..2ceb4dc3b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands private ICredentials _credentials; private Uri _proxyAddress; - internal WebProxy (Uri address) + internal WebProxy(Uri address) { if (address == null) { @@ -37,10 +37,12 @@ namespace Microsoft.PowerShell.Commands internal bool UseDefaultCredentials { - get { + get + { return _credentials == CredentialCache.DefaultCredentials; } - set { + set + { _credentials = value ? CredentialCache.DefaultCredentials : null; } } @@ -51,7 +53,7 @@ namespace Microsoft.PowerShell.Commands { throw new ArgumentNullException("destination"); } - + if (destination.IsLoopback) { return destination; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebRequestPSCmdlet.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebRequestPSCmdlet.CoreClr.cs index a13f99406..85e5f1dfe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebRequestPSCmdlet.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebRequestPSCmdlet.CoreClr.cs @@ -38,7 +38,7 @@ namespace Microsoft.PowerShell.Commands /// /// Cancellation token source /// - private CancellationTokenSource cancelToken = null; + private CancellationTokenSource _cancelToken = null; private HttpMethod GetHttpMethod(WebRequestMethod method) { @@ -129,7 +129,7 @@ namespace Microsoft.PowerShell.Commands { Uri requestUri = PrepareUri(uri); HttpMethod httpMethod = GetHttpMethod(Method); - + // create the base WebRequest object var request = new HttpRequestMessage(httpMethod, requestUri); @@ -191,7 +191,7 @@ namespace Microsoft.PowerShell.Commands return (request); } - + internal virtual void FillRequestStream(HttpRequestMessage request) { if (null == request) { throw new ArgumentNullException("request"); } @@ -300,11 +300,11 @@ namespace Microsoft.PowerShell.Commands internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request) { - if (client == null) { throw new ArgumentNullException("client"); } + if (client == null) { throw new ArgumentNullException("client"); } if (request == null) { throw new ArgumentNullException("request"); } - cancelToken = new CancellationTokenSource(); - return client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancelToken.Token).GetAwaiter().GetResult(); + _cancelToken = new CancellationTokenSource(); + return client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); } internal virtual void UpdateSession(HttpResponseMessage response) @@ -342,7 +342,7 @@ namespace Microsoft.PowerShell.Commands request.RequestUri, requestContentLength); WriteVerbose(reqVerboseMsg); - + HttpResponseMessage response = GetResponse(client, request); response.EnsureSuccessStatusCode(); @@ -394,16 +394,16 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - if (cancelToken != null) + if (_cancelToken != null) { - cancelToken.Cancel(); + _cancelToken.Cancel(); } } #endregion Overrides #region Helper Methods - + /// /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. /// @@ -535,7 +535,7 @@ namespace Microsoft.PowerShell.Commands } -#endregion Helper Methods + #endregion Helper Methods } } #endif \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index 8cd466de8..1ebf57146 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -26,7 +26,7 @@ namespace Microsoft.PowerShell.Commands internal static int GetStatusCode(HttpResponseMessage response) { - int statusCode = (int) response.StatusCode; + int statusCode = (int)response.StatusCode; return statusCode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObject.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObject.CoreClr.cs index 1ea26bec0..4413c6d73 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObject.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObject.CoreClr.cs @@ -50,7 +50,8 @@ namespace Microsoft.PowerShell.Commands /// /// public WebResponseObject(HttpResponseMessage response) - : this(response, null) { } + : this(response, null) + { } /// /// Constructor for WebResponseObject with contentStream diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index 573192001..d815a3e49 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -46,7 +46,7 @@ namespace Microsoft.PowerShell.Commands Fields = new Dictionary(); } - internal void AddField( string key, string value ) + internal void AddField(string key, string value) { string test; if (null != key && !Fields.TryGetValue(key, out test)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/BasicHtmlWebResponseObject.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/BasicHtmlWebResponseObject.FullClr.cs index c8e60f2b8..80ee6bb1d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/BasicHtmlWebResponseObject.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/BasicHtmlWebResponseObject.FullClr.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Net; using System.IO; using System.Text; @@ -19,7 +20,8 @@ namespace Microsoft.PowerShell.Commands /// /// public BasicHtmlWebResponseObject(WebResponse response) - : this(response, null) { } + : this(response, null) + { } /// /// Constructor for HtmlWebResponseObject with memory stream diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/HtmlWebResponseObject.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/HtmlWebResponseObject.FullClr.cs index df86744cd..2b869f59d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/HtmlWebResponseObject.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/HtmlWebResponseObject.FullClr.cs @@ -24,7 +24,8 @@ namespace Microsoft.PowerShell.Commands /// /// internal HtmlWebResponseObject(WebResponse response, ExecutionContext executionContext) - : this(response, null, executionContext) { } + : this(response, null, executionContext) + { } /// /// Constructor for HtmlWebResponseObject with memory stream diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/InvokeRestMethodCommand.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/InvokeRestMethodCommand.FullClr.cs index 870fc32a2..a084d6eff 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/InvokeRestMethodCommand.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/InvokeRestMethodCommand.FullClr.cs @@ -80,11 +80,11 @@ namespace Microsoft.PowerShell.Commands } } } - + #endregion Virtual Method Overrides #region Helper Methods - + private RestReturnType CheckReturnType(WebResponse response) { if (null == response) { throw new ArgumentNullException("response"); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebRequestPSCmdlet.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebRequestPSCmdlet.FullClr.cs index 97f74fff1..9969757d9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebRequestPSCmdlet.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebRequestPSCmdlet.FullClr.cs @@ -734,7 +734,6 @@ namespace Microsoft.PowerShell.Commands string body = FormatDictionary(content); return (SetRequestContent(request, body)); - } #endregion Helper Methods diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseHelper.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseHelper.FullClr.cs index cf99c83e5..8e6542760 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseHelper.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseHelper.FullClr.cs @@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands HttpWebResponse httpResponse = response as HttpWebResponse; if (null != httpResponse) { - protocol = string.Format(CultureInfo.InvariantCulture, + protocol = string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", httpResponse.ProtocolVersion); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObject.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObject.FullClr.cs index 67182e4af..ee9087c46 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObject.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObject.FullClr.cs @@ -48,7 +48,8 @@ namespace Microsoft.PowerShell.Commands /// /// public WebResponseObject(WebResponse response) - : this(response, null) { } + : this(response, null) + { } /// /// Constructor for WebResponseObject with contentStream @@ -105,7 +106,6 @@ namespace Microsoft.PowerShell.Commands } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, null); - } // set the position of the content stream to the beginning _rawContentStream.Position = 0; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObjectFactory.FullClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObjectFactory.FullClr.cs index d5b9f98e6..1d42838ee 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObjectFactory.FullClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FullClr/WebResponseObjectFactory.FullClr.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Net; using System.IO; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 2a873fe3c..159328d05 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -196,7 +196,7 @@ namespace Microsoft.PowerShell.Commands { // It is not, try to load it. // Make sure that PSModuleAutoLoadingPreference is not set to 'None'. - PSModuleAutoLoadingPreference moduleAutoLoadingPreference = + PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(cmdlet.Context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if (moduleAutoLoadingPreference == PSModuleAutoLoadingPreference.None) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index 1a6e8111a..8b3911810 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -120,7 +120,7 @@ namespace Microsoft.PowerShell.Commands internal static string Platform { - get + get { return ("Windows NT"); } @@ -135,7 +135,7 @@ namespace Microsoft.PowerShell.Commands #else OperatingSystem os = Environment.OSVersion; string platform = GetOSName(os.Platform); - string formattedOS = string.Format(CultureInfo.InvariantCulture, + string formattedOS = string.Format(CultureInfo.InvariantCulture, "{0} {1}.{2}", platform, os.Version.Major, os.Version.Minor); return (formattedOS); #endif diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index e072ab59e..c0a96bd67 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -27,9 +27,9 @@ namespace Microsoft.PowerShell.Commands { #region Data - private Stream originalStreamToProxy; - private bool isInitialized = false; - private Cmdlet ownerCmdlet; + private Stream _originalStreamToProxy; + private bool _isInitialized = false; + private Cmdlet _ownerCmdlet; #endregion @@ -43,8 +43,8 @@ namespace Microsoft.PowerShell.Commands internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet) : base(initialCapacity) { - originalStreamToProxy = stream; - ownerCmdlet = cmdlet; + _originalStreamToProxy = stream; + _ownerCmdlet = cmdlet; } #endregion @@ -270,28 +270,28 @@ namespace Microsoft.PowerShell.Commands /// private void Initialize() { - if (isInitialized) { return; } - isInitialized = true; + if (_isInitialized) { return; } + _isInitialized = true; try { long totalLength = 0; byte[] buffer = new byte[StreamHelper.ChunkSize]; for (int read = 1; 0 < read; totalLength += read) { - if (null != ownerCmdlet) + if (null != _ownerCmdlet) { ProgressRecord record = new ProgressRecord(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, StringUtil.Format(WebCmdletStrings.ReadResponseProgressStatus, totalLength)); - ownerCmdlet.WriteProgress(record); + _ownerCmdlet.WriteProgress(record); - if (ownerCmdlet.IsStopping) + if (_ownerCmdlet.IsStopping) { break; } } - read = originalStreamToProxy.Read(buffer, 0, buffer.Length); + read = _originalStreamToProxy.Read(buffer, 0, buffer.Length); if (0 < read) { @@ -299,13 +299,13 @@ namespace Microsoft.PowerShell.Commands } } - if (ownerCmdlet != null) + if (_ownerCmdlet != null) { ProgressRecord record = new ProgressRecord(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalLength)); record.RecordType = ProgressRecordType.Completed; - ownerCmdlet.WriteProgress(record); + _ownerCmdlet.WriteProgress(record); } // make sure the length is set appropriately @@ -334,7 +334,7 @@ namespace Microsoft.PowerShell.Commands #endregion Constants #region Static Methods - + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet) { byte[] data = new byte[ChunkSize]; @@ -372,7 +372,7 @@ namespace Microsoft.PowerShell.Commands output.Flush(); } - + internal static void WriteToStream(byte[] input, Stream output) { output.Write(input, 0, input.Length); @@ -407,7 +407,7 @@ namespace Microsoft.PowerShell.Commands // just use the default encoding if one wasn't provided encoding = ContentHelper.GetDefaultEncoding(); } - + StringBuilder result = new StringBuilder(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); @@ -449,7 +449,7 @@ namespace Microsoft.PowerShell.Commands } } while (bytesRead != 0); - + return result.ToString(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs index e7781ce30..8dfe117b1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs @@ -33,7 +33,7 @@ namespace Microsoft.PowerShell.Commands /// PUT method /// Put, - + /// /// DELETE method /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index 38cf7a7e8..009ef4396 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.Commands /// gets or sets the Header property /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public Dictionary Headers { get; set; } + public Dictionary Headers { get; set; } #if CORECLR /// @@ -66,7 +66,7 @@ namespace Microsoft.PowerShell.Commands /// gets or sets the RedirectMax property /// public int MaximumRedirection { get; set; } - + /// /// Construct a new instance of a WebRequestSession object. /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs index f30cd01ae..cb0b6e92f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands [Cmdlet("Write", "Output", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113427", RemotingCapability = RemotingCapability.None)] public sealed class WriteOutputCommand : PSCmdlet { - private PSObject[] inputObjects = null; + private PSObject[] _inputObjects = null; /// /// Holds the list of objects to be Written @@ -24,8 +24,8 @@ namespace Microsoft.PowerShell.Commands [AllowEmptyCollection] public PSObject[] InputObject { - get { return inputObjects; } - set { inputObjects = value; } + get { return _inputObjects; } + set { _inputObjects = value; } } /// @@ -44,9 +44,9 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (null == inputObjects) + if (null == _inputObjects) { - WriteObject(inputObjects); + WriteObject(_inputObjects); return; } @@ -55,7 +55,7 @@ namespace Microsoft.PowerShell.Commands { enumerate = false; } - foreach (PSObject inputObject in inputObjects) // compensate for ValueFromRemainingArguments + foreach (PSObject inputObject in _inputObjects) // compensate for ValueFromRemainingArguments { WriteObject(inputObject, enumerate); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs index 8087acb9d..2c158c833 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -1,9 +1,10 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { @@ -19,19 +20,19 @@ namespace Microsoft.PowerShell.Commands /// The Name parameter for the command /// /// - [Parameter (Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string Name { get { - return name; + return _name; } set { - name = value; + _name = value; } } - private string name; + private string _name; /// /// The Value parameter for the command @@ -42,14 +43,14 @@ namespace Microsoft.PowerShell.Commands { get { - return aliasValue; + return _aliasValue; } set { - aliasValue = value; + _aliasValue = value; } } - private string aliasValue; + private string _aliasValue; /// /// The description for the alias. @@ -60,15 +61,15 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description = String.Empty; + private string _description = String.Empty; /// /// The Option parameter allows the alias to be set to @@ -81,15 +82,15 @@ namespace Microsoft.PowerShell.Commands { get { - return options; + return _options; } set { - options = value; + _options = value; } } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// /// If set to true, the alias that is set is passed to the @@ -101,15 +102,15 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; /// /// The scope parameter for the command determines @@ -121,15 +122,15 @@ namespace Microsoft.PowerShell.Commands { get { - return scope; + return _scope; } set { - scope = value; + _scope = value; } } - private string scope; + private string _scope; /// @@ -142,15 +143,15 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; #endregion Parameters } // class WriteAliasCommandBase diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 23a7754fe..b98a545f6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -36,12 +36,12 @@ namespace Microsoft.PowerShell.Commands { get { - return objectToEcho; + return _objectToEcho; } set { - objectToEcho = value; + _objectToEcho = value; } } @@ -57,11 +57,11 @@ namespace Microsoft.PowerShell.Commands { get { - return notAppendNewline; + return _notAppendNewline; } set { - notAppendNewline = value; + _notAppendNewline = value; } } @@ -79,11 +79,11 @@ namespace Microsoft.PowerShell.Commands { get { - return separator; + return _separator; } set { - separator = value; + _separator = value; } } @@ -99,7 +99,7 @@ namespace Microsoft.PowerShell.Commands { string s = o as string; IEnumerable enumerable = null; - if (s != null) + if (s != null) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -151,7 +151,7 @@ namespace Microsoft.PowerShell.Commands protected override void ProcessRecord() { string result = ProcessObject(Object); - if(result == null) + if (result == null) { result = ""; } @@ -175,9 +175,8 @@ namespace Microsoft.PowerShell.Commands this.Host.UI.TranscribeResult(result); } - private Boolean notAppendNewline = false; - private object objectToEcho = null; - private object separator = " "; + private Boolean _notAppendNewline = false; + private object _objectToEcho = null; + private object _separator = " "; } - } // namespace Microsoft.PowerShell.Commands \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index fb09811d8..10994543f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -27,23 +27,23 @@ namespace Microsoft.PowerShell.Commands /// /// /// - + [Parameter( - Position = 0, - Mandatory = true, - HelpMessageBaseName = HelpMessageBaseName, + Position = 0, + Mandatory = true, + HelpMessageBaseName = HelpMessageBaseName, HelpMessageResourceId = "ActivityParameterHelpMessage")] - public - string + public + string Activity { get { - return activity; + return _activity; } set { - activity = value; + _activity = value; } } @@ -54,23 +54,23 @@ namespace Microsoft.PowerShell.Commands /// /// /// - + [Parameter( - Position = 1, + Position = 1, HelpMessageBaseName = HelpMessageBaseName, HelpMessageResourceId = "StatusParameterHelpMessage")] [ValidateNotNullOrEmpty] - public + public string Status { get { - return status; + return _status; } set { - status = value; + _status = value; } } @@ -91,11 +91,11 @@ namespace Microsoft.PowerShell.Commands { get { - return activityId; + return _activityId; } set { - activityId = value; + _activityId = value; } } @@ -116,11 +116,11 @@ namespace Microsoft.PowerShell.Commands { get { - return percentComplete; + return _percentComplete; } set { - percentComplete = value; + _percentComplete = value; } } @@ -141,11 +141,11 @@ namespace Microsoft.PowerShell.Commands { get { - return secondsRemaining; + return _secondsRemaining; } set { - secondsRemaining = value; + _secondsRemaining = value; } } @@ -165,11 +165,11 @@ namespace Microsoft.PowerShell.Commands { get { - return currentOperation; + return _currentOperation; } set { - currentOperation = value; + _currentOperation = value; } } @@ -190,11 +190,11 @@ namespace Microsoft.PowerShell.Commands { get { - return parentId; + return _parentId; } set { - parentId = value; + _parentId = value; } } @@ -239,11 +239,11 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceId; + return _sourceId; } set { - sourceId = value; + _sourceId = value; } } @@ -271,14 +271,14 @@ namespace Microsoft.PowerShell.Commands - private int activityId = 0; - private string activity; - private string status = WriteProgressResourceStrings.Processing; - private int percentComplete = -1; - private int secondsRemaining = -1; - private string currentOperation; - private int parentId = -1; - private int sourceId; + private int _activityId = 0; + private string _activity; + private string _status = WriteProgressResourceStrings.Processing; + private int _percentComplete = -1; + private int _secondsRemaining = -1; + private string _currentOperation; + private int _parentId = -1; + private int _sourceId; private bool _completed; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8b0659e7a..82055f90d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -45,7 +45,7 @@ namespace Microsoft.PowerShell.Commands _depth = value; } } - int _depth = 0; + private int _depth = 0; /// /// mandatory file name to write to @@ -79,10 +79,10 @@ namespace Microsoft.PowerShell.Commands set { _path = value; - isLiteralPath = true; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Input object to be exported @@ -128,14 +128,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noclobber; + return _noclobber; } set { - noclobber = value; + _noclobber = value; } } - private bool noclobber; + private bool _noclobber; /// /// Encoding optional flag @@ -207,7 +207,7 @@ namespace Microsoft.PowerShell.Commands protected override void StopProcessing() { base.StopProcessing(); - this._serializer.Stop(); + _serializer.Stop(); } #endregion Overrides @@ -217,7 +217,7 @@ namespace Microsoft.PowerShell.Commands /// /// handle to file stream /// - FileStream _fs; + private FileStream _fs; /// /// stream writer used to write to file @@ -232,7 +232,7 @@ namespace Microsoft.PowerShell.Commands /// /// FileInfo of file to clear read-only flag when operation is complete /// - private FileInfo readOnlyFileInfo = null; + private FileInfo _readOnlyFileInfo = null; private void CreateFileStream() { @@ -242,19 +242,19 @@ namespace Microsoft.PowerShell.Commands StreamWriter sw; PathUtils.MasterStreamOpen( - this, - this.Path, - this.Encoding, + this, + this.Path, + this.Encoding, false, // default encoding false, // append - this.Force, + this.Force, this.NoClobber, - out _fs, - out sw, - out readOnlyFileInfo, - isLiteralPath + out _fs, + out sw, + out _readOnlyFileInfo, + _isLiteralPath ); - + // create xml writer XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.CloseOutput = true; @@ -287,10 +287,10 @@ namespace Microsoft.PowerShell.Commands _fs = null; } // reset the read-only attribute - if (null != readOnlyFileInfo) + if (null != _readOnlyFileInfo) { - readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; - this.readOnlyFileInfo = null; + _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; + _readOnlyFileInfo = null; } } @@ -301,7 +301,7 @@ namespace Microsoft.PowerShell.Commands /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// public dispose method @@ -360,38 +360,38 @@ namespace Microsoft.PowerShell.Commands set { _paths = value; - isLiteralPath = true; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; #endregion Command Line Parameters #region IDisposable Members - private bool disposed = false; + private bool _disposed = false; /// /// public dispose method /// public void Dispose() { - if (!this.disposed) + if (!_disposed) { GC.SuppressFinalize(this); - if (this.helper != null) + if (_helper != null) { - this.helper.Dispose(); - this.helper = null; + _helper.Dispose(); + _helper = null; } - this.disposed = true; + _disposed = true; } } #endregion - private ImportXmlHelper helper; + private ImportXmlHelper _helper; /// /// ProcessRecord overload @@ -402,8 +402,8 @@ namespace Microsoft.PowerShell.Commands { foreach (string path in _paths) { - this.helper = new ImportXmlHelper(path, this, isLiteralPath); - this.helper.Import(); + _helper = new ImportXmlHelper(path, this, _isLiteralPath); + _helper.Import(); } } } @@ -414,7 +414,7 @@ namespace Microsoft.PowerShell.Commands protected override void StopProcessing() { base.StopProcessing(); - this.helper.Stop(); + _helper.Stop(); } } @@ -446,7 +446,7 @@ namespace Microsoft.PowerShell.Commands _depth = value; } } - int _depth = 0; + private int _depth = 0; /// @@ -593,7 +593,7 @@ namespace Microsoft.PowerShell.Commands WriteObject(data); } } - + //Cleaning up CleanUp(); } @@ -669,7 +669,7 @@ namespace Microsoft.PowerShell.Commands _serializer = new CustomSerialization(_xw, _notypeinformation, _depth); } } - + /// ///Cleaning up the MemoryStream /// @@ -695,7 +695,7 @@ namespace Microsoft.PowerShell.Commands /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// public dispose method @@ -731,7 +731,7 @@ namespace Microsoft.PowerShell.Commands /// Reference to cmdlet which is using this helper class /// private readonly PSCmdlet _cmdlet; - private bool isLiteralPath; + private bool _isLiteralPath; internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { @@ -745,7 +745,7 @@ namespace Microsoft.PowerShell.Commands } _path = fileName; _cmdlet = cmdlet; - this.isLiteralPath = isLiteralPath; + _isLiteralPath = isLiteralPath; } #endregion constructor @@ -782,7 +782,7 @@ namespace Microsoft.PowerShell.Commands internal void CreateFileStream() { - _fs = PathUtils.OpenFileStream(_path, _cmdlet, isLiteralPath); + _fs = PathUtils.OpenFileStream(_path, _cmdlet, _isLiteralPath); _xr = CreateXmlReader(_fs); } @@ -802,7 +802,7 @@ namespace Microsoft.PowerShell.Commands /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// public dispose method @@ -832,7 +832,7 @@ namespace Microsoft.PowerShell.Commands _cmdlet.WriteObject(totalCount); } - + ulong skip = _cmdlet.PagingParameters.Skip; ulong first = _cmdlet.PagingParameters.First; @@ -850,7 +850,6 @@ namespace Microsoft.PowerShell.Commands _cmdlet.WriteObject(result); first--; - } } // else try to flatten the output if possible @@ -926,13 +925,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public String[] Path { - get { return path; } + get { return _path; } set { - path = value; + _path = value; } } - private String[] path; + private String[] _path; /// /// Specifies the literal path which contains the xml files. The default is the current @@ -944,14 +943,14 @@ namespace Microsoft.PowerShell.Commands [Alias("PSPath")] public String[] LiteralPath { - get { return path; } + get { return _path; } set { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// The following is the definition of the input parameter "XML". @@ -965,13 +964,13 @@ namespace Microsoft.PowerShell.Commands [Alias("Node")] public System.Xml.XmlNode[] Xml { - get { return xml; } + get { return _xml; } set { - xml = value; + _xml = value; } } - private System.Xml.XmlNode[] xml; + private System.Xml.XmlNode[] _xml; /// /// The following is the definition of the input parameter in string format. @@ -983,13 +982,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string[] Content { - get { return content; } + get { return _content; } set { - content = value; + _content = value; } } - private string[] content; + private string[] _content; /// /// The following is the definition of the input parameter "Xpath". @@ -1000,13 +999,13 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string XPath { - get { return xpath; } + get { return _xpath; } set { - xpath = value; + _xpath = value; } } - private string xpath; + private string _xpath; /// /// The following definition used to specify the @@ -1040,7 +1039,7 @@ namespace Microsoft.PowerShell.Commands { SelectXmlInfo selectXmlInfo = new SelectXmlInfo(); selectXmlInfo.Node = foundXmlNode; - selectXmlInfo.Pattern = this.xpath; + selectXmlInfo.Pattern = _xpath; selectXmlInfo.Path = filePath; this.WriteObject(selectXmlInfo); @@ -1052,14 +1051,14 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); XmlNodeList xList; - if (this._namespace != null) + if (_namespace != null) { - XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, this._namespace); - xList = xmlNode.SelectNodes(xpath, xmlns); + XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, _namespace); + xList = xmlNode.SelectNodes(_xpath, xmlns); } else { - xList = xmlNode.SelectNodes(xpath); + xList = xmlNode.SelectNodes(_xpath); } this.WriteResults(xList, filePath); } @@ -1179,9 +1178,9 @@ namespace Microsoft.PowerShell.Commands { //If any file not resolved, execution stops. this is to make consistent with select-string. List fullresolvedPaths = new List(); - foreach (string fpath in path) + foreach (string fpath in _path) { - if (isLiteralPath) + if (_isLiteralPath) { string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath); fullresolvedPaths.Add(resolvedPath); @@ -1209,7 +1208,7 @@ namespace Microsoft.PowerShell.Commands } else if (ParameterSetName.Equals("Content", StringComparison.OrdinalIgnoreCase)) { - foreach (string xmlstring in content) + foreach (string xmlstring in _content) { XmlDocument xmlDocument; try @@ -1230,9 +1229,8 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(false, "Unrecognized parameterset"); } }//End ProcessRecord() - - #endregion overrides + #endregion overrides }//End Class /// @@ -1246,7 +1244,7 @@ namespace Microsoft.PowerShell.Commands private const string inputStream = "InputStream"; private const string MatchFormat = "{0}:{1}"; private const string SimpleFormat = "{0}"; - + /// /// The XmlNode that matches search /// @@ -1255,14 +1253,14 @@ namespace Microsoft.PowerShell.Commands { get { - return node; + return _node; } set { - node = value; + _node = value; } } - private XmlNode node; + private XmlNode _node; /// /// The FileName from which the match is found. @@ -1271,21 +1269,21 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { if (String.IsNullOrEmpty(value)) { - path = inputStream; + _path = inputStream; } else { - path = value; + _path = value; } } } - private string path; + private string _path; /// /// The pattern used to search @@ -1294,14 +1292,14 @@ namespace Microsoft.PowerShell.Commands { get { - return pattern; + return _pattern; } set { - pattern = value; + _pattern = value; } } - private string pattern; + private string _pattern; /// /// Returns the string representation of this object. The format @@ -1320,7 +1318,7 @@ namespace Microsoft.PowerShell.Commands /// private string ToString(string directory) { - string displayPath = (directory != null) ? RelativePath(directory) : this.path; + string displayPath = (directory != null) ? RelativePath(directory) : _path; return FormatLine(GetNodeText(), displayPath); } @@ -1331,15 +1329,15 @@ namespace Microsoft.PowerShell.Commands internal string GetNodeText() { string nodeText = String.Empty; - if (this.node != null) + if (_node != null) { - if (this.node.Value != null) + if (_node.Value != null) { - nodeText = this.node.Value.Trim(); + nodeText = _node.Value.Trim(); } else { - nodeText = this.node.InnerXml.Trim(); + nodeText = _node.InnerXml.Trim(); } } return nodeText; @@ -1356,7 +1354,7 @@ namespace Microsoft.PowerShell.Commands /// The relative path that was produced. private string RelativePath(string directory) { - string relPath = this.path; + string relPath = _path; if (!relPath.Equals(inputStream)) { if (relPath.StartsWith(directory, StringComparison.CurrentCultureIgnoreCase)) @@ -1382,7 +1380,7 @@ namespace Microsoft.PowerShell.Commands /// private string FormatLine(string text, string displaypath) { - if (this.path.Equals(inputStream)) + if (_path.Equals(inputStream)) { return StringUtil.Format(SimpleFormat, text); } @@ -1393,7 +1391,6 @@ namespace Microsoft.PowerShell.Commands } } - #endregion Select-Xml } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs index 8f4e3e97c..7ce0846f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/compare-object.cs @@ -119,15 +119,15 @@ namespace Microsoft.PowerShell.Commands #endregion Parameters #region Internal - private List referenceEntries; - private List referenceEntryBacklog + private List _referenceEntries; + private List _referenceEntryBacklog = new List(); - private List differenceEntryBacklog + private List _differenceEntryBacklog = new List(); - private OrderByProperty orderByProperty = null; - private OrderByPropertyComparer comparer = null; + private OrderByProperty _orderByProperty = null; + private OrderByPropertyComparer _comparer = null; - private int referenceObjectIndex /* = 0 */; + private int _referenceObjectIndex /* = 0 */; // These are programmatic strings, not subject to INTL private const string SideIndicatorPropertyName = "SideIndicator"; @@ -171,13 +171,13 @@ namespace Microsoft.PowerShell.Commands /// private void Process(OrderByPropertyEntry differenceEntry) { - Diagnostics.Assert(null != referenceEntries, "null referenceEntries"); + Diagnostics.Assert(null != _referenceEntries, "null referenceEntries"); // Retrieve the next reference object (referenceEntry) if any OrderByPropertyEntry referenceEntry = null; - if (referenceObjectIndex < referenceEntries.Count) + if (_referenceObjectIndex < _referenceEntries.Count) { - referenceEntry = referenceEntries[referenceObjectIndex++]; + referenceEntry = _referenceEntries[_referenceObjectIndex++]; } // If differenceEntry matches referenceEntry @@ -186,7 +186,7 @@ namespace Microsoft.PowerShell.Commands // 2005/07/19 Switched order of referenceEntry and differenceEntry // so that we cast differenceEntry to the type of referenceEntry. if (null != referenceEntry && null != differenceEntry && - 0 == comparer.Compare(referenceEntry, differenceEntry)) + 0 == _comparer.Compare(referenceEntry, differenceEntry)) { EmitMatch(referenceEntry); return; @@ -197,7 +197,7 @@ namespace Microsoft.PowerShell.Commands // Remove the backlog entry from referenceEntryBacklog // Clear differenceEntry OrderByPropertyEntry matchingEntry = - MatchAndRemove(differenceEntry, referenceEntryBacklog); + MatchAndRemove(differenceEntry, _referenceEntryBacklog); if (null != matchingEntry) { EmitMatch(matchingEntry); @@ -209,7 +209,7 @@ namespace Microsoft.PowerShell.Commands // Remove the backlog entry from differenceEntryBacklog // Clear referenceEntry matchingEntry = - MatchAndRemove(referenceEntry, differenceEntryBacklog); + MatchAndRemove(referenceEntry, _differenceEntryBacklog); if (null != matchingEntry) { EmitMatch(referenceEntry); @@ -228,12 +228,12 @@ namespace Microsoft.PowerShell.Commands { if (0 < SyncWindow) { - while (differenceEntryBacklog.Count >= SyncWindow) + while (_differenceEntryBacklog.Count >= SyncWindow) { - EmitDifferenceOnly(differenceEntryBacklog[0]); - differenceEntryBacklog.RemoveAt(0); + EmitDifferenceOnly(_differenceEntryBacklog[0]); + _differenceEntryBacklog.RemoveAt(0); } - differenceEntryBacklog.Add(differenceEntry); + _differenceEntryBacklog.Add(differenceEntry); } else { @@ -253,12 +253,12 @@ namespace Microsoft.PowerShell.Commands { if (0 < SyncWindow) { - while (referenceEntryBacklog.Count >= SyncWindow) + while (_referenceEntryBacklog.Count >= SyncWindow) { - EmitReferenceOnly(referenceEntryBacklog[0]); - referenceEntryBacklog.RemoveAt(0); + EmitReferenceOnly(_referenceEntryBacklog[0]); + _referenceEntryBacklog.RemoveAt(0); } - referenceEntryBacklog.Add(referenceEntry); + _referenceEntryBacklog.Add(referenceEntry); } else { @@ -269,24 +269,24 @@ namespace Microsoft.PowerShell.Commands private void InitComparer() { - if (null != comparer) + if (null != _comparer) return; List referenceObjectList = new List(ReferenceObject); - orderByProperty = new OrderByProperty( + _orderByProperty = new OrderByProperty( this, referenceObjectList, Property, true, _cultureInfo, CaseSensitive); - Diagnostics.Assert(orderByProperty.Comparer != null, "no comparer"); + Diagnostics.Assert(_orderByProperty.Comparer != null, "no comparer"); Diagnostics.Assert( - orderByProperty.OrderMatrix != null && - orderByProperty.OrderMatrix.Count == ReferenceObject.Length, + _orderByProperty.OrderMatrix != null && + _orderByProperty.OrderMatrix.Count == ReferenceObject.Length, "no OrderMatrix"); - if (orderByProperty.Comparer == null || orderByProperty.OrderMatrix == null || orderByProperty.OrderMatrix.Count == 0) + if (_orderByProperty.Comparer == null || _orderByProperty.OrderMatrix == null || _orderByProperty.OrderMatrix.Count == 0) { return; } - comparer = orderByProperty.Comparer; - referenceEntries = orderByProperty.OrderMatrix; + _comparer = _orderByProperty.Comparer; + _referenceEntries = _orderByProperty.OrderMatrix; } private OrderByPropertyEntry MatchAndRemove( @@ -295,12 +295,12 @@ namespace Microsoft.PowerShell.Commands { if (null == match || null == list) return null; - Diagnostics.Assert(null != comparer, "null comparer"); + Diagnostics.Assert(null != _comparer, "null comparer"); for (int i = 0; i < list.Count; i++) { OrderByPropertyEntry listEntry = list[i]; Diagnostics.Assert(null != listEntry, "null listEntry " + i); - if (0 == comparer.Compare(match, listEntry)) + if (0 == _comparer.Compare(match, listEntry)) { list.RemoveAt(i); return listEntry; @@ -348,7 +348,7 @@ namespace Microsoft.PowerShell.Commands } else { - List mshParameterList = orderByProperty.MshParameterList; + List mshParameterList = _orderByProperty.MshParameterList; Diagnostics.Assert(null != mshParameterList, "null mshParameterList"); Diagnostics.Assert(mshParameterList.Count == Property.Length, "mshParameterList.Count " + mshParameterList.Count); @@ -425,7 +425,7 @@ namespace Microsoft.PowerShell.Commands return; } - if (null == comparer && 0 < DifferenceObject.Length) + if (null == _comparer && 0 < DifferenceObject.Length) { InitComparer(); } @@ -433,7 +433,7 @@ namespace Microsoft.PowerShell.Commands List differenceList = new List(DifferenceObject); List differenceEntries = OrderByProperty.CreateOrderMatrix( - this, differenceList, orderByProperty.MshParameterList); + this, differenceList, _orderByProperty.MshParameterList); foreach (OrderByPropertyEntry incomingEntry in differenceEntries) { @@ -448,25 +448,25 @@ namespace Microsoft.PowerShell.Commands { // Clear remaining reference objects if there are more // reference objects than difference objects - if (referenceEntries != null) + if (_referenceEntries != null) { - while (referenceObjectIndex < referenceEntries.Count) + while (_referenceObjectIndex < _referenceEntries.Count) { Process(null); } } // emit all remaining backlogged objects - foreach (OrderByPropertyEntry differenceEntry in differenceEntryBacklog) + foreach (OrderByPropertyEntry differenceEntry in _differenceEntryBacklog) { EmitDifferenceOnly(differenceEntry); } - differenceEntryBacklog.Clear(); - foreach (OrderByPropertyEntry referenceEntry in referenceEntryBacklog) + _differenceEntryBacklog.Clear(); + foreach (OrderByPropertyEntry referenceEntry in _referenceEntryBacklog) { EmitReferenceOnly(referenceEntry); } - referenceEntryBacklog.Clear(); + _referenceEntryBacklog.Clear(); } #endregion Overrides @@ -478,11 +478,11 @@ namespace Microsoft.PowerShell.Commands } List differenceList = new List(DifferenceObject); - orderByProperty = new OrderByProperty( + _orderByProperty = new OrderByProperty( this, differenceList, Property, true, _cultureInfo, CaseSensitive); List differenceEntries = OrderByProperty.CreateOrderMatrix( - this, differenceList, orderByProperty.MshParameterList); + this, differenceList, _orderByProperty.MshParameterList); foreach (OrderByPropertyEntry entry in differenceEntries) { @@ -501,5 +501,5 @@ namespace Microsoft.PowerShell.Commands Process(null); } } -} +} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs index c992b38e4..0810d5549 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs @@ -14,6 +14,7 @@ using System.Net; using System.Reflection; using System.Text; using Microsoft.PowerShell.Commands.Internal.Format; + namespace Microsoft.PowerShell.Commands { /// @@ -34,71 +35,71 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; } } - private PSObject inputObject; + private PSObject _inputObject; /// /// The list of properties to display /// These take the form of an MshExpression /// /// - [Parameter (Position = 0)] + [Parameter(Position = 0)] public object[] Property { get { - return property; + return _property; } set { - property = value; + _property = value; } } - private object[] property; + private object[] _property; /// /// Text to go after the opening body tag /// and before the table /// /// - [Parameter(ParameterSetName = "Page",Position = 3)] + [Parameter(ParameterSetName = "Page", Position = 3)] public string[] Body { get { - return body; + return _body; } set { - body = value; + _body = value; } } - private string[] body; + private string[] _body; /// /// Text to go into the head section /// of the html doc /// /// - [Parameter(ParameterSetName = "Page",Position = 1)] + [Parameter(ParameterSetName = "Page", Position = 1)] public string[] Head { get { - return head; + return _head; } set { - head = value; + _head = value; } } - private string[] head; + private string[] _head; /// /// The string for the title tag @@ -114,14 +115,14 @@ namespace Microsoft.PowerShell.Commands { get { - return title; + return _title; } set { - title = value; + _title = value; } } - private string title = "HTML TABLE"; + private string _title = "HTML TABLE"; /// /// This specifies whether the objects should @@ -131,7 +132,7 @@ namespace Microsoft.PowerShell.Commands /// [Parameter] [ValidateNotNullOrEmpty] - [ValidateSet("Table","List")] + [ValidateSet("Table", "List")] public string As { get @@ -151,7 +152,7 @@ namespace Microsoft.PowerShell.Commands /// The html should reference the css file specified /// [Parameter(ParameterSetName = "Page")] - [Alias("cu","uri")] + [Alias("cu", "uri")] [ValidateNotNullOrEmpty] public Uri CssUri { @@ -162,11 +163,11 @@ namespace Microsoft.PowerShell.Commands set { _cssuri = value; - cssuriSpecified = true; + _cssuriSpecified = true; } } private Uri _cssuri; - private bool cssuriSpecified; + private bool _cssuriSpecified; /// /// When this switch is specified generate only the @@ -264,7 +265,7 @@ namespace Microsoft.PowerShell.Commands new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition()); if (properties == null) { - properties = new object[]{"*"}; + properties = new object[] { "*" }; } return processor.ProcessParameters(properties, invocationContext); } @@ -277,13 +278,13 @@ namespace Microsoft.PowerShell.Commands // temp list of properties with wildcards resolved ArrayList resolvedNameProperty = new ArrayList(); - foreach (MshParameter p in this.propertyMshParameterList) + foreach (MshParameter p in _propertyMshParameterList) { string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; - List resolvedNames = ex.ResolveNames(inputObject); + List resolvedNames = ex.ResolveNames(_inputObject); if (resolvedNames.Count == 1) { Hashtable ht = CreateAuxPropertyHT(label, alignment, width); @@ -303,7 +304,7 @@ namespace Microsoft.PowerShell.Commands } } } - resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray()); + _resolvedNameMshParameters = ProcessParameter(resolvedNameProperty.ToArray()); } private static Hashtable CreateAuxPropertyHT( @@ -349,7 +350,7 @@ namespace Microsoft.PowerShell.Commands } return ""; } - + /// /// @@ -357,18 +358,18 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { //ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here - if ((cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim()))) + if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim()))) { ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri")); ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri"); ThrowTerminatingError(er); } - propertyMshParameterList = ProcessParameter(property); + _propertyMshParameterList = ProcessParameter(_property); - if (!String.IsNullOrEmpty(title)) + if (!String.IsNullOrEmpty(_title)) { - WebUtility.HtmlEncode(title); + WebUtility.HtmlEncode(_title); } @@ -381,15 +382,15 @@ namespace Microsoft.PowerShell.Commands WriteObject(""); WriteObject(""); WriteObject(""); - WriteObject(head ?? new string[] { "" + title + "" }, true); - if (cssuriSpecified) + WriteObject(_head ?? new string[] { "" + _title + "" }, true); + if (_cssuriSpecified) { WriteObject(""); } WriteObject(""); - if (body != null) + if (_body != null) { - WriteObject(body, true); + WriteObject(_body, true); } } if (_preContent != null) @@ -397,8 +398,8 @@ namespace Microsoft.PowerShell.Commands WriteObject(_preContent, true); } WriteObject(""); - isTHWritten = false; - propertyCollector = new StringCollection(); + _isTHWritten = false; + _propertyCollector = new StringCollection(); } /// @@ -441,7 +442,7 @@ namespace Microsoft.PowerShell.Commands /// private void WriteListEntry() { - foreach (MshParameter p in resolvedNameMshParameters) + foreach (MshParameter p in _resolvedNameMshParameters) { StringBuilder Listtag = new StringBuilder(); Listtag.Append(""); WriteListEntry(); } else //if the As parameter is Table, first we have to write the property names { - WriteColumns(resolvedNameMshParameters); + WriteColumns(_resolvedNameMshParameters); StringBuilder THtag = new StringBuilder(""); //write the table header - WriteTableHeader(THtag, resolvedNameMshParameters); + WriteTableHeader(THtag, _resolvedNameMshParameters); THtag.Append(""); WriteObject(THtag.ToString()); - isTHWritten = true; + _isTHWritten = true; } } //if the As parameter is Table, write the property values @@ -584,7 +585,7 @@ namespace Microsoft.PowerShell.Commands StringBuilder TRtag = new StringBuilder(""); //write the table row - WriteTableRow(TRtag, resolvedNameMshParameters); + WriteTableRow(TRtag, _resolvedNameMshParameters); TRtag.Append(""); WriteObject(TRtag.ToString()); @@ -613,10 +614,10 @@ namespace Microsoft.PowerShell.Commands /// /// list of incoming objects to compare /// - private bool isTHWritten; - private StringCollection propertyCollector; - private List propertyMshParameterList; - private List resolvedNameMshParameters; + private bool _isTHWritten; + private StringCollection _propertyCollector; + private List _propertyMshParameterList; + private List _resolvedNameMshParameters; //private string ResourcesBaseName = "ConvertHTMLStrings"; #endregion private diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/group-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/group-object.cs index 0de84b172..81893b21f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/group-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/group-object.cs @@ -12,6 +12,7 @@ using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using System.Text; + namespace Microsoft.PowerShell.Commands { /// @@ -99,8 +100,8 @@ namespace Microsoft.PowerShell.Commands { group = new Collection(); this.Add(groupValue.inputObject); - this.groupValue = groupValue; - name = BuildName(groupValue.orderValues); + _groupValue = groupValue; + _name = BuildName(groupValue.orderValues); } internal virtual void Add(PSObject groupValue) @@ -123,7 +124,7 @@ namespace Microsoft.PowerShell.Commands { sb.Append("{"); var length = sb.Length; - + foreach (object item in propertyValueItems) { sb.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", item.ToString())); @@ -152,7 +153,7 @@ namespace Microsoft.PowerShell.Commands get { ArrayList values = new ArrayList(); - foreach (ObjectCommandPropertyValue propValue in groupValue.orderValues) + foreach (ObjectCommandPropertyValue propValue in _groupValue.orderValues) { values.Add(propValue.PropertyValue); } @@ -188,9 +189,9 @@ namespace Microsoft.PowerShell.Commands /// public string Name { - get { return name; } + get { return _name; } } - private string name = null; + private string _name = null; /// /// @@ -199,9 +200,9 @@ namespace Microsoft.PowerShell.Commands /// internal OrderByPropertyEntry GroupValue { - get { return groupValue; } + get { return _groupValue; } } - private OrderByPropertyEntry groupValue = null; + private OrderByPropertyEntry _groupValue = null; } /// @@ -221,7 +222,7 @@ namespace Microsoft.PowerShell.Commands [TraceSourceAttribute( "GroupObjectCommand", "Class that has group base implementation")] - private static PSTraceSource tracer = + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("GroupObjectCommand", "Class that has group base implementation"); @@ -238,10 +239,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter NoElement { - get { return noElement; } - set { noElement = value; } + get { return _noElement; } + set { _noElement = value; } } - private bool noElement; + private bool _noElement; /// /// the Ashashtable parameter /// @@ -251,10 +252,10 @@ namespace Microsoft.PowerShell.Commands [Alias("AHT")] public SwitchParameter AsHashTable { - get { return ashashtable; } - set { ashashtable = value; } + get { return _ashashtable; } + set { _ashashtable = value; } } - private SwitchParameter ashashtable; + private SwitchParameter _ashashtable; /// /// /// @@ -262,16 +263,16 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "HashTable")] public SwitchParameter AsString { - get { return asstring; } - set { asstring = value; } + get { return _asstring; } + set { _asstring = value; } } - private SwitchParameter asstring; + private SwitchParameter _asstring; - private List groups = new List(); - private OrderByProperty orderByProperty = new OrderByProperty(); - private bool hasProcessedFirstInputObject; - private Dictionary tupleToGroupInfoMappingDictionary = new Dictionary(); - private OrderByPropertyComparer orderByPropertyComparer = null; + private List _groups = new List(); + private OrderByProperty _orderByProperty = new OrderByProperty(); + private bool _hasProcessedFirstInputObject; + private Dictionary _tupleToGroupInfoMappingDictionary = new Dictionary(); + private OrderByPropertyComparer _orderByPropertyComparer = null; #endregion @@ -320,7 +321,7 @@ namespace Microsoft.PowerShell.Commands if (!isCurrentItemGrouped) { // create a new group - tracer.WriteLine("Create a new group: {0}", currentObjectEntry.orderValues); + s_tracer.WriteLine("Create a new group: {0}", currentObjectEntry.orderValues); GroupInfo newObjGrp = noElement ? new GroupInfoNoElement(currentObjectEntry) : new GroupInfo(currentObjectEntry); groups.Add(newObjGrp); @@ -346,30 +347,30 @@ namespace Microsoft.PowerShell.Commands { OrderByPropertyEntry currentEntry = null; - if (!hasProcessedFirstInputObject) + if (!_hasProcessedFirstInputObject) { if (Property == null) { Property = OrderByProperty.GetDefaultKeyPropertySet(InputObject); } - orderByProperty.ProcessExpressionParameter(this, Property); + _orderByProperty.ProcessExpressionParameter(this, Property); - currentEntry = orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); + currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); bool[] ascending = new bool[currentEntry.orderValues.Count]; for (int index = 0; index < currentEntry.orderValues.Count; index++) { ascending[index] = true; } - orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive); + _orderByPropertyComparer = new OrderByPropertyComparer(ascending, _cultureInfo, CaseSensitive); - hasProcessedFirstInputObject = true; + _hasProcessedFirstInputObject = true; } else { - currentEntry = orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); + currentEntry = _orderByProperty.CreateOrderByPropertyEntry(this, InputObject, CaseSensitive, _cultureInfo); } - DoGrouping(currentEntry, this.NoElement, this.groups, tupleToGroupInfoMappingDictionary, orderByPropertyComparer); + DoGrouping(currentEntry, this.NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); } } @@ -378,17 +379,17 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - tracer.WriteLine(groups.Count); - if (groups.Count > 0) + s_tracer.WriteLine(_groups.Count); + if (_groups.Count > 0) { - if (ashashtable) + if (_ashashtable) { Hashtable _table = CollectionsUtil.CreateCaseInsensitiveHashtable(); try { - foreach (GroupInfo _grp in groups) + foreach (GroupInfo _grp in _groups) { - if (asstring) + if (_asstring) { _table.Add(_grp.Name, _grp.Group); } @@ -416,20 +417,19 @@ namespace Microsoft.PowerShell.Commands } else { - if (asstring) + if (_asstring) { ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectWithHashTable); - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, this.asstring); + ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, _asstring); ThrowTerminatingError(er); } else { - WriteObject(groups, true); + WriteObject(_groups, true); } } } } - } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs index 2928600f7..757fac639 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/new-object.cs @@ -26,28 +26,28 @@ namespace Microsoft.PowerShell.Commands public sealed class NewObjectCommand : PSCmdlet { #region parameters - private string typeName = null; + private string _typeName = null; /// the number [Parameter(ParameterSetName = netSetName, Mandatory = true, Position = 0)] public string TypeName { - get { return typeName; } - set { typeName = value; } + get { return _typeName; } + set { _typeName = value; } } - private string comObject = null; - private Guid comObjectClsId = Guid.Empty; + private string _comObject = null; + private Guid _comObjectClsId = Guid.Empty; /// the ProgID of the Com object [Parameter(ParameterSetName = "Com", Mandatory = true, Position = 0)] public string ComObject { - get { return comObject; } - set { comObject = value; } + get { return _comObject; } + set { _comObject = value; } } - private object[] arguments = null; + private object[] _arguments = null; /// /// The parameters for the constructor /// @@ -56,11 +56,11 @@ namespace Microsoft.PowerShell.Commands [Alias("Args")] public object[] ArgumentList { - get { return arguments; } - set { arguments = value; } + get { return _arguments; } + set { _arguments = value; } } - private SwitchParameter strict /* = false */; + private SwitchParameter _strict /* = false */; /// /// True if we should have an error when Com objects will use an interop assembly @@ -68,12 +68,12 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "Com")] public SwitchParameter Strict { - get { return strict; } - set { strict = value; } + get { return _strict; } + set { _strict = value; } } // Updated from Hashtable to IDictionary to support the work around ordered hashtables. - private IDictionary property; + private IDictionary _property; /// /// gets the properties to be set. /// @@ -81,8 +81,8 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary Property { - get { return property; } - set { property = value; } + get { return _property; } + set { _property = value; } } # endregion parameters @@ -93,7 +93,6 @@ namespace Microsoft.PowerShell.Commands try { result = DotNetAdapter.ConstructorInvokeDotNet(type, constructors, args); - } catch (MethodException e) { @@ -105,7 +104,6 @@ namespace Microsoft.PowerShell.Commands } // let other exceptions propagate return result; - } private void CreateMemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType) @@ -159,7 +157,7 @@ namespace Microsoft.PowerShell.Commands object _newObject = null; try { - type = LanguagePrimitives.ConvertTo(typeName, typeof(Type), CultureInfo.InvariantCulture) as Type; + type = LanguagePrimitives.ConvertTo(_typeName, typeof(Type), CultureInfo.InvariantCulture) as Type; } catch (Exception e) { @@ -178,7 +176,7 @@ namespace Microsoft.PowerShell.Commands mshArgE = PSTraceSource.NewArgumentException( "TypeName", NewObjectStrings.TypeNotFound, - typeName); + _typeName); ThrowTerminatingError( new ErrorRecord( mshArgE, @@ -207,13 +205,13 @@ namespace Microsoft.PowerShell.Commands "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null)); } - if (arguments == null || arguments.Length == 0) + if (_arguments == null || _arguments.Length == 0) { ConstructorInfo ci = type.GetConstructor(PSTypeExtensions.EmptyTypes); if (ci != null && ci.IsPublic) { _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, new object[] { }); - if (_newObject != null && property != null) + if (_newObject != null && _property != null) { // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -228,7 +226,7 @@ namespace Microsoft.PowerShell.Commands try { _newObject = Activator.CreateInstance(type); - if (_newObject != null && property != null) + if (_newObject != null && _property != null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -252,8 +250,8 @@ namespace Microsoft.PowerShell.Commands if (ctorInfos.Length != 0) { - _newObject = CallConstructor(type, ctorInfos, arguments); - if (_newObject != null && property != null) + _newObject = CallConstructor(type, ctorInfos, _arguments); + if (_newObject != null && _property != null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -261,11 +259,10 @@ namespace Microsoft.PowerShell.Commands WriteObject(_newObject); return; } - } mshArgE = PSTraceSource.NewArgumentException( - "TypeName", NewObjectStrings.CannotFindAppropriateCtor, typeName); + "TypeName", NewObjectStrings.CannotFindAppropriateCtor, _typeName); ThrowTerminatingError( new ErrorRecord( mshArgE, @@ -274,7 +271,7 @@ namespace Microsoft.PowerShell.Commands } else // Parameterset -Com { - int result = NewObjectNativeMethods.CLSIDFromProgID(this.comObject, out comObjectClsId); + int result = NewObjectNativeMethods.CLSIDFromProgID(_comObject, out _comObjectClsId); // If we're in ConstrainedLanguage, do additional restrictions if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) @@ -285,7 +282,7 @@ namespace Microsoft.PowerShell.Commands if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if ((result >= 0) && - SystemPolicy.IsClassInApprovedList(comObjectClsId)) + SystemPolicy.IsClassInApprovedList(_comObjectClsId)) { isAllowed = true; } @@ -315,14 +312,13 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.InvalidArgument, comObject)); } } - if (comObject != null && property != null) + if (comObject != null && _property != null) { // Win8:649519 comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } WriteObject(comObject); } - }//protected override void BeginProcessing() #endregion Overrides @@ -402,9 +398,9 @@ namespace Microsoft.PowerShell.Commands public Exception e; } - ComCreateInfo createInfo; + private ComCreateInfo createInfo; - void STAComCreateThreadProc(Object createstruct) + private void STAComCreateThreadProc(Object createstruct) { ComCreateInfo info = (ComCreateInfo)createstruct; try @@ -412,19 +408,19 @@ namespace Microsoft.PowerShell.Commands Type type = null; PSArgumentException mshArgE = null; - type = Type.GetTypeFromCLSID(comObjectClsId); + type = Type.GetTypeFromCLSID(_comObjectClsId); if (type == null) { mshArgE = PSTraceSource.NewArgumentException( "ComObject", NewObjectStrings.CannotLoadComObjectType, - comObject); + _comObject); info.e = mshArgE; info.success = false; return; } - info.objectCreated = SafeCreateInstance(type, arguments); + info.objectCreated = SafeCreateInstance(type, _arguments); info.success = true; } catch (Exception e) @@ -443,14 +439,14 @@ namespace Microsoft.PowerShell.Commands try { - type = Marshal.GetTypeFromCLSID(comObjectClsId); + type = Marshal.GetTypeFromCLSID(_comObjectClsId); if (type == null) { - mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, comObject); + mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, _comObject); ThrowTerminatingError( new ErrorRecord(mshArgE, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); } - return SafeCreateInstance(type, arguments); + return SafeCreateInstance(type, _arguments); } catch (COMException e) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs index 04bda6939..f3aed8508 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/neweventcommand.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; @@ -24,14 +25,14 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; } } - private string sourceIdentifier = null; + private string _sourceIdentifier = null; /// /// Data relating to this event @@ -42,14 +43,14 @@ namespace Microsoft.PowerShell.Commands { get { - return sender; + return _sender; } set { - sender = value; + _sender = value; } } - private PSObject sender = null; + private PSObject _sender = null; /// /// Data relating to this event @@ -60,17 +61,17 @@ namespace Microsoft.PowerShell.Commands { get { - return eventArguments; + return _eventArguments; } set { - if (eventArguments != null) + if (_eventArguments != null) { - eventArguments = value; + _eventArguments = value; } } } - private PSObject[] eventArguments = new PSObject[0]; + private PSObject[] _eventArguments = new PSObject[0]; /// /// Data relating to this event @@ -80,14 +81,14 @@ namespace Microsoft.PowerShell.Commands { get { - return messageData; + return _messageData; } set { - messageData = value; + _messageData = value; } } - private PSObject messageData = null; + private PSObject _messageData = null; #endregion parameters @@ -100,11 +101,11 @@ namespace Microsoft.PowerShell.Commands object[] baseEventArgs = null; // Get the BaseObject from the event arguments - if (eventArguments != null) + if (_eventArguments != null) { - baseEventArgs = new object[eventArguments.Length]; + baseEventArgs = new object[_eventArguments.Length]; int loopCounter = 0; - foreach (PSObject eventArg in eventArguments) + foreach (PSObject eventArg in _eventArguments) { if (eventArg != null) baseEventArgs[loopCounter] = eventArg.BaseObject; @@ -114,10 +115,10 @@ namespace Microsoft.PowerShell.Commands } Object messageSender = null; - if (sender != null) { messageSender = sender.BaseObject; } + if (_sender != null) { messageSender = _sender.BaseObject; } // And then generate the event - WriteObject(Events.GenerateEvent(sourceIdentifier, messageSender, baseEventArgs, messageData, true, false)); + WriteObject(Events.GenerateEvent(_sourceIdentifier, messageSender, baseEventArgs, _messageData, true, false)); } } } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs index 07211d296..83012c01c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/select-object.cs @@ -17,7 +17,6 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace Microsoft.PowerShell.Commands { - /// /// helper class to do wildcard matching on MshExpressions /// @@ -27,18 +26,17 @@ namespace Microsoft.PowerShell.Commands /// construnt the class, using an array of patterns /// /// array of pattern strings to use - internal MshExpressionFilter (string[] wildcardPatternsStrings) + internal MshExpressionFilter(string[] wildcardPatternsStrings) { - if (wildcardPatternsStrings == null) { - throw new ArgumentNullException ("wildcardPatternsStrings"); + throw new ArgumentNullException("wildcardPatternsStrings"); } _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; for (int k = 0; k < wildcardPatternsStrings.Length; k++) { - _wildcardPatterns[k] = WildcardPattern .Get(wildcardPatternsStrings[k], WildcardOptions.IgnoreCase); + _wildcardPatterns[k] = WildcardPattern.Get(wildcardPatternsStrings[k], WildcardOptions.IgnoreCase); } } @@ -48,11 +46,11 @@ namespace Microsoft.PowerShell.Commands /// /// MshExpression to test against /// true if there is a match, else false - internal bool IsMatch (MshExpression expression) + internal bool IsMatch(MshExpression expression) { for (int k = 0; k < _wildcardPatterns.Length; k++) { - if (_wildcardPatterns[k].IsMatch (expression.ToString ())) + if (_wildcardPatterns[k].IsMatch(expression.ToString())) return true; } return false; @@ -63,10 +61,10 @@ namespace Microsoft.PowerShell.Commands internal class SelectObjectExpressionParameterDefinition : CommandParameterDefinition { - protected override void SetEntries () + protected override void SetEntries() { - this.hashEntries.Add (new ExpressionEntryDefinition ()); - this.hashEntries.Add (new NameEntryDefinition ()); + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new NameEntryDefinition()); } } @@ -89,8 +87,8 @@ namespace Microsoft.PowerShell.Commands set { _inputObject = value; } get { return _inputObject; } } - - private PSObject _inputObject = AutomationNull.Value; + + private PSObject _inputObject = AutomationNull.Value; /// @@ -101,11 +99,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, ParameterSetName = "SkipLastParameter")] public object[] Property { - get { return expr; } - set { expr = value; } + get { return _expr; } + set { _expr = value; } } - private object[] expr; + private object[] _expr; /// /// @@ -115,10 +113,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "SkipLastParameter")] public string[] ExcludeProperty { - get { return excludeArray; } - set { excludeArray = value; } + get { return _excludeArray; } + set { _excludeArray = value; } } - private string[] excludeArray = null; + private string[] _excludeArray = null; /// /// @@ -128,10 +126,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "SkipLastParameter")] public string ExpandProperty { - get { return expand; } - set { expand = value; } + get { return _expand; } + set { _expand = value; } } - private string expand = null; + private string _expand = null; /// /// @@ -140,10 +138,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Unique { - get { return unique; } - set { unique = value; } + get { return _unique; } + set { _unique = value; } } - private bool unique; + private bool _unique; /// /// @@ -155,10 +153,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, int.MaxValue)] public int Last { - get { return last; } - set { last = value; firstOrLastSpecified = true; } + get { return _last; } + set { _last = value; _firstOrLastSpecified = true; } } - private int last = 0; + private int _last = 0; /// /// @@ -170,13 +168,13 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, int.MaxValue)] public int First { - get { return first; } - set { first = value; firstOrLastSpecified = true; } + get { return _first; } + set { _first = value; _firstOrLastSpecified = true; } } - private int first = 0; - private bool firstOrLastSpecified; + private int _first = 0; + private bool _firstOrLastSpecified; + - /// /// Skips the sepecified number of items from top when used with First,from end when used with Last /// @@ -185,10 +183,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, int.MaxValue)] public int Skip { - get { return skip; } - set { skip = value; } + get { return _skip; } + set { _skip = value; } } - private int skip = 0; + private int _skip = 0; /// /// Skip the specified number of items from end. @@ -197,10 +195,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, int.MaxValue)] public int SkipLast { - get { return skipLast; } - set { skipLast = value; } + get { return _skipLast; } + set { _skipLast = value; } } - private int skipLast = 0; + private int _skipLast = 0; /// /// With this switch present, the cmdlet won't "short-circuit" @@ -209,7 +207,7 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "DefaultParameter")] [Parameter(ParameterSetName = "IndexParameter")] public SwitchParameter Wait { get; set; } - + /// /// Used to display the object at specified index /// @@ -221,95 +219,95 @@ namespace Microsoft.PowerShell.Commands { get { - return index; + return _index; } set { - index = value; - indexSpecified = true; - Array.Sort(index); + _index = value; + _indexSpecified = true; + Array.Sort(_index); } } - private int[] index; - private bool indexSpecified; + private int[] _index; + private bool _indexSpecified; #endregion - SelectObjectQueue selectObjectQueue; - + private SelectObjectQueue _selectObjectQueue; + private class SelectObjectQueue : Queue { internal SelectObjectQueue(int first, int last, int skip, int skipLast, bool firstOrLastSpecified) { - this.first = first; - this.last = last; - this.skip = skip; - this.skipLast = skipLast; - this.firstOrLastSpecified = firstOrLastSpecified; + _first = first; + _last = last; + _skip = skip; + _skipLast = skipLast; + _firstOrLastSpecified = firstOrLastSpecified; } public bool AllRequestedObjectsProcessed { get { - return firstOrLastSpecified && last == 0 && first != 0 && streamedObjectCount >= first; + return _firstOrLastSpecified && _last == 0 && _first != 0 && _streamedObjectCount >= _first; } } new public void Enqueue(PSObject obj) { - if (last > 0 && this.Count >= (last + skip) && first == 0) + if (_last > 0 && this.Count >= (_last + _skip) && _first == 0) { base.Dequeue(); } - else if (last > 0 && this.Count >= last && first != 0) + else if (_last > 0 && this.Count >= _last && _first != 0) { base.Dequeue(); } base.Enqueue(obj); } - + public PSObject StreamingDequeue() { //if skip parameter is not mentioned or there are no more objects to skip - if (skip == 0 ) + if (_skip == 0) { - if (skipLast > 0) + if (_skipLast > 0) { // We are going to skip some items from end, but it's okay to process // the early input objects once we have more items in queue than the // specified 'skipLast' value. - if (this.Count > skipLast) + if (this.Count > _skipLast) { return Dequeue(); } } else { - if (streamedObjectCount < first || !firstOrLastSpecified) + if (_streamedObjectCount < _first || !_firstOrLastSpecified) { Diagnostics.Assert(this.Count > 0, "Streaming an empty queue"); - streamedObjectCount++; + _streamedObjectCount++; return Dequeue(); } - if (last == 0) + if (_last == 0) { Dequeue(); } - } + } } else { //if last paramater is not mentioned,remove the objects and decrement the skip - if (last == 0) + if (_last == 0) { Dequeue(); - skip--; + _skip--; } - else if (first != 0) + else if (_first != 0) { - skip--; + _skip--; Dequeue(); } } @@ -317,86 +315,84 @@ namespace Microsoft.PowerShell.Commands return null; } - private int streamedObjectCount; - private int first, last, skip, skipLast; - private bool firstOrLastSpecified; + private int _streamedObjectCount; + private int _first,_last,_skip,_skipLast; + private bool _firstOrLastSpecified; } - + /// /// list of processed parameters obtained from the Expression array /// - private List propertyMshParameterList; + private List _propertyMshParameterList; /// /// singleton list of process parameters obtained from ExpandProperty /// - private List expandMshParameterList; + private List _expandMshParameterList; - - private MshExpressionFilter exclusionFilter; + + private MshExpressionFilter _exclusionFilter; private class UniquePSObjectHelper { internal UniquePSObjectHelper(PSObject o, int notePropertyCount) { WrittenObject = o; - this.notePropertyCount = notePropertyCount; + _notePropertyCount = notePropertyCount; } internal readonly PSObject WrittenObject; internal int NotePropertyCount { - get { return notePropertyCount; } + get { return _notePropertyCount; } } - private int notePropertyCount; + private int _notePropertyCount; } - private List uniques = null; + private List _uniques = null; - private void ProcessExpressionParameter () + private void ProcessExpressionParameter() { TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); ParameterProcessor processor = new ParameterProcessor(new SelectObjectExpressionParameterDefinition()); - if ((this.expr != null) && (this.expr.Length != 0)) + if ((_expr != null) && (_expr.Length != 0)) { - this.propertyMshParameterList = processor.ProcessParameters(this.expr, invocationContext); + _propertyMshParameterList = processor.ProcessParameters(_expr, invocationContext); } else { - this.propertyMshParameterList = new List(); + _propertyMshParameterList = new List(); } - if (!string.IsNullOrEmpty(expand)) + if (!string.IsNullOrEmpty(_expand)) { - this.expandMshParameterList = processor.ProcessParameters(new string[] { this.expand }, invocationContext); + _expandMshParameterList = processor.ProcessParameters(new string[] { _expand }, invocationContext); } - if (this.excludeArray != null) + if (_excludeArray != null) { - this.exclusionFilter = new MshExpressionFilter(this.excludeArray); + _exclusionFilter = new MshExpressionFilter(_excludeArray); } - } private void ProcessObject(PSObject inputObject) { - - if ((expr == null || expr.Length == 0) && string.IsNullOrEmpty(expand)) + if ((_expr == null || _expr.Length == 0) && string.IsNullOrEmpty(_expand)) { FilteredWriteObject(inputObject, new List()); return; } - - + + //If property parameter is mentioned List matchedProperties = new List(); - foreach (MshParameter p in this.propertyMshParameterList) + foreach (MshParameter p in _propertyMshParameterList) { ProcessParameter(p, inputObject, matchedProperties); } - if (string.IsNullOrEmpty(this.expand)) + if (string.IsNullOrEmpty(_expand)) { PSObject result = new PSObject(); if (matchedProperties.Count != 0) @@ -426,17 +422,15 @@ namespace Microsoft.PowerShell.Commands } } FilteredWriteObject(result, matchedProperties); - } else { - ProcessExpandParameter(this.expandMshParameterList[0], inputObject, matchedProperties); + ProcessExpandParameter(_expandMshParameterList[0], inputObject, matchedProperties); } - } - - + + private void ProcessParameter(MshParameter p, PSObject inputObject, List result) { string name = p.GetEntry(NameEntryDefinition.NameEntryKey) as string; @@ -445,7 +439,7 @@ namespace Microsoft.PowerShell.Commands List expressionResults = new List(); foreach (MshExpression resolvedName in ex.ResolveNames(inputObject)) { - if (exclusionFilter == null || !this.exclusionFilter.IsMatch(resolvedName)) + if (_exclusionFilter == null || !_exclusionFilter.IsMatch(resolvedName)) { List tempExprResults = resolvedName.GetValues(inputObject); if (tempExprResults == null) continue; @@ -487,7 +481,7 @@ namespace Microsoft.PowerShell.Commands foreach (MshExpressionResult r in expressionResults) { // filter the exclusions, if any - if (this.exclusionFilter != null && this.exclusionFilter.IsMatch(r.ResolvedExpression)) + if (_exclusionFilter != null && _exclusionFilter.IsMatch(r.ResolvedExpression)) continue; PSNoteProperty mshProp; @@ -510,23 +504,21 @@ namespace Microsoft.PowerShell.Commands else { mshProp = new PSNoteProperty(name, r.Result); - } result.Add(mshProp); } - } private void ProcessExpandParameter(MshParameter p, PSObject inputObject, List matchedProperties) { MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; List expressionResults = ex.GetValues(inputObject); - - if (expressionResults.Count == 0) + + if (expressionResults.Count == 0) { ErrorRecord errorRecord = new ErrorRecord( - PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.PropertyNotFound, this.expand), + PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.PropertyNotFound, _expand), "ExpandPropertyNotFound", ErrorCategory.InvalidArgument, inputObject); @@ -535,7 +527,7 @@ namespace Microsoft.PowerShell.Commands if (expressionResults.Count > 1) { ErrorRecord errorRecord = new ErrorRecord( - PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.MutlipleExpandProperties, this.expand), + PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.MutlipleExpandProperties, _expand), "MutlipleExpandProperties", ErrorCategory.InvalidArgument, inputObject); @@ -624,8 +616,8 @@ namespace Microsoft.PowerShell.Commands private void FilteredWriteObject(PSObject obj, List addedNoteProperties) { Diagnostics.Assert(obj != null, "This command should never write null"); - - if (!unique) + + if (!_unique) { if (obj != AutomationNull.Value) { @@ -635,10 +627,10 @@ namespace Microsoft.PowerShell.Commands return; } //if only unique is mentioned - else if ((unique)) + else if ((_unique)) { bool isObjUnique = true; - foreach (UniquePSObjectHelper uniqueObj in uniques) + foreach (UniquePSObjectHelper uniqueObj in _uniques) { ObjectCommandComparer comparer = new ObjectCommandComparer(true, CultureInfo.CurrentCulture, true); if ((comparer.Compare(obj.BaseObject, uniqueObj.WrittenObject.BaseObject) == 0) && @@ -667,16 +659,16 @@ namespace Microsoft.PowerShell.Commands } if (isObjUnique) { - SetPSCustomObject(obj); - uniques.Add(new UniquePSObjectHelper(obj, addedNoteProperties.Count)); + SetPSCustomObject(obj); + _uniques.Add(new UniquePSObjectHelper(obj, addedNoteProperties.Count)); } } } private void SetPSCustomObject(PSObject psObj) { - if(psObj.ImmediateBaseObject is PSCustomObject) - psObj.TypeNames.Insert(0, "Selected." + _inputObject.BaseObject.GetType().ToString()); + if (psObj.ImmediateBaseObject is PSCustomObject) + psObj.TypeNames.Insert(0, "Selected." + _inputObject.BaseObject.GetType().ToString()); } private void ProcessObjectAndHandleErrors(PSObject pso) @@ -696,20 +688,20 @@ namespace Microsoft.PowerShell.Commands /// /// /// - protected override void BeginProcessing () + protected override void BeginProcessing() { - ProcessExpressionParameter (); - - if (unique) + ProcessExpressionParameter(); + + if (_unique) { - uniques = new List(); + _uniques = new List(); } - selectObjectQueue = new SelectObjectQueue(this.first, this.last, this.skip, this.skipLast, this.firstOrLastSpecified); + _selectObjectQueue = new SelectObjectQueue(_first, _last, _skip, _skipLast, _firstOrLastSpecified); } - private int indexOfCurrentObject = 0; - private int indexCount = 0; + private int _indexOfCurrentObject = 0; + private int _indexCount = 0; /// /// /// @@ -717,15 +709,15 @@ namespace Microsoft.PowerShell.Commands { if (_inputObject != AutomationNull.Value && _inputObject != null) { - if (!indexSpecified) + if (!_indexSpecified) { - selectObjectQueue.Enqueue(_inputObject); - PSObject streamingInputObject = selectObjectQueue.StreamingDequeue(); + _selectObjectQueue.Enqueue(_inputObject); + PSObject streamingInputObject = _selectObjectQueue.StreamingDequeue(); if (streamingInputObject != null) { ProcessObjectAndHandleErrors(streamingInputObject); } - if (selectObjectQueue.AllRequestedObjectsProcessed && !this.Wait) + if (_selectObjectQueue.AllRequestedObjectsProcessed && !this.Wait) { this.EndProcessing(); throw new StopUpstreamCommandsException(this); @@ -733,26 +725,26 @@ namespace Microsoft.PowerShell.Commands } else { - if(indexOfCurrentObject < index.Length) + if (_indexOfCurrentObject < _index.Length) { - int currentlyRequestedIndex = index[indexOfCurrentObject]; - if (indexCount == currentlyRequestedIndex) + int currentlyRequestedIndex = _index[_indexOfCurrentObject]; + if (_indexCount == currentlyRequestedIndex) { ProcessObjectAndHandleErrors(_inputObject); - while ((indexOfCurrentObject < index.Length) && (index[indexOfCurrentObject] == currentlyRequestedIndex)) + while ((_indexOfCurrentObject < _index.Length) && (_index[_indexOfCurrentObject] == currentlyRequestedIndex)) { - indexOfCurrentObject++; + _indexOfCurrentObject++; } } } - if (!this.Wait && indexOfCurrentObject >= index.Length) + if (!this.Wait && _indexOfCurrentObject >= _index.Length) { this.EndProcessing(); throw new StopUpstreamCommandsException(this); } - - indexCount++; + + _indexCount++; } } } @@ -767,21 +759,21 @@ namespace Microsoft.PowerShell.Commands // 2. 'SkipLastParameter' set should have processed all valid input in the ProcessRecord. if (ParameterSetName == "DefaultParameter") { - if (first != 0) + if (_first != 0) { - while ((selectObjectQueue.Count > 0)) + while ((_selectObjectQueue.Count > 0)) { - ProcessObjectAndHandleErrors(selectObjectQueue.Dequeue()); + ProcessObjectAndHandleErrors(_selectObjectQueue.Dequeue()); } } else { - while ((selectObjectQueue.Count > 0)) + while ((_selectObjectQueue.Count > 0)) { - int lenQueue = selectObjectQueue.Count; - if (lenQueue > skip) + int lenQueue = _selectObjectQueue.Count; + if (lenQueue > _skip) { - ProcessObjectAndHandleErrors(selectObjectQueue.Dequeue()); + ProcessObjectAndHandleErrors(_selectObjectQueue.Dequeue()); } else { @@ -791,15 +783,15 @@ namespace Microsoft.PowerShell.Commands } } - if (uniques != null) + if (_uniques != null) { - foreach (UniquePSObjectHelper obj in uniques) + foreach (UniquePSObjectHelper obj in _uniques) { if (obj.WrittenObject == null || obj.WrittenObject == AutomationNull.Value) { continue; } - + WriteObject(obj.WrittenObject); } } @@ -814,17 +806,17 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "This exception is internal and never thrown by any public API")] internal class SelectObjectException : SystemException { - private ErrorRecord errorRecord; + private ErrorRecord _errorRecord; internal ErrorRecord ErrorRecord { get { - return this.errorRecord; + return _errorRecord; } } internal SelectObjectException(ErrorRecord errorRecord) { - this.errorRecord = errorRecord; + _errorRecord = errorRecord; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs index afa1ce46a..2bbb9d844 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/sort-object.cs @@ -29,10 +29,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Unique { - get { return unique; } - set { unique = value; } + get { return _unique; } + set { _unique = value; } } - private bool unique; + private bool _unique; #endregion @@ -73,7 +73,7 @@ namespace Microsoft.PowerShell.Commands } orderByProperty.OrderMatrix.Sort(orderByProperty.Comparer); - if (unique) + if (_unique) { RemoveDuplicates(orderByProperty); } @@ -85,5 +85,5 @@ namespace Microsoft.PowerShell.Commands } } } -} +} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs index 6dba07a4d..00442d41e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/tee-object.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Microsoft.PowerShell.Commands.Internal.Format; @@ -19,21 +20,21 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true)] public PSObject InputObject { - get { return inputObject; } - set { inputObject = value; } + get { return _inputObject; } + set { _inputObject = value; } } - private PSObject inputObject; - + private PSObject _inputObject; + /// /// FilePath parameter /// [Parameter(Mandatory = true, Position = 0, ParameterSetName = "File")] public string FilePath { - get{ return fileName;} - set{ fileName = value;} + get { return _fileName; } + set { _fileName = value; } } - private string fileName; + private string _fileName; /// /// Literal FilePath parameter @@ -44,12 +45,12 @@ namespace Microsoft.PowerShell.Commands { get { - return fileName; + return _fileName; } set { - fileName = value; - } + _fileName = value; + } } /// @@ -58,10 +59,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "File")] public SwitchParameter Append { - get{ return append;} - set{ append = value;} + get { return _append; } + set { _append = value; } } - private bool append; + private bool _append; /// /// Variable parameter @@ -69,34 +70,34 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, ParameterSetName = "Variable")] public string Variable { - get { return variable; } - set { variable = value; } + get { return _variable; } + set { _variable = value; } } - private string variable; + private string _variable; /// /// /// protected override void BeginProcessing() { - commandWrapper = new CommandWrapper(); + _commandWrapper = new CommandWrapper(); if (String.Equals(ParameterSetName, "File", StringComparison.OrdinalIgnoreCase)) { - commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); - commandWrapper.AddNamedParameter("filepath", fileName); - commandWrapper.AddNamedParameter("append", append); + _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); + _commandWrapper.AddNamedParameter("filepath", _fileName); + _commandWrapper.AddNamedParameter("append", _append); } else if (String.Equals(ParameterSetName, "LiteralFile", StringComparison.OrdinalIgnoreCase)) { - commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); - commandWrapper.AddNamedParameter("LiteralPath", fileName); - commandWrapper.AddNamedParameter("append", append); + _commandWrapper.Initialize(Context, "out-file", typeof(OutFileCommand)); + _commandWrapper.AddNamedParameter("LiteralPath", _fileName); + _commandWrapper.AddNamedParameter("append", _append); } else { // variable parameter set - commandWrapper.Initialize(Context, "set-variable", typeof(SetVariableCommand)); - commandWrapper.AddNamedParameter("name", variable); + _commandWrapper.Initialize(Context, "set-variable", typeof(SetVariableCommand)); + _commandWrapper.AddNamedParameter("name", _variable); // Can't use set-var's passthru because it writes the var object to the pipeline, we want just // the values to be written } @@ -106,8 +107,8 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - commandWrapper.Process(inputObject); - WriteObject(inputObject); + _commandWrapper.Process(_inputObject); + WriteObject(_inputObject); } /// @@ -115,19 +116,18 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - commandWrapper.ShutDown(); + _commandWrapper.ShutDown(); } private void Dispose(bool isDisposing) { - if (!alreadyDisposed) + if (!_alreadyDisposed) { - alreadyDisposed = true; - if (isDisposing && commandWrapper != null) + _alreadyDisposed = true; + if (isDisposing && _commandWrapper != null) { - commandWrapper.Dispose(); - commandWrapper = null; - + _commandWrapper.Dispose(); + _commandWrapper = null; } } } @@ -149,8 +149,8 @@ namespace Microsoft.PowerShell.Commands Dispose(false); } #region private - private CommandWrapper commandWrapper; - private bool alreadyDisposed; + private CommandWrapper _commandWrapper; + private bool _alreadyDisposed; #endregion private } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index 55f4e78bf..c64bfa9ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -21,12 +21,12 @@ namespace Microsoft.PowerShell.Commands /// which trace switch to get. /// /// - [Parameter (Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Name { - get - { - return names; + get + { + return _names; } set @@ -36,10 +36,10 @@ namespace Microsoft.PowerShell.Commands value = new string[] { "*" }; } - names = value; + _names = value; } } // TraceSource - private string[] names = new string[] { "*" }; + private string[] _names = new string[] { "*" }; #endregion Parameters @@ -48,11 +48,11 @@ namespace Microsoft.PowerShell.Commands /// /// Gets the PSTraceSource for the specified category /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - var sources = GetMatchingTraceSource(names, true); + var sources = GetMatchingTraceSource(_names, true); var result = sources.OrderBy(source => source.Name); - WriteObject (result, true); + WriteObject(result, true); } // ProcessRecord #endregion Cmdlet code diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index 1ddda4afa..d7cc4aed0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.IO; using System.Text; @@ -16,28 +17,28 @@ using System.Security.Permissions; namespace Microsoft.PowerShell.Commands { - /// - /// This subclass of TraceListener allows for the trace output - /// coming from a System.Management.Automation.TraceSwitch - /// to be passed to the Msh host's RawUI methods. - /// - /// + /// + /// This subclass of TraceListener allows for the trace output + /// coming from a System.Management.Automation.TraceSwitch + /// to be passed to the Msh host's RawUI methods. + /// + /// /// /// This trace listener cannot be specified in the app.config file. /// It must be added through the add-tracelistener cmdlet. /// /// - internal class PSHostTraceListener + internal class PSHostTraceListener : System.Diagnostics.TraceListener - { + { #region TraceListener constructors and disposer /// /// Default constructor used if no. /// - internal PSHostTraceListener (PSCmdlet cmdlet) + internal PSHostTraceListener(PSCmdlet cmdlet) : base("") - { + { if (cmdlet == null) { throw new PSArgumentNullException("cmdlet"); @@ -47,8 +48,8 @@ namespace Microsoft.PowerShell.Commands cmdlet.Host.UI is InternalHostUserInterface, "The internal host must be available to trace"); - this.ui = cmdlet.Host.UI as InternalHostUserInterface; - } + _ui = cmdlet.Host.UI as InternalHostUserInterface; + } ~PSHostTraceListener() { @@ -73,7 +74,7 @@ namespace Microsoft.PowerShell.Commands #else try { - if (disposing) + if (disposing) { this.Close(); } @@ -83,7 +84,7 @@ namespace Microsoft.PowerShell.Commands base.Dispose(disposing); } #endif - } + } #if !CORECLR /// @@ -112,7 +113,7 @@ namespace Microsoft.PowerShell.Commands { try { - cachedWrite.Append(output); + _cachedWrite.Append(output); } catch (Exception e) { @@ -121,7 +122,7 @@ namespace Microsoft.PowerShell.Commands // We don't want tracing to bring down the process. } } - private StringBuilder cachedWrite = new StringBuilder(); + private StringBuilder _cachedWrite = new StringBuilder(); /// /// Sends the given output string to the host for processing @@ -134,10 +135,10 @@ namespace Microsoft.PowerShell.Commands { try { - cachedWrite.Append(output); + _cachedWrite.Append(output); - ui.WriteDebugLine(cachedWrite.ToString()); - cachedWrite.Remove(0, cachedWrite.Length); + _ui.WriteDebugLine(_cachedWrite.ToString()); + _cachedWrite.Remove(0, _cachedWrite.Length); } catch (Exception e) { @@ -150,7 +151,6 @@ namespace Microsoft.PowerShell.Commands /// /// The host interface to write the debug line to. /// - private InternalHostUserInterface ui; - + private InternalHostUserInterface _ui; } // class PSHostTraceListener } // namespace System.Management.Automation diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index 561d12a44..2ae416cf5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -33,7 +33,7 @@ namespace Microsoft.PowerShell.Commands /// The flags to be set on the TraceSource /// /// - [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "optionsSet")] + [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "optionsSet")] public PSTraceSourceOptions Option { get { return base.OptionsInternal; } @@ -49,7 +49,7 @@ namespace Microsoft.PowerShell.Commands /// trace listeners. /// /// - [Parameter (ParameterSetName = "optionsSet")] + [Parameter(ParameterSetName = "optionsSet")] public TraceOptions ListenerOption { get { return base.ListenerOptionsInternal; } @@ -63,7 +63,7 @@ namespace Microsoft.PowerShell.Commands /// Adds the file trace listener using the specified file /// /// - [Parameter (ParameterSetName = "optionsSet")] + [Parameter(ParameterSetName = "optionsSet")] [Alias("PSPath")] public string FilePath { @@ -86,7 +86,7 @@ namespace Microsoft.PowerShell.Commands /// will be added. /// /// - [Parameter (ParameterSetName = "optionsSet")] + [Parameter(ParameterSetName = "optionsSet")] public SwitchParameter Debugger { get { return base.DebuggerListener; } @@ -110,14 +110,14 @@ namespace Microsoft.PowerShell.Commands /// of their type. /// /// - [Parameter (ParameterSetName = "removeAllListenersSet")] + [Parameter(ParameterSetName = "removeAllListenersSet")] [ValidateNotNullOrEmpty] public string[] RemoveListener { - get { return removeListeners; } - set { removeListeners = value; } + get { return _removeListeners; } + set { _removeListeners = value; } } - private string[] removeListeners = new string[] { "*" }; + private string[] _removeListeners = new string[] { "*" }; /// /// If set, the specified file trace listeners will be removed. @@ -127,23 +127,23 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string[] RemoveFileListener { - get { return removeFileListeners; } - set { removeFileListeners = value; } + get { return _removeFileListeners; } + set { _removeFileListeners = value; } } - private string[] removeFileListeners = new string[] { "*" }; - + private string[] _removeFileListeners = new string[] { "*" }; + /// /// Determines if the modified PSTraceSource should be written out. /// Default is false. /// /// - [Parameter (ParameterSetName = "optionsSet")] + [Parameter(ParameterSetName = "optionsSet")] public SwitchParameter PassThru { - get { return passThru; } - set { passThru = value; } + get { return _passThru; } + set { _passThru = value; } } // Passthru - private bool passThru; + private bool _passThru; #endregion Parameters @@ -152,7 +152,7 @@ namespace Microsoft.PowerShell.Commands /// /// Sets the TraceSource properties /// - protected override void ProcessRecord () + protected override void ProcessRecord() { Collection matchingSources = null; @@ -179,7 +179,6 @@ namespace Microsoft.PowerShell.Commands RemoveListenersByName(matchingSources, RemoveFileListener, true); break; } - } // ProcessRecord #endregion Cmdlet code diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs index 2322303a7..1dfb756b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index c303bddfd..69348b948 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -11,7 +11,7 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Threading; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { @@ -27,7 +27,7 @@ namespace Microsoft.PowerShell.Commands /// /// This parameter specifies the current pipeline object /// - [Parameter (ValueFromPipeline = true)] + [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set { _inputObject = value; } @@ -68,35 +68,35 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 1, Mandatory = true, ParameterSetName = "expressionSet")] public ScriptBlock Expression { - get { return expression; } - set { expression = value; } + get { return _expression; } + set { _expression = value; } } - private ScriptBlock expression; + private ScriptBlock _expression; /// /// The parameter for the expression that should be traced. /// /// - [Parameter(Position = 1, Mandatory = true, ParameterSetName = "commandSet")] + [Parameter(Position = 1, Mandatory = true, ParameterSetName = "commandSet")] public string Command { - get { return command; } - set { command = value; } + get { return _command; } + set { _command = value; } } - private string command; + private string _command; /// /// When set, this parameter is the arguments to pass to the command specified by /// the -Command parameter /// - [Parameter(ParameterSetName = "commandSet", ValueFromRemainingArguments = true)] + [Parameter(ParameterSetName = "commandSet", ValueFromRemainingArguments = true)] [Alias("Args")] public object[] ArgumentList { - get { return commandArgs; } - set { commandArgs = value; } + get { return _commandArgs; } + set { _commandArgs = value; } } - private object[] commandArgs; + private object[] _commandArgs; /// /// The parameter which determines the options for output from the @@ -164,7 +164,7 @@ namespace Microsoft.PowerShell.Commands #region Cmdlet code - private Collection matchingSources; + private Collection _matchingSources; /// /// Gets the PSTraceSource instances that match the names specified. @@ -172,10 +172,10 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { Collection preconfiguredSources = null; - matchingSources = ConfigureTraceSource(base.NameInternal, false, out preconfiguredSources); + _matchingSources = ConfigureTraceSource(base.NameInternal, false, out preconfiguredSources); - TurnOnTracing(matchingSources, false); + TurnOnTracing(_matchingSources, false); TurnOnTracing(preconfiguredSources, true); // Now that tracing has been configured, move all the sources into a @@ -183,32 +183,30 @@ namespace Microsoft.PowerShell.Commands foreach (PSTraceSource preconfiguredSource in preconfiguredSources) { - matchingSources.Add(preconfiguredSource); + _matchingSources.Add(preconfiguredSource); } if (ParameterSetName == "commandSet") { - // Create the CommmandProcessor and add it to a pipeline CommandProcessorBase commandProcessor = - this.Context.CommandDiscovery.LookupCommandProcessor(command, CommandOrigin.Runspace, false); + this.Context.CommandDiscovery.LookupCommandProcessor(_command, CommandOrigin.Runspace, false); // Add the parameters that were specified ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, ArgumentList); - - pipeline = new PipelineProcessor(); - pipeline.Add(commandProcessor); + + _pipeline = new PipelineProcessor(); + _pipeline.Add(commandProcessor); // Hook up the success and error pipelines to this cmdlet's WriteObject and // WriteError methods - pipeline.ExternalErrorOutput = new TracePipelineWriter(this, true, matchingSources); - pipeline.ExternalSuccessOutput = new TracePipelineWriter(this, false, matchingSources); - + _pipeline.ExternalErrorOutput = new TracePipelineWriter(this, true, _matchingSources); + _pipeline.ExternalSuccessOutput = new TracePipelineWriter(this, false, _matchingSources); } - ResetTracing(matchingSources); + ResetTracing(_matchingSources); } /// @@ -216,9 +214,9 @@ namespace Microsoft.PowerShell.Commands /// /// Note, this was taken from apply-expression /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - TurnOnTracing (matchingSources, false); + TurnOnTracing(_matchingSources, false); object result = null; switch (ParameterSetName) @@ -231,7 +229,7 @@ namespace Microsoft.PowerShell.Commands result = StepCommand(); break; } - ResetTracing (matchingSources); + ResetTracing(_matchingSources); if (result == null) { @@ -243,28 +241,26 @@ namespace Microsoft.PowerShell.Commands { WriteObject(result, true); } - } // ProcessRecord - + /// /// Finishes running the command if specified and then sets the /// tracing options and listeners back to their original values. /// - protected override void EndProcessing () + protected override void EndProcessing() { - if (pipeline != null) + if (_pipeline != null) { - TurnOnTracing(matchingSources, false); + TurnOnTracing(_matchingSources, false); - Array results = pipeline.SynchronousExecuteEnumerate(AutomationNull.Value); + Array results = _pipeline.SynchronousExecuteEnumerate(AutomationNull.Value); + + ResetTracing(_matchingSources); - ResetTracing(matchingSources); - WriteObject(results, true); - } - this.Dispose (); + this.Dispose(); } /// @@ -273,9 +269,9 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - if (pipeline != null) + if (_pipeline != null) { - pipeline.Stop(); + _pipeline.Stop(); } } @@ -283,25 +279,25 @@ namespace Microsoft.PowerShell.Commands private object RunExpression() { - return expression.DoInvokeReturnAsIs( - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: InputObject, - input: new object[] {InputObject}, - scriptThis: AutomationNull.Value, - args: Utils.EmptyArray()); + return _expression.DoInvokeReturnAsIs( + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, + input: new object[] { InputObject }, + scriptThis: AutomationNull.Value, + args: Utils.EmptyArray()); } private object StepCommand() { if (InputObject != AutomationNull.Value) { - pipeline.Step(InputObject); + _pipeline.Step(InputObject); } return null; } - private PipelineProcessor pipeline; + private PipelineProcessor _pipeline; #region IDisposable @@ -309,21 +305,21 @@ namespace Microsoft.PowerShell.Commands /// Resets the TraceSource flags back to their original value and restores /// the original TraceListeners. /// - public void Dispose () + public void Dispose() { - if (!disposed) + if (!_disposed) { - disposed = true; + _disposed = true; // Reset the flags for the trace switch back to the original value - ResetTracing (matchingSources); + ResetTracing(_matchingSources); ClearStoredState(); - matchingSources = null; + _matchingSources = null; - if (pipeline != null) + if (_pipeline != null) { - pipeline.Dispose(); - pipeline = null; + _pipeline.Dispose(); + _pipeline = null; } // If there are any file streams, close those as well. @@ -338,9 +334,8 @@ namespace Microsoft.PowerShell.Commands } GC.SuppressFinalize(this); } - } // Dispose - private bool disposed; + private bool _disposed; #endregion IDisposable } @@ -353,8 +348,8 @@ namespace Microsoft.PowerShell.Commands internal class TracePipelineWriter : PipelineWriter { internal TracePipelineWriter( - TraceListenerCommandBase cmdlet, - bool writeError, + TraceListenerCommandBase cmdlet, + bool writeError, Collection matchingSources) { if (cmdlet == null) @@ -367,9 +362,9 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentNullException("matchingSources"); } - this.cmdlet = cmdlet; - this.writeError = writeError; - this.matchingSources = matchingSources; + _cmdlet = cmdlet; + _writeError = writeError; + _matchingSources = matchingSources; } /// @@ -393,7 +388,7 @@ namespace Microsoft.PowerShell.Commands { get { - return isOpen; + return _isOpen; } } @@ -434,10 +429,10 @@ namespace Microsoft.PowerShell.Commands /// public override void Close() { - if (isOpen) + if (_isOpen) { Flush(); - isOpen = false; + _isOpen = false; } } @@ -466,23 +461,23 @@ namespace Microsoft.PowerShell.Commands /// public override int Write(object obj) { - cmdlet.ResetTracing(matchingSources); + _cmdlet.ResetTracing(_matchingSources); - if (writeError) + if (_writeError) { ErrorRecord errorRecord = ConvertToErrorRecord(obj); if (errorRecord != null) { - cmdlet.WriteError(errorRecord); + _cmdlet.WriteError(errorRecord); } } else { - cmdlet.WriteObject(obj); + _cmdlet.WriteObject(obj); } - cmdlet.TurnOnTracing(matchingSources, false); + _cmdlet.TurnOnTracing(_matchingSources, false); return 1; } @@ -506,10 +501,10 @@ namespace Microsoft.PowerShell.Commands /// public override int Write(object obj, bool enumerateCollection) { - cmdlet.ResetTracing(matchingSources); + _cmdlet.ResetTracing(_matchingSources); int numWritten = 0; - if (writeError) + if (_writeError) { if (enumerateCollection) { @@ -519,7 +514,7 @@ namespace Microsoft.PowerShell.Commands if (errorRecord != null) { numWritten++; - cmdlet.WriteError(errorRecord); + _cmdlet.WriteError(errorRecord); } } } @@ -529,17 +524,17 @@ namespace Microsoft.PowerShell.Commands if (errorRecord != null) { numWritten++; - cmdlet.WriteError(errorRecord); + _cmdlet.WriteError(errorRecord); } } } else { numWritten++; - cmdlet.WriteObject(obj, enumerateCollection); + _cmdlet.WriteObject(obj, enumerateCollection); } - cmdlet.TurnOnTracing(matchingSources, false); + _cmdlet.TurnOnTracing(_matchingSources, false); return numWritten; } @@ -566,9 +561,9 @@ namespace Microsoft.PowerShell.Commands return result; } - private TraceListenerCommandBase cmdlet; - private bool writeError; - private bool isOpen = true; - private Collection matchingSources = new Collection(); + private TraceListenerCommandBase _cmdlet; + private bool _writeError; + private bool _isOpen = true; + private Collection _matchingSources = new Collection(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index 7615b910b..e3e76cfbf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -10,7 +10,7 @@ using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { @@ -29,10 +29,10 @@ namespace Microsoft.PowerShell.Commands /// internal string[] NameInternal { - get { return names; } - set { names = value; } + get { return _names; } + set { _names = value; } } - private string[] names = new string[0]; + private string[] _names = new string[0]; /// @@ -41,14 +41,14 @@ namespace Microsoft.PowerShell.Commands /// internal PSTraceSourceOptions OptionsInternal { - get { return options; } - set - { - options = value; - optionsSpecified = true; + get { return _options; } + set + { + _options = value; + optionsSpecified = true; } } // Flags - private PSTraceSourceOptions options = PSTraceSourceOptions.All; + private PSTraceSourceOptions _options = PSTraceSourceOptions.All; /// /// True if the Options parameter has been set, or false otherwise. @@ -62,14 +62,14 @@ namespace Microsoft.PowerShell.Commands /// internal TraceOptions ListenerOptionsInternal { - get { return traceOptions; } - set + get { return _traceOptions; } + set { - traceOptionsSpecified = true; - traceOptions = value; + traceOptionsSpecified = true; + _traceOptions = value; } } - private TraceOptions traceOptions = TraceOptions.None; + private TraceOptions _traceOptions = TraceOptions.None; /// /// True if the TraceOptions parameter was specified, or false otherwise @@ -82,10 +82,10 @@ namespace Microsoft.PowerShell.Commands /// internal string FileListener { - get { return file; } - set { file = value; } + get { return _file; } + set { _file = value; } } // File - private string file; + private string _file; /// /// Property that sets force parameter. This will clear the @@ -96,11 +96,11 @@ namespace Microsoft.PowerShell.Commands /// public bool ForceWrite { - get { return forceWrite; } - set { forceWrite = value; } + get { return _forceWrite; } + set { _forceWrite = value; } } // Force - private bool forceWrite; + private bool _forceWrite; /// /// If this parameter is specified the Debugger trace listener @@ -109,10 +109,10 @@ namespace Microsoft.PowerShell.Commands /// internal bool DebuggerListener { - get { return debugger; } - set { debugger = value; } + get { return _debugger; } + set { _debugger = value; } } // Debugger - private bool debugger; + private bool _debugger; /// /// If this parameter is specified the Msh Host trace listener @@ -121,10 +121,10 @@ namespace Microsoft.PowerShell.Commands /// internal SwitchParameter PSHostListener { - get { return host; } - set { host = value; } + get { return _host; } + set { _host = value; } } // UseHost - private bool host = false; + private bool _host = false; #endregion Parameters @@ -217,36 +217,36 @@ namespace Microsoft.PowerShell.Commands { if (DebuggerListener) { - if (defaultListener == null) + if (_defaultListener == null) { - defaultListener = + _defaultListener = new DefaultTraceListener(); // Note, this is not meant to be localized. - defaultListener.Name = "Debug"; + _defaultListener.Name = "Debug"; } - AddListenerToSources(matchingSources, defaultListener); + AddListenerToSources(matchingSources, _defaultListener); } if (PSHostListener) { - if (hostListener == null) + if (_hostListener == null) { ((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue; - hostListener = new PSHostTraceListener(this); + _hostListener = new PSHostTraceListener(this); // Note, this is not meant to be localized. - hostListener.Name = "Host"; + _hostListener.Name = "Host"; } - AddListenerToSources (matchingSources, hostListener); + AddListenerToSources(matchingSources, _hostListener); } if (FileListener != null) { - if (fileListeners == null) + if (_fileListeners == null) { - fileListeners = new Collection(); - fileStreams = new Collection(); + _fileListeners = new Collection(); + _fileStreams = new Collection(); Exception error = null; @@ -257,7 +257,7 @@ namespace Microsoft.PowerShell.Commands { // Resolve the file path ProviderInfo provider = null; - resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(file, out provider); + resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(_file, out provider); // We can only export aliases to the file system if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) @@ -265,10 +265,9 @@ namespace Microsoft.PowerShell.Commands throw new PSNotSupportedException( StringUtil.Format(TraceCommandStrings.TraceFileOnly, - file, + _file, provider.FullName)); } - } catch (ItemNotFoundException) { @@ -277,9 +276,9 @@ namespace Microsoft.PowerShell.Commands PSDriveInfo driveInfo = null; ProviderInfo provider = null; - string path = + string path = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath( - file, + _file, new CmdletProviderContext(this.Context), out provider, out driveInfo); @@ -290,7 +289,7 @@ namespace Microsoft.PowerShell.Commands throw new PSNotSupportedException( StringUtil.Format(TraceCommandStrings.TraceFileOnly, - file, + _file, provider.FullName)); } resolvedPaths.Add(path); @@ -299,7 +298,7 @@ namespace Microsoft.PowerShell.Commands if (resolvedPaths.Count > 1) { throw - new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, file)); + new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, _file)); } string resolvedPath = resolvedPaths[0]; @@ -324,16 +323,16 @@ namespace Microsoft.PowerShell.Commands // Trace commands always append..So there is no need to set overwrite with force.. FileStream fileStream = new FileStream(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); - fileStreams.Add(fileStream); + _fileStreams.Add(fileStream); // Open the file stream TextWriterTraceListener fileListener = new TextWriterTraceListener(fileStream, resolvedPath); - fileListener.Name = file; + fileListener.Name = _file; - fileListeners.Add(fileListener); + _fileListeners.Add(fileListener); } catch (IOException ioException) { @@ -380,21 +379,21 @@ namespace Microsoft.PowerShell.Commands error, "FileListenerPathResolutionFailed", ErrorCategory.InvalidArgument, - file); + _file); WriteError(errorRecord); } } - foreach (TraceListener listener in fileListeners) + foreach (TraceListener listener in _fileListeners) { AddListenerToSources(matchingSources, listener); } } } - private DefaultTraceListener defaultListener; - private PSHostTraceListener hostListener; - private Collection fileListeners; + private DefaultTraceListener _defaultListener; + private PSHostTraceListener _hostListener; + private Collection _fileListeners; /// /// The file streams that were open by this command @@ -402,9 +401,9 @@ namespace Microsoft.PowerShell.Commands /// internal Collection FileStreams { - get { return fileStreams; } + get { return _fileStreams; } } - private Collection fileStreams; + private Collection _fileStreams; private static void AddListenerToSources(Collection matchingSources, TraceListener listener) { @@ -424,8 +423,8 @@ namespace Microsoft.PowerShell.Commands /// /// internal static void RemoveListenersByName( - Collection matchingSources, - string[] listenerNames, + Collection matchingSources, + string[] listenerNames, bool fileListenersOnly) { Collection listenerMatcher = @@ -498,7 +497,7 @@ namespace Microsoft.PowerShell.Commands /// Sets the flags for all the specified TraceSources /// /// - internal void SetFlags (Collection matchingSources) + internal void SetFlags(Collection matchingSources) { foreach (PSTraceSource structuredSource in matchingSources) { @@ -513,19 +512,19 @@ namespace Microsoft.PowerShell.Commands /// Turns on tracing for the TraceSources, flags, and listeners defined by /// the parameters /// - internal void TurnOnTracing (Collection matchingSources, bool preConfigured) + internal void TurnOnTracing(Collection matchingSources, bool preConfigured) { foreach (PSTraceSource source in matchingSources) { // Store the current state of the TraceSource - if (!storedTraceSourceState.ContainsKey(source)) + if (!_storedTraceSourceState.ContainsKey(source)) { // Copy the listeners into a different collection - Collection listenerCollection = new Collection (); + Collection listenerCollection = new Collection(); foreach (TraceListener listener in source.Listeners) { - listenerCollection.Add (listener); + listenerCollection.Add(listener); } if (preConfigured) @@ -533,14 +532,14 @@ namespace Microsoft.PowerShell.Commands // If the source is a preconfigured source, then the default options // and listeners should be stored as the existing state. - storedTraceSourceState[source] = + _storedTraceSourceState[source] = new KeyValuePair>( PSTraceSourceOptions.None, new Collection()); } else { - storedTraceSourceState[source] = + _storedTraceSourceState[source] = new KeyValuePair>( source.Options, listenerCollection); @@ -552,9 +551,9 @@ namespace Microsoft.PowerShell.Commands } // Now turn on the listeners - - AddTraceListenersToSources (matchingSources); - SetTraceListenerOptions (matchingSources); + + AddTraceListenersToSources(matchingSources); + SetTraceListenerOptions(matchingSources); } #endregion TurnOnTracing @@ -577,17 +576,17 @@ namespace Microsoft.PowerShell.Commands listener.Flush(); } - if (storedTraceSourceState.ContainsKey (source)) + if (_storedTraceSourceState.ContainsKey(source)) { // Restore the TraceSource to its original state KeyValuePair> storedState = - storedTraceSourceState[source]; + _storedTraceSourceState[source]; - source.Listeners.Clear (); + source.Listeners.Clear(); foreach (TraceListener listener in storedState.Value) { - source.Listeners.Add (listener); + source.Listeners.Add(listener); } source.Options = storedState.Key; @@ -597,7 +596,7 @@ namespace Microsoft.PowerShell.Commands // Since we don't have any stored state for this TraceSource, // just turn it off. - source.Listeners.Clear (); + source.Listeners.Clear(); source.Options = PSTraceSourceOptions.None; } } @@ -610,11 +609,11 @@ namespace Microsoft.PowerShell.Commands /// /// Clears the store TraceSource state. /// - protected void ClearStoredState () + protected void ClearStoredState() { // First close all listeners - foreach (KeyValuePair> pair in storedTraceSourceState.Values) + foreach (KeyValuePair> pair in _storedTraceSourceState.Values) { foreach (TraceListener listener in pair.Value) { @@ -622,11 +621,11 @@ namespace Microsoft.PowerShell.Commands listener.Dispose(); } } - storedTraceSourceState.Clear (); + _storedTraceSourceState.Clear(); } - private Dictionary>> storedTraceSourceState = - new Dictionary>> (); + private Dictionary>> _storedTraceSourceState = + new Dictionary>>(); #endregion stored state } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs index 5e8a72a53..f5910c782 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/update-list.cs @@ -97,7 +97,7 @@ namespace Microsoft.PowerShell.Commands } private string _property; - private PSListModifier listModifier; + private PSListModifier _listModifier; /// /// ProcessRecord method. @@ -112,9 +112,9 @@ namespace Microsoft.PowerShell.Commands } else { - if (listModifier == null) + if (_listModifier == null) { - listModifier = CreatePSListModifier(); + _listModifier = CreatePSListModifier(); } PSMemberInfo memberInfo = InputObject.Members[Property]; @@ -122,7 +122,7 @@ namespace Microsoft.PowerShell.Commands { try { - listModifier.ApplyTo(memberInfo.Value); + _listModifier.ApplyTo(memberInfo.Value); WriteObject(InputObject); } catch (PSInvalidOperationException e) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs index 1e0bd26e6..65ac129c6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/write.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -26,21 +27,21 @@ namespace Microsoft.PowerShell.Commands /// /// Message to be sent and processed if debug mode is on. /// - [Parameter( Position = 0, Mandatory = true, ValueFromPipeline = true )] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowEmptyString] [Alias("Msg")] public string Message { get { - return message; + return _message; } set { - message = value; + _message = value; } } - private string message = null; + private string _message = null; /// @@ -87,21 +88,21 @@ namespace Microsoft.PowerShell.Commands /// /// Message to be sent if verbose messages are being shown. /// - [Parameter( Position = 0, Mandatory = true, ValueFromPipeline = true )] + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowEmptyString] [Alias("Msg")] public string Message { get { - return message; + return _message; } set { - message = value; + _message = value; } } - private string message = null; + private string _message = null; /// @@ -155,14 +156,14 @@ namespace Microsoft.PowerShell.Commands { get { - return message; + return _message; } set { - message = value; + _message = value; } } - private string message = null; + private string _message = null; /// @@ -462,17 +463,17 @@ namespace Microsoft.PowerShell.Commands { */ - // 2005/07/14-913791 "write-error output is confusing and misleading" - // set InvocationInfo to the script not the command - InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (null != myInvocation) - { - errorRecord.SetInvocationInfo(myInvocation); - errorRecord.PreserveInvocationInfoOnce = true; - errorRecord.CategoryInfo.Activity = "Write-Error"; - } + // 2005/07/14-913791 "write-error output is confusing and misleading" + // set InvocationInfo to the script not the command + InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; + if (null != myInvocation) + { + errorRecord.SetInvocationInfo(myInvocation); + errorRecord.PreserveInvocationInfoOnce = true; + errorRecord.CategoryInfo.Activity = "Write-Error"; + } - WriteError(errorRecord); + WriteError(errorRecord); /* } */ @@ -494,25 +495,25 @@ namespace Microsoft.PowerShell.Commands } } -/* 2005/01/25 removing throw-error - /// - /// This class implements Write-Error command - /// - [Cmdlet("Throw", "Error", DefaultParameterSetName = "NoException")] - public sealed class ThrowErrorCommand : WriteOrThrowErrorCommand - { + /* 2005/01/25 removing throw-error /// - /// constructor + /// This class implements Write-Error command /// - public ThrowErrorCommand() + [Cmdlet("Throw", "Error", DefaultParameterSetName = "NoException")] + public sealed class ThrowErrorCommand : WriteOrThrowErrorCommand { - using (tracer.TraceConstructor(this)) + /// + /// constructor + /// + public ThrowErrorCommand() { - _terminating = true; + using (tracer.TraceConstructor(this)) + { + _terminating = true; + } } } - } -*/ + */ #endregion WriteOrThrowErrorCommand @@ -573,7 +574,6 @@ namespace Microsoft.PowerShell.Commands #endregion Serialization } // WriteErrorException #endregion WriteErrorException - } //namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs b/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs index a3b73ab20..048403f35 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs @@ -7,27 +7,27 @@ using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif -[assembly:InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #if CORECLR -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] #else -[assembly:AssemblyConfiguration("")] -[assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] -[assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] -[assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] -[assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyInformationalVersionAttribute(@"10.0.10011.16384")] +[assembly: ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] +[assembly: AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] +[assembly: AssemblyDescription("Microsoft Windows PowerShell Console Host")] -[assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] -[assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] +[assembly: System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] +[assembly: System.Reflection.AssemblyFileVersion("10.0.10011.16384")] #endif -[assembly:System.Runtime.InteropServices.ComVisible(false)] -[assembly:System.Reflection.AssemblyVersion("3.0.0.0")] -[assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] -[assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] -[assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] +[assembly: System.Runtime.InteropServices.ComVisible(false)] +[assembly: System.Reflection.AssemblyVersion("3.0.0.0")] +[assembly: System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] +[assembly: System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] +[assembly: System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index e2695a7c8..b0bac1649 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -26,20 +26,20 @@ namespace Microsoft.PowerShell { Dbg.Assert(p != null, "parent ConsoleHost must be supplied"); - this.bannerText = bannerText; - this.helpText = helpText; - this.parent = p; - this.ui = (ConsoleHostUserInterface)p.UI; - this.ver = ver; + _bannerText = bannerText; + _helpText = helpText; + _parent = p; + _ui = (ConsoleHostUserInterface)p.UI; + _ver = ver; } internal bool AbortStartup { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return abortStartup; + return _abortStartup; } } @@ -47,9 +47,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return commandLineCommand; + return _commandLineCommand; } } @@ -57,9 +57,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return wasCommandEncoded; + return _wasCommandEncoded; } } @@ -67,8 +67,8 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); - return showBanner; + Dbg.Assert(_dirty, "Parse has not been called yet"); + return _showBanner; } } @@ -76,9 +76,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return noExit; + return _noExit; } } @@ -86,7 +86,7 @@ namespace Microsoft.PowerShell { get { - return importSystemModules; + return _importSystemModules; } } @@ -94,9 +94,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return skipUserInit; + return _skipUserInit; } } @@ -104,9 +104,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return exitCode; + return _exitCode; } } @@ -114,9 +114,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return explicitReadCommandsFromStdin; + return _explicitReadCommandsFromStdin; } } @@ -124,9 +124,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return noPrompt; + return _noPrompt; } } @@ -134,35 +134,35 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return collectedArgs; + return _collectedArgs; } } internal string ConfigurationName { - get { return configurationName; } + get { return _configurationName; } } internal bool SocketServerMode { get { - return socketServerMode; + return _socketServerMode; } } internal bool NamedPipeServerMode { - get { return namedPipeServerMode; } + get { return _namedPipeServerMode; } } internal bool ServerMode { get { - return serverMode; + return _serverMode; } } @@ -170,9 +170,9 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); + Dbg.Assert(_dirty, "Parse has not been called yet"); - return outFormat; + return _outFormat; } } @@ -180,8 +180,8 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); - return inFormat; + Dbg.Assert(_dirty, "Parse has not been called yet"); + return _inFormat; } } @@ -189,8 +189,8 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); - return file; + Dbg.Assert(_dirty, "Parse has not been called yet"); + return _file; } } @@ -198,8 +198,8 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(dirty, "Parse has not been called yet"); - return executionPolicy; + Dbg.Assert(_dirty, "Parse has not been called yet"); + return _executionPolicy; } } @@ -207,36 +207,36 @@ namespace Microsoft.PowerShell { get { - return noInteractive; + return _noInteractive; } } internal bool NonInteractive { - get { return noInteractive; } + get { return _noInteractive; } } private void ShowHelp() { - ui.WriteLine(""); - if (this.helpText == null) + _ui.WriteLine(""); + if (_helpText == null) { - ui.WriteLine(CommandLineParameterParserStrings.DefaultHelp); + _ui.WriteLine(CommandLineParameterParserStrings.DefaultHelp); } else { - ui.Write(helpText); + _ui.Write(_helpText); } - ui.WriteLine(""); + _ui.WriteLine(""); } private void DisplayBanner() { // If banner text is not supplied do nothing. - if (!String.IsNullOrEmpty(bannerText)) + if (!String.IsNullOrEmpty(_bannerText)) { - ui.WriteLine(bannerText); - ui.WriteLine(); + _ui.WriteLine(_bannerText); + _ui.WriteLine(); } } @@ -244,9 +244,9 @@ namespace Microsoft.PowerShell { get { - if (staMode.HasValue) + if (_staMode.HasValue) { - return staMode.Value; + return _staMode.Value; } else { @@ -276,12 +276,12 @@ namespace Microsoft.PowerShell internal void Parse(string[] args) { - Dbg.Assert(!dirty, "This instance has already been used. Create a new instance."); + Dbg.Assert(!_dirty, "This instance has already been used. Create a new instance."); // indicates that we've called this method on this instance, and that when it's done, the state variables // will reflect the parse. - dirty = true; + _dirty = true; ParseHelper(args); @@ -290,26 +290,26 @@ namespace Microsoft.PowerShell var configurationName = GetConfigurationNameFromGroupPolicy(); if (!string.IsNullOrEmpty(configurationName)) { - this.configurationName = configurationName; + _configurationName = configurationName; } } - private static string groupPolicyBase = @"Software\Policies\Microsoft\Windows\PowerShell"; - private static string ConsoleSessionConfigurationKey = "ConsoleSessionConfiguration"; - private static string EnableConsoleSessionConfiguration = "EnableConsoleSessionConfiguration"; - private static string ConsoleSessionConfigurationName = "ConsoleSessionConfigurationName"; + private static string s_groupPolicyBase = @"Software\Policies\Microsoft\Windows\PowerShell"; + private static string s_consoleSessionConfigurationKey = "ConsoleSessionConfiguration"; + private static string s_enableConsoleSessionConfiguration = "EnableConsoleSessionConfiguration"; + private static string s_consoleSessionConfigurationName = "ConsoleSessionConfigurationName"; private static string GetConfigurationNameFromGroupPolicy() { // Current user policy takes precedence. - var groupPolicySettings = Utils.GetGroupPolicySetting(groupPolicyBase, ConsoleSessionConfigurationKey, Utils.RegCurrentUserThenLocalMachine); + var groupPolicySettings = Utils.GetGroupPolicySetting(s_groupPolicyBase, s_consoleSessionConfigurationKey, Utils.RegCurrentUserThenLocalMachine); if (groupPolicySettings != null) { object keyValue; - if (groupPolicySettings.TryGetValue(EnableConsoleSessionConfiguration, out keyValue)) + if (groupPolicySettings.TryGetValue(s_enableConsoleSessionConfiguration, out keyValue)) { if (String.Equals(keyValue.ToString(), "1", StringComparison.OrdinalIgnoreCase)) { - if (groupPolicySettings.TryGetValue(ConsoleSessionConfigurationName, out keyValue)) + if (groupPolicySettings.TryGetValue(s_consoleSessionConfigurationName, out keyValue)) { string consoleSessionConfigurationName = keyValue.ToString(); if (!string.IsNullOrEmpty(consoleSessionConfigurationName)) @@ -361,41 +361,41 @@ namespace Microsoft.PowerShell if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?")) { - showHelp = true; - abortStartup = true; + _showHelp = true; + _abortStartup = true; } else if (MatchSwitch(switchKey, "noexit", "noe")) { - noExit = true; + _noExit = true; noexitSeen = true; } else if (MatchSwitch(switchKey, "importsystemmodules", "imp")) { - importSystemModules = true; + _importSystemModules = true; } else if (MatchSwitch(switchKey, "noprofile", "nop")) { - skipUserInit = true; + _skipUserInit = true; } else if (MatchSwitch(switchKey, "nologo", "nol")) { - showBanner = false; + _showBanner = false; } else if (MatchSwitch(switchKey, "noninteractive", "noni")) { - noInteractive = true; + _noInteractive = true; } else if (MatchSwitch(switchKey, "socketservermode", "so")) { - socketServerMode = true; + _socketServerMode = true; } else if (MatchSwitch(switchKey, "servermode", "s")) { - serverMode = true; + _serverMode = true; } else if (MatchSwitch(switchKey, "namedpipeservermode", "nam")) { - namedPipeServerMode = true; + _namedPipeServerMode = true; } else if (MatchSwitch(switchKey, "configurationname", "config")) { @@ -407,7 +407,7 @@ namespace Microsoft.PowerShell break; } - configurationName = args[i]; + _configurationName = args[i]; } else if (MatchSwitch(switchKey, "command", "c")) { @@ -432,7 +432,6 @@ namespace Microsoft.PowerShell ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo( args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture); ConsoleControl.SetConsoleMode(style); - } catch (PSInvalidCastException e) { @@ -461,21 +460,21 @@ namespace Microsoft.PowerShell // Don't show the startup banner unless -noexit has been specified. if (!noexitSeen) - showBanner = false; + _showBanner = false; // Process interactive input... if (args[i] == "-") { // the arg to -file is -, which is secret code for "read the commands from stdin with prompts" - explicitReadCommandsFromStdin = true; - noPrompt = false; + _explicitReadCommandsFromStdin = true; + _noPrompt = false; } else { // Exit on script completion unless -noexit was specified... if (!noexitSeen) - noExit = false; + _noExit = false; // We need to get the full path to the script because it will be // executed after the profiles are run and they may change the current @@ -484,9 +483,9 @@ namespace Microsoft.PowerShell try { // Normalize slashes - file = args[i].Replace(StringLiterals.AlternatePathSeparator, + _file = args[i].Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); - file = Path.GetFullPath(file); + _file = Path.GetFullPath(_file); } catch (Exception e) { @@ -505,7 +504,7 @@ namespace Microsoft.PowerShell break; } - if (!Path.GetExtension(file).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) + if (!Path.GetExtension(_file).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i]), @@ -513,7 +512,7 @@ namespace Microsoft.PowerShell break; } - if (!System.IO.File.Exists(file)) + if (!System.IO.File.Exists(_file)) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]), @@ -535,7 +534,7 @@ namespace Microsoft.PowerShell // using the pending parameter and current argument if (pendingParameter != null) { - collectedArgs.Add(new CommandParameter(pendingParameter, arg)); + _collectedArgs.Add(new CommandParameter(pendingParameter, arg)); pendingParameter = null; } else if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0])) @@ -550,17 +549,17 @@ namespace Microsoft.PowerShell } else { - collectedArgs.Add(new CommandParameter(arg.Substring(0, offset), arg.Substring(offset + 1))); + _collectedArgs.Add(new CommandParameter(arg.Substring(0, offset), arg.Substring(offset + 1))); } } else { - collectedArgs.Add(new CommandParameter(arg)); + _collectedArgs.Add(new CommandParameter(arg)); } } else { - collectedArgs.Add(new CommandParameter(null, arg)); + _collectedArgs.Add(new CommandParameter(null, arg)); } ++i; } @@ -574,8 +573,8 @@ namespace Microsoft.PowerShell { // This does not need to be localized: its chk only - ui.WriteToConsole("Waiting - type enter to continue:", false); - ui.ReadLine(); + _ui.WriteToConsole("Waiting - type enter to continue:", false); + _ui.ReadLine(); } // this option is useful for testing the initial InitialSessionState experience @@ -623,25 +622,25 @@ namespace Microsoft.PowerShell } if (moduleCount < 1) { - ui.WriteErrorLine("No modules specified for -module option"); + _ui.WriteErrorLine("No modules specified for -module option"); } } #endif else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o")) { - ParseFormat(args, ref i, ref outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter); + ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter); } else if (MatchSwitch(switchKey, "inputformat", "i") || MatchSwitch(switchKey, "if", "i")) { - ParseFormat(args, ref i, ref inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter); + ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter); } else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep")) { - ParseExecutionPolicy(args, ref i, ref executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter); + ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter); } else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e")) { - wasCommandEncoded = true; + _wasCommandEncoded = true; if (!ParseCommand(args, ref i, noexitSeen, true)) { break; @@ -657,7 +656,7 @@ namespace Microsoft.PowerShell #if !CORECLR // explicit setting of the ApartmentState Not supported on NanoServer else if (MatchSwitch(switchKey, "sta", "s")) { - if (staMode.HasValue) + if (_staMode.HasValue) { // -sta and -mta are mutually exclusive. WriteCommandLineError( @@ -665,13 +664,13 @@ namespace Microsoft.PowerShell break; } - staMode = true; + _staMode = true; } // Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta. // Not deleting -sta for backward compatability reasons else if (MatchSwitch(switchKey, "mta", "mta")) { - if (staMode.HasValue) + if (_staMode.HasValue) { // -sta and -mta are mutually exclusive. WriteCommandLineError( @@ -679,7 +678,7 @@ namespace Microsoft.PowerShell break; } - staMode = false; + _staMode = false; } #endif else @@ -694,29 +693,29 @@ namespace Microsoft.PowerShell } } - if (showHelp) + if (_showHelp) { ShowHelp(); } - - if (showBanner && !showHelp) + + if (_showBanner && !_showHelp) { DisplayBanner(); } Dbg.Assert( - ((exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && abortStartup) - || (exitCode == ConsoleHost.ExitCodeSuccess), + ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) + || (_exitCode == ConsoleHost.ExitCodeSuccess), "if exit code is failure, then abortstartup should be true"); } private void WriteCommandLineError(string msg, bool showHelp = false, bool showBanner = false) { - this.ui.WriteErrorLine(msg); - this.showHelp = showHelp; - this.showBanner = showBanner; - this.abortStartup = true; - this.exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(msg); + _showHelp = showHelp; + _showBanner = showBanner; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; } private bool MatchSwitch(string switchKey, string match, string smallestUnambiguousMatch) @@ -750,13 +749,13 @@ namespace Microsoft.PowerShell ++i; if (i >= args.Length) { - ui.WriteErrorLine( + _ui.WriteErrorLine( StringUtil.Format( resourceStr, sb.ToString())); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return; } @@ -766,14 +765,14 @@ namespace Microsoft.PowerShell } catch (ArgumentException) { - ui.WriteErrorLine( + _ui.WriteErrorLine( StringUtil.Format( CommandLineParameterParserStrings.BadFormatParameterValue, args[i], sb.ToString())); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; } } @@ -782,11 +781,11 @@ namespace Microsoft.PowerShell ++i; if (i >= args.Length) { - ui.WriteErrorLine(resourceStr); + _ui.WriteErrorLine(resourceStr); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return; } @@ -795,24 +794,24 @@ namespace Microsoft.PowerShell private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded) { - if (commandLineCommand != null) + if (_commandLineCommand != null) { // we've already set the command, so squawk - ui.WriteErrorLine(CommandLineParameterParserStrings.CommandAlreadySpecified); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.CommandAlreadySpecified); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } ++i; if (i >= args.Length) { - ui.WriteErrorLine(CommandLineParameterParserStrings.MissingCommandParameter); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.MissingCommandParameter); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } @@ -820,44 +819,43 @@ namespace Microsoft.PowerShell { try { - commandLineCommand = StringToBase64Converter.Base64ToString(args[i]); + _commandLineCommand = StringToBase64Converter.Base64ToString(args[i]); } // decoding failed catch { - ui.WriteErrorLine(CommandLineParameterParserStrings.BadCommandValue); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.BadCommandValue); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } - } else if (args[i] == "-") { // the arg to -command is -, which is secret code for "read the commands from stdin with no prompts" - explicitReadCommandsFromStdin = true; - noPrompt = true; + _explicitReadCommandsFromStdin = true; + _noPrompt = true; ++i; if (i != args.Length) { // there are more parameters to -command than -, which is an error. - ui.WriteErrorLine(CommandLineParameterParserStrings.TooManyParametersToCommand); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.TooManyParametersToCommand); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } if (!Console.IsInputRedirected) { - ui.WriteErrorLine(CommandLineParameterParserStrings.StdinNotRedirected); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.StdinNotRedirected); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } } @@ -870,46 +868,45 @@ namespace Microsoft.PowerShell while (i < args.Length) { cmdLineCmdSB.Append(args[i] + " "); - ++i; + ++i; } if (cmdLineCmdSB.Length > 0) { // remove the last blank cmdLineCmdSB.Remove(cmdLineCmdSB.Length - 1, 1); } - commandLineCommand = cmdLineCmdSB.ToString(); + _commandLineCommand = cmdLineCmdSB.ToString(); } - if (!noexitSeen && !explicitReadCommandsFromStdin) + if (!noexitSeen && !_explicitReadCommandsFromStdin) { // don't reset this if they've already specified -noexit - noExit = false; + _noExit = false; } - showBanner = false; + _showBanner = false; return true; } private bool CollectArgs(string[] args, ref int i) { - - if (collectedArgs.Count != 0) + if (_collectedArgs.Count != 0) { - ui.WriteErrorLine(CommandLineParameterParserStrings.ArgsAlreadySpecified); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.ArgsAlreadySpecified); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } ++i; if (i >= args.Length) { - ui.WriteErrorLine(CommandLineParameterParserStrings.MissingArgsValue); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.MissingArgsValue); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } @@ -920,7 +917,7 @@ namespace Microsoft.PowerShell { foreach (object obj in a) { - collectedArgs.Add(new CommandParameter(null, obj)); + _collectedArgs.Add(new CommandParameter(null, obj)); } } } @@ -928,51 +925,50 @@ namespace Microsoft.PowerShell { // decoding failed - ui.WriteErrorLine(CommandLineParameterParserStrings.BadArgsValue); - showHelp = true; - abortStartup = true; - exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; + _ui.WriteErrorLine(CommandLineParameterParserStrings.BadArgsValue); + _showHelp = true; + _abortStartup = true; + _exitCode = ConsoleHost.ExitCodeBadCommandLineParameter; return false; } return true; } - private bool socketServerMode; - private bool serverMode; - private bool namedPipeServerMode; - private string configurationName; - private ConsoleHost parent; - private ConsoleHostUserInterface ui; - private bool showHelp; - private bool showBanner = true; - private bool noInteractive; - private string bannerText; - private string helpText; - private bool abortStartup; - private bool skipUserInit; + private bool _socketServerMode; + private bool _serverMode; + private bool _namedPipeServerMode; + private string _configurationName; + private ConsoleHost _parent; + private ConsoleHostUserInterface _ui; + private bool _showHelp; + private bool _showBanner = true; + private bool _noInteractive; + private string _bannerText; + private string _helpText; + private bool _abortStartup; + private bool _skipUserInit; // Win8: 182409 PowerShell 3.0 should run in STA mode by default // -sta and -mta are mutually exclusive..so tracking them using nullable boolean // if true, then sta is specified on the command line. // if false, then mta is specified on the command line. // if null, then none is specified on the command line..use default in this case // default is sta. - private bool? staMode = null; - private bool noExit = true; - private bool explicitReadCommandsFromStdin; - private bool noPrompt; - private string commandLineCommand; - private bool wasCommandEncoded; - private uint exitCode = ConsoleHost.ExitCodeSuccess; - private bool dirty; - private Version ver; - private Serialization.DataFormat outFormat = Serialization.DataFormat.Text; - private Serialization.DataFormat inFormat = Serialization.DataFormat.Text; - private Collection collectedArgs = new Collection(); - private string file; - private string executionPolicy; - private bool importSystemModules = false; + private bool? _staMode = null; + private bool _noExit = true; + private bool _explicitReadCommandsFromStdin; + private bool _noPrompt; + private string _commandLineCommand; + private bool _wasCommandEncoded; + private uint _exitCode = ConsoleHost.ExitCodeSuccess; + private bool _dirty; + private Version _ver; + private Serialization.DataFormat _outFormat = Serialization.DataFormat.Text; + private Serialization.DataFormat _inFormat = Serialization.DataFormat.Text; + private Collection _collectedArgs = new Collection(); + private string _file; + private string _executionPolicy; + private bool _importSystemModules = false; } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 90bce23ca..a1a32b245 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -30,9 +30,9 @@ using Microsoft.Win32.SafeHandles; using Dbg = System.Management.Automation.Diagnostics; using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle; -using WORD = System.UInt16; -using ULONG = System.UInt32; -using DWORD = System.UInt32; +using WORD = System.UInt16; +using ULONG = System.UInt32; +using DWORD = System.UInt32; using NakedWin32Handle = System.IntPtr; using HWND = System.IntPtr; using HDC = System.IntPtr; @@ -48,7 +48,7 @@ namespace Microsoft.PowerShell internal static class ConsoleControl { - #region structs +#region structs internal enum InputRecordEventTypes : ushort { @@ -246,7 +246,7 @@ namespace Microsoft.PowerShell public byte tmCharSet; } - #region SentInput Data Structures +#region SentInput Data Structures [StructLayout(LayoutKind.Sequential)] internal struct INPUT @@ -386,7 +386,7 @@ namespace Microsoft.PowerShell /// INPUT_KEYBOARD = 0x01 /// Keyboard = 1, - + /// /// INPUT_HARDWARE = 0x02 /// @@ -417,11 +417,11 @@ namespace Microsoft.PowerShell ScanCode = 0x0008 } - #endregion SentInput Data Structures +#endregion SentInput Data Structures - #endregion structs +#endregion structs - #region Window Visibility +#region Window Visibility [DllImport(PinvokeDllNames.GetConsoleWindowDllName)] internal static extern IntPtr GetConsoleWindow(); @@ -451,12 +451,12 @@ namespace Microsoft.PowerShell /// true it it was successful [DllImport("user32.dll")] internal static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow); - + internal static void SetConsoleMode(ProcessWindowStyle style) { IntPtr hwnd = GetConsoleWindow(); Dbg.Assert(hwnd != IntPtr.Zero, "Console handle should never be zero"); - switch(style) + switch (style) { case ProcessWindowStyle.Hidden: ShowWindow(hwnd, SW_HIDE); @@ -473,9 +473,9 @@ namespace Microsoft.PowerShell } } #endif - #endregion +#endregion - #region Input break handler (Ctrl-C, Ctrl-Break) +#region Input break handler (Ctrl-C, Ctrl-Break) /// /// @@ -548,13 +548,13 @@ namespace Microsoft.PowerShell } } - #endregion +#endregion - #region Win32Handles +#region Win32Handles - static readonly Lazy _keyboardInputHandle = new Lazy(() => + private static readonly Lazy _keyboardInputHandle = new Lazy(() => { - var handle = NativeMethods.CreateFile( + var handle = NativeMethods.CreateFile( "CONIN$", (UInt32) (NativeMethods.AccessQualifiers.GenericRead | NativeMethods.AccessQualifiers.GenericWrite), @@ -586,7 +586,7 @@ namespace Microsoft.PowerShell return _keyboardInputHandle.Value; } - static readonly Lazy _outputHandle = new Lazy(() => + private static readonly Lazy _outputHandle = new Lazy(() => { // We use CreateFile here instead of GetStdWin32Handle, as GetStdWin32Handle will return redirected handles var handle = NativeMethods.CreateFile( @@ -623,9 +623,9 @@ namespace Microsoft.PowerShell return _outputHandle.Value; } - #endregion +#endregion - #region Mode +#region Mode /// /// @@ -720,9 +720,9 @@ namespace Microsoft.PowerShell } - #endregion +#endregion - #region Input +#region Input @@ -800,9 +800,9 @@ namespace Microsoft.PowerShell ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleExceptionTemplate); throw e; } - if (charsReadUnused > (uint) buffer.Length) - charsReadUnused = (uint) buffer.Length; - return buffer.ToString(0, (int) charsReadUnused); + if (charsReadUnused > (uint)buffer.Length) + charsReadUnused = (uint)buffer.Length; + return buffer.ToString(0, (int)charsReadUnused); } /// @@ -969,9 +969,9 @@ namespace Microsoft.PowerShell } } - #endregion Input +#endregion Input - #region Buffer +#region Buffer /// /// Wraps Win32 GetConsoleScreenBufferInfo @@ -1183,7 +1183,6 @@ namespace Microsoft.PowerShell { WriteConsoleOutputPlain(consoleHandle, origin, contents); } - } private static void BuildEdgeTypeInfo( @@ -1198,7 +1197,7 @@ namespace Microsoft.PowerShell BufferCellArrayRowType edgeType = GetEdgeType(contents[contentsRegion.Top, contentsRegion.Left], contents[contentsRegion.Top, contentsRegion.Right]); - for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; ) + for (int r = contentsRegion.Top; r <= contentsRegion.Bottom;) { BufferCellArrayRowTypeRange range; range.Start = r; @@ -1211,7 +1210,7 @@ namespace Microsoft.PowerShell { firstRightLeadingRow = r; } - for (; ; ) + for (;;) { r++; if (r > contentsRegion.Bottom) @@ -1382,8 +1381,8 @@ namespace Microsoft.PowerShell "origin must be within the output buffer"); int rows = contentsRegion.Bottom - contentsRegion.Top + 1; int cols = contentsRegion.Right - contentsRegion.Left + 1; - - CONSOLE_FONT_INFO_EX fontInfo = GetConsoleFontInfo(consoleHandle); + + CONSOLE_FONT_INFO_EX fontInfo = GetConsoleFontInfo(consoleHandle); int fontType = fontInfo.FontFamily & NativeMethods.FontTypeMask; bool trueTypeInUse = (fontType & NativeMethods.TrueTypeFont) == NativeMethods.TrueTypeFont; @@ -1800,7 +1799,7 @@ namespace Microsoft.PowerShell } } - #region ReadConsoleOutput CJK +#region ReadConsoleOutput CJK /// /// If an edge cell read is a blank, it is potentially part of a double width character. Hence, /// at least one of the left and right edges should be checked @@ -2030,7 +2029,6 @@ namespace Microsoft.PowerShell bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit); continue; } - } } colsRemaining -= bufferSize.X; @@ -2092,7 +2090,7 @@ namespace Microsoft.PowerShell rowIndex++; } } - #endregion ReadConsoleOutput CJK +#endregion ReadConsoleOutput CJK private static void ReadConsoleOutputPlain @@ -2459,9 +2457,9 @@ namespace Microsoft.PowerShell } } - #endregion Buffer +#endregion Buffer - #region Window +#region Window /// /// Wraps Win32 SetConsoleWindowInfo @@ -2603,10 +2601,10 @@ namespace Microsoft.PowerShell } } - #endregion Window +#endregion Window #if !CORECLR - #region Font Selection +#region Font Selection /// /// UpdateLocaleSpecificFont is a helper method used to update @@ -2706,7 +2704,7 @@ namespace Microsoft.PowerShell return LucidaSupportedCodePages.Contains(currentLocaleCodePage); } - #endregion +#endregion #endif /// /// @@ -2815,7 +2813,7 @@ namespace Microsoft.PowerShell } - #region Dealing with CJK +#region Dealing with CJK /// /// From IsConsoleFullWidth in \windows\core\ntcon\server\dbcs.c @@ -3139,7 +3137,7 @@ namespace Microsoft.PowerShell /// /// /// - internal static bool IsCJKOutputCodePage(out uint codePage) + internal static bool IsCJKOutputCodePage(out uint codePage) { codePage = NativeMethods.GetConsoleOutputCP(); return codePage == 932 || // Japanese @@ -3148,9 +3146,9 @@ namespace Microsoft.PowerShell codePage == 950; // Traditional Chinese } - #endregion Dealing with CJK +#endregion Dealing with CJK - #region Cursor +#region Cursor /// @@ -3285,9 +3283,9 @@ namespace Microsoft.PowerShell } } - #endregion Cursor +#endregion Cursor - #region helper +#region helper /// /// Helper function to create the proper HostException @@ -3306,9 +3304,9 @@ namespace Microsoft.PowerShell return e; } - #endregion helper +#endregion helper - #region SendInput +#region SendInput internal static void MimicKeyPress(INPUT[] inputs) { @@ -3325,7 +3323,7 @@ namespace Microsoft.PowerShell } } - #endregion SendInput +#endregion SendInput /// /// @@ -3339,7 +3337,7 @@ namespace Microsoft.PowerShell internal const int FontTypeMask = 0x06; internal const int TrueTypeFont = 0x04; - #region CreateFile +#region CreateFile [Flags] internal enum AccessQualifiers : uint @@ -3379,9 +3377,9 @@ namespace Microsoft.PowerShell NakedWin32Handle templateFileWin32Handle ); - #endregion CreateFile +#endregion CreateFile - #region Code Page +#region Code Page [DllImport(PinvokeDllNames.GetConsoleCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern uint GetConsoleCP(); @@ -3389,7 +3387,7 @@ namespace Microsoft.PowerShell [DllImport(PinvokeDllNames.GetConsoleOutputCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern uint GetConsoleOutputCP(); - #endregion Code Page +#endregion Code Page [DllImport(PinvokeDllNames.GetConsoleWindowDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern HWND GetConsoleWindow(); @@ -3570,7 +3568,6 @@ namespace Microsoft.PowerShell { COMMON_LVB_LEADING_BYTE = 0x0100, COMMON_LVB_TRAILING_BYTE = 0x0200 - } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index adfb05726..9d44553d5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -55,7 +55,6 @@ namespace Microsoft.PowerShell IHostSupportsInteractiveSession, IHostProvidesTelemetryData { - #region static methods internal const uint ExitCodeSuccess = 0x00000000; @@ -208,8 +207,8 @@ namespace Microsoft.PowerShell System.Threading.Thread.CurrentThread.Name = "ConsoleHost main thread"; - theConsoleHost = ConsoleHost.CreateSingletonInstance(configuration); - theConsoleHost.BindBreakHandler(); + s_theConsoleHost = ConsoleHost.CreateSingletonInstance(configuration); + s_theConsoleHost.BindBreakHandler(); PSHost.IsStdOutputRedirected = Console.IsOutputRedirected; @@ -220,61 +219,61 @@ namespace Microsoft.PowerShell if (!string.IsNullOrEmpty(preStartWarning)) { - theConsoleHost.UI.WriteWarningLine(preStartWarning); + s_theConsoleHost.UI.WriteWarningLine(preStartWarning); } try { - cpp = new CommandLineParameterParser(theConsoleHost, theConsoleHost.ver, bannerText, helpText); + s_cpp = new CommandLineParameterParser(s_theConsoleHost, s_theConsoleHost._ver, bannerText, helpText); string[] tempArgs = new string[args.GetLength(0)]; args.CopyTo(tempArgs, 0); - cpp.Parse(tempArgs); + s_cpp.Parse(tempArgs); // Servermode parameter validation check. - if ((cpp.ServerMode && cpp.NamedPipeServerMode) || (cpp.ServerMode && cpp.SocketServerMode) || (cpp.NamedPipeServerMode && cpp.SocketServerMode)) + if ((s_cpp.ServerMode && s_cpp.NamedPipeServerMode) || (s_cpp.ServerMode && s_cpp.SocketServerMode) || (s_cpp.NamedPipeServerMode && s_cpp.SocketServerMode)) { - tracer.TraceError("Conflicting server mode parameters, parameters must be used exclusively."); - theConsoleHost.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); + s_tracer.TraceError("Conflicting server mode parameters, parameters must be used exclusively."); + s_theConsoleHost.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); unchecked { return (int)ExitCodeBadCommandLineParameter; } } - if (cpp.ServerMode) + if (s_cpp.ServerMode) { ClrFacade.StartProfileOptimization("StartupProfileData-ServerMode"); - System.Management.Automation.Remoting.Server.OutOfProcessMediator.Run(cpp.InitialCommand); + System.Management.Automation.Remoting.Server.OutOfProcessMediator.Run(s_cpp.InitialCommand); exitCode = 0; } - else if (cpp.NamedPipeServerMode) + else if (s_cpp.NamedPipeServerMode) { ClrFacade.StartProfileOptimization("StartupProfileData-NamedPipeServerMode"); System.Management.Automation.Remoting.RemoteSessionNamedPipeServer.RunServerMode( - cpp.ConfigurationName); + s_cpp.ConfigurationName); exitCode = 0; } - else if (cpp.SocketServerMode) + else if (s_cpp.SocketServerMode) { ClrFacade.StartProfileOptimization("StartupProfileData-SocketServerMode"); - System.Management.Automation.Remoting.Server.HyperVSocketMediator.Run(cpp.InitialCommand, - cpp.ConfigurationName); + System.Management.Automation.Remoting.Server.HyperVSocketMediator.Run(s_cpp.InitialCommand, + s_cpp.ConfigurationName); exitCode = 0; } else { ClrFacade.StartProfileOptimization( - theConsoleHost.LoadPSReadline() + s_theConsoleHost.LoadPSReadline() ? "StartupProfileData-Interactive" : "StartupProfileData-NonInteractive"); - exitCode = theConsoleHost.Run(cpp, !string.IsNullOrEmpty(preStartWarning)); + exitCode = s_theConsoleHost.Run(s_cpp, !string.IsNullOrEmpty(preStartWarning)); } } finally { - TelemetryAPI.ReportExitTelemetry(theConsoleHost); - theConsoleHost.Dispose(); + TelemetryAPI.ReportExitTelemetry(s_theConsoleHost); + s_theConsoleHost.Dispose(); } unchecked @@ -282,7 +281,7 @@ namespace Microsoft.PowerShell return (int)exitCode; } } - private static CommandLineParameterParser cpp; + private static CommandLineParameterParser s_cpp; @@ -355,10 +354,10 @@ namespace Microsoft.PowerShell Debugger debugger = null; lock (host.hostGlobalLock) { - if (host.runspaceRef.Runspace != null && - host.runspaceRef.Runspace.GetCurrentlyRunningPipeline() != null) + if (host._runspaceRef.Runspace != null && + host._runspaceRef.Runspace.GetCurrentlyRunningPipeline() != null) { - debugger = host.runspaceRef.Runspace.Debugger; + debugger = host._runspaceRef.Runspace.Debugger; } } if (debugger != null) @@ -393,11 +392,11 @@ namespace Microsoft.PowerShell lock (host.hostGlobalLock) { - if (host.isCtrlCDisabled) + if (host._isCtrlCDisabled) { return; } - bht = host.breakHandlerThread; + bht = host._breakHandlerThread; if (!host.ShouldEndSession && shouldEndSession) { host.ShouldEndSession = shouldEndSession; @@ -412,16 +411,16 @@ namespace Microsoft.PowerShell { // we're not already running HandleBreak on a separate thread, so run it now. - host.breakHandlerThread = new Thread(new ThreadStart(ConsoleHost.HandleBreak)); - host.breakHandlerThread.Name = "ConsoleHost.HandleBreak"; - host.breakHandlerThread.Start(); + host._breakHandlerThread = new Thread(new ThreadStart(ConsoleHost.HandleBreak)); + host._breakHandlerThread.Name = "ConsoleHost.HandleBreak"; + host._breakHandlerThread.Start(); } } } private static void HandleBreak() { - ConsoleHost consoleHost = theConsoleHost; + ConsoleHost consoleHost = s_theConsoleHost; if (consoleHost != null) { if (consoleHost.InDebugMode) @@ -451,7 +450,7 @@ namespace Microsoft.PowerShell if (consoleHost.ShouldEndSession) { - var runspaceRef = ConsoleHost.SingletonInstance.runspaceRef; + var runspaceRef = ConsoleHost.SingletonInstance._runspaceRef; if (runspaceRef != null) { var runspace = runspaceRef.Runspace; @@ -471,7 +470,7 @@ namespace Microsoft.PowerShell ConsoleControl.FlushConsoleInputBuffer(handle); #endif - ConsoleHost.SingletonInstance.breakHandlerThread = null; + ConsoleHost.SingletonInstance._breakHandlerThread = null; } private static bool StopPipeline(Pipeline cmd) @@ -499,23 +498,23 @@ namespace Microsoft.PowerShell /// internal static ConsoleHost CreateSingletonInstance(RunspaceConfiguration configuration) { - Dbg.Assert(theConsoleHost == null, "CreateSingletonInstance should not be called multiple times"); - theConsoleHost = new ConsoleHost(configuration); - return theConsoleHost; + Dbg.Assert(s_theConsoleHost == null, "CreateSingletonInstance should not be called multiple times"); + s_theConsoleHost = new ConsoleHost(configuration); + return s_theConsoleHost; } internal static ConsoleHost SingletonInstance { get { - Dbg.Assert(theConsoleHost != null, "CreateSingletonInstance should be called before calling this method"); - return theConsoleHost; + Dbg.Assert(s_theConsoleHost != null, "CreateSingletonInstance should be called before calling this method"); + return s_theConsoleHost; } } -#endregion static methods + #endregion static methods -#region overrides + #region overrides /// /// @@ -549,7 +548,7 @@ namespace Microsoft.PowerShell get { // const, no lock needed. - return ver; + return _ver; } } @@ -566,7 +565,7 @@ namespace Microsoft.PowerShell get { // const, no lock needed. - return id; + return _id; } } @@ -591,15 +590,15 @@ namespace Microsoft.PowerShell /// public void PushRunspace(Runspace newRunspace) { - if (this.runspaceRef == null) { return; } + if (_runspaceRef == null) { return; } RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); remoteRunspace.StateChanged += new EventHandler(HandleRemoteRunspaceStateChanged); // Unsubscribe the local session debugger. - if (this.runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger != null) { - this.runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; + _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; } // Subscribe to debugger stop event. @@ -612,17 +611,17 @@ namespace Microsoft.PowerShell this.runningCmd = Microsoft.PowerShell.Commands.EnterPSSessionCommand.ConnectRunningPipeline(remoteRunspace); // Push runspace. - this.runspaceRef.Override(remoteRunspace, hostGlobalLock, out _isRunspacePushed); + _runspaceRef.Override(remoteRunspace, hostGlobalLock, out _isRunspacePushed); RunspacePushed.SafeInvoke(this, EventArgs.Empty); if (this.runningCmd != null) { Microsoft.PowerShell.Commands.EnterPSSessionCommand.ContinueCommand( - remoteRunspace, - this.runningCmd, - this, - this.inDebugMode, - this.runspaceRef.OldRunspace.ExecutionContext); + remoteRunspace, + this.runningCmd, + this, + _inDebugMode, + _runspaceRef.OldRunspace.ExecutionContext); } this.runningCmd = null; @@ -635,7 +634,7 @@ namespace Microsoft.PowerShell /// /// not sure /// arguments describing this event - void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) + private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { RunspaceState state = eventArgs.RunspaceStateInfo.State; @@ -662,22 +661,22 @@ namespace Microsoft.PowerShell /// public void PopRunspace() { - if (this.runspaceRef == null || - !this.runspaceRef.IsRunspaceOverridden ) + if (_runspaceRef == null || + !_runspaceRef.IsRunspaceOverridden) { return; } - if (this.inPushedConfiguredSession) + if (_inPushedConfiguredSession) { // For configured endpoint sessions, end session when configured runspace is popped. this.ShouldEndSession = true; } - if (this.runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger != null) { // Unsubscribe pushed runspace debugger. - this.runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; + _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; StopPipeline(this.runningCmd); @@ -691,12 +690,12 @@ namespace Microsoft.PowerShell lock (hostGlobalLock) { - this.runspaceRef.Revert(); + _runspaceRef.Revert(); _isRunspacePushed = false; } // Re-subscribe local runspace debugger. - this.runspaceRef.Runspace.Debugger.DebuggerStop += OnExecutionSuspended; + _runspaceRef.Runspace.Debugger.DebuggerStop += OnExecutionSuspended; // raise events outside the lock RunspacePopped.SafeInvoke(this, EventArgs.Empty); @@ -741,92 +740,112 @@ namespace Microsoft.PowerShell public class ConsoleColorProxy { - private ConsoleHostUserInterface ui; + private ConsoleHostUserInterface _ui; public ConsoleColorProxy(ConsoleHostUserInterface ui) { if (ui == null) throw new ArgumentNullException("ui"); - this.ui = ui; + _ui = ui; } public ConsoleColor ErrorForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.ErrorForegroundColor; } + get + { return _ui.ErrorForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.ErrorForegroundColor = value; } + set + { _ui.ErrorForegroundColor = value; } } public ConsoleColor ErrorBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.ErrorBackgroundColor; } + get + { return _ui.ErrorBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.ErrorBackgroundColor = value; } + set + { _ui.ErrorBackgroundColor = value; } } public ConsoleColor WarningForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.WarningForegroundColor; } + get + { return _ui.WarningForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.WarningForegroundColor = value; } + set + { _ui.WarningForegroundColor = value; } } public ConsoleColor WarningBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.WarningBackgroundColor; } + get + { return _ui.WarningBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.WarningBackgroundColor = value; } + set + { _ui.WarningBackgroundColor = value; } } public ConsoleColor DebugForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.DebugForegroundColor; } + get + { return _ui.DebugForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.DebugForegroundColor = value; } + set + { _ui.DebugForegroundColor = value; } } public ConsoleColor DebugBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.DebugBackgroundColor; } + get + { return _ui.DebugBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.DebugBackgroundColor = value; } + set + { _ui.DebugBackgroundColor = value; } } public ConsoleColor VerboseForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.VerboseForegroundColor; } + get + { return _ui.VerboseForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.VerboseForegroundColor = value; } + set + { _ui.VerboseForegroundColor = value; } } public ConsoleColor VerboseBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.VerboseBackgroundColor; } + get + { return _ui.VerboseBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.VerboseBackgroundColor = value; } + set + { _ui.VerboseBackgroundColor = value; } } public ConsoleColor ProgressForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.ProgressForegroundColor; } + get + { return _ui.ProgressForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.ProgressForegroundColor = value; } + set + { _ui.ProgressForegroundColor = value; } } public ConsoleColor ProgressBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return ui.ProgressBackgroundColor; } + get + { return _ui.ProgressBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { ui.ProgressBackgroundColor = value; } + set + { _ui.ProgressBackgroundColor = value; } } } @@ -836,14 +855,15 @@ namespace Microsoft.PowerShell /// public override PSObject PrivateData { - get { + get + { if (ui == null) return null; - if (consoleColorProxy == null) - consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui)); - return consoleColorProxy; + if (_consoleColorProxy == null) + _consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui)); + return _consoleColorProxy; } } - private PSObject consoleColorProxy; + private PSObject _consoleColorProxy; @@ -909,14 +929,14 @@ namespace Microsoft.PowerShell { this.PopRunspace(); } - else if (this.inDebugMode) + else if (_inDebugMode) { ExitDebugMode(DebuggerResumeAction.Continue); } else { - setShouldExitCalled = true; - exitCodeFromRunspace = exitCode; + _setShouldExitCalled = true; + _exitCodeFromRunspace = exitCode; ShouldEndSession = true; } } @@ -947,9 +967,9 @@ namespace Microsoft.PowerShell Executor.CurrentExecutor = null; lock (hostGlobalLock) { - this.isNested = oldCurrent != null || this.ui.IsCommandCompletionRunning; + _isNested = oldCurrent != null || this.ui.IsCommandCompletionRunning; } - InputLoop.RunNewInputLoop(this, isNested); + InputLoop.RunNewInputLoop(this, _isNested); } finally { @@ -971,7 +991,7 @@ namespace Microsoft.PowerShell { lock (hostGlobalLock) { - this.isNested = InputLoop.ExitCurrentLoop(); + _isNested = InputLoop.ExitCurrentLoop(); } } @@ -984,12 +1004,12 @@ namespace Microsoft.PowerShell { lock (hostGlobalLock) { - ++beginApplicationNotifyCount; - if (beginApplicationNotifyCount == 1) + ++_beginApplicationNotifyCount; + if (_beginApplicationNotifyCount == 1) { // save the window title when first notified. - savedWindowTitle = ui.RawUI.WindowTitle; + _savedWindowTitle = ui.RawUI.WindowTitle; } } } @@ -1004,13 +1024,13 @@ namespace Microsoft.PowerShell { lock (hostGlobalLock) { - Dbg.Assert(beginApplicationNotifyCount > 0, "Not running an executable - NotifyBeginApplication was not called!"); - --beginApplicationNotifyCount; - if (beginApplicationNotifyCount == 0) + Dbg.Assert(_beginApplicationNotifyCount > 0, "Not running an executable - NotifyBeginApplication was not called!"); + --_beginApplicationNotifyCount; + if (_beginApplicationNotifyCount == 0) { // restore the window title when the last application started has ended. - ui.RawUI.WindowTitle = savedWindowTitle; + ui.RawUI.WindowTitle = _savedWindowTitle; } } } @@ -1019,8 +1039,8 @@ namespace Microsoft.PowerShell { get { - return !cpp.NonInteractive && !cpp.AbortStartup && - ((cpp.InitialCommand == null && cpp.File == null) || cpp.NoExit); + return !s_cpp.NonInteractive && !s_cpp.AbortStartup && + ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit); } } double IHostProvidesTelemetryData.ProfileLoadTimeInMS { get { return _profileLoadTimeInMS; } } @@ -1030,10 +1050,10 @@ namespace Microsoft.PowerShell private double _profileLoadTimeInMS; private double _readyForInputTimeInMS; private int _interactiveCommandCount; - -#endregion overrides -#region non-overrides + #endregion overrides + + #region non-overrides /// /// @@ -1049,12 +1069,12 @@ namespace Microsoft.PowerShell // Thread. base.ShouldSetThreadUILanguageToZero = true; - this.inDebugMode = false; - this.displayDebuggerBanner = true; + _inDebugMode = false; + _displayDebuggerBanner = true; - this.configuration = configuration; + _configuration = configuration; this.ui = new ConsoleHostUserInterface(this); - this.consoleWriter = new ConsoleTextWriter(ui); + _consoleWriter = new ConsoleTextWriter(ui); #if !CORECLR // CurrentDomain.UnhandledException not supported on CoreCLR UnhandledExceptionEventHandler handler = new UnhandledExceptionEventHandler(UnhandledExceptionHandler); @@ -1080,7 +1100,7 @@ namespace Microsoft.PowerShell // The CLR will shut down the app as soon as this handler is complete, but just in case, we want // to exit at our next opportunity. - shouldEndSession = true; + _shouldEndSession = true; Exception e = null; @@ -1121,7 +1141,7 @@ namespace Microsoft.PowerShell private void Dispose(bool isDisposingNotFinalizing) { - if (!isDisposed) + if (!_isDisposed) { #if !UNIX Dbg.Assert(breakHandlerGcHandle != null, "break handler should be set"); @@ -1135,31 +1155,31 @@ namespace Microsoft.PowerShell { StopTranscribing(); } - if (outputSerializer != null) + if (_outputSerializer != null) { - outputSerializer.End(); + _outputSerializer.End(); } - if (errorSerializer != null) + if (_errorSerializer != null) { - errorSerializer.End(); + _errorSerializer.End(); } - if (runspaceRef != null) + if (_runspaceRef != null) { // NTRAID#Windows Out Of Band Releases-925297-2005/12/14 try { - runspaceRef.Runspace.Dispose(); + _runspaceRef.Runspace.Dispose(); } catch (InvalidRunspaceStateException) { } } - runspaceRef = null; + _runspaceRef = null; ui = null; } } - isDisposed = true; + _isDisposed = true; } /// @@ -1183,7 +1203,7 @@ namespace Microsoft.PowerShell lock (hostGlobalLock) { - result = shouldEndSession; + result = _shouldEndSession; } return result; @@ -1194,10 +1214,10 @@ namespace Microsoft.PowerShell { // If ShouldEndSession is already true, you can't set it back - Dbg.Assert(shouldEndSession != true || value != false, + Dbg.Assert(_shouldEndSession != true || value != false, "ShouldEndSession can only be set from false to true"); - shouldEndSession = value; + _shouldEndSession = value; } } } @@ -1212,7 +1232,7 @@ namespace Microsoft.PowerShell { get { - return runspaceRef; + return _runspaceRef; } } @@ -1220,7 +1240,7 @@ namespace Microsoft.PowerShell { get { - return outputFormat; + return _outputFormat; } } @@ -1230,7 +1250,7 @@ namespace Microsoft.PowerShell { get { - return inputFormat; + return _inputFormat; } } @@ -1238,11 +1258,11 @@ namespace Microsoft.PowerShell { get { - WrappedDeserializer.DataFormat format = outputFormat; + WrappedDeserializer.DataFormat format = _outputFormat; //If this shell is invoked in minishell interop mode and error is redirected, //always write data in error stream in xml format. - if (IsInteractive == false && Console.IsErrorRedirected && wasInitialCommandEncoded) + if (IsInteractive == false && Console.IsErrorRedirected && _wasInitialCommandEncoded) { format = Serialization.DataFormat.XML; } @@ -1260,22 +1280,22 @@ namespace Microsoft.PowerShell internal bool IsNested { - get { return this.isNested; } + get { return _isNested; } } internal WrappedSerializer OutputSerializer { get { - if (outputSerializer == null) + if (_outputSerializer == null) { - outputSerializer = + _outputSerializer = new WrappedSerializer( - outputFormat, + _outputFormat, "Output", Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter); } - return outputSerializer; + return _outputSerializer; } } @@ -1283,15 +1303,15 @@ namespace Microsoft.PowerShell { get { - if (errorSerializer == null) + if (_errorSerializer == null) { - errorSerializer = + _errorSerializer = new WrappedSerializer( ErrorFormat, "Error", Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter); } - return errorSerializer; + return _errorSerializer; } } @@ -1301,7 +1321,7 @@ namespace Microsoft.PowerShell { // we're running interactive if we're in a prompt loop, and we're not reading keyboard input from stdin. - return isRunningPromptLoop && !ui.ReadFromStdin; + return _isRunningPromptLoop && !ui.ReadFromStdin; } } @@ -1309,8 +1329,8 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(consoleWriter != null, "consoleWriter should have been initialized"); - return consoleWriter; + Dbg.Assert(_consoleWriter != null, "consoleWriter should have been initialized"); + return _consoleWriter; } } @@ -1342,12 +1362,12 @@ namespace Microsoft.PowerShell do { - runspaceInitTracer.WriteLine("starting parse of command line parameters"); + s_runspaceInitTracer.WriteLine("starting parse of command line parameters"); exitCode = ExitCodeSuccess; if (!string.IsNullOrEmpty(cpp.InitialCommand) && isPrestartWarned) { - tracer.TraceError("Start up warnings made command \"{0}\" not executed", cpp.InitialCommand); + s_tracer.TraceError("Start up warnings made command \"{0}\" not executed", cpp.InitialCommand); string msg = StringUtil.Format(ConsoleHostStrings.InitialCommandNotExecuted, cpp.InitialCommand); ui.WriteErrorLine(msg); exitCode = ExitCodeInitFailure; @@ -1356,23 +1376,23 @@ namespace Microsoft.PowerShell if (cpp.AbortStartup) { - tracer.WriteLine("processing of cmdline args failed, exiting"); + s_tracer.WriteLine("processing of cmdline args failed, exiting"); exitCode = cpp.ExitCode; break; } - outputFormat = cpp.OutputFormat; - inputFormat = cpp.InputFormat; - wasInitialCommandEncoded = cpp.WasInitialCommandEncoded; + _outputFormat = cpp.OutputFormat; + _inputFormat = cpp.InputFormat; + _wasInitialCommandEncoded = cpp.WasInitialCommandEncoded; ui.ReadFromStdin = cpp.ExplicitReadCommandsFromStdin || Console.IsInputRedirected; ui.NoPrompt = cpp.NoPrompt; ui.ThrowOnReadAndPrompt = cpp.ThrowOnReadAndPrompt; - noExit = cpp.NoExit; + _noExit = cpp.NoExit; // See if we need to change the process-wide execution // policy - if(! String.IsNullOrEmpty(cpp.ExecutionPolicy)) + if (!String.IsNullOrEmpty(cpp.ExecutionPolicy)) { ExecutionPolicy executionPolicy = SecuritySupport.ParseExecutionPolicy(cpp.ExecutionPolicy); SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, executionPolicy, null); @@ -1399,9 +1419,9 @@ namespace Microsoft.PowerShell [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private uint Run(string bannerText, string helpText, bool isPrestartWarned, string[] args) { - cpp = new CommandLineParameterParser(this, ver, bannerText, helpText); - cpp.Parse(args); - return Run(cpp, isPrestartWarned); + s_cpp = new CommandLineParameterParser(this, _ver, bannerText, helpText); + s_cpp.Parse(args); + return Run(s_cpp, isPrestartWarned); } /// @@ -1426,7 +1446,7 @@ namespace Microsoft.PowerShell if (ExitCode == ExitCodeInitFailure) { break; } - if (!noExit) + if (!_noExit) { // Wait for runspace to open, init, and run init script before // setting ShouldEndSession, to allow debugger to work. @@ -1438,9 +1458,9 @@ namespace Microsoft.PowerShell EnterNestedPrompt(); } - if (setShouldExitCalled) + if (_setShouldExitCalled) { - ExitCode = unchecked((uint)exitCodeFromRunspace); + ExitCode = unchecked((uint)_exitCodeFromRunspace); } else { @@ -1448,7 +1468,7 @@ namespace Microsoft.PowerShell bool dollarHook = exec.ExecuteCommandAndGetResultAsBool("$global:?") ?? false; - if (dollarHook && (lastRunspaceInitializationException == null)) + if (dollarHook && (_lastRunspaceInitializationException == null)) { ExitCode = ExitCodeSuccess; } @@ -1458,8 +1478,8 @@ namespace Microsoft.PowerShell } } - runspaceRef.Runspace.Close(); - runspaceRef = null; + _runspaceRef.Runspace.Close(); + _runspaceRef = null; if (staMode) // don't recycle the Runspace in STA mode { ShouldEndSession = true; @@ -1474,7 +1494,7 @@ namespace Microsoft.PowerShell Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); Dbg.Assert(exec != null, "non-null Executor instance needed"); - runspaceInitTracer.WriteLine("running command {0}", command); + s_runspaceInitTracer.WriteLine("running command {0}", command); Exception e = null; @@ -1529,7 +1549,7 @@ namespace Microsoft.PowerShell // Note that PSReadline doesn't support redirected stdin/stdout, but we don't check that here because // a future version might, and we should automatically load it at that unknown point in the future. // PSReadline will ideally fall back to Console.ReadLine or whatever when stdin/stdout is redirected. - return ((cpp.InitialCommand == null && cpp.File == null) || cpp.NoExit) && !cpp.NonInteractive; + return ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit) && !s_cpp.NonInteractive; } /// @@ -1542,12 +1562,12 @@ namespace Microsoft.PowerShell //private void CreateRunspace(string initialCommand, bool skipProfiles, bool staMode, Collection initialCommandArgs) private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, bool importSystemModules, string configurationName, Collection initialCommandArgs) { - Dbg.Assert(runspaceRef == null, "runspace should be null"); + Dbg.Assert(_runspaceRef == null, "runspace should be null"); #if !DEBUG - Dbg.Assert(configuration != null, "configuration should be set"); + Dbg.Assert(_configuration != null, "configuration should be set"); #endif - runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace"); + s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace"); try { @@ -1598,11 +1618,11 @@ namespace Microsoft.PowerShell } else { - consoleRunspace = RunspaceFactory.CreateRunspace(this, this.configuration); + consoleRunspace = RunspaceFactory.CreateRunspace(this, _configuration); OpenConsoleRunspace(consoleRunspace, staMode); } - runspaceRef = new RunspaceRef(consoleRunspace); + _runspaceRef = new RunspaceRef(consoleRunspace); if (psReadlineFailed) { @@ -1648,17 +1668,17 @@ namespace Microsoft.PowerShell runspace.EngineActivityId = EtwActivity.GetActivityId(); - runspaceInitTracer.WriteLine("Calling Runspace.Open"); + s_runspaceInitTracer.WriteLine("Calling Runspace.Open"); runspace.Open(); } private void DoRunspaceInitialization(bool importSystemModules, bool skipProfiles, string initialCommand, string configurationName, Collection initialCommandArgs) { - if (runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger != null) { - runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); - runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended; + _runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); + _runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended; } Executor exec = new Executor(this, false, false); @@ -1668,7 +1688,7 @@ namespace Microsoft.PowerShell { Exception exception = InitializeRunspaceHelper("ImportSystemModules", exec, Executor.ExecutionOptions.None); } - + if (!string.IsNullOrEmpty(configurationName)) { // If an endpoint configuration is specified then create a loop-back remote runspace targeting @@ -1680,7 +1700,7 @@ namespace Microsoft.PowerShell PushRunspace(remoteRunspace); // Ensure that session ends when configured remote runspace is popped. - this.inPushedConfiguredSession = true; + _inPushedConfiguredSession = true; } catch (Exception e) { @@ -1691,24 +1711,24 @@ namespace Microsoft.PowerShell { // Run the built-in scripts RunspaceConfigurationEntryCollection scripts = new RunspaceConfigurationEntryCollection(); - if (configuration != null) - scripts = configuration.InitializationScripts; + if (_configuration != null) + scripts = _configuration.InitializationScripts; if ((scripts == null) || (scripts.Count == 0)) { - runspaceInitTracer.WriteLine("There are no built-in scripts to run"); + s_runspaceInitTracer.WriteLine("There are no built-in scripts to run"); } else { foreach (ScriptConfigurationEntry s in scripts) { - runspaceInitTracer.WriteLine("Running script: '{0}'", s.Name); + s_runspaceInitTracer.WriteLine("Running script: '{0}'", s.Name); // spec claims that Ctrl-C is not supposed to stop these. try { - isCtrlCDisabled = true; + _isCtrlCDisabled = true; Exception e = InitializeRunspaceHelper(s.Definition, exec, Executor.ExecutionOptions.AddOutputter); if (e != null) { @@ -1717,7 +1737,7 @@ namespace Microsoft.PowerShell } finally { - isCtrlCDisabled = false; + _isCtrlCDisabled = false; } } } @@ -1725,8 +1745,8 @@ namespace Microsoft.PowerShell // If -iss has been specified, then there won't be a runspace // configuration to get the shell ID from, so we'll use the default... string shellId = null; - if (configuration != null) - shellId = configuration.ShellId; + if (_configuration != null) + shellId = _configuration.ShellId; else shellId = "Microsoft.PowerShell"; // TODO: what will happen for custom shells built using Make-Shell.exe @@ -1734,7 +1754,7 @@ namespace Microsoft.PowerShell // are loaded so that they are trusted. (Validation of their signatures is done in F&O) if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { - runspaceRef.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; + _runspaceRef.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } string allUsersProfile = HostUtilities.GetFullProfileFileName(null, false); @@ -1745,7 +1765,7 @@ namespace Microsoft.PowerShell // $PROFILE has to be set from the host // Should be "per-user,host-specific profile.ps1" // This should be set even if -noprofile is specified - runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE", + _runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE", HostUtilities.GetDollarProfile( allUsersProfile, allUsersHostSpecificProfile, @@ -1770,7 +1790,7 @@ namespace Microsoft.PowerShell sw.Stop(); var profileLoadTimeInMs = sw.ElapsedMilliseconds; - if (profileLoadTimeInMs > 500 && cpp.ShowBanner) + if (profileLoadTimeInMs > 500 && s_cpp.ShowBanner) { Console.Error.WriteLine(ConsoleHostStrings.SlowProfileLoadingMessage, profileLoadTimeInMs); } @@ -1779,7 +1799,7 @@ namespace Microsoft.PowerShell } else { - tracer.WriteLine("-noprofile option specified: skipping profiles"); + s_tracer.WriteLine("-noprofile option specified: skipping profiles"); } } @@ -1788,11 +1808,11 @@ namespace Microsoft.PowerShell TelemetryAPI.ReportStartupTelemetry(this); // If a file was specified as the argument to run, then run it... - if (cpp != null && cpp.File != null) + if (s_cpp != null && s_cpp.File != null) { - string filePath = cpp.File; + string filePath = s_cpp.File; - tracer.WriteLine("running -file '{0}'", filePath); + s_tracer.WriteLine("running -file '{0}'", filePath); Pipeline tempPipeline = exec.CreatePipeline(); Command c = new Command(filePath, false, false); @@ -1810,7 +1830,7 @@ namespace Microsoft.PowerShell // If we're not going to continue, then get the exit code out of the runspace and // and indicate that it should be returned... - if (!noExit && !(this.Runspace is RemoteRunspace)) + if (!_noExit && !(this.Runspace is RemoteRunspace)) { this.Runspace.ExecutionContext.ScriptCommandProcessorShouldRethrowExit = true; } @@ -1845,13 +1865,13 @@ namespace Microsoft.PowerShell // execute properly. These exceptions should be reflected in the exit code if (e1 != null) { - if (!noExit) + if (!_noExit) { // Set ExitCode to 0x1 lock (hostGlobalLock) { - setShouldExitCalled = true; - exitCodeFromRunspace = 0x1; + _setShouldExitCalled = true; + _exitCodeFromRunspace = 0x1; ShouldEndSession = true; } } @@ -1863,7 +1883,7 @@ namespace Microsoft.PowerShell { // Run the command passed on the command line - tracer.WriteLine("running initial command"); + s_tracer.WriteLine("running initial command"); Pipeline tempPipeline = exec.CreatePipeline(initialCommand, true); @@ -1881,7 +1901,7 @@ namespace Microsoft.PowerShell if (IsRunningAsync) { - Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter; + Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter; Token[] tokens; ParseError[] errors; @@ -1906,7 +1926,7 @@ namespace Microsoft.PowerShell if (e1 != null) { // Remember last exception - lastRunspaceInitializationException = e1; + _lastRunspaceInitializationException = e1; ReportException(e1, exec); } } @@ -1916,7 +1936,7 @@ namespace Microsoft.PowerShell { if (!String.IsNullOrEmpty(profileFileName)) { - runspaceInitTracer.WriteLine("checking profile" + profileFileName); + s_runspaceInitTracer.WriteLine("checking profile" + profileFileName); try { @@ -1929,7 +1949,7 @@ namespace Microsoft.PowerShell } else { - runspaceInitTracer.WriteLine("profile file not found"); + s_runspaceInitTracer.WriteLine("profile file not found"); } } catch (Exception e) // Catch-all OK, 3rd party callout @@ -1937,7 +1957,7 @@ namespace Microsoft.PowerShell CommandProcessorBase.CheckForSevereException(e); ReportException(e, exec); - runspaceInitTracer.WriteLine("Could not load profile."); + s_runspaceInitTracer.WriteLine("Could not load profile."); } } } @@ -2095,9 +2115,9 @@ namespace Microsoft.PowerShell internal event EventHandler RunspacePushed; -#endregion non-overrides + #endregion non-overrides -#region debugger + #region debugger /// /// Handler for debugger events @@ -2108,7 +2128,7 @@ namespace Microsoft.PowerShell LocalRunspace localrunspace = LocalRunspace; if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) { return; } - this.debuggerStopEventArgs = e; + _debuggerStopEventArgs = e; InputLoop baseLoop = null; try @@ -2127,11 +2147,11 @@ namespace Microsoft.PowerShell // // Display the banner only once per session // - if (this.displayDebuggerBanner) + if (_displayDebuggerBanner) { WriteDebuggerMessage(ConsoleHostStrings.EnteringDebugger); WriteDebuggerMessage(""); - this.displayDebuggerBanner = false; + _displayDebuggerBanner = false; } // @@ -2165,7 +2185,7 @@ namespace Microsoft.PowerShell } finally { - this.debuggerStopEventArgs = null; + _debuggerStopEventArgs = null; if (baseLoop != null) { baseLoop.ResumeCommandOutput(); @@ -2180,7 +2200,7 @@ namespace Microsoft.PowerShell { get { - return this.inDebugMode; + return _inDebugMode; } } @@ -2194,7 +2214,7 @@ namespace Microsoft.PowerShell set; } - private Exception lastRunspaceInitializationException = null; + private Exception _lastRunspaceInitializationException = null; internal uint ExitCode; /// @@ -2202,7 +2222,7 @@ namespace Microsoft.PowerShell /// private void EnterDebugMode() { - this.inDebugMode = true; + _inDebugMode = true; try { @@ -2211,7 +2231,7 @@ namespace Microsoft.PowerShell // // EnterNestedPrompt must always be run on the local runspace. - Runspace runspace = this.runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; + Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; runspace.ExecutionContext.EngineHostInterface.EnterNestedPrompt(); } catch (PSNotImplementedException) @@ -2220,7 +2240,7 @@ namespace Microsoft.PowerShell } finally { - this.inDebugMode = false; + _inDebugMode = false; } } @@ -2229,7 +2249,7 @@ namespace Microsoft.PowerShell /// private void ExitDebugMode(DebuggerResumeAction resumeAction) { - this.debuggerStopEventArgs.ResumeAction = resumeAction; + _debuggerStopEventArgs.ResumeAction = resumeAction; try { @@ -2238,7 +2258,7 @@ namespace Microsoft.PowerShell // // ExitNestedPrompt must always be run on the local runspace. - Runspace runspace = this.runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; + Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace; runspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt(); } catch (ExitNestedPromptException) @@ -2255,9 +2275,9 @@ namespace Microsoft.PowerShell this.ui.WriteWrappedLine(this.ui.DebugForegroundColor, this.ui.DebugBackgroundColor, line); } -#endregion debugger + #endregion debugger -#region aux classes + #region aux classes /// /// @@ -2274,7 +2294,7 @@ namespace Microsoft.PowerShell { // creates an instance and adds it to the stack and starts it running. - int stackCount = instanceStack.Count; + int stackCount = s_instanceStack.Count; if (stackCount == PSHost.MaximumNestedPromptLevel) { @@ -2283,12 +2303,12 @@ namespace Microsoft.PowerShell InputLoop il = new InputLoop(parent, isNested); - instanceStack.Push(il); - il.Run(instanceStack.Count > 1); + s_instanceStack.Push(il); + il.Run(s_instanceStack.Count > 1); // Once the loop has finished running, remove it from the instance stack. - InputLoop il2 = instanceStack.Pop(); + InputLoop il2 = s_instanceStack.Pop(); Dbg.Assert(il == il2, "top of instance stack does not correspond to the instance pushed"); } @@ -2307,18 +2327,18 @@ namespace Microsoft.PowerShell internal static bool ExitCurrentLoop() { - if (instanceStack.Count == 0) + if (s_instanceStack.Count == 0) { throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.InputExitCurrentLoopOutOfSyncError); } - InputLoop il = instanceStack.Peek(); - il.shouldExit = true; + InputLoop il = s_instanceStack.Peek(); + il._shouldExit = true; // The main (non-nested) input loop has Count == 1, // so Count == 2 is the value that indicates the next // popped stack input loop is non-nested. - return (instanceStack.Count > 2); + return (s_instanceStack.Count > 2); } /// @@ -2330,9 +2350,9 @@ namespace Microsoft.PowerShell /// internal static InputLoop GetNonNestedLoop() { - if (instanceStack.Count == 1) + if (s_instanceStack.Count == 1) { - return instanceStack.Peek(); + return s_instanceStack.Peek(); } return null; @@ -2340,21 +2360,21 @@ namespace Microsoft.PowerShell private InputLoop(ConsoleHost parent, bool isNested) { - this.parent = parent; - this.isNested = isNested; - isRunspacePushed = parent.IsRunspacePushed; + _parent = parent; + _isNested = isNested; + _isRunspacePushed = parent.IsRunspacePushed; parent.RunspacePopped += new EventHandler(HandleRunspacePopped); parent.RunspacePushed += new EventHandler(HandleRunspacePushed); - exec = new Executor(parent, isNested, false); - promptExec = new Executor(parent, isNested, true); + _exec = new Executor(parent, isNested, false); + _promptExec = new Executor(parent, isNested, true); } private void HandleRunspacePushed(object sender, EventArgs e) { - lock (syncObject) + lock (_syncObject) { - isRunspacePushed = true; - runspacePopped = false; + _isRunspacePushed = true; + _runspacePopped = false; } } @@ -2366,10 +2386,10 @@ namespace Microsoft.PowerShell /// arguments describing this event, unused private void HandleRunspacePopped(object sender, EventArgs eventArgs) { - lock (syncObject) + lock (_syncObject) { - isRunspacePushed = false; - runspacePopped = true; + _isRunspacePushed = false; + _runspacePopped = true; } } @@ -2383,7 +2403,7 @@ namespace Microsoft.PowerShell /// internal void Run(bool inputLoopIsNested) { - System.Management.Automation.Host.PSHostUserInterface c = parent.UI; + System.Management.Automation.Host.PSHostUserInterface c = _parent.UI; ConsoleHostUserInterface ui = c as ConsoleHostUserInterface; Dbg.Assert(ui != null, "Host.UI should return an instance."); @@ -2392,11 +2412,11 @@ namespace Microsoft.PowerShell bool previousResponseWasEmpty = false; StringBuilder inputBlock = new StringBuilder(); - while (!parent.ShouldEndSession && !shouldExit) + while (!_parent.ShouldEndSession && !_shouldExit) { try { - parent.isRunningPromptLoop = true; + _parent._isRunningPromptLoop = true; string prompt = null; string line = null; @@ -2417,13 +2437,13 @@ namespace Microsoft.PowerShell ui.WriteLine(); // Evaluate any suggestions - if(! previousResponseWasEmpty) + if (!previousResponseWasEmpty) { EvaluateSuggestions(ui); } // Then output the prompt - if (this.parent.InDebugMode) + if (_parent.InDebugMode) { prompt = EvaluateDebugPrompt(); } @@ -2436,7 +2456,7 @@ namespace Microsoft.PowerShell } previousResponseWasEmpty = false; // There could be a profile. So there could be a user defined custom readline command - line = ui.ReadLineWithTabCompletion(exec); + line = ui.ReadLineWithTabCompletion(_exec); // line will be null in the case that Ctrl-C terminated the input @@ -2444,7 +2464,7 @@ namespace Microsoft.PowerShell { previousResponseWasEmpty = true; - tracer.WriteLine("line is null"); + s_tracer.WriteLine("line is null"); if (!ui.ReadFromStdin) { // If we're not reading from stdin, the we probably got here @@ -2457,7 +2477,7 @@ namespace Microsoft.PowerShell if (Console.IsInputRedirected) { // null is also the result of reading stdin to EOF. - parent.ShouldEndSession = true; + _parent.ShouldEndSession = true; break; } @@ -2470,11 +2490,11 @@ namespace Microsoft.PowerShell { // end block mode and execute the block accumulated block - tracer.WriteLine("exiting block mode"); + s_tracer.WriteLine("exiting block mode"); line = inputBlock.ToString(); inBlockMode = false; } - else if (!this.parent.InDebugMode) + else if (!_parent.InDebugMode) { previousResponseWasEmpty = true; continue; @@ -2484,7 +2504,7 @@ namespace Microsoft.PowerShell { if (inBlockMode) { - tracer.WriteLine("adding line to block"); + s_tracer.WriteLine("adding line to block"); inputBlock.Append("\n"); inputBlock.Append(line); continue; @@ -2492,18 +2512,18 @@ namespace Microsoft.PowerShell } Dbg.Assert(line != null, "line should not be null"); - Dbg.Assert(line.Length > 0 || this.parent.InDebugMode, "line should not be empty unless the host is in debug mode"); + Dbg.Assert(line.Length > 0 || _parent.InDebugMode, "line should not be empty unless the host is in debug mode"); Dbg.Assert(!inBlockMode, "should not be in block mode at point of pipeline execution"); Exception e = null; - if (this.parent.InDebugMode) + if (_parent.InDebugMode) { DebuggerCommandResults results = ProcessDebugCommand(line.Trim(), out e); if (results.ResumeAction != null) { - this.parent.ExitDebugMode(results.ResumeAction.Value); + _parent.ExitDebugMode(results.ResumeAction.Value); } if (e != null) @@ -2516,7 +2536,7 @@ namespace Microsoft.PowerShell ex.ErrorRecord.FullyQualifiedErrorId.Equals("Debugger:CannotProcessCommandNotStopped", StringComparison.OrdinalIgnoreCase))) { // Debugger session is broken. Exit nested loop. - this.parent.ExitDebugMode(DebuggerResumeAction.Continue); + _parent.ExitDebugMode(DebuggerResumeAction.Continue); } else { @@ -2528,28 +2548,28 @@ namespace Microsoft.PowerShell continue; } - if (runspacePopped) + if (_runspacePopped) { string msg = StringUtil.Format(ConsoleHostStrings.CommandNotExecuted, line); ui.WriteErrorLine(msg); - runspacePopped = false; + _runspacePopped = false; } else { - if (parent.IsRunningAsync && !parent.IsNested) + if (_parent.IsRunningAsync && !_parent.IsNested) { - exec.ExecuteCommandAsync(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); + _exec.ExecuteCommandAsync(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); } else { - exec.ExecuteCommand(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); + _exec.ExecuteCommand(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory); } Thread bht = null; - lock (parent.hostGlobalLock) + lock (_parent.hostGlobalLock) { - bht = parent.breakHandlerThread; + bht = _parent._breakHandlerThread; } if (bht != null) @@ -2569,30 +2589,30 @@ namespace Microsoft.PowerShell // If a remote runspace is pushed and it is not in a good state // then pop it. - if (isRunspacePushed && (parent.Runspace != null) && - ((parent.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) || - (parent.Runspace.RunspaceAvailability != RunspaceAvailability.Available))) + if (_isRunspacePushed && (_parent.Runspace != null) && + ((_parent.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) || + (_parent.Runspace.RunspaceAvailability != RunspaceAvailability.Available))) { - parent.PopRunspace(); + _parent.PopRunspace(); } } if (!inBlockMode) - theConsoleHost._interactiveCommandCount += 1; + s_theConsoleHost._interactiveCommandCount += 1; } } // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure finally { - parent.isRunningPromptLoop = false; + _parent._isRunningPromptLoop = false; } } // end while } internal void BlockCommandOutput() { - RemotePipeline rCmdPipeline = parent.runningCmd as RemotePipeline; + RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; if (rCmdPipeline != null) { rCmdPipeline.DrainIncomingData(); @@ -2600,21 +2620,21 @@ namespace Microsoft.PowerShell } else { - exec.BlockCommandOutput(); + _exec.BlockCommandOutput(); } } internal void ResumeCommandOutput() { - RemotePipeline rCmdPipeline = parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) - { - rCmdPipeline.ResumeIncomingData(); - } - else - { - exec.ResumeCommandOutput(); - } + RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; + if (rCmdPipeline != null) + { + rCmdPipeline.ResumeIncomingData(); + } + else + { + _exec.ResumeCommandOutput(); + } } private bool HandleErrors(Exception e, string line, bool inBlockMode, ref StringBuilder inputBlock) @@ -2636,7 +2656,7 @@ namespace Microsoft.PowerShell else { // an exception ocurred when the command was executed. Tell the user about it. - parent.ReportException(e, exec); + _parent.ReportException(e, _exec); } return inBlockMode; @@ -2648,14 +2668,14 @@ namespace Microsoft.PowerShell try { - parent.DebuggerCanStopCommand = true; + _parent.DebuggerCanStopCommand = true; // Use PowerShell object to write streaming data to host. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { - Host = this.parent + Host = _parent }; PSDataCollection output = new PSDataCollection(); @@ -2663,7 +2683,7 @@ namespace Microsoft.PowerShell IAsyncResult async = ps.BeginInvoke(output, settings, null, null); // Let debugger evaluate command and stream output data. - results = this.parent.Runspace.Debugger.ProcessCommand( + results = _parent.Runspace.Debugger.ProcessCommand( new PSCommand( new Command(cmd, true)), output); @@ -2682,7 +2702,7 @@ namespace Microsoft.PowerShell } finally { - parent.DebuggerCanStopCommand = false; + _parent.DebuggerCanStopCommand = false; } // Exit debugger if command fails to evaluate. @@ -2712,7 +2732,7 @@ namespace Microsoft.PowerShell // Output any training suggestions try { - ArrayList suggestions = HostUtilities.GetSuggestion(this.parent.Runspace); + ArrayList suggestions = HostUtilities.GetSuggestion(_parent.Runspace); if (suggestions.Count > 0) { @@ -2722,7 +2742,7 @@ namespace Microsoft.PowerShell bool first = true; foreach (string suggestion in suggestions) { - if(! first) + if (!first) ui.WriteLine(); ui.WriteLine(suggestion); @@ -2742,7 +2762,7 @@ namespace Microsoft.PowerShell ui.WriteErrorLine(e.Message); - LocalRunspace localRunspace = (LocalRunspace)this.parent.Runspace; + LocalRunspace localRunspace = (LocalRunspace)_parent.Runspace; localRunspace.GetExecutionContext.AppendDollarError(e); } } @@ -2750,7 +2770,7 @@ namespace Microsoft.PowerShell private string EvaluatePrompt() { Exception unused = null; - string promptString = promptExec.ExecuteCommandAndGetResultAsString("prompt", out unused); + string promptString = _promptExec.ExecuteCommandAndGetResultAsString("prompt", out unused); if (String.IsNullOrEmpty(promptString)) { @@ -2758,19 +2778,19 @@ namespace Microsoft.PowerShell } // Check for the pushed runspace scenario. - if (isRunspacePushed) + if (_isRunspacePushed) { - RemoteRunspace remoteRunspace = this.parent.Runspace as RemoteRunspace; + RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; if (remoteRunspace != null) { - promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, parent.inPushedConfiguredSession); + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } } else { - if (runspacePopped) + if (_runspacePopped) { - runspacePopped = false; + _runspacePopped = false; } } @@ -2784,47 +2804,47 @@ namespace Microsoft.PowerShell try { - this.parent.Runspace.Debugger.ProcessCommand( + _parent.Runspace.Debugger.ProcessCommand( new PSCommand(new Command("prompt")), output); } catch (Exception ex) { ConsoleHost.CheckForSevereException(ex); - this.parent.ReportException(ex, exec); + _parent.ReportException(ex, _exec); } PSObject prompt = output.ReadAndRemoveAt0(); string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; if (promptString != null) { - RemoteRunspace remoteRunspace = this.parent.Runspace as RemoteRunspace; + RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; if (remoteRunspace != null) { - promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, parent.inPushedConfiguredSession); + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } } return promptString; } - private ConsoleHost parent; - private bool isNested; - private bool shouldExit; - private Executor exec; - private Executor promptExec; - private object syncObject = new object(); - private bool isRunspacePushed = false; - private bool runspacePopped = false; + private ConsoleHost _parent; + private bool _isNested; + private bool _shouldExit; + private Executor _exec; + private Executor _promptExec; + private object _syncObject = new object(); + private bool _isRunspacePushed = false; + private bool _runspacePopped = false; // The instance stack is used to keep track of which InputLoop instance should be told to exit // when PSHost.ExitNestedPrompt is called. // threadsafety guaranteed by enclosing class - private static Stack instanceStack = new Stack(); + private static Stack s_instanceStack = new Stack(); } - + [Serializable] [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "This exception cannot be used outside of the console host application. It is not thrown by a library routine, only by an application.")] @@ -2861,35 +2881,35 @@ namespace Microsoft.PowerShell } } -#endregion aux classes + #endregion aux classes - /// - /// By declaring runspace as ObjectRef<Runspace> we are able to hide the real runspace with - /// a remote runspace in the PushRunspace scenario. By declaring it as a mask, the variable - /// runspace becomes an indirect reference to the actual runspace which we can override with - /// a remote runspace while it is pushed. Also we can easily revert back to the original - /// runspace when the PopRunspace command is invoked. - /// - private RunspaceRef runspaceRef; + /// + /// By declaring runspace as ObjectRef<Runspace> we are able to hide the real runspace with + /// a remote runspace in the PushRunspace scenario. By declaring it as a mask, the variable + /// runspace becomes an indirect reference to the actual runspace which we can override with + /// a remote runspace while it is pushed. Also we can easily revert back to the original + /// runspace when the PopRunspace command is invoked. + /// + private RunspaceRef _runspaceRef; #if !UNIX private GCHandle breakHandlerGcHandle; #endif - private System.Threading.Thread breakHandlerThread; - private bool isDisposed; + private System.Threading.Thread _breakHandlerThread; + private bool _isDisposed; internal ConsoleHostUserInterface ui; - private string savedWindowTitle = ""; - private Guid id = Guid.NewGuid(); - private Version ver = PSVersionInfo.PSVersion; - private int exitCodeFromRunspace; - private bool noExit = true; - private bool isCtrlCDisabled; - private bool setShouldExitCalled; - private Serialization.DataFormat outputFormat; - private Serialization.DataFormat inputFormat; - private bool isRunningPromptLoop; - private bool wasInitialCommandEncoded; - private RunspaceConfiguration configuration; + private string _savedWindowTitle = ""; + private Guid _id = Guid.NewGuid(); + private Version _ver = PSVersionInfo.PSVersion; + private int _exitCodeFromRunspace; + private bool _noExit = true; + private bool _isCtrlCDisabled; + private bool _setShouldExitCalled; + private Serialization.DataFormat _outputFormat; + private Serialization.DataFormat _inputFormat; + private bool _isRunningPromptLoop; + private bool _wasInitialCommandEncoded; + private RunspaceConfiguration _configuration; // hostGlobalLock is used to sync public method calls (in case multiple threads call into the host) and access to // state that persists across method calls, like progress data. It's internal because the ui object also @@ -2900,23 +2920,23 @@ namespace Microsoft.PowerShell // These members are possibly accessed from multiple threads (the break handler thread, a pipeline thread, or the main // thread). We use hostGlobalLock to sync access to them. - private bool shouldEndSession; - private int beginApplicationNotifyCount; + private bool _shouldEndSession; + private int _beginApplicationNotifyCount; - private ConsoleTextWriter consoleWriter; - private WrappedSerializer outputSerializer; - private WrappedSerializer errorSerializer; - private bool inDebugMode; - private bool displayDebuggerBanner; - private DebuggerStopEventArgs debuggerStopEventArgs; - private bool isNested; - private bool inPushedConfiguredSession; + private ConsoleTextWriter _consoleWriter; + private WrappedSerializer _outputSerializer; + private WrappedSerializer _errorSerializer; + private bool _inDebugMode; + private bool _displayDebuggerBanner; + private DebuggerStopEventArgs _debuggerStopEventArgs; + private bool _isNested; + private bool _inPushedConfiguredSession; internal Pipeline runningCmd; // The ConsoleHost class is a singleton. Note that there is not a thread-safety issue with these statics as there can // only be one console host per process. - private static ConsoleHost theConsoleHost; + private static ConsoleHost s_theConsoleHost; internal static InitialSessionState DefaultInitialSessionState; @@ -2925,10 +2945,10 @@ namespace Microsoft.PowerShell [TraceSource("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost")] private static - PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost"); + PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost"); [TraceSource("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace")] - private static PSTraceSource runspaceInitTracer = + private static PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace", false); } // ConsoleHost @@ -2937,7 +2957,6 @@ namespace Microsoft.PowerShell /// internal sealed class RunspaceCreationEventArgs : EventArgs { - /// /// Constructs RunspaceCreationEventArgs /// @@ -2969,7 +2988,6 @@ namespace Microsoft.PowerShell internal string ConfigurationName { get; set; } internal Collection InitialCommandArgs { get; set; } } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index b5d4f585f..c6cf93950 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -44,7 +44,7 @@ namespace Microsoft.PowerShell /// /// - internal + internal ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() { defaultForeground = ForegroundColor; @@ -121,11 +121,11 @@ namespace Microsoft.PowerShell ConsoleHandle handle = GetBufferInfo(out bufferInfo); // mask in the foreground from the current color. - short a = (short) bufferInfo.Attributes; + short a = (short)bufferInfo.Attributes; - a &= (short) ~0x0f; - a = (short) ((ushort) a | (ushort) value); - ConsoleControl.SetConsoleTextAttribute(handle, (WORD) a); + a &= (short)~0x0f; + a = (short)((ushort)a | (ushort)value); + ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a); } else { @@ -179,11 +179,11 @@ namespace Microsoft.PowerShell ConsoleHandle handle = GetBufferInfo(out bufferInfo); // mask in the background from the current color. - short a = (short) bufferInfo.Attributes; + short a = (short)bufferInfo.Attributes; - a &= (short) ~0xf0; - a = (short) ((ushort) a | (ushort) ((uint) value << 4)); - ConsoleControl.SetConsoleTextAttribute(handle, (WORD) a); + a &= (short)~0xf0; + a = (short)((ushort)a | (ushort)((uint)value << 4)); + ConsoleControl.SetConsoleTextAttribute(handle, (WORD)a); } else { @@ -237,8 +237,8 @@ namespace Microsoft.PowerShell } } - - + + /// /// /// See base class @@ -280,7 +280,7 @@ namespace Microsoft.PowerShell const int MinCursorSize = 0; const int MaxCursorSize = 100; - if (value >= MinCursorSize && value <= MaxCursorSize ) + if (value >= MinCursorSize && value <= MaxCursorSize) { ConsoleHandle consoleHandle = ConsoleControl.GetActiveScreenBufferHandle(); ConsoleControl.CONSOLE_CURSOR_INFO cursorInfo = @@ -292,7 +292,7 @@ namespace Microsoft.PowerShell } else { - cursorInfo.Size = (uint) value; + cursorInfo.Size = (uint)value; cursorInfo.Visible = true; } @@ -365,13 +365,13 @@ namespace Microsoft.PowerShell ConsoleHostRawUserInterfaceStrings.InvalidYWindowPositionError); } - r.Left = (short) value.X; - r.Top = (short) value.Y; + r.Left = (short)value.X; + r.Top = (short)value.Y; // subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in // span" but "starting and ending position" - r.Right = (short) (r.Left + windowWidth - 1); - r.Bottom = (short) (r.Top + windowHeight - 1); + r.Right = (short)(r.Left + windowWidth - 1); + r.Bottom = (short)(r.Top + windowHeight - 1); Dbg.Assert(r.Right >= r.Left, "Window size is too narrow"); Dbg.Assert(r.Bottom >= r.Top, "Window size is too short"); ConsoleControl.SetConsoleWindowInfo(handle, true, r); @@ -430,7 +430,6 @@ namespace Microsoft.PowerShell { throw PSTraceSource.NewArgumentOutOfRangeException("value", value, ConsoleHostRawUserInterfaceStrings.InvalidBufferSizeError); - } else { @@ -440,8 +439,8 @@ namespace Microsoft.PowerShell } } - - + + /// /// /// See base class @@ -487,7 +486,7 @@ namespace Microsoft.PowerShell // the dimensions of the window can't extend past the dimensions of the screen buffer. This means that the // width of the window is limited to the buffer width minus one minus the window X position, and the height // of the window is limited to the buffer height minus one minus the window Y position. - + if (value.Width < 1) { throw PSTraceSource.NewArgumentOutOfRangeException("value.Width", value.Width, @@ -528,14 +527,14 @@ namespace Microsoft.PowerShell // if the new size will extend past the edge of screen buffer, then move the window position to try to // accomodate that. - + ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect; // subtract 1 from each dimension because the semantics of the win32 api are not "number of characters in // span" but "starting and ending position" - - r.Right = (short) (r.Left + value.Width - 1); - r.Bottom = (short) (r.Top + value.Height - 1); + + r.Right = (short)(r.Left + value.Width - 1); + r.Bottom = (short)(r.Top + value.Height - 1); // Now we check if the bottom right coordinate of our window went over the coordinate of the bottom // right of the buffer. If it did then we need to adjust the window. @@ -543,8 +542,8 @@ namespace Microsoft.PowerShell // bufferInfo.BufferSize.X - 1 will give us the rightmost coordinate of the buffer. // r.Right - rightCoordinateOfBuffer will give us how much we need to adjust the window left and right coordinates. // Then we can do the same for top and bottom. - short adjustLeft = (short) (r.Right - (bufferInfo.BufferSize.X - 1)); - short adjustTop = (short) (r.Bottom - (bufferInfo.BufferSize.Y - 1)); + short adjustLeft = (short)(r.Right - (bufferInfo.BufferSize.X - 1)); + short adjustTop = (short)(r.Bottom - (bufferInfo.BufferSize.Y - 1)); if (adjustLeft > 0) { @@ -742,7 +741,7 @@ namespace Microsoft.PowerShell actualNumberOfInput)); if (actualNumberOfInput == 1) { - if (((ConsoleControl.InputRecordEventTypes) inputRecords[0].EventType) == + if (((ConsoleControl.InputRecordEventTypes)inputRecords[0].EventType) == ConsoleControl.InputRecordEventTypes.KEY_EVENT) { Dbg.Assert((inputRecords[0].KeyEvent.KeyDown && inputRecords[0].KeyEvent.RepeatCount != 0) || @@ -785,10 +784,9 @@ namespace Microsoft.PowerShell if ((options & ReadKeyOptions.NoEcho) == 0) { - parent.WriteToConsole( - keyInfo.Character.ToString(), - true); - + parent.WriteToConsole( + keyInfo.Character.ToString(), + true); } return keyInfo; @@ -869,7 +867,7 @@ namespace Microsoft.PowerShell for (int i = 0; i < acutalNumberOfInputRecords; i++) { - if (((ConsoleControl.InputRecordEventTypes) inputRecords[i].EventType) == + if (((ConsoleControl.InputRecordEventTypes)inputRecords[i].EventType) == ConsoleControl.InputRecordEventTypes.KEY_EVENT) { Dbg.Assert((inputRecords[i].KeyEvent.KeyDown && inputRecords[i].KeyEvent.RepeatCount != 0) || @@ -1054,7 +1052,7 @@ namespace Microsoft.PowerShell /// there is not enough memory to complete calls to Win32's WriteConsoleOutput /// /// - public override + public override void SetBufferContents(Rectangle region, BufferCell fill) { @@ -1192,8 +1190,8 @@ namespace Microsoft.PowerShell } } - - + + /// /// /// See base class. @@ -1278,8 +1276,8 @@ namespace Microsoft.PowerShell return contents; } - - + + /// /// /// See base class @@ -1323,20 +1321,20 @@ namespace Microsoft.PowerShell ) { ConsoleControl.SMALL_RECT scrollRectangle; - scrollRectangle.Left = (short) source.Left; - scrollRectangle.Right = (short) source.Right; - scrollRectangle.Top = (short) source.Top; - scrollRectangle.Bottom = (short) source.Bottom; + scrollRectangle.Left = (short)source.Left; + scrollRectangle.Right = (short)source.Right; + scrollRectangle.Top = (short)source.Top; + scrollRectangle.Bottom = (short)source.Bottom; ConsoleControl.SMALL_RECT clipRectangle; - clipRectangle.Left = (short) clip.Left; - clipRectangle.Right = (short) clip.Right; - clipRectangle.Top = (short) clip.Top; - clipRectangle.Bottom = (short) clip.Bottom; + clipRectangle.Left = (short)clip.Left; + clipRectangle.Right = (short)clip.Right; + clipRectangle.Top = (short)clip.Top; + clipRectangle.Bottom = (short)clip.Bottom; ConsoleControl.COORD origin; - origin.X = (short) destination.X; - origin.Y = (short) destination.Y; + origin.X = (short)destination.X; + origin.Y = (short)destination.Y; ConsoleControl.CHAR_INFO fillChar; @@ -1413,7 +1411,7 @@ namespace Microsoft.PowerShell return ConsoleControl.LengthInBufferCells(c); } - #region internal +#region internal /// /// @@ -1426,12 +1424,12 @@ namespace Microsoft.PowerShell cachedKeyEvent.RepeatCount = 0; } - #endregion internal +#endregion internal - #region helpers +#region helpers -// pass-by-ref for speed. + // pass-by-ref for speed. /// /// /// @@ -1462,7 +1460,7 @@ namespace Microsoft.PowerShell } } - + /// /// Get output buffer info /// @@ -1522,17 +1520,17 @@ namespace Microsoft.PowerShell internal sealed class ConsoleHostRawUserInterface : PSHostRawUserInterface { - private ConsoleColor defaultForeground = ConsoleColor.Gray; + private ConsoleColor _defaultForeground = ConsoleColor.Gray; - private ConsoleColor defaultBackground = ConsoleColor.Black; + private ConsoleColor _defaultBackground = ConsoleColor.Black; - private ConsoleHostUserInterface parent = null; + private ConsoleHostUserInterface _parent = null; internal ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() { - defaultForeground = ForegroundColor; - defaultBackground = BackgroundColor; - parent = mshConsole; + _defaultForeground = ForegroundColor; + _defaultBackground = BackgroundColor; + _parent = mshConsole; } /// @@ -1546,14 +1544,14 @@ namespace Microsoft.PowerShell // Console can return UnknownColor, a private enum, equivalent // to -1. When this is a case, map it instead to our default. return Console.BackgroundColor == (ConsoleColor)(-1) - ? defaultBackground + ? _defaultBackground : Console.BackgroundColor; } set { Console.BackgroundColor = value; } } // TODO: Make wrap width user-customizable. - private static Size WrapSize = new Size(80, 40); + private static Size s_wrapSize = new Size(80, 40); /// /// Gets or sets the size of the host buffer. @@ -1565,7 +1563,7 @@ namespace Microsoft.PowerShell // Console can return zero when a pseduo-TTY is allocated, which // is useless for us. Instead, map to the wrap size. return Console.BufferWidth == 0 || Console.BufferHeight == 0 - ? WrapSize + ? s_wrapSize : new Size(Console.BufferWidth, Console.BufferHeight); } set { Console.SetBufferSize(value.Width, value.Height); } @@ -1577,8 +1575,11 @@ namespace Microsoft.PowerShell public override Coordinates CursorPosition { get { return new Coordinates(Console.CursorLeft, Console.CursorTop); } - set { Console.SetCursorPosition(value.X < 0 ? 0 : value.X, - value.Y < 0 ? 0 : value.Y); } + set + { + Console.SetCursorPosition(value.X < 0 ? 0 : value.X, + value.Y < 0 ? 0 : value.Y); + } } /// @@ -1604,7 +1605,7 @@ namespace Microsoft.PowerShell // Console can return UnknownColor, a private enum, equivalent // to -1. When this is a case, map it instead to our default. return Console.ForegroundColor == (ConsoleColor)(-1) - ? defaultForeground + ? _defaultForeground : Console.ForegroundColor; } set { Console.ForegroundColor = value; } @@ -1642,7 +1643,7 @@ namespace Microsoft.PowerShell // Console can return zero when a pseduo-TTY is allocated, which // is useless for us. Instead, map to the wrap size. return Console.LargestWindowWidth == 0 || Console.LargestWindowHeight == 0 - ? WrapSize + ? s_wrapSize : new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); } } @@ -1670,7 +1671,7 @@ namespace Microsoft.PowerShell // Console can return zero when a pseduo-TTY is allocated, which // is useless for us. Instead, map to the wrap size. return Console.WindowWidth == 0 || Console.WindowHeight == 0 - ? WrapSize + ? s_wrapSize : new Size(Console.WindowWidth, Console.WindowHeight); } set { Console.SetWindowSize(value.Width, value.Height); } @@ -1679,7 +1680,7 @@ namespace Microsoft.PowerShell /// /// Cached Window Title, for systems that needs it /// - private string title = String.Empty; + private string _title = String.Empty; /// /// Gets or sets the title of the displayed window. The example @@ -1691,13 +1692,13 @@ namespace Microsoft.PowerShell { // Console throws an exception on Unix platforms, so we handle // caching and returning the Window title ourselves. - return Platform.IsWindows ? Console.Title : title; + return Platform.IsWindows ? Console.Title : _title; } set { Console.Title = value; - title = value; + _title = value; } } @@ -1712,9 +1713,9 @@ namespace Microsoft.PowerShell } } - public void ScrollBuffer(int lines) + public void ScrollBuffer(int lines) { - for (int i=0; i /// Command completion implementation object /// - private PowerShell commandCompletionPowerShell; + private PowerShell _commandCompletionPowerShell; /// /// This is a test hook for programmatically reading and writing ConsoleHost I/O. /// - private static PSHostUserInterface _h = null; + private static PSHostUserInterface s_h = null; /// /// Return true if the console supports a VT100 like virtual terminal @@ -58,11 +58,11 @@ namespace Microsoft.PowerShell { Dbg.Assert(parent != null, "parent may not be null"); - this.parent = parent; - this.rawui = new ConsoleHostRawUserInterface(this); + _parent = parent; + _rawui = new ConsoleHostRawUserInterface(this); #if UNIX - this._supportsVirtualTerminal = true; + _supportsVirtualTerminal = true; #else try { @@ -71,7 +71,7 @@ namespace Microsoft.PowerShell // This might throw - not sure how exactly (no console), but if it does, we shouldn't fail to start. var handle = ConsoleControl.GetActiveScreenBufferHandle(); var m = ConsoleControl.GetMode(handle); - if (ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint) (m | ConsoleControl.ConsoleModes.VirtualTerminal))) + if (ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint)(m | ConsoleControl.ConsoleModes.VirtualTerminal))) { // We only know if vt100 is supported if the previous call actually set the new flag, older // systems ignore the setting. @@ -84,7 +84,7 @@ namespace Microsoft.PowerShell } #endif - isInteractiveTestToolListening = false; + _isInteractiveTestToolListening = false; } /// @@ -99,11 +99,11 @@ namespace Microsoft.PowerShell { get { - Dbg.Assert(this.rawui != null, "rawui should have been created by ctor"); + Dbg.Assert(_rawui != null, "rawui should have been created by ctor"); // no locking because this is read-only, and allocated in the ctor. - return rawui; + return _rawui; } } @@ -140,8 +140,8 @@ namespace Microsoft.PowerShell { get { - return this.commandCompletionPowerShell != null && - this.commandCompletionPowerShell.InvocationStateInfo.State == PSInvocationState.Running; + return _commandCompletionPowerShell != null && + _commandCompletionPowerShell.InvocationStateInfo.State == PSInvocationState.Running; } } @@ -163,11 +163,11 @@ namespace Microsoft.PowerShell { get { - return noPrompt; + return _noPrompt; } set { - noPrompt = value; + _noPrompt = value; } } @@ -193,7 +193,7 @@ namespace Microsoft.PowerShell public override string ReadLine() { - HandleThrowOnReadAndPrompt(); + HandleThrowOnReadAndPrompt(); // call our internal version such that it does not end input on a tab ReadLineResult unused; @@ -233,7 +233,7 @@ namespace Microsoft.PowerShell // we lock here so that multiple threads won't interleave the various reads and writes here. object result = null; - lock (instanceLock) + lock (_instanceLock) { result = ReadLineSafe(true, printToken); } @@ -337,10 +337,10 @@ namespace Microsoft.PowerShell { isModeChanged = false; } - rawui.ClearKeyCache(); + _rawui.ClearKeyCache(); #endif - Coordinates originalCursorPos = rawui.CursorPosition; + Coordinates originalCursorPos = _rawui.CursorPosition; do { @@ -495,8 +495,8 @@ namespace Microsoft.PowerShell "Calling WritePrintToken with printToken being null or empty"); Dbg.Assert(printToken.Length == 1, "Calling WritePrintToken with printToken's Length being " + printToken.Length); - Size consoleBufferSize = rawui.BufferSize; - Coordinates currentCursorPosition = rawui.CursorPosition; + Size consoleBufferSize = _rawui.BufferSize; + Coordinates currentCursorPosition = _rawui.CursorPosition; // if the cursor is currently at the lower right corner, this write will cause the screen buffer to // scroll up. So, it is necessary to adjust the original cursor position one row up. @@ -533,7 +533,7 @@ namespace Microsoft.PowerShell private void WriteBackSpace(Coordinates originalCursorPosition) { - Coordinates cursorPosition = rawui.CursorPosition; + Coordinates cursorPosition = _rawui.CursorPosition; if (cursorPosition == originalCursorPosition) { // at originalCursorPosition, don't move @@ -547,7 +547,7 @@ namespace Microsoft.PowerShell return; } // BufferSize.Width is 1 larger than cursor position - cursorPosition.X = rawui.BufferSize.Width - 1; + cursorPosition.X = _rawui.BufferSize.Width - 1; cursorPosition.Y--; BlankAtCursor(cursorPosition); } @@ -567,9 +567,9 @@ namespace Microsoft.PowerShell /// Position to blank out private void BlankAtCursor(Coordinates cursorPosition) { - rawui.CursorPosition = cursorPosition; + _rawui.CursorPosition = cursorPosition; WriteToConsole(" ", true); - rawui.CursorPosition = cursorPosition; + _rawui.CursorPosition = cursorPosition; } @@ -610,7 +610,6 @@ namespace Microsoft.PowerShell internal void WriteToConsole(string value, bool transcribeResult) { - #if !UNIX ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle(); @@ -640,7 +639,7 @@ namespace Microsoft.PowerShell Console.Out.Write(value); #endif - if (isInteractiveTestToolListening && Console.IsOutputRedirected) + if (_isInteractiveTestToolListening && Console.IsOutputRedirected) { Console.Out.Write(value); } @@ -721,15 +720,15 @@ namespace Microsoft.PowerShell } // If the test hook is set, write to it and continue. - if (_h != null) _h.Write(value); + if (s_h != null) s_h.Write(value); - TextWriter writer = Console.IsOutputRedirected ? Console.Out : parent.ConsoleTextWriter; + TextWriter writer = Console.IsOutputRedirected ? Console.Out : _parent.ConsoleTextWriter; - if (parent.IsRunningAsync) + if (_parent.IsRunningAsync) { - Dbg.Assert(writer == parent.OutputSerializer.textWriter, "writers should be the same"); + Dbg.Assert(writer == _parent.OutputSerializer.textWriter, "writers should be the same"); - parent.OutputSerializer.Serialize(value); + _parent.OutputSerializer.Serialize(value); } else { @@ -767,7 +766,7 @@ namespace Microsoft.PowerShell { // Sync access so that we don't race on color settings if called from multiple threads. - lock (instanceLock) + lock (_instanceLock) { ConsoleColor fg = RawUI.ForegroundColor; ConsoleColor bg = RawUI.BackgroundColor; @@ -811,7 +810,7 @@ namespace Microsoft.PowerShell { // lock here so that the newline is written atomically with the value - lock (instanceLock) + lock (_instanceLock) { this.Write(value); this.Write(Crlf); @@ -1044,7 +1043,6 @@ namespace Microsoft.PowerShell inWs = false; continue; - } else if (text[wordEnd] == ' ') { @@ -1254,16 +1252,16 @@ namespace Microsoft.PowerShell message = HostUtilities.RemoveGuidFromMessage(message, out unused); //We should write debug to error stream only if debug is redirected.) - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { - parent.ErrorSerializer.Serialize(message, "debug"); + _parent.ErrorSerializer.Serialize(message, "debug"); } else { // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... WriteWrappedLine( - debugForegroundColor, - debugBackgroundColor, + _debugForegroundColor, + _debugBackgroundColor, StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message)); } } @@ -1277,9 +1275,9 @@ namespace Microsoft.PowerShell public override void WriteInformation(InformationRecord record) { //We should write information to error stream only if redirected.) - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { - parent.ErrorSerializer.Serialize(record, "information"); + _parent.ErrorSerializer.Serialize(record, "information"); } else { @@ -1316,15 +1314,15 @@ namespace Microsoft.PowerShell message = HostUtilities.RemoveGuidFromMessage(message, out unused); // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { - parent.ErrorSerializer.Serialize(message, "verbose"); + _parent.ErrorSerializer.Serialize(message, "verbose"); } else { WriteWrappedLine( - verboseForegroundColor, - verboseBackgroundColor, + _verboseForegroundColor, + _verboseBackgroundColor, StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message)); } } @@ -1359,9 +1357,9 @@ namespace Microsoft.PowerShell message = HostUtilities.RemoveGuidFromMessage(message, out unused); // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { - parent.ErrorSerializer.Serialize(message, "warning"); + _parent.ErrorSerializer.Serialize(message, "warning"); } else { @@ -1390,20 +1388,20 @@ namespace Microsoft.PowerShell string currentOperation = HostUtilities.RemoveIdentifierInfoFromMessage(record.CurrentOperation, out matchPattern); if (matchPattern) { - record = new ProgressRecord(record) {CurrentOperation = currentOperation}; + record = new ProgressRecord(record) { CurrentOperation = currentOperation }; } // We allow only one thread at a time to update the progress state.) - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { PSObject obj = new PSObject(); obj.Properties.Add(new PSNoteProperty("SourceId", sourceId)); obj.Properties.Add(new PSNoteProperty("Record", record)); - parent.ErrorSerializer.Serialize(obj, "progress"); + _parent.ErrorSerializer.Serialize(obj, "progress"); } else { - lock (instanceLock) + lock (_instanceLock) { HandleIncomingProgressRecord(sourceId, record); } @@ -1422,114 +1420,133 @@ namespace Microsoft.PowerShell return; } - TextWriter writer = (!Console.IsErrorRedirected || parent.IsInteractive) - ? parent.ConsoleTextWriter + TextWriter writer = (!Console.IsErrorRedirected || _parent.IsInteractive) + ? _parent.ConsoleTextWriter : Console.Error; - if (parent.ErrorFormat == Serialization.DataFormat.XML) + if (_parent.ErrorFormat == Serialization.DataFormat.XML) { - Dbg.Assert(writer == parent.ErrorSerializer.textWriter, "writers should be the same"); + Dbg.Assert(writer == _parent.ErrorSerializer.textWriter, "writers should be the same"); - parent.ErrorSerializer.Serialize(value + Crlf); + _parent.ErrorSerializer.Serialize(value + Crlf); } else { - if (writer == parent.ConsoleTextWriter) - WriteLine(errorForegroundColor, errorBackgroundColor, value); + if (writer == _parent.ConsoleTextWriter) + WriteLine(_errorForegroundColor, _errorBackgroundColor, value); else Console.Error.Write(value + Crlf); } } // Error colors - private ConsoleColor errorForegroundColor = ConsoleColor.Red; + private ConsoleColor _errorForegroundColor = ConsoleColor.Red; public ConsoleColor ErrorForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return errorForegroundColor; } + get + { return _errorForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { errorForegroundColor = value; } + set + { _errorForegroundColor = value; } } - private ConsoleColor errorBackgroundColor = ConsoleColor.Black; + private ConsoleColor _errorBackgroundColor = ConsoleColor.Black; public ConsoleColor ErrorBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return errorBackgroundColor; } + get + { return _errorBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { errorBackgroundColor = value; } + set + { _errorBackgroundColor = value; } } // Warning colors - private ConsoleColor warningForegroundColor = ConsoleColor.Yellow; + private ConsoleColor _warningForegroundColor = ConsoleColor.Yellow; public ConsoleColor WarningForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return warningForegroundColor; } + get + { return _warningForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { warningForegroundColor = value; } + set + { _warningForegroundColor = value; } } - private ConsoleColor warningBackgroundColor = ConsoleColor.Black; + private ConsoleColor _warningBackgroundColor = ConsoleColor.Black; public ConsoleColor WarningBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return warningBackgroundColor; } + get + { return _warningBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { warningBackgroundColor = value; } + set + { _warningBackgroundColor = value; } } // Debug colors - private ConsoleColor debugForegroundColor = ConsoleColor.Yellow; + private ConsoleColor _debugForegroundColor = ConsoleColor.Yellow; public ConsoleColor DebugForegroundColor { - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return debugForegroundColor; } + get + { return _debugForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { debugForegroundColor = value; } + set + { _debugForegroundColor = value; } } - private ConsoleColor debugBackgroundColor = ConsoleColor.Black; + private ConsoleColor _debugBackgroundColor = ConsoleColor.Black; public ConsoleColor DebugBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return debugBackgroundColor; } + get + { return _debugBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { debugBackgroundColor = value; } + set + { _debugBackgroundColor = value; } } // Verbose colors - private ConsoleColor verboseForegroundColor = ConsoleColor.Yellow; + private ConsoleColor _verboseForegroundColor = ConsoleColor.Yellow; public ConsoleColor VerboseForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return verboseForegroundColor; } + get + { return _verboseForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { verboseForegroundColor = value; } + set + { _verboseForegroundColor = value; } } - private ConsoleColor verboseBackgroundColor = ConsoleColor.Black; + private ConsoleColor _verboseBackgroundColor = ConsoleColor.Black; public ConsoleColor VerboseBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return verboseBackgroundColor; } + get + { return _verboseBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { verboseBackgroundColor = value; } + set + { _verboseBackgroundColor = value; } } // Progress colors - private ConsoleColor progressForegroundColor = ConsoleColor.Yellow; + private ConsoleColor _progressForegroundColor = ConsoleColor.Yellow; public ConsoleColor ProgressForegroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return progressForegroundColor; } + get + { return _progressForegroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { progressForegroundColor = value; } + set + { _progressForegroundColor = value; } } - private ConsoleColor progressBackgroundColor = ConsoleColor.DarkCyan; + private ConsoleColor _progressBackgroundColor = ConsoleColor.DarkCyan; public ConsoleColor ProgressBackgroundColor { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - get { return progressBackgroundColor; } + get + { return _progressBackgroundColor; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - set { progressBackgroundColor = value; } + set + { _progressBackgroundColor = value; } } #endregion Line-oriented interaction @@ -1552,7 +1569,7 @@ namespace Microsoft.PowerShell endedOnBreak = 3 } - const int maxInputLineLength = 8192; + private const int maxInputLineLength = 8192; /// /// @@ -1612,7 +1629,7 @@ namespace Microsoft.PowerShell result = ReadLineResult.endedOnEnter; // If the test hook is set, read from it. - if (_h != null) return _h.ReadLine(); + if (s_h != null) return s_h.ReadLine(); string restOfLine = null; @@ -1734,68 +1751,68 @@ namespace Microsoft.PowerShell try { - ConsoleKeyInfo keyInfo; - string s = ""; - int index = 0; - int cursorLeft = Console.CursorLeft; - int cursorCurrent = cursorLeft; - bool insertMode = true; - Console.TreatControlCAsInput = true; + ConsoleKeyInfo keyInfo; + string s = ""; + int index = 0; + int cursorLeft = Console.CursorLeft; + int cursorCurrent = cursorLeft; + bool insertMode = true; + Console.TreatControlCAsInput = true; #else - rawui.ClearKeyCache(); + _rawui.ClearKeyCache(); uint keyState = 0; string s = ""; #endif - do - { + do + { #if UNIX - keyInfo = Console.ReadKey(true); + keyInfo = Console.ReadKey(true); #else s += ConsoleControl.ReadConsole(handle, initialContent, maxInputLineLength, endOnTab, out keyState); Dbg.Assert(s != null, "s should never be null"); #endif #if UNIX - // Handle Ctrl-C ending input - if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) + // Handle Ctrl-C ending input + if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) #else if (s.Length == 0) #endif - { - result = ReadLineResult.endedOnBreak; - s = null; - - if (calledFromPipeline) { - // make sure that the pipeline that called us is stopped + result = ReadLineResult.endedOnBreak; + s = null; - throw new PipelineStoppedException(); + if (calledFromPipeline) + { + // make sure that the pipeline that called us is stopped + + throw new PipelineStoppedException(); + } + break; } - break; - } #if UNIX - if (keyInfo.Key == ConsoleKey.Enter) + if (keyInfo.Key == ConsoleKey.Enter) #else if (s.EndsWith(Crlf, StringComparison.CurrentCulture)) #endif - { - result = ReadLineResult.endedOnEnter; + { + result = ReadLineResult.endedOnEnter; #if UNIX - // We're intercepting characters, so we need to echo the newline - Console.Out.WriteLine(); + // We're intercepting characters, so we need to echo the newline + Console.Out.WriteLine(); #else s = s.Remove(s.Length - Crlf.Length); #endif - break; - } + break; + } #if UNIX - if (keyInfo.Key == ConsoleKey.Tab) - { - // This is unsupported - continue; - } + if (keyInfo.Key == ConsoleKey.Tab) + { + // This is unsupported + continue; + } #else int i = s.IndexOf(Tab, StringComparison.CurrentCulture); @@ -1848,127 +1865,127 @@ namespace Microsoft.PowerShell } #endif #if UNIX - if (keyInfo.Key == ConsoleKey.Backspace) - { - if (index > 0) + if (keyInfo.Key == ConsoleKey.Backspace) { - int length = s.Length; - s = s.Remove(index - 1, 1); - index--; - cursorCurrent = Console.CursorLeft; - Console.CursorLeft = cursorLeft; - Console.Out.Write(s.PadRight(length)); - Console.CursorLeft = cursorCurrent - 1; + if (index > 0) + { + int length = s.Length; + s = s.Remove(index - 1, 1); + index--; + cursorCurrent = Console.CursorLeft; + Console.CursorLeft = cursorLeft; + Console.Out.Write(s.PadRight(length)); + Console.CursorLeft = cursorCurrent - 1; + } + continue; } - continue; - } - if (keyInfo.Key == ConsoleKey.Delete - || (keyInfo.Key == ConsoleKey.D && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) - { - if (index < s.Length) + if (keyInfo.Key == ConsoleKey.Delete + || (keyInfo.Key == ConsoleKey.D && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (index < s.Length) + { + int length = s.Length; + s = s.Remove(index, 1); + cursorCurrent = Console.CursorLeft; + Console.CursorLeft = cursorLeft; + Console.Out.Write(s.PadRight(length)); + Console.CursorLeft = cursorCurrent; + } + continue; + } + + if (keyInfo.Key == ConsoleKey.LeftArrow + || (keyInfo.Key == ConsoleKey.B && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (Console.CursorLeft > cursorLeft) + { + Console.CursorLeft--; + index--; + } + continue; + } + + if (keyInfo.Key == ConsoleKey.RightArrow + || (keyInfo.Key == ConsoleKey.F && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + if (Console.CursorLeft < cursorLeft + s.Length) + { + Console.CursorLeft++; + index++; + } + continue; + } + + if (keyInfo.Key == ConsoleKey.UpArrow + || keyInfo.Key == ConsoleKey.DownArrow + || keyInfo.Key == ConsoleKey.PageUp + || keyInfo.Key == ConsoleKey.PageDown) + { + // Arrow/Page Up/down is unimplemented, so fail gracefully + continue; + } + + if (keyInfo.Key == ConsoleKey.Home + || (keyInfo.Key == ConsoleKey.A && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + Console.CursorLeft = cursorLeft; + index = 0; + continue; + } + + if (keyInfo.Key == ConsoleKey.End + || (keyInfo.Key == ConsoleKey.E && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) + { + Console.CursorLeft = cursorLeft + s.Length; + index = s.Length; + continue; + } + + if (keyInfo.Key == ConsoleKey.Escape) + { + Console.CursorLeft = cursorLeft; + index = s.Length; + s = ""; + continue; + } + + if (keyInfo.Key == ConsoleKey.Insert) + { + // Toggle insert/overwrite mode + insertMode = !insertMode; + continue; + } + + if (Char.IsControl(keyInfo.KeyChar)) + { + // blacklist control characters + continue; + } + + // Modify string + if (!insertMode) // then overwrite mode { - int length = s.Length; s = s.Remove(index, 1); - cursorCurrent = Console.CursorLeft; - Console.CursorLeft = cursorLeft; - Console.Out.Write(s.PadRight(length)); - Console.CursorLeft = cursorCurrent; } - continue; - } + s = s.Insert(index, keyInfo.KeyChar.ToString()); + index++; - if (keyInfo.Key == ConsoleKey.LeftArrow - || (keyInfo.Key == ConsoleKey.B && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) - { - if (Console.CursorLeft > cursorLeft) - { - Console.CursorLeft--; - index--; - } - continue; - } - - if (keyInfo.Key == ConsoleKey.RightArrow - || (keyInfo.Key == ConsoleKey.F && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) - { - if (Console.CursorLeft < cursorLeft + s.Length) - { - Console.CursorLeft++; - index++; - } - continue; - } - - if (keyInfo.Key == ConsoleKey.UpArrow - || keyInfo.Key == ConsoleKey.DownArrow - || keyInfo.Key == ConsoleKey.PageUp - || keyInfo.Key == ConsoleKey.PageDown) - { - // Arrow/Page Up/down is unimplemented, so fail gracefully - continue; - } - - if (keyInfo.Key == ConsoleKey.Home - || (keyInfo.Key == ConsoleKey.A && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) - { + // Redisplay string + cursorCurrent = Console.CursorLeft; Console.CursorLeft = cursorLeft; - index = 0; - continue; - } - - if (keyInfo.Key == ConsoleKey.End - || (keyInfo.Key == ConsoleKey.E && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))) - { - Console.CursorLeft = cursorLeft + s.Length; - index = s.Length; - continue; - } - - if (keyInfo.Key == ConsoleKey.Escape) - { - Console.CursorLeft = cursorLeft; - index = s.Length; - s = ""; - continue; - } - - if (keyInfo.Key == ConsoleKey.Insert) - { - // Toggle insert/overwrite mode - insertMode = !insertMode; - continue; - } - - if (Char.IsControl(keyInfo.KeyChar)) - { - // blacklist control characters - continue; - } - - // Modify string - if (!insertMode) // then overwrite mode - { - s = s.Remove(index, 1); - } - s = s.Insert(index, keyInfo.KeyChar.ToString()); - index++; - - // Redisplay string - cursorCurrent = Console.CursorLeft; - Console.CursorLeft = cursorLeft; - Console.Out.Write(s); - Console.CursorLeft = cursorCurrent + 1; + Console.Out.Write(s); + Console.CursorLeft = cursorCurrent + 1; #endif - } - while (true); + } + while (true); - Dbg.Assert( - (s == null && result == ReadLineResult.endedOnBreak) - || (s != null && result != ReadLineResult.endedOnBreak), - "s should only be null if input ended with a break"); + Dbg.Assert( + (s == null && result == ReadLineResult.endedOnBreak) + || (s != null && result != ReadLineResult.endedOnBreak), + "s should only be null if input ended with a break"); - return s; + return s; #if UNIX } finally @@ -2014,7 +2031,7 @@ namespace Microsoft.PowerShell /// /// The string to process /// The string with any \0 characters removed... - string RemoveNulls(string input) + private string RemoveNulls(string input) { if (input.IndexOf('\0') == -1) return input; @@ -2202,11 +2219,11 @@ namespace Microsoft.PowerShell // Since we did not transcribe any call to ReadLine, transcribe the results here. - if (parent.IsTranscribing) + if (_parent.IsTranscribing) { // Reads always terminate with the enter key, so add that. - parent.WriteToTranscript(input + Crlf); + _parent.WriteToTranscript(input + Crlf); } return input; @@ -2216,28 +2233,28 @@ namespace Microsoft.PowerShell private void SendLeftArrows(int length) { var inputs = new ConsoleControl.INPUT[length * 2]; - for (int i=0; i < length; i++) + for (int i = 0; i < length; i++) { var down = new ConsoleControl.INPUT(); - down.Type = (UInt32) ConsoleControl.InputType.Keyboard; + down.Type = (UInt32)ConsoleControl.InputType.Keyboard; down.Data.Keyboard = new ConsoleControl.KeyboardInput(); - down.Data.Keyboard.Vk = (UInt16) ConsoleControl.VirtualKeyCode.Left; + down.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; down.Data.Keyboard.Scan = 0; down.Data.Keyboard.Flags = 0; down.Data.Keyboard.Time = 0; down.Data.Keyboard.ExtraInfo = IntPtr.Zero; var up = new ConsoleControl.INPUT(); - up.Type = (UInt32) ConsoleControl.InputType.Keyboard; + up.Type = (UInt32)ConsoleControl.InputType.Keyboard; up.Data.Keyboard = new ConsoleControl.KeyboardInput(); - up.Data.Keyboard.Vk = (UInt16) ConsoleControl.VirtualKeyCode.Left; + up.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; up.Data.Keyboard.Scan = 0; - up.Data.Keyboard.Flags = (UInt32) ConsoleControl.KeyboardFlag.KeyUp; + up.Data.Keyboard.Flags = (UInt32)ConsoleControl.KeyboardFlag.KeyUp; up.Data.Keyboard.Time = 0; up.Data.Keyboard.ExtraInfo = IntPtr.Zero; - inputs[2*i] = down; - inputs[2*i + 1] = up; + inputs[2 * i] = down; + inputs[2 * i + 1] = up; } ConsoleControl.MimicKeyPress(inputs); @@ -2248,7 +2265,7 @@ namespace Microsoft.PowerShell { try { - var runspace = this.parent.Runspace; + var runspace = _parent.Runspace; var debugger = runspace.Debugger; if ((debugger != null) && debugger.InBreakpoint) @@ -2261,35 +2278,35 @@ namespace Microsoft.PowerShell catch (PSInvalidOperationException) { } } - + if (runspace is LocalRunspace && runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) { - commandCompletionPowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); + _commandCompletionPowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } else { - commandCompletionPowerShell = PowerShell.Create(); - commandCompletionPowerShell.SetIsNested(parent.IsNested); - commandCompletionPowerShell.Runspace = runspace; + _commandCompletionPowerShell = PowerShell.Create(); + _commandCompletionPowerShell.SetIsNested(_parent.IsNested); + _commandCompletionPowerShell.Runspace = runspace; } - return CommandCompletion.CompleteInput(input, input.Length, null, commandCompletionPowerShell); + return CommandCompletion.CompleteInput(input, input.Length, null, _commandCompletionPowerShell); } finally { - commandCompletionPowerShell = null; + _commandCompletionPowerShell = null; } } - const string CustomReadlineCommand = "PSConsoleHostReadLine"; + private const string CustomReadlineCommand = "PSConsoleHostReadLine"; private bool TryInvokeUserDefinedReadLine(out string input) { // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded. // The idea is that if someone hasn't defined the command (say because they started -noprofile), we shouldn't auto-load // this function. - var runspace = this.parent.LocalRunspace; + var runspace = _parent.LocalRunspace; if (runspace != null && runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any()) @@ -2329,9 +2346,9 @@ namespace Microsoft.PowerShell // used to serialize access to instance data - private object instanceLock = new object(); + private object _instanceLock = new object(); - private bool noPrompt; + private bool _noPrompt; //If this is true, class throws on read or prompt method which require //access to console. @@ -2339,14 +2356,14 @@ namespace Microsoft.PowerShell { set { - throwOnReadAndPrompt = value; + _throwOnReadAndPrompt = value; } } - private bool throwOnReadAndPrompt; + private bool _throwOnReadAndPrompt; internal void HandleThrowOnReadAndPrompt() { - if (throwOnReadAndPrompt) + if (_throwOnReadAndPrompt) { throw PSTraceSource.NewInvalidOperationException(ConsoleHostUserInterfaceStrings.ReadFailsOnNonInteractiveFlag); } @@ -2354,17 +2371,16 @@ namespace Microsoft.PowerShell // this is a test hook for the ConsoleInteractiveTestTool, which sets this field to true. - private bool isInteractiveTestToolListening; + private bool _isInteractiveTestToolListening; // This instance data is "read-only" and need not have access serialized. - private ConsoleHostRawUserInterface rawui; - private ConsoleHost parent; - + private ConsoleHostRawUserInterface _rawui; + private ConsoleHost _parent; + [TraceSourceAttribute("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console")] private static - PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console"); + PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console"); } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index c6879a095..66f2198a0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -24,7 +24,7 @@ namespace Microsoft.PowerShell /// outstanding progress activity state. /// /// - + internal void ResetProgress() @@ -32,14 +32,14 @@ namespace Microsoft.PowerShell // destroy the data structures representing outstanding progress records // take down and destroy the progress display - if (progPane != null) + if (_progPane != null) { - Dbg.Assert(pendingProgress != null, "How can you have a progress pane and no backing data structure?"); + Dbg.Assert(_pendingProgress != null, "How can you have a progress pane and no backing data structure?"); - progPane.Hide(); - progPane = null; + _progPane.Hide(); + _progPane = null; } - pendingProgress = null; + _pendingProgress = null; } @@ -57,35 +57,35 @@ namespace Microsoft.PowerShell { Dbg.Assert(record != null, "record should not be null"); - if (pendingProgress == null) + if (_pendingProgress == null) { - Dbg.Assert(progPane == null, "If there is no data struct, there shouldn't be a pane, either."); + Dbg.Assert(_progPane == null, "If there is no data struct, there shouldn't be a pane, either."); - pendingProgress = new PendingProgress(); + _pendingProgress = new PendingProgress(); } - pendingProgress.Update(sourceId, record); + _pendingProgress.Update(sourceId, record); - if (progPane == null) + if (_progPane == null) { // This is the first time we've received a progress record. Create a pane to show it, and // then show it. - progPane = new ProgressPane(this); + _progPane = new ProgressPane(this); } - progPane.Show(pendingProgress); + _progPane.Show(_pendingProgress); } - + private void PreWrite() { - if (progPane != null) + if (_progPane != null) { - progPane.Hide(); + _progPane.Hide(); } } @@ -95,32 +95,31 @@ namespace Microsoft.PowerShell void PostWrite() { - if (progPane != null) + if (_progPane != null) { - progPane.Show(); + _progPane.Show(); } } - - + + private void PostWrite(string value) { PostWrite(); - if (parent.IsTranscribing) + if (_parent.IsTranscribing) { try { - parent.WriteToTranscript(value); + _parent.WriteToTranscript(value); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); - parent.IsTranscribing = false; + _parent.IsTranscribing = false; } - } } @@ -130,9 +129,9 @@ namespace Microsoft.PowerShell void PreRead() { - if (progPane != null) + if (_progPane != null) { - progPane.Hide(); + _progPane.Hide(); } } @@ -142,9 +141,9 @@ namespace Microsoft.PowerShell void PostRead() { - if (progPane != null) + if (_progPane != null) { - progPane.Show(); + _progPane.Show(); } } @@ -156,29 +155,26 @@ namespace Microsoft.PowerShell { PostRead(); - if (parent.IsTranscribing) + if (_parent.IsTranscribing) { try { // Reads always terminate with the enter key, so add that. - parent.WriteToTranscript(value + Crlf); + _parent.WriteToTranscript(value + Crlf); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); - parent.IsTranscribing = false; + _parent.IsTranscribing = false; } } } - - - private ProgressPane progPane = null; - private PendingProgress pendingProgress = null; + + + private ProgressPane _progPane = null; + private PendingProgress _pendingProgress = null; } - - - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index d32653318..0983adeef 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -43,7 +43,7 @@ namespace Microsoft.PowerShell /// /// Overflow error /// - Overflow + Overflow } @@ -128,7 +128,7 @@ namespace Microsoft.PowerShell // we lock here so that multiple threads won't interleave the various reads and writes here. - lock (instanceLock) + lock (_instanceLock) { Dictionary results = new Dictionary(); @@ -173,13 +173,13 @@ namespace Microsoft.PowerShell // defense in depth. if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) { - string paramName = + string paramName = string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex); throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName); } Type fieldType = InternalHostUserInterface.GetFieldType(desc); - if(fieldType == null) + if (fieldType == null) { if (InternalHostUserInterface.IsSecuritySensitiveType(desc.ParameterTypeName)) { @@ -229,9 +229,9 @@ namespace Microsoft.PowerShell string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); Boolean inputListEnd = false; Object convertedObj = null; - string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, + string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, desc, fieldEchoOnPrompt, true, out inputListEnd, out cancelInput, out convertedObj); - + if (cancelInput || inputListEnd) { break; @@ -255,7 +255,6 @@ namespace Microsoft.PowerShell { inputPSObject = PSObject.AsPSObject(inputList); } - } } else @@ -275,7 +274,7 @@ namespace Microsoft.PowerShell } if (cancelInput) { - tracer.WriteLine("Prompt canceled"); + s_tracer.WriteLine("Prompt canceled"); WriteLineToConsole(); results.Clear(); break; @@ -287,10 +286,10 @@ namespace Microsoft.PowerShell } private string PromptForSingleItem(Type fieldType, - string printFieldPrompt, + string printFieldPrompt, string fieldPrompt, - string caption, - string message, + string caption, + string message, FieldDescription desc, bool fieldEchoOnPrompt, bool listInput, @@ -412,7 +411,7 @@ namespace Microsoft.PowerShell else if (rawInputString.StartsWith(PromptCommandPrefix, StringComparison.CurrentCulture)) { - processedInputString = PromptCommandMode(rawInputString, desc, out inputDone); + processedInputString = PromptCommandMode(rawInputString, desc, out inputDone); } else { @@ -506,10 +505,10 @@ namespace Microsoft.PowerShell /// /// /// - + private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) { - Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix,StringComparison.OrdinalIgnoreCase), + Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), string.Format(CultureInfo.InvariantCulture, "input should start with {0}", PromptCommandPrefix)); Dbg.Assert(desc != null, "desc should never be null when PromptCommandMode is called"); string command = input.Substring(1); @@ -527,7 +526,7 @@ namespace Microsoft.PowerShell { string noHelpErrMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptNoHelpAvailableErrorTemplate, desc.Name); - tracer.TraceWarning(noHelpErrMsg); + s_tracer.TraceWarning(noHelpErrMsg); WriteLineToConsole(WrapToCurrentWindowWidth(noHelpErrMsg)); } else @@ -559,7 +558,6 @@ namespace Microsoft.PowerShell inputDone = false; return null; } - } private void ReportUnrecognizedPromptCommand(string command) @@ -571,8 +569,5 @@ namespace Microsoft.PowerShell // Prefix for command mode in Prompt private const string PromptCommandPrefix = "!"; } - - - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index df674b80e..10918e18b 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -77,7 +77,7 @@ namespace Microsoft.PowerShell // we lock here so that multiple threads won't interleave the various reads and writes here. - lock (instanceLock) + lock (_instanceLock) { if (!string.IsNullOrEmpty(caption)) { @@ -198,7 +198,7 @@ namespace Microsoft.PowerShell throw PSTraceSource.NewArgumentException("choices", ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } - + Dictionary defaultChoiceKeys = new Dictionary(); if (null != defaultChoices) @@ -208,8 +208,8 @@ namespace Microsoft.PowerShell if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, - ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, - "defaultChoice", + ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, + "defaultChoice", "choices", defaultChoice); } @@ -223,7 +223,7 @@ namespace Microsoft.PowerShell Collection result = new Collection(); // we lock here so that multiple threads won't interleave the various reads and writes here. - lock (instanceLock) + lock (_instanceLock) { // write caption on the console, if present. if (!string.IsNullOrEmpty(caption)) @@ -274,7 +274,7 @@ namespace Microsoft.PowerShell // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. - + // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { @@ -309,10 +309,10 @@ namespace Microsoft.PowerShell return result; } - } - + } + private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, - Dictionary defaultChoiceKeys, + Dictionary defaultChoiceKeys, bool shouldEmulateForMultipleChoiceSelection) { System.Management.Automation.Diagnostics.Assert(defaultChoiceKeys != null, "defaultChoiceKeys cannot be null."); @@ -414,7 +414,7 @@ namespace Microsoft.PowerShell } WriteToConsole(fg, bg, trimEnd ? text.TrimEnd(null) : text); - } + } private void ShowChoiceHelp(Collection choices, string[,] hotkeysAndPlainLabels) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs index 8a575d53c..f5e46f884 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -41,19 +41,19 @@ namespace Microsoft.PowerShell /// /// PSCredential object /// - + public override PSCredential PromptForCredential( - string caption, + string caption, string message, string userName, - string targetName ) + string targetName) { - return PromptForCredential( caption, + return PromptForCredential(caption, message, userName, targetName, PSCredentialTypes.Default, - PSCredentialUIOptions.Default ); + PSCredentialUIOptions.Default); } /// @@ -73,16 +73,16 @@ namespace Microsoft.PowerShell /// /// PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF) /// - + public override PSCredential PromptForCredential( - string caption, + string caption, string message, - string userName, + string userName, string targetName, PSCredentialTypes allowedCredentialTypes, - PSCredentialUIOptions options ) + PSCredentialUIOptions options) { - if (! PromptUsingConsole()) + if (!PromptUsingConsole()) { IntPtr mainWindowHandle = GetMainWindowHandle(); return HostUtilities.CredUIPromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options, mainWindowHandle); @@ -156,11 +156,11 @@ namespace Microsoft.PowerShell #else System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); IntPtr mainWindowHandle = currentProcess.MainWindowHandle; - - while((mainWindowHandle == IntPtr.Zero) && (currentProcess != null)) + + while ((mainWindowHandle == IntPtr.Zero) && (currentProcess != null)) { currentProcess = PsUtils.GetParentProcess(currentProcess); - if(currentProcess != null) + if (currentProcess != null) { mainWindowHandle = currentProcess.MainWindowHandle; } @@ -189,7 +189,7 @@ namespace Microsoft.PowerShell } catch (System.Security.SecurityException) { - tracer.TraceError("User doesn't have access to read CredUI registry key."); + s_tracer.TraceError("User doesn't have access to read CredUI registry key."); return promptUsingConsole; } @@ -206,24 +206,24 @@ namespace Microsoft.PowerShell } catch (System.Security.SecurityException e) { - tracer.TraceError("Could not read CredUI registry key: " + e.Message); + s_tracer.TraceError("Could not read CredUI registry key: " + e.Message); if (key != null) { key.Dispose(); } // No RegistryKey.Close() on CoreCLR return promptUsingConsole; } catch (InvalidCastException e) { - tracer.TraceError("Could not parse CredUI registry key: " + e.Message); + s_tracer.TraceError("Could not parse CredUI registry key: " + e.Message); if (key != null) { key.Dispose(); } // No RegistryKey.Close() on CoreCLR return promptUsingConsole; } catch (FormatException e) { - tracer.TraceError("Could not parse CredUI registry key: " + e.Message); + s_tracer.TraceError("Could not parse CredUI registry key: " + e.Message); if (key != null) { key.Dispose(); } // No RegistryKey.Close() on CoreCLR return promptUsingConsole; } - tracer.WriteLine("DetermineCredUIPolicy: policy == {0}", promptUsingConsole); + s_tracer.WriteLine("DetermineCredUIPolicy: policy == {0}", promptUsingConsole); if (key != null) { key.Dispose(); } // No RegistryKey.Close() on CoreCLR return promptUsingConsole; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index e9536c2d9..04841952c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -13,8 +13,8 @@ namespace Microsoft.PowerShell /// This class provides an entry point which is called by minishell's main /// to transfer control to Msh console host implementation. /// - - public static + + public static class ConsoleShell { #if CORECLR diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs index e48a62e72..0e036a7b3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -36,7 +36,7 @@ namespace Microsoft.PowerShell { Dbg.Assert(ui != null, "ui needs a value"); - this.ui = ui; + _ui = ui; } @@ -57,7 +57,7 @@ namespace Microsoft.PowerShell void Write(string value) { - ui.WriteToConsole(value, true); + _ui.WriteToConsole(value, true); } @@ -98,9 +98,8 @@ namespace Microsoft.PowerShell - private ConsoleHostUserInterface ui; + private ConsoleHostUserInterface _ui; } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 9ba4e829f..6099d1371 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -67,12 +67,12 @@ namespace Microsoft.PowerShell /// internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) { - Dbg.Assert(parent != null, "parent should not be null"); + Dbg.Assert(parent != null, "parent should not be null"); - this.parent = parent; - this.useNestedPipelines = useNestedPipelines; - this.isPromptFunctionExecutor = isPromptFunctionExecutor; - Reset(); + _parent = parent; + this.useNestedPipelines = useNestedPipelines; + _isPromptFunctionExecutor = isPromptFunctionExecutor; + Reset(); } #region async @@ -93,7 +93,7 @@ namespace Microsoft.PowerShell Collection objects = reader.NonBlockingRead(); foreach (PSObject obj in objects) { - parent.OutputSerializer.Serialize(obj); + _parent.OutputSerializer.Serialize(obj); } } @@ -116,7 +116,7 @@ namespace Microsoft.PowerShell Collection objects = reader.NonBlockingRead(); foreach (object obj in objects) { - parent.ErrorSerializer.Serialize(obj); + _parent.ErrorSerializer.Serialize(obj); } } @@ -141,7 +141,7 @@ namespace Microsoft.PowerShell { er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); } - parent.ErrorSerializer.Serialize(er); + _parent.ErrorSerializer.Serialize(er); } private class PipelineFinishedWaitHandle @@ -153,7 +153,7 @@ namespace Microsoft.PowerShell internal void Wait() { - eventHandle.WaitOne(); + _eventHandle.WaitOne(); } private void PipelineStateChangedHandler(object sender, PipelineStateEventArgs e) @@ -163,11 +163,11 @@ namespace Microsoft.PowerShell || e.PipelineStateInfo.State == PipelineState.Failed || e.PipelineStateInfo.State == PipelineState.Stopped) { - eventHandle.Set(); + _eventHandle.Set(); } } - private System.Threading.ManualResetEvent eventHandle = new System.Threading.ManualResetEvent(false); + private System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false); } internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options) @@ -176,27 +176,27 @@ namespace Microsoft.PowerShell Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); bool addToHistory = (options & ExecutionOptions.AddToHistory) > 0; - Pipeline tempPipeline = this.parent.RunspaceRef.CreatePipeline(command, addToHistory, false); + Pipeline tempPipeline = _parent.RunspaceRef.CreatePipeline(command, addToHistory, false); ExecuteCommandAsyncHelper(tempPipeline, out exceptionThrown, options); } internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { - Dbg.Assert(!isPromptFunctionExecutor, "should not async invoke the prompt"); + Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt"); exceptionThrown = null; Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; - lock (instanceStateLock) + lock (_instanceStateLock) { - Dbg.Assert(pipeline == null, "no other pipeline should exist"); - pipeline = tempPipeline; + Dbg.Assert(_pipeline == null, "no other pipeline should exist"); + _pipeline = tempPipeline; } try { - if ((options & ExecutionOptions.AddOutputter) > 0 && parent.OutputFormat == Serialization.DataFormat.Text) + if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text) { // Tell the script command to merge it's output and error streams @@ -219,7 +219,7 @@ namespace Microsoft.PowerShell { // read input objects from stdin - WrappedDeserializer des = new WrappedDeserializer(parent.InputFormat, "Input", Console.In); + WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", Console.In); while (!des.AtEnd) { object o = des.Deserialize(); @@ -250,7 +250,7 @@ namespace Microsoft.PowerShell //report error if pipeline failed if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null) { - if (parent.OutputFormat == Serialization.DataFormat.Text) + if (_parent.OutputFormat == Serialization.DataFormat.Text) { //Report the exception using normal error reporting exceptionThrown = tempPipeline.PipelineStateInfo.Reason; @@ -271,7 +271,7 @@ namespace Microsoft.PowerShell { // Once we have the results, or an exception is thrown, we throw away the pipeline. - parent.ui.ResetProgress(); + _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } @@ -283,18 +283,18 @@ namespace Microsoft.PowerShell { if (useNestedPipelines) { - return parent.RunspaceRef.CreateNestedPipeline(); + return _parent.RunspaceRef.CreateNestedPipeline(); } else { - return parent.RunspaceRef.CreatePipeline(); + return _parent.RunspaceRef.CreatePipeline(); } } internal Pipeline CreatePipeline(string command, bool addToHistory) { Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value"); - return parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines); + return _parent.RunspaceRef.CreatePipeline(command, addToHistory, useNestedPipelines); } /// @@ -368,7 +368,7 @@ namespace Microsoft.PowerShell } // Add Out-Default to the pipeline to render. - tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement:false)); + tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false)); } else { @@ -382,7 +382,7 @@ namespace Microsoft.PowerShell { // End of statement needs to pipe to Out-Default. cmd.IsEndOfStatement = false; - executeCommands.Add(GetOutDefaultCommand(endOfStatement:true)); + executeCommands.Add(GetOutDefaultCommand(endOfStatement: true)); } } @@ -390,9 +390,9 @@ namespace Microsoft.PowerShell if (!((lastCmd.CommandText != null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) - { + { // Ensure pipeline output goes to Out-Default. - executeCommands.Add(GetOutDefaultCommand(endOfStatement:false)); + executeCommands.Add(GetOutDefaultCommand(endOfStatement: false)); } tempPipeline.Commands.Clear(); @@ -406,10 +406,10 @@ namespace Microsoft.PowerShell Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; - lock (instanceStateLock) + lock (_instanceStateLock) { - Dbg.Assert(pipeline == null, "no other pipeline should exist"); - pipeline = tempPipeline; + Dbg.Assert(_pipeline == null, "no other pipeline should exist"); + _pipeline = tempPipeline; } try @@ -426,7 +426,7 @@ namespace Microsoft.PowerShell { // Once we have the results, or an exception is thrown, we throw away the pipeline. - parent.ui.ResetProgress(); + _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } @@ -609,25 +609,25 @@ namespace Microsoft.PowerShell { // if there's a pipeline running, stop it. - lock (instanceStateLock) + lock (_instanceStateLock) { - if (pipeline != null && !cancelled) + if (_pipeline != null && !_cancelled) { - cancelled = true; + _cancelled = true; - if (isPromptFunctionExecutor) + if (_isPromptFunctionExecutor) { System.Threading.Thread.Sleep(100); } - pipeline.Stop(); + _pipeline.Stop(); } } } internal void BlockCommandOutput() { - RemotePipeline remotePipeline = pipeline as RemotePipeline; + RemotePipeline remotePipeline = _pipeline as RemotePipeline; if (remotePipeline != null) { // Waits until queued data is handled. @@ -640,7 +640,7 @@ namespace Microsoft.PowerShell internal void ResumeCommandOutput() { - RemotePipeline remotePipeline = pipeline as RemotePipeline; + RemotePipeline remotePipeline = _pipeline as RemotePipeline; if (remotePipeline != null) { // Resumes data flow. @@ -655,10 +655,10 @@ namespace Microsoft.PowerShell /// private void Reset() { - lock (instanceStateLock) + lock (_instanceStateLock) { - pipeline = null; - cancelled = false; + _pipeline = null; + _cancelled = false; } } @@ -715,24 +715,24 @@ namespace Microsoft.PowerShell { Executor result = null; - lock (staticStateLock) + lock (s_staticStateLock) { - result = currentExecutor; + result = s_currentExecutor; } return result; } set { - lock (staticStateLock) + lock (s_staticStateLock) { // null is acceptable. - currentExecutor = value; + s_currentExecutor = value; } } } - + /// /// /// Cancels the execution of the current instance (the instance last passed to PushCurrentExecutor), if any. If no @@ -743,9 +743,9 @@ namespace Microsoft.PowerShell { Executor temp = null; - lock (staticStateLock) + lock (s_staticStateLock) { - temp = currentExecutor; + temp = s_currentExecutor; } if (temp != null) @@ -753,20 +753,19 @@ namespace Microsoft.PowerShell temp.Cancel(); } } - + // These statics are threadsafe, as there can be only one instance of ConsoleHost in a process at a time, and access // to currentExecutor is guarded by staticStateLock, and static initializers are run by the CLR at program init time. - private static Executor currentExecutor; - private static object staticStateLock = new object(); + private static Executor s_currentExecutor; + private static object s_staticStateLock = new object(); - private ConsoleHost parent; - private Pipeline pipeline; - private bool cancelled; + private ConsoleHost _parent; + private Pipeline _pipeline; + private bool _cancelled; internal bool useNestedPipelines; - private object instanceStateLock = new object(); - private bool isPromptFunctionExecutor; - } - + private object _instanceStateLock = new object(); + private bool _isPromptFunctionExecutor; + } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 48174d1c2..5bbacac4f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -28,9 +28,9 @@ namespace Microsoft.PowerShell /// Command line arguments to the managed MSH /// #if CORECLR - #pragma warning disable 1573 +#pragma warning disable 1573 public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)]string[] args, int argc) - #pragma warning restore 1573 +#pragma warning restore 1573 #else public int Start(string consoleFilePath, string[] args) #endif @@ -94,14 +94,14 @@ namespace Microsoft.PowerShell ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } - else + else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } #else ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); - configuration = null; + configuration = null; #endif } else diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 0a1ecbed5..8dc81cb99 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -123,7 +123,7 @@ namespace Microsoft.PowerShell // If we're adding a node, and we have no more space, then we need to pick a node to evict. - while (nodeCount >= maxNodeCount) + while (_nodeCount >= maxNodeCount) { EvictNode(); } @@ -150,7 +150,7 @@ namespace Microsoft.PowerShell newNode.ParentActivityId = -1; } - AddNode(topLevelNodes, newNode); + AddNode(_topLevelNodes, newNode); } while (false); // At this point the tree is up-to-date. Make a pass to age all of the nodes @@ -176,7 +176,7 @@ namespace Microsoft.PowerShell // We'll just pick the root node, then. - RemoveNode(topLevelNodes, 0); + RemoveNode(_topLevelNodes, 0); } else { @@ -200,13 +200,13 @@ namespace Microsoft.PowerShell /// Index into the list of the node to be removed. /// /// - + private void RemoveNode(ArrayList nodes, int indexToRemove) { #if DEBUG || ASSERTIONS_TRACE - ProgressNode nodeToRemove = (ProgressNode) nodes[indexToRemove]; + ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; Dbg.Assert(nodes != null, "can't remove nodes from a null list"); Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); @@ -215,10 +215,10 @@ namespace Microsoft.PowerShell #endif nodes.RemoveAt(indexToRemove); - --nodeCount; + --_nodeCount; #if DEBUG || ASSERTIONS_ON - Dbg.Assert(nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); #endif } @@ -227,7 +227,7 @@ namespace Microsoft.PowerShell void RemoveNodeAndPromoteChildren(ArrayList nodes, int indexToRemove) { - ProgressNode nodeToRemove = (ProgressNode) nodes[indexToRemove]; + ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; Dbg.Assert(nodes != null, "can't remove nodes from a null list"); Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); @@ -246,17 +246,17 @@ namespace Microsoft.PowerShell { // unparent the children. If the children are ever updated again, they will be reparented. - ((ProgressNode) nodeToRemove.Children[i]).ParentActivityId = -1; + ((ProgressNode)nodeToRemove.Children[i]).ParentActivityId = -1; } // add the children as siblings nodes.RemoveAt(indexToRemove); - --nodeCount; + --_nodeCount; nodes.InsertRange(indexToRemove, nodeToRemove.Children); #if DEBUG || ASSERTIONS_TRACE - Dbg.Assert(nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); #endif } else @@ -291,11 +291,11 @@ namespace Microsoft.PowerShell AddNode(ArrayList nodes, ProgressNode nodeToAdd) { nodes.Add(nodeToAdd); - ++nodeCount; + ++_nodeCount; #if DEBUG || ASSERTIONS_TRACE - Dbg.Assert(nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); - Dbg.Assert(nodeCount <= maxNodeCount, "Too many nodes in tree!"); + Dbg.Assert(_nodeCount == this.CountNodes(), "We've lost track of the number of nodes in the tree"); + Dbg.Assert(_nodeCount <= maxNodeCount, "Too many nodes in tree!"); #endif } @@ -308,9 +308,9 @@ namespace Microsoft.PowerShell bool Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound) { - if (node.Age >= oldestSoFar) + if (node.Age >= _oldestSoFar) { - oldestSoFar = node.Age; + _oldestSoFar = node.Age; FoundNode = node; this.ListWhereFound = listWhereFound; this.IndexWhereFound = indexWhereFound; @@ -338,7 +338,7 @@ namespace Microsoft.PowerShell IndexWhereFound = -1; - private int oldestSoFar; + private int _oldestSoFar; } @@ -361,8 +361,8 @@ namespace Microsoft.PowerShell { Dbg.Assert(listWhereFound == null, "list should be null when no node found"); Dbg.Assert(indexWhereFound == -1, "index should indicate no node found"); - Dbg.Assert(topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty"); - Dbg.Assert(nodeCount == 0, "if there is no oldest node, then the tree must be empty"); + Dbg.Assert(_topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty"); + Dbg.Assert(_nodeCount == 0, "if there is no oldest node, then the tree must be empty"); } #endif return v.FoundNode; @@ -377,7 +377,7 @@ namespace Microsoft.PowerShell indexWhereFound = -1; ProgressNode result = null; - ArrayList treeToSearch = topLevelNodes; + ArrayList treeToSearch = _topLevelNodes; do { @@ -402,7 +402,7 @@ namespace Microsoft.PowerShell /// Convenience overload. /// /// - + private ProgressNode FindNodeById(Int64 sourceId, int activityId) @@ -421,8 +421,8 @@ namespace Microsoft.PowerShell internal FindByIdNodeVisitor(Int64 sourceIdToFind, int activityIdToFind) { - this.sourceIdToFind = sourceIdToFind; - this.idToFind = activityIdToFind; + _sourceIdToFind = sourceIdToFind; + _idToFind = activityIdToFind; } @@ -431,7 +431,7 @@ namespace Microsoft.PowerShell bool Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound) { - if (node.ActivityId == idToFind && node.SourceId == sourceIdToFind) + if (node.ActivityId == _idToFind && node.SourceId == _sourceIdToFind) { this.FoundNode = node; this.ListWhereFound = listWhereFound; @@ -461,8 +461,8 @@ namespace Microsoft.PowerShell - private int idToFind = -1; - private Int64 sourceIdToFind; + private int _idToFind = -1; + private Int64 _sourceIdToFind; } @@ -507,7 +507,7 @@ namespace Microsoft.PowerShell indexWhereFound = -1; FindByIdNodeVisitor v = new FindByIdNodeVisitor(sourceId, activityId); - NodeVisitor.VisitNodes(topLevelNodes, v); + NodeVisitor.VisitNodes(_topLevelNodes, v); listWhereFound = v.ListWhereFound; indexWhereFound = v.IndexWhereFound; @@ -561,7 +561,7 @@ namespace Microsoft.PowerShell ProgressNode found = null; for (int i = 0; i < nodes.Count; ++i) { - ProgressNode node = (ProgressNode) nodes[i]; + ProgressNode node = (ProgressNode)nodes[i]; Dbg.Assert(node != null, "nodes should not contain null elements"); if (node.Age >= oldestSoFar && node.Style == style) @@ -596,10 +596,10 @@ namespace Microsoft.PowerShell - private + private class AgeAndResetStyleVisitor : NodeVisitor { - internal override + internal override bool Visit(ProgressNode node, ArrayList unused, int unusedToo) { @@ -619,13 +619,13 @@ namespace Microsoft.PowerShell /// All nodes are aged every time a new ProgressRecord is received. /// /// - + private void AgeNodesAndResetStyle() { AgeAndResetStyleVisitor arsv = new AgeAndResetStyleVisitor(); - NodeVisitor.VisitNodes(topLevelNodes, arsv); + NodeVisitor.VisitNodes(_topLevelNodes, arsv); } @@ -664,16 +664,16 @@ namespace Microsoft.PowerShell /// An array of strings containing the textual representation of the outstanding progress activities. /// /// - + internal string[] Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI) { - Dbg.Assert(topLevelNodes != null, "Shouldn't need to render progress if no data exists"); + Dbg.Assert(_topLevelNodes != null, "Shouldn't need to render progress if no data exists"); Dbg.Assert(maxWidth > 0, "maxWidth is too small"); Dbg.Assert(maxHeight >= 3, "maxHeight is too small"); - if (topLevelNodes == null || topLevelNodes.Count <= 0) + if (_topLevelNodes == null || _topLevelNodes.Count <= 0) { // we have nothing to render. @@ -693,7 +693,7 @@ namespace Microsoft.PowerShell string border = new string(' ', maxWidth); result.Add(border); - RenderHelper(result, topLevelNodes, 0, maxWidth, rawUI); + RenderHelper(result, _topLevelNodes, 0, maxWidth, rawUI); if (invisible == 1) { result.Add( @@ -713,11 +713,11 @@ namespace Microsoft.PowerShell result.Add(border); - return (string[]) result.ToArray(typeof(string)); + return (string[])result.ToArray(typeof(string)); } - + /// /// /// Helper function for Render(). Recursively renders nodes. @@ -748,7 +748,7 @@ namespace Microsoft.PowerShell /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// /// - + private void RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI) @@ -780,24 +780,24 @@ namespace Microsoft.PowerShell - private + private class HeightTallyer : NodeVisitor { internal HeightTallyer(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { - this.rawUi = rawUi; - this.maxHeight = maxHeight; - this.maxWidth = maxWidth; + _rawUi = rawUi; + _maxHeight = maxHeight; + _maxWidth = maxWidth; } - internal override + internal override bool Visit(ProgressNode node, ArrayList unused, int unusedToo) { - Tally += node.LinesRequiredMethod(rawUi, maxWidth); + Tally += node.LinesRequiredMethod(_rawUi, _maxWidth); // We don't need to walk all the nodes, once it's larger than the max height, we should stop - if (Tally > maxHeight) + if (Tally > _maxHeight) { return false; } @@ -805,9 +805,9 @@ namespace Microsoft.PowerShell return true; } - private PSHostRawUserInterface rawUi; - private int maxHeight; - private int maxWidth; + private PSHostRawUserInterface _rawUi; + private int _maxHeight; + private int _maxWidth; internal int Tally; } @@ -842,7 +842,7 @@ namespace Microsoft.PowerShell private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { HeightTallyer ht = new HeightTallyer(rawUi, maxHeight, maxWidth); - NodeVisitor.VisitNodes(topLevelNodes, ht); + NodeVisitor.VisitNodes(_topLevelNodes, ht); return ht.Tally; } @@ -869,7 +869,7 @@ namespace Microsoft.PowerShell for (int i = 0; i < nodes.Count; ++i) { - ProgressNode node = (ProgressNode) nodes[i]; + ProgressNode node = (ProgressNode)nodes[i]; Dbg.Assert(node != null, "nodes should not contain null elements"); if (node.Style != style) @@ -888,7 +888,7 @@ namespace Microsoft.PowerShell return true; } - + /// /// @@ -913,8 +913,8 @@ namespace Microsoft.PowerShell Count; } - - + + /// /// /// Debugging code. Counts the number of nodes in the tree of nodes. @@ -926,12 +926,12 @@ namespace Microsoft.PowerShell /// /// - private + private int CountNodes() { CountingNodeVisitor cnv = new CountingNodeVisitor(); - NodeVisitor.VisitNodes(topLevelNodes, cnv); + NodeVisitor.VisitNodes(_topLevelNodes, cnv); return cnv.Count; } @@ -999,7 +999,7 @@ namespace Microsoft.PowerShell do { - ProgressNode node = FindOldestNodeOfGivenStyle(topLevelNodes, age, priorStyle); + ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, age, priorStyle); if (node == null) { // We've compressed every node of the prior style already. @@ -1020,10 +1020,10 @@ namespace Microsoft.PowerShell #if DEBUG || ASSERTIONS_TRACE Dbg.Assert( - nodesCompressed == CountNodes(), + nodesCompressed == CountNodes(), "We should have compressed every node in the tree."); Dbg.Assert( - AllNodesHaveGivenStyle(topLevelNodes, newStyle), + AllNodesHaveGivenStyle(_topLevelNodes, newStyle), "We should have compressed every node in the tree."); #endif @@ -1064,12 +1064,12 @@ namespace Microsoft.PowerShell /// The number of nodes that were made invisible during the compression. /// /// - + private int CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { - Dbg.Assert(topLevelNodes != null, "Shouldn't need to compress if no data exists"); + Dbg.Assert(_topLevelNodes != null, "Shouldn't need to compress if no data exists"); int nodesCompressed = 0; @@ -1091,10 +1091,10 @@ namespace Microsoft.PowerShell if ( CompressToFitHelper( rawUi, - maxHeight, + maxHeight, maxWidth, - out nodesCompressed, - ProgressNode.RenderStyle.Full, + out nodesCompressed, + ProgressNode.RenderStyle.Full, ProgressNode.RenderStyle.Compact)) { return 0; @@ -1103,10 +1103,10 @@ namespace Microsoft.PowerShell if ( CompressToFitHelper( rawUi, - maxHeight, + maxHeight, maxWidth, - out nodesCompressed, - ProgressNode.RenderStyle.Compact, + out nodesCompressed, + ProgressNode.RenderStyle.Compact, ProgressNode.RenderStyle.Minimal)) { return 0; @@ -1115,10 +1115,10 @@ namespace Microsoft.PowerShell if ( CompressToFitHelper( rawUi, - maxHeight, + maxHeight, maxWidth, - out nodesCompressed, - ProgressNode.RenderStyle.Minimal, + out nodesCompressed, + ProgressNode.RenderStyle.Minimal, ProgressNode.RenderStyle.Invisible)) { // The nodes that we compressed here are now invisible. @@ -1130,7 +1130,7 @@ namespace Microsoft.PowerShell return 0; } - + @@ -1168,7 +1168,7 @@ namespace Microsoft.PowerShell /// true to continue visiting nodes, false if not. /// /// - + internal abstract bool Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound); @@ -1205,11 +1205,10 @@ namespace Microsoft.PowerShell - private ArrayList topLevelNodes = new ArrayList(); - private int nodeCount; + private ArrayList _topLevelNodes = new ArrayList(); + private int _nodeCount; private const int maxNodeCount = 128; } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index f876f94cf..a5c1515fc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell /// outstanding activities received by the host, and rendering them in the console. /// /// - + internal class ProgressNode : ProgressRecord @@ -31,14 +31,14 @@ namespace Microsoft.PowerShell /// Indicates the various layouts for rendering a particular node. Each style is progressively less terse. /// /// - + internal enum RenderStyle { Invisible = 0, Minimal = 1, - Compact = 2, + Compact = 2, /// /// Allocate only one line for displaying the StatusDescription or the CurrentOperation, @@ -59,7 +59,7 @@ namespace Microsoft.PowerShell /// Constructs an instance from a ProgressRecord. /// /// - + internal ProgressNode(Int64 sourceId, ProgressRecord record) : @@ -166,7 +166,7 @@ namespace Microsoft.PowerShell /// Indicate if the full StatusDescription and CurrentOperation should be displayed. /// /// - + private void RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus) @@ -258,7 +258,6 @@ namespace Microsoft.PowerShell { oldDescription = StringUtil.Format(" {0}{1}", indent, oldDescription.Substring(newDescription.Length)); } - } while (isFullPlus); } @@ -323,8 +322,8 @@ namespace Microsoft.PowerShell StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format( - " {0}{1}{2}{3} ", - indent, + " {0}{1}{2}{3} ", + indent, percent, secRemain, StatusDescription), @@ -397,20 +396,20 @@ namespace Microsoft.PowerShell " {0}{1} {2}{3}{4} ", indent, Activity, - percent, + percent, secRemain, StatusDescription), maxWidth)); } - - + + /// /// /// The nodes that have this node as their parent. /// /// - + internal ArrayList Children; @@ -429,7 +428,7 @@ namespace Microsoft.PowerShell /// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first. /// /// - + internal int Age; @@ -441,7 +440,7 @@ namespace Microsoft.PowerShell /// The style in which this node should be rendered. /// /// - + internal RenderStyle Style = RenderStyle.FullPlus; @@ -569,10 +568,10 @@ namespace Microsoft.PowerShell get { // Since the fields of this instance could have been changed, we compute this on-the-fly. - + // NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to // word-wrap text fields, then this calculation will need updating. - + // Start with 1 for the Activity, and 1 for the Status. int lines = 2; @@ -585,7 +584,6 @@ namespace Microsoft.PowerShell } } } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 466864c0d..99a394964 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell /// progress updates are shown. /// /// - + internal class ProgressPane { @@ -34,17 +34,17 @@ namespace Microsoft.PowerShell /// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden. /// /// - + internal ProgressPane(ConsoleHostUserInterface ui) { if (ui == null) throw new ArgumentNullException("ui"); - this.ui = ui; - this.rawui = ui.RawUI; + _ui = ui; + _rawui = ui.RawUI; } - - + + /// /// /// Indicates whether the pane is visible on the screen buffer or not. @@ -55,14 +55,14 @@ namespace Microsoft.PowerShell /// true if the pane is visible, false if not. /// /// - + internal bool IsShowing { - get + get { - return (savedRegion != null); + return (_savedRegion != null); } } @@ -74,7 +74,7 @@ namespace Microsoft.PowerShell /// that it can be restored again. /// /// - + internal void Show() @@ -83,7 +83,7 @@ namespace Microsoft.PowerShell { // Get temporary reference to the progress region since it can be // changed at any time by a call to WriteProgress. - BufferCell[,] tempProgressRegion = progressRegion; + BufferCell[,] tempProgressRegion = _progressRegion; if (tempProgressRegion == null) { return; @@ -93,40 +93,40 @@ namespace Microsoft.PowerShell int rows = tempProgressRegion.GetLength(0); int cols = tempProgressRegion.GetLength(1); - location = rawui.WindowPosition; + _location = _rawui.WindowPosition; // We have to show the progress pane in the first column, as the screen buffer at any point might contain // a CJK double-cell characters, which makes it impractical to try to find a position where the pane would // not slice a character. Column 0 is the only place where we know for sure we can place the pane. - location.X = 0; - location.Y = Math.Min(location.Y + 2, bufSize.Height); + _location.X = 0; + _location.Y = Math.Min(_location.Y + 2, _bufSize.Height); #if UNIX // replace the saved region in the screen buffer with our progress display - location = rawui.CursorPosition; + _location = _rawui.CursorPosition; //set the cursor position back to the beginning of the region to overwrite write-progress //if the cursor is at the bottom, back it up to overwrite the previous write progress - if (location.Y >= rawui.BufferSize.Height - rows) + if (_location.Y >= _rawui.BufferSize.Height - rows) { Console.Out.Write('\n'); - if (location.Y >= rows) + if (_location.Y >= rows) { - location.Y -= rows; + _location.Y -= rows; } } - rawui.CursorPosition = location; + _rawui.CursorPosition = _location; #else // Save off the current contents of the screen buffer in the region that we will occupy - savedRegion = - rawui.GetBufferContents( - new Rectangle(location.X, location.Y, location.X + cols - 1, location.Y + rows - 1)); + _savedRegion = + _rawui.GetBufferContents( + new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1)); #endif // replace the saved region in the screen buffer with our progress display - rawui.SetBufferContents(location, tempProgressRegion); + _rawui.SetBufferContents(_location, tempProgressRegion); } } @@ -150,8 +150,8 @@ namespace Microsoft.PowerShell // detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would // be very complicated. - rawui.SetBufferContents(location, savedRegion); - savedRegion = null; + _rawui.SetBufferContents(_location, _savedRegion); + _savedRegion = null; } } @@ -167,41 +167,41 @@ namespace Microsoft.PowerShell /// A PendingProgress instance that represents the outstanding activities that should be shown. /// /// - + internal void Show(PendingProgress pendingProgress) { Dbg.Assert(pendingProgress != null, "pendingProgress may not be null"); - bufSize = rawui.BufferSize; + _bufSize = _rawui.BufferSize; // In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer, // we use the full width of the buffer. - int maxWidth = bufSize.Width; - int maxHeight = Math.Max(5, rawui.WindowSize.Height / 3); + int maxWidth = _bufSize.Width; + int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3); - string[] contents = pendingProgress.Render(maxWidth, maxHeight, rawui); + string[] contents = pendingProgress.Render(maxWidth, maxHeight, _rawui); if (contents == null) { // There's nothing to show. Hide(); - progressRegion = null; + _progressRegion = null; return; } // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... - BufferCell[,] newRegion = rawui.NewBufferCellArray(contents, ui.ProgressForegroundColor, ui.ProgressBackgroundColor); + BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); - if (progressRegion == null) + if (_progressRegion == null) { // we've never shown this pane before. - progressRegion = newRegion; + _progressRegion = newRegion; Show(); } else @@ -216,11 +216,11 @@ namespace Microsoft.PowerShell // would usually result in detection of a change, so why bother? bool sizeChanged = - (newRegion.GetLength(0) != progressRegion.GetLength(0)) - || (newRegion.GetLength(1) != progressRegion.GetLength(1)) + (newRegion.GetLength(0) != _progressRegion.GetLength(0)) + || (newRegion.GetLength(1) != _progressRegion.GetLength(1)) ? true : false; - progressRegion = newRegion; + _progressRegion = newRegion; if (sizeChanged) { @@ -232,19 +232,19 @@ namespace Microsoft.PowerShell } else { - rawui.SetBufferContents(location, progressRegion); + _rawui.SetBufferContents(_location, _progressRegion); } } } - private Coordinates location = new Coordinates(0, 0); - private Size bufSize; - private BufferCell[,] savedRegion; - private BufferCell[,] progressRegion; - private PSHostRawUserInterface rawui; - private ConsoleHostUserInterface ui; + private Coordinates _location = new Coordinates(0, 0); + private Size _bufSize; + private BufferCell[,] _savedRegion; + private BufferCell[,] _progressRegion; + private PSHostRawUserInterface _rawui; + private ConsoleHostUserInterface _ui; } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 8647781aa..dee202393 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -36,8 +36,6 @@ namespace Microsoft.PowerShell internal enum DataFormat { - - /// /// /// text format -- i.e. stream text just as out-default would display it. @@ -64,7 +62,7 @@ namespace Microsoft.PowerShell - protected + protected Serialization(DataFormat dataFormat, string streamName) { Dbg.Assert(!string.IsNullOrEmpty(streamName), "stream needs a name"); @@ -100,8 +98,8 @@ namespace Microsoft.PowerShell XmlWriterSettings settings = new XmlWriterSettings(); settings.CheckCharacters = false; settings.OmitXmlDeclaration = true; - xmlWriter = XmlWriter.Create(textWriter, settings); - xmlSerializer = new Serializer(xmlWriter); + _xmlWriter = XmlWriter.Create(textWriter, settings); + _xmlSerializer = new Serializer(_xmlWriter); break; case DataFormat.Text: default: @@ -130,12 +128,12 @@ namespace Microsoft.PowerShell case DataFormat.None: break; case DataFormat.XML: - if (firstCall) + if (_firstCall) { - firstCall = false; + _firstCall = false; textWriter.WriteLine(Serialization.XmlCliTag); } - xmlSerializer.Serialize(o, streamName); + _xmlSerializer.Serialize(o, streamName); break; case DataFormat.Text: default: @@ -156,8 +154,8 @@ namespace Microsoft.PowerShell break; case DataFormat.XML: - xmlSerializer.Done(); - xmlSerializer = null; + _xmlSerializer.Done(); + _xmlSerializer = null; break; case DataFormat.Text: @@ -170,9 +168,9 @@ namespace Microsoft.PowerShell internal TextWriter textWriter; - private XmlWriter xmlWriter; - private Serializer xmlSerializer; - bool firstCall = true; + private XmlWriter _xmlWriter; + private Serializer _xmlSerializer; + private bool _firstCall = true; } @@ -192,8 +190,8 @@ namespace Microsoft.PowerShell return; textReader = input; - firstLine = textReader.ReadLine(); - if (String.Compare(firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0) + _firstLine = textReader.ReadLine(); + if (String.Compare(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0) { // format should be XML @@ -203,8 +201,8 @@ namespace Microsoft.PowerShell switch (format) { case DataFormat.XML: - xmlReader = XmlReader.Create(textReader); - xmlDeserializer = new Deserializer(xmlReader); + _xmlReader = XmlReader.Create(textReader); + _xmlDeserializer = new Deserializer(_xmlReader); break; case DataFormat.Text: default: @@ -224,31 +222,31 @@ namespace Microsoft.PowerShell switch (format) { case DataFormat.None: - atEnd = true; + _atEnd = true; return null; case DataFormat.XML: string unused; - o = xmlDeserializer.Deserialize(out unused); + o = _xmlDeserializer.Deserialize(out unused); break; case DataFormat.Text: default: - if (atEnd) + if (_atEnd) { return null; } - if (firstLine != null) + if (_firstLine != null) { - o = firstLine; - firstLine = null; + o = _firstLine; + _firstLine = null; } else { o = textReader.ReadLine(); if (o == null) { - atEnd = true; + _atEnd = true; } } break; @@ -268,17 +266,17 @@ namespace Microsoft.PowerShell switch (format) { case DataFormat.None: - atEnd = true; + _atEnd = true; result = true; break; case DataFormat.XML: - result = xmlDeserializer.Done(); + result = _xmlDeserializer.Done(); break; case DataFormat.Text: default: - result = atEnd; + result = _atEnd; break; } return result; @@ -305,12 +303,11 @@ namespace Microsoft.PowerShell internal TextReader textReader; - private XmlReader xmlReader; - private Deserializer xmlDeserializer; - private string firstLine; - bool atEnd; + private XmlReader _xmlReader; + private Deserializer _xmlDeserializer; + private string _firstLine; + private bool _atEnd; } - } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index c6c2c77a7..7bf968163 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -33,19 +33,19 @@ namespace Microsoft.PowerShell.Commands /// /// /// - + [Parameter(Position = 0, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty] public string Path { get { - return outFilename; + return _outFilename; } set { - isFilenameSet = true; - outFilename = value; + _isFilenameSet = true; + _outFilename = value; } } @@ -59,16 +59,16 @@ namespace Microsoft.PowerShell.Commands { get { - return outFilename; + return _outFilename; } set { - isFilenameSet = true; - outFilename = value; - isLiteralPath = true; + _isFilenameSet = true; + _outFilename = value; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// The literal name of the file in which to write the transcript. @@ -86,17 +86,17 @@ namespace Microsoft.PowerShell.Commands /// /// /// - + [Parameter] public SwitchParameter Append { get { - return shouldAppend; + return _shouldAppend; } set { - shouldAppend = value; + _shouldAppend = value; } } @@ -107,20 +107,20 @@ namespace Microsoft.PowerShell.Commands /// /// The read-only attribute will not be replaced when the transcript is done. /// - + [Parameter()] public SwitchParameter Force { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Property that prevents file overwrite. @@ -131,14 +131,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noclobber; + return _noclobber; } set { - noclobber = value; + _noclobber = value; } } - private bool noclobber; + private bool _noclobber; /// /// Whether to include command invocation time headers between commands. @@ -157,35 +157,35 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // If they haven't specified a path, figure out the correct output path. - if (!isFilenameSet) + if (!_isFilenameSet) { // read the filename from $TRANSCRIPT object value = this.GetVariableValue("global:TRANSCRIPT", null); - + // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt) if (value == null) { // If they've specified an output directory, use it. Otherwise, use "My Documents" - if(OutputDirectory != null) + if (OutputDirectory != null) { - outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); - isLiteralPath = true; + _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); + _isLiteralPath = true; } else { - outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(); + _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(); } } else { - outFilename = (string) value; + _outFilename = (string)value; } } // Normalize outFilename here in case it is a relative path try { - string effectiveFilePath = ResolveFilePath(Path, isLiteralPath); + string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath); if (!ShouldProcess(effectiveFilePath)) return; @@ -200,7 +200,7 @@ namespace Microsoft.PowerShell.Commands Exception uae = new UnauthorizedAccessException(message); ErrorRecord errorRecord = new ErrorRecord( uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath); - + // NOTE: this call will throw ThrowTerminatingError(errorRecord); } @@ -225,16 +225,16 @@ namespace Microsoft.PowerShell.Commands } // If they didn't specify -Append, delete the file - if (!shouldAppend) + if (!_shouldAppend) { System.IO.File.Delete(effectiveFilePath); } } - System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = + System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool()); - + // ch.StartTranscribing(effectiveFilePath, Append); // NTRAID#Windows Out Of Band Releases-931008-2006/03/21 @@ -335,9 +335,9 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(errorRecord); } - private bool shouldAppend; - private string outFilename; - private bool isFilenameSet; + private bool _shouldAppend; + private string _outFilename; + private bool _isFilenameSet; } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index f9340f912..deb3960cb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -28,12 +28,12 @@ namespace Microsoft.PowerShell.Commands /// /// Starts the transcription /// - + protected override void BeginProcessing() { - try + try { string outFilename = Host.UI.StopTranscribing(); if (outFilename != null) diff --git a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/AssemblyInfo.cs b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/AssemblyInfo.cs index a0aa90969..9de8c21e8 100644 --- a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/AssemblyInfo.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; using System.Reflection; -[assembly:InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly:InternalsVisibleTo("powershell,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly:AssemblyFileVersionAttribute("1.0.0.0")] -[assembly:AssemblyVersion("1.0.0.0")] +[assembly: InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("powershell,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: AssemblyFileVersionAttribute("1.0.0.0")] +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/AssemblyMetadataHelper.cs b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/AssemblyMetadataHelper.cs index 062ff320e..b06662f2e 100644 --- a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/AssemblyMetadataHelper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/AssemblyMetadataHelper.cs @@ -25,7 +25,7 @@ namespace System.Management.Automation AssemblyHashAlgorithm hashAlgorithm = assemblyDefinition.HashAlgorithm; BlobHandle blobHandle = assemblyDefinition.PublicKey; BlobReader blobReader = metadataReader.GetBlobReader(blobHandle); - + string publicKeyTokenString = "null"; // Extract public key token only if PublicKey exists in the metadata if (blobReader.Length > 0) @@ -65,7 +65,7 @@ namespace System.Management.Automation // Convert bytes to hex format strings in lower case. publicKeyTokenString = BitConverter.ToString(publicKeyTokenBytes).Replace("-", string.Empty).ToLowerInvariant(); } - + string strongAssemblyName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", asmName, asmVersion, asmCulture, publicKeyTokenString); diff --git a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs index 6cf0d58b8..99a5cb757 100644 --- a/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/Microsoft.PowerShell.CoreCLR.AssemblyLoadContext/CoreCLR/CorePsAssemblyLoadContext.cs @@ -46,7 +46,7 @@ namespace System.Management.Automation /// internal static PowerShellAssemblyLoadContext InitializeSingleton(string basePaths, bool useResolvingHandlerOnly) { - lock (syncObj) + lock (s_syncObj) { if (Instance != null) throw new InvalidOperationException(SingletonAlreadyInitialized); @@ -89,10 +89,10 @@ namespace System.Management.Automation throw new ArgumentNullException("basePaths"); } - this.basePaths = basePaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < this.basePaths.Length; i++) + _basePaths = basePaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < _basePaths.Length; i++) { - string basePath = this.basePaths[i]; + string basePath = _basePaths[i]; if (!Directory.Exists(basePath)) { string message = string.Format( @@ -101,31 +101,31 @@ namespace System.Management.Automation basePath); throw new ArgumentException(message, "basePaths"); } - this.basePaths[i] = basePath.Trim(); + _basePaths[i] = basePath.Trim(); } #endregion Validation // FIRST: Add basePaths to probing paths - this.probingPaths = new List(this.basePaths); + _probingPaths = new List(_basePaths); // NEXT: Initialize the CoreCLR type catalog dictionary [OrdinalIgnoreCase] - coreClrTypeCatalog = InitializeTypeCatalog(); + _coreClrTypeCatalog = InitializeTypeCatalog(); // LAST: Handle useResolvingHandlerOnly flag - this.useResolvingHandlerOnly = useResolvingHandlerOnly; - this.activeLoadContext = useResolvingHandlerOnly ? Default : this; + _useResolvingHandlerOnly = useResolvingHandlerOnly; + _activeLoadContext = useResolvingHandlerOnly ? Default : this; if (useResolvingHandlerOnly) { Default.Resolving += Resolve; } else { - var tempSet = new HashSet(coreClrTypeCatalog.Values, StringComparer.OrdinalIgnoreCase); - tpaSet = new HashSet(StringComparer.OrdinalIgnoreCase); + var tempSet = new HashSet(_coreClrTypeCatalog.Values, StringComparer.OrdinalIgnoreCase); + _tpaSet = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string tpa in tempSet) { string shortName = tpa.Substring(0, tpa.IndexOf(',')); - tpaSet.Add(shortName); + _tpaSet.Add(shortName); } } } @@ -133,23 +133,23 @@ namespace System.Management.Automation #endregion Constructor #region Fields - - private readonly bool useResolvingHandlerOnly; - private readonly AssemblyLoadContext activeLoadContext; - private readonly static object syncObj = new object(); - private readonly string[] basePaths; + + private readonly bool _useResolvingHandlerOnly; + private readonly AssemblyLoadContext _activeLoadContext; + private readonly static object s_syncObj = new object(); + private readonly string[] _basePaths; // Initially, 'probingPaths' only contains psbase path. But every time we load an assembly through 'LoadFrom(string AssemblyPath)', we // add its parent path to 'probingPaths', so that we are able to support implicit loading of an assembly from the same place where the // requesting assembly is located. // We don't need to worry about removing any paths from 'probingPaths', because once an assembly is loaded, it won't be unloaded until // the current process exits, and thus the assembly itself and its parent folder cannot be deleted or renamed. - private readonly List probingPaths; + private readonly List _probingPaths; // CoreCLR type catalog dictionary // - Key: namespace qualified type name (FullName) // - Value: strong name of the TPA that contains the type represented by Key. - private readonly Dictionary coreClrTypeCatalog; - private readonly HashSet tpaSet; - private readonly string[] extensions = new string[] { ".ni.dll", ".dll" }; + private readonly Dictionary _coreClrTypeCatalog; + private readonly HashSet _tpaSet; + private readonly string[] _extensions = new string[] { ".ni.dll", ".dll" }; /// /// Assembly cache accross the AppDomain @@ -165,7 +165,7 @@ namespace System.Management.Automation /// /// Therefore, there is no need to use the full assembly name as the key. Short assembly name is sufficient. /// - private static readonly ConcurrentDictionary AssemblyCache = + private static readonly ConcurrentDictionary s_assemblyCache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); #endregion Fields @@ -199,14 +199,14 @@ namespace System.Management.Automation /// protected override Assembly Load(AssemblyName assemblyName) { - if (useResolvingHandlerOnly) + if (_useResolvingHandlerOnly) throw new NotSupportedException(UseResolvingEventHandlerOnly); // We let the default context load the assemblies included in the type catalog as there // appears to be a bug in .NET with method resolution with system libraries loaded by our // context and not the default. We use the short name because some packages have inconsistent // verions between reference and runtime assemblies. - if (tpaSet.Contains(assemblyName.Name)) + if (_tpaSet.Contains(assemblyName.Name)) return null; return Resolve(this, assemblyName); @@ -223,7 +223,7 @@ namespace System.Management.Automation return asmLoaded; // Prepare to load the assembly - lock (syncObj) + lock (s_syncObj) { // Probe the cache again in case it's already loaded if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) @@ -235,13 +235,13 @@ namespace System.Management.Automation string asmCultureName = assemblyName.CultureName ?? string.Empty; string asmFilePath = null; - for (int i = 0; i < probingPaths.Count; i++) + for (int i = 0; i < _probingPaths.Count; i++) { - string probingPath = probingPaths[i]; + string probingPath = _probingPaths[i]; string asmCulturePath = Path.Combine(probingPath, asmCultureName); - for (int k = 0; k < extensions.Length; k++) + for (int k = 0; k < _extensions.Length; k++) { - string asmFileName = assemblyName.Name + extensions[k]; + string asmFileName = assemblyName.Name + _extensions[k]; asmFilePath = Path.Combine(asmCulturePath, asmFileName); if (File.Exists(asmFilePath)) @@ -269,13 +269,13 @@ namespace System.Management.Automation return null; } - asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) - ? loadContext.LoadFromNativeImagePath(asmFilePath, null) + asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) + ? loadContext.LoadFromNativeImagePath(asmFilePath, null) : loadContext.LoadFromAssemblyPath(asmFilePath); if (asmLoaded != null) { // Add the loaded assembly to the cache - AssemblyCache.TryAdd(assemblyName.Name, asmLoaded); + s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); } } @@ -299,7 +299,7 @@ namespace System.Management.Automation return asmLoaded; // Prepare to load the assembly - lock (syncObj) + lock (s_syncObj) { // Probe the cache again in case it's already loaded if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) @@ -307,18 +307,18 @@ namespace System.Management.Automation // Load the assembly through 'LoadFromNativeImagePath' or 'LoadFromAssemblyPath' asmLoaded = assemblyPath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) - ? activeLoadContext.LoadFromNativeImagePath(assemblyPath, null) - : activeLoadContext.LoadFromAssemblyPath(assemblyPath); + ? _activeLoadContext.LoadFromNativeImagePath(assemblyPath, null) + : _activeLoadContext.LoadFromAssemblyPath(assemblyPath); if (asmLoaded != null) { // Add the loaded assembly to the cache - AssemblyCache.TryAdd(assemblyName.Name, asmLoaded); + s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); // Add its parent path to our probing paths string parentPath = Path.GetDirectoryName(assemblyPath); - if (!probingPaths.Contains(parentPath)) + if (!_probingPaths.Contains(parentPath)) { - probingPaths.Add(parentPath); + _probingPaths.Add(parentPath); } } } @@ -344,18 +344,18 @@ namespace System.Management.Automation return asmLoaded; // Prepare to load the assembly - lock (syncObj) + lock (s_syncObj) { // Probe the cache again in case it's already loaded if (TryGetAssemblyFromCache(assemblyName, out asmLoaded)) return asmLoaded; // Load the assembly through 'LoadFromStream' - asmLoaded = activeLoadContext.LoadFromStream(assembly); + asmLoaded = _activeLoadContext.LoadFromStream(assembly); if (asmLoaded != null) { // Add the loaded assembly to the cache - AssemblyCache.TryAdd(assemblyName.Name, asmLoaded); + s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); } } @@ -374,7 +374,7 @@ namespace System.Management.Automation if (!string.IsNullOrEmpty(namespaceQualifiedTypeName)) { string tpaStrongName; - if (coreClrTypeCatalog.TryGetValue(namespaceQualifiedTypeName, out tpaStrongName)) + if (_coreClrTypeCatalog.TryGetValue(namespaceQualifiedTypeName, out tpaStrongName)) { try { @@ -393,7 +393,7 @@ namespace System.Management.Automation } // Otherwise, we return all assemblies from the AssemblyCache - return AssemblyCache.Values; + return s_assemblyCache.Values; } /// @@ -407,7 +407,7 @@ namespace System.Management.Automation internal bool TryAddAssemblyToCache(Assembly assembly) { AssemblyName asmName = assembly.GetName(); - bool success = AssemblyCache.TryAdd(asmName.Name, assembly); + bool success = s_assemblyCache.TryAdd(asmName.Name, assembly); // Raise AssemblyLoad event if (success) { OnAssemblyLoaded(assembly); } return success; @@ -434,20 +434,20 @@ namespace System.Management.Automation } // Construct the probing paths for searching the specified assembly file - string[] metadataProbingPaths = this.basePaths; + string[] metadataProbingPaths = _basePaths; if (useAdditionalSearchPath) { var searchPaths = new List() { additionalSearchPath }; - searchPaths.AddRange(this.basePaths); + searchPaths.AddRange(_basePaths); metadataProbingPaths = searchPaths.ToArray(); } for (int i = 0; i < metadataProbingPaths.Length; i++) { string metadataProbingPath = metadataProbingPaths[i]; - for (int k = 0; k < extensions.Length; k++) + for (int k = 0; k < _extensions.Length; k++) { - string asmFileName = assemblyShortName + extensions[k]; + string asmFileName = assemblyShortName + _extensions[k]; string asmFilePath = Path.Combine(metadataProbingPath, asmFileName); if (File.Exists(asmFilePath)) { @@ -465,7 +465,7 @@ namespace System.Management.Automation /// internal IEnumerable GetAvailableDotNetTypes() { - return coreClrTypeCatalog.Keys; + return _coreClrTypeCatalog.Keys; } /// @@ -482,8 +482,8 @@ namespace System.Management.Automation /// internal void SetProfileOptimizationRootImpl(string directoryPath) { - if (this.useResolvingHandlerOnly) - activeLoadContext.SetProfileOptimizationRoot(directoryPath); + if (_useResolvingHandlerOnly) + _activeLoadContext.SetProfileOptimizationRoot(directoryPath); } /// @@ -500,8 +500,8 @@ namespace System.Management.Automation /// internal void StartProfileOptimizationImpl(string profile) { - if (this.useResolvingHandlerOnly) - activeLoadContext.StartProfileOptimization(profile); + if (_useResolvingHandlerOnly) + _activeLoadContext.StartProfileOptimization(profile); } #endregion Protected_Internal_Methods @@ -516,10 +516,12 @@ namespace System.Management.Automation Action assemblyLoadHandler = AssemblyLoad; if (assemblyLoaded != null && assemblyLoadHandler != null) { - try { + try + { assemblyLoadHandler(assemblyLoaded); } - catch { + catch + { // Catch all exceptions, same behavior as AppDomain.AssemblyLoad } } @@ -539,7 +541,7 @@ namespace System.Management.Automation { throw new ArgumentException(AbsolutePathRequired, parameterName); } - + if (!File.Exists(assemblyPath)) { ThrowFileNotFoundException( @@ -554,7 +556,7 @@ namespace System.Management.Automation assemblyPath); } } - + /// /// Get AssemblyName of an assembly stream /// @@ -569,7 +571,7 @@ namespace System.Management.Automation MetadataReader metadataReader = peReader.GetMetadataReader(); strongAssemblyName = AssemblyMetadataHelper.GetAssemblyStrongName(metadataReader); } - + assembly.Seek(0, SeekOrigin.Begin); return new AssemblyName(strongAssemblyName); } @@ -579,7 +581,7 @@ namespace System.Management.Automation /// private bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded) { - if (AssemblyCache.TryGetValue(assemblyName.Name, out asmLoaded)) + if (s_assemblyCache.TryGetValue(assemblyName.Name, out asmLoaded)) { // Check if loaded assembly matches the request if (IsAssemblyMatching(assemblyName, asmLoaded.GetName())) @@ -687,7 +689,7 @@ namespace System.Management.Automation /// public class PowerShellAssemblyLoadContextInitializer { - private static object[] EmptyArray = new object[0]; + private static object[] s_emptyArray = new object[0]; /// /// Create a singleton of PowerShellAssemblyLoadContext. @@ -798,7 +800,7 @@ namespace System.Management.Automation if (string.IsNullOrEmpty(entryMethodName)) throw new ArgumentNullException("entryMethodName"); - args = args ?? EmptyArray; + args = args ?? s_emptyArray; var psLoadContext = PowerShellAssemblyLoadContext.InitializeSingleton(basePaths, useResolvingHandlerOnly: false); var entryAssembly = psLoadContext.LoadFromAssemblyName(entryAssemblyName); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs index 5b6784900..9fd13be4e 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs @@ -1,5 +1,5 @@ using System.Runtime.CompilerServices; using System.Reflection; -[assembly:InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly:AssemblyFileVersionAttribute("1.0.0.0")] -[assembly:AssemblyVersion("1.0.0.0")] +[assembly: InternalsVisibleTo("System.Management.Automation,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: AssemblyFileVersionAttribute("1.0.0.0")] +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs index 2c5cb5253..41c587577 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -14,19 +14,19 @@ namespace System.Diagnostics.Eventing public struct EventDescriptor { [FieldOffset(0)] - private ushort m_id; + private ushort _id; [FieldOffset(2)] - private byte m_version; + private byte _version; [FieldOffset(3)] - private byte m_channel; + private byte _channel; [FieldOffset(4)] - private byte m_level; + private byte _level; [FieldOffset(5)] - private byte m_opcode; + private byte _opcode; [FieldOffset(6)] - private ushort m_task; + private ushort _task; [FieldOffset(8)] - private long m_keywords; + private long _keywords; [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] public EventDescriptor( @@ -49,12 +49,12 @@ namespace System.Diagnostics.Eventing throw new ArgumentOutOfRangeException("id", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); } - m_id = (ushort)id; - m_version = version; - m_channel = channel; - m_level = level; - m_opcode = opcode; - m_keywords = keywords; + _id = (ushort)id; + _version = version; + _channel = channel; + _level = level; + _opcode = opcode; + _keywords = keywords; if (task < 0) { @@ -66,12 +66,14 @@ namespace System.Diagnostics.Eventing throw new ArgumentOutOfRangeException("task", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); } - m_task = (ushort)task; + _task = (ushort)task; } - public int EventId { - get { - return m_id; + public int EventId + { + get + { + return _id; } } @@ -79,7 +81,7 @@ namespace System.Diagnostics.Eventing { get { - return m_version; + return _version; } } @@ -87,14 +89,14 @@ namespace System.Diagnostics.Eventing { get { - return m_channel; + return _channel; } } public byte Level { get { - return m_level; + return _level; } } @@ -103,7 +105,7 @@ namespace System.Diagnostics.Eventing { get { - return m_opcode; + return _opcode; } } @@ -111,7 +113,7 @@ namespace System.Diagnostics.Eventing { get { - return m_task; + return _task; } } @@ -119,7 +121,7 @@ namespace System.Diagnostics.Eventing { get { - return m_keywords; + return _keywords; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 95f58dcbc..67c40783c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -11,19 +11,19 @@ using System.Threading; using System.Security; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing{ - - public class EventProvider : IDisposable +namespace System.Diagnostics.Eventing +{ + public class EventProvider : IDisposable { [SecurityCritical] - UnsafeNativeMethods.EtwEnableCallback m_etwCallback; // Trace Callback function - private long m_regHandle; // Trace Registration Handle - private byte m_level; // Tracing Level - private long m_anyKeywordMask; // Trace Enable Flags - private long m_allKeywordMask; // Match all keyword - private int m_enabled; // Enabled flag from Trace callback - private Guid m_providerId; // Control Guid - private int m_disposed; // when 1, provider has unregister + private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function + private long _regHandle; // Trace Registration Handle + private byte _level; // Tracing Level + private long _anyKeywordMask; // Trace Enable Flags + private long _allKeywordMask; // Match all keyword + private int _enabled; // Enabled flag from Trace callback + private Guid _providerId; // Control Guid + private int _disposed; // when 1, provider has unregister [ThreadStatic] private static WriteEventErrorCode t_returnCode; // thread slot to keep last error @@ -75,8 +75,8 @@ namespace System.Diagnostics.Eventing{ [SecuritySafeCritical] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] public EventProvider(Guid providerGuid) - { - m_providerId = providerGuid; + { + _providerId = providerGuid; // // EtwRegister the ProviderId with ETW @@ -96,14 +96,13 @@ namespace System.Diagnostics.Eventing{ { uint status; - m_etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack); - - status = UnsafeNativeMethods.EventRegister(ref m_providerId, m_etwCallback, null, ref m_regHandle); + _etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack); + + status = UnsafeNativeMethods.EventRegister(ref _providerId, _etwCallback, null, ref _regHandle); if (status != 0) { throw new Win32Exception((int)status); } - } // @@ -131,9 +130,9 @@ namespace System.Diagnostics.Eventing{ // // check if the object has been already disposed // - if (m_disposed == 1) return; + if (_disposed == 1) return; - if (Interlocked.Exchange(ref m_disposed, 1) != 0) + if (Interlocked.Exchange(ref _disposed, 1) != 0) { // somebody is allready disposing the provider return; @@ -143,7 +142,7 @@ namespace System.Diagnostics.Eventing{ // Disables Tracing in the provider, then unregister // - m_enabled = 0; + _enabled = 0; Deregister(); } @@ -173,15 +172,15 @@ namespace System.Diagnostics.Eventing{ // the register call. // - if (m_regHandle != 0) + if (_regHandle != 0) { - UnsafeNativeMethods.EventUnregister(m_regHandle); - m_regHandle = 0; + UnsafeNativeMethods.EventUnregister(_regHandle); + _regHandle = 0; } } [System.Security.SecurityCritical] - unsafe void EtwEnableCallBack( + private unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int isEnabled, [In] byte setLevel, @@ -191,11 +190,10 @@ namespace System.Diagnostics.Eventing{ [In] void* callbackContext ) { - - m_enabled = isEnabled; - m_level = setLevel; - m_anyKeywordMask = anyKeyword; - m_allKeywordMask = allKeyword; + _enabled = isEnabled; + _level = setLevel; + _anyKeywordMask = anyKeyword; + _allKeywordMask = allKeyword; return; } @@ -204,7 +202,7 @@ namespace System.Diagnostics.Eventing{ /// public bool IsEnabled() { - return (m_enabled != 0) ? true : false; + return (_enabled != 0) ? true : false; } /// @@ -218,28 +216,26 @@ namespace System.Diagnostics.Eventing{ /// public bool IsEnabled(byte level, long keywords) { - // // If not enabled at all, return false. // - if (m_enabled == 0) + if (_enabled == 0) { return false; } // This also covers the case of Level == 0. - if ((level <= m_level) || - (m_level == 0)) + if ((level <= _level) || + (_level == 0)) { - // // Check if Keyword is enabled // if ((keywords == 0) || - (((keywords & m_anyKeywordMask) != 0) && - ((keywords & m_allKeywordMask) == m_allKeywordMask))) + (((keywords & _anyKeywordMask) != 0) && + ((keywords & _allKeywordMask) == _allKeywordMask))) { return true; } @@ -251,12 +247,13 @@ namespace System.Diagnostics.Eventing{ public static WriteEventErrorCode GetLastWriteEventError() { return t_returnCode; - } + } // // Helper function to set the last error on the thread // - private static void SetLastError(int error){ + private static void SetLastError(int error) + { switch (error) { case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW: @@ -465,7 +462,7 @@ namespace System.Diagnostics.Eventing{ { fixed (char* pdata = eventMessage) { - status = (int)UnsafeNativeMethods.EventWriteString(m_regHandle, eventLevel, eventKeywords, pdata); + status = (int)UnsafeNativeMethods.EventWriteString(_regHandle, eventLevel, eventKeywords, pdata); } if (status != 0) @@ -499,9 +496,9 @@ namespace System.Diagnostics.Eventing{ /// /// /// - public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload) + public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload) { - return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload); + return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload); } /// @@ -528,13 +525,13 @@ namespace System.Diagnostics.Eventing{ { if (data.Length > s_traceEventMaximumStringSize) { - t_returnCode = WriteEventErrorCode.EventTooBig; + t_returnCode = WriteEventErrorCode.EventTooBig; return false; } EventData userData; - userData.Size = (uint)((data.Length +1)* 2); + userData.Size = (uint)((data.Length + 1) * 2); userData.Reserved = 0; unsafe @@ -544,7 +541,7 @@ namespace System.Diagnostics.Eventing{ Guid activityId = GetActivityId(); userData.DataPointer = (ulong)pdata; - status = UnsafeNativeMethods.EventWriteTransfer(m_regHandle, + status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, @@ -584,7 +581,7 @@ namespace System.Diagnostics.Eventing{ Guid activityId = GetActivityId(); status = UnsafeNativeMethods.EventWriteTransfer( - m_regHandle, + _regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, @@ -598,7 +595,6 @@ namespace System.Diagnostics.Eventing{ return false; } return true; - } @@ -625,7 +621,7 @@ namespace System.Diagnostics.Eventing{ { int argCount = 0; EventData* userDataPtr = null; - + if ((eventPayload != null) && (eventPayload.Length != 0)) { argCount = eventPayload.Length; @@ -655,7 +651,7 @@ namespace System.Diagnostics.Eventing{ // size value set in EncodeObjec method. // for (index = 0; index < eventPayload.Length; index++) - { + { string isString; isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); currentBuffer += s_basicTypeAllocationBufferSize; @@ -674,7 +670,7 @@ namespace System.Diagnostics.Eventing{ throw new ArgumentOutOfRangeException("eventPayload", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); } - } + } } if (totalEventSize > s_traceEventMaximumSize) @@ -722,7 +718,7 @@ namespace System.Diagnostics.Eventing{ } } - status = UnsafeNativeMethods.EventWriteTransfer(m_regHandle, + status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, (relatedActivityId == Guid.Empty) ? null : &relatedActivityId, @@ -743,17 +739,17 @@ namespace System.Diagnostics.Eventing{ protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) { uint status = 0; - - Guid activityId = GetActivityId(); - + + Guid activityId = GetActivityId(); + unsafe - { + { status = UnsafeNativeMethods.EventWriteTransfer( - m_regHandle, + _regHandle, ref eventDescriptor, - (activityId == Guid.Empty) ? null : &activityId, - &relatedActivityId, - (uint)dataCount, + (activityId == Guid.Empty) ? null : &activityId, + &relatedActivityId, + (uint)dataCount, (void*)data); } @@ -767,7 +763,7 @@ namespace System.Diagnostics.Eventing{ [System.Security.SecurityCritical] private static Guid GetActivityId() - { + { return t_activityId; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index b335f0f03..72bdbfbab 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -8,8 +8,8 @@ using System.Text; using System.Globalization; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing{ - +namespace System.Diagnostics.Eventing +{ public class EventProviderTraceListener : TraceListener { // @@ -22,11 +22,11 @@ namespace System.Diagnostics.Eventing{ // Event payload is "delimiter" separated, which can be configured // // - private EventProvider m_provider; + private EventProvider _provider; private const string s_nullStringValue = "null"; private const string s_nullStringComaValue = "null,"; private const string s_nullCStringValue = ": null"; - private string m_delimiter = ";"; + private string _delimiter = ";"; private const uint s_keyWordMask = 0xFFFFFF00; private const int s_defaultPayloadSize = 512; @@ -35,7 +35,7 @@ namespace System.Diagnostics.Eventing{ { get { - return m_delimiter; + return _delimiter; } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] @@ -47,7 +47,7 @@ namespace System.Diagnostics.Eventing{ if (value.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); - m_delimiter = value; + _delimiter = value; } } @@ -78,19 +78,18 @@ namespace System.Diagnostics.Eventing{ if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); - m_delimiter = delimiter; + _delimiter = delimiter; InitProvider(providerId); } private void InitProvider(string providerId) { - Guid controlGuid = new Guid(providerId); // // Create The ETW TraceProvider // - m_provider = new EventProvider(controlGuid); + _provider = new EventProvider(controlGuid); } // @@ -112,18 +111,18 @@ namespace System.Diagnostics.Eventing{ { if (disposing) { - m_provider.Close(); + _provider.Close(); } } public sealed override void Write(string message) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } - m_provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0); + _provider.WriteMessageEvent(message, (byte)TraceEventType.Information, 0); } public sealed override void WriteLine(string message) @@ -139,12 +138,12 @@ namespace System.Diagnostics.Eventing{ // public sealed override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null,null,null,null)) + if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } @@ -160,14 +159,14 @@ namespace System.Diagnostics.Eventing{ dataString.Append(s_nullCStringValue); } - m_provider.WriteMessageEvent(dataString.ToString(), + _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } @@ -176,11 +175,11 @@ namespace System.Diagnostics.Eventing{ { return; } - + int index; StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); - if ((data != null) && (data.Length > 0) ) + if ((data != null) && (data.Length > 0)) { for (index = 0; index < (data.Length - 1); index++) { @@ -209,14 +208,14 @@ namespace System.Diagnostics.Eventing{ dataString.Append(s_nullStringValue); } - m_provider.WriteMessageEvent(dataString.ToString(), + _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } @@ -226,14 +225,14 @@ namespace System.Diagnostics.Eventing{ return; } - m_provider.WriteMessageEvent(String.Empty, + _provider.WriteMessageEvent(String.Empty, (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } @@ -246,14 +245,14 @@ namespace System.Diagnostics.Eventing{ StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); dataString.Append(message); - m_provider.WriteMessageEvent(dataString.ToString(), + _provider.WriteMessageEvent(dataString.ToString(), (byte)eventType, (long)eventType & s_keyWordMask); } public sealed override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { - if (!m_provider.IsEnabled()) + if (!_provider.IsEnabled()) { return; } @@ -265,13 +264,13 @@ namespace System.Diagnostics.Eventing{ if (args == null) { - m_provider.WriteMessageEvent(format, + _provider.WriteMessageEvent(format, (byte)eventType, (long)eventType & s_keyWordMask); } else { - m_provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args), + _provider.WriteMessageEvent(String.Format(CultureInfo.InvariantCulture, format, args), (byte)eventType, (long)eventType & s_keyWordMask); } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs index 4b770ccdd..bb5eafb1c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: CoTaskMemSafeHandle ** ** Purpose: ** This internal class is a SafeHandle implementation over a @@ -15,35 +10,41 @@ using System.Runtime.InteropServices; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ // // Marked as SecurityCritical due to link demands from inherited // SafeHandle members. // [System.Security.SecurityCritical] - internal sealed class CoTaskMemSafeHandle : SafeHandle { - + internal sealed class CoTaskMemSafeHandle : SafeHandle + { internal CoTaskMemSafeHandle() - : base(IntPtr.Zero, true) { + : base(IntPtr.Zero, true) + { } - internal void SetMemory(IntPtr handle) { + internal void SetMemory(IntPtr handle) + { SetHandle(handle); } - internal IntPtr GetMemory() { + internal IntPtr GetMemory() + { return handle; } - - public override bool IsInvalid { - get { + + public override bool IsInvalid + { + get + { return IsClosed || handle == IntPtr.Zero; } } - protected override bool ReleaseHandle() { + protected override bool ReleaseHandle() + { Marshal.FreeCoTaskMem(handle); handle = IntPtr.Zero; return true; @@ -53,9 +54,11 @@ namespace System.Diagnostics.Eventing.Reader { // DONT compare CoTaskMemSafeHandle with CoTaskMemSafeHandle.Zero // use IsInvalid instead. Zero is provided where a NULL handle needed // - - public static CoTaskMemSafeHandle Zero { - get { + + public static CoTaskMemSafeHandle Zero + { + get + { return new CoTaskMemSafeHandle(); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs index a2cc77fb9..651ca6b0a 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: CoTaskMemUnicodeSafeHandle ** ** Purpose: ** This internal class is a SafeHandle implementation over a @@ -15,40 +10,47 @@ using System.Runtime.InteropServices; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ // // Marked as SecurityCritical due to link demands from inherited // SafeHandle members. // [System.Security.SecurityCritical] - internal sealed class CoTaskMemUnicodeSafeHandle : SafeHandle { - + internal sealed class CoTaskMemUnicodeSafeHandle : SafeHandle + { internal CoTaskMemUnicodeSafeHandle() - : base(IntPtr.Zero, true) { + : base(IntPtr.Zero, true) + { } internal CoTaskMemUnicodeSafeHandle(IntPtr handle, bool ownsHandle) - : base(IntPtr.Zero, ownsHandle) { + : base(IntPtr.Zero, ownsHandle) + { SetHandle(handle); } - internal void SetMemory(IntPtr handle) { + internal void SetMemory(IntPtr handle) + { SetHandle(handle); } - internal IntPtr GetMemory() { + internal IntPtr GetMemory() + { return handle; } - - public override bool IsInvalid { - get { + + public override bool IsInvalid + { + get + { return IsClosed || handle == IntPtr.Zero; } } - protected override bool ReleaseHandle() { + protected override bool ReleaseHandle() + { Marshal.ZeroFreeCoTaskMemUnicode(handle); handle = IntPtr.Zero; return true; @@ -56,8 +58,10 @@ namespace System.Diagnostics.Eventing.Reader { // DONT compare CoTaskMemUnicodeSafeHandle with CoTaskMemUnicodeSafeHandle.Zero // use IsInvalid instead. Zero is provided where a NULL handle needed - public static CoTaskMemUnicodeSafeHandle Zero { - get { + public static CoTaskMemUnicodeSafeHandle Zero + { + get + { return new CoTaskMemUnicodeSafeHandle(); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventBookmark.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventBookmark.cs index e4ce4677d..6f697f33d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventBookmark.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventBookmark.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventBookmark ** ** Purpose: ** This public class represents an opaque Event Bookmark obtained @@ -16,30 +11,32 @@ ** ============================================================*/ -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ // // NOTE: This class must be generic enough to be used across // eventing base implementations. Cannot add anything // that ties it to one particular implementation. // - + /// /// Represents an opaque Event Bookmark obtained from an EventRecord. /// The bookmark denotes a unique identifier for the event instance as /// well as marks the location in the the result set of the EventReader /// that the event instance was obtained from. /// - public class EventBookmark { - string bookmark; + public class EventBookmark + { + private string _bookmark; - internal EventBookmark(string bookmarkText) { + internal EventBookmark(string bookmarkText) + { if (bookmarkText == null) throw new ArgumentNullException("bookmarkText"); - this.bookmark = bookmarkText; + _bookmark = bookmarkText; } - internal string BookmarkText { get { return bookmark; } } + internal string BookmarkText { get { return _bookmark; } } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventKeyword.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventKeyword.cs index d44222fa4..9533df1e4 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventKeyword.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventKeyword.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventKeyword ** ** Purpose: ** This public class describes the metadata for a specific Keyword @@ -16,75 +11,88 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the metadata for a specific Keyword defined by a Provider. /// An instance of this class is obtained from a ProviderMetadata object. /// - public sealed class EventKeyword { - private long value; - private string name; - private string displayName; - private bool dataReady; - ProviderMetadata pmReference; - object syncObject; + public sealed class EventKeyword + { + private long _value; + private string _name; + private string _displayName; + private bool _dataReady; + private ProviderMetadata _pmReference; + private object _syncObject; //called from EventMetadata - internal EventKeyword(long value, ProviderMetadata pmReference) { - this.value = value; - this.pmReference = pmReference; - this.syncObject = new object(); + internal EventKeyword(long value, ProviderMetadata pmReference) + { + _value = value; + _pmReference = pmReference; + _syncObject = new object(); } //called from ProviderMetadata - internal EventKeyword(string name, long value, string displayName) { - this.value = value; - this.name = name; - this.displayName = displayName; - this.dataReady = true; - this.syncObject = new object(); + internal EventKeyword(string name, long value, string displayName) + { + _value = value; + _name = name; + _displayName = displayName; + _dataReady = true; + _syncObject = new object(); } - internal void PrepareData() { - if (dataReady == true) return; + internal void PrepareData() + { + if (_dataReady == true) return; - lock (syncObject) { - if (dataReady == true) return; + lock (_syncObject) + { + if (_dataReady == true) return; - IEnumerable result = pmReference.Keywords; + IEnumerable result = _pmReference.Keywords; - this.name = null; - this.displayName = null; - this.dataReady = true; + _name = null; + _displayName = null; + _dataReady = true; - foreach (EventKeyword key in result) { - if (key.Value == this.value) { - this.name = key.Name; - this.displayName = key.DisplayName; + foreach (EventKeyword key in result) + { + if (key.Value == _value) + { + _name = key.Name; + _displayName = key.DisplayName; break; } } } } - public string Name { - get { + public string Name + { + get + { PrepareData(); - return this.name; + return _name; } } - public long Value { - get { - return this.value; + public long Value + { + get + { + return _value; } } - public string DisplayName { - get { + public string DisplayName + { + get + { PrepareData(); - return this.displayName; + return _displayName; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLevel.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLevel.cs index 397d99029..d01dd15e2 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLevel.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLevel.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLevel ** ** Purpose: ** This public class describes the metadata for a specific Level @@ -16,74 +11,86 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the metadata for a specific Level defined by a Provider. /// An instance of this class is obtained from a ProviderMetadata object. /// - public sealed class EventLevel { - - private int value; - private string name; - private string displayName; - private bool dataReady; - ProviderMetadata pmReference; - object syncObject; + public sealed class EventLevel + { + private int _value; + private string _name; + private string _displayName; + private bool _dataReady; + private ProviderMetadata _pmReference; + private object _syncObject; //called from EventMetadata - internal EventLevel(int value, ProviderMetadata pmReference) { - this.value = value; - this.pmReference = pmReference; - this.syncObject = new object(); + internal EventLevel(int value, ProviderMetadata pmReference) + { + _value = value; + _pmReference = pmReference; + _syncObject = new object(); } //called from ProviderMetadata - internal EventLevel(string name, int value, string displayName) { - this.value = value; - this.name = name; - this.displayName = displayName; - this.dataReady = true; - this.syncObject = new object(); + internal EventLevel(string name, int value, string displayName) + { + _value = value; + _name = name; + _displayName = displayName; + _dataReady = true; + _syncObject = new object(); } - internal void PrepareData() { - if (dataReady == true) return; + internal void PrepareData() + { + if (_dataReady == true) return; - lock (syncObject) { - if (dataReady == true) return; + lock (_syncObject) + { + if (_dataReady == true) return; - IEnumerable result = pmReference.Levels; - this.name = null; - this.displayName = null; - this.dataReady = true; - foreach (EventLevel lev in result) { - if (lev.Value == this.value) { - this.name = lev.Name; - this.displayName = lev.DisplayName; + IEnumerable result = _pmReference.Levels; + _name = null; + _displayName = null; + _dataReady = true; + foreach (EventLevel lev in result) + { + if (lev.Value == _value) + { + _name = lev.Name; + _displayName = lev.DisplayName; break; } } } } - public string Name { - get { + public string Name + { + get + { PrepareData(); - return this.name; + return _name; } } - public int Value { - get { - return this.value; + public int Value + { + get + { + return _value; } } - public string DisplayName { - get { + public string DisplayName + { + get + { PrepareData(); - return this.displayName; + return _displayName; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs index 6dc452e40..220dac6e4 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogConfiguration.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogConfiguration ** ** Purpose: ** This public class allows accessing static channel information and @@ -16,12 +11,13 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Log Type /// - public enum EventLogType { + public enum EventLogType + { Administrative = 0, Operational, Analytical, @@ -31,7 +27,8 @@ namespace System.Diagnostics.Eventing.Reader { /// /// Log Isolation /// - public enum EventLogIsolation { + public enum EventLogIsolation + { Application = 0, System, Custom @@ -40,7 +37,8 @@ namespace System.Diagnostics.Eventing.Reader { /// /// Log Mode /// - public enum EventLogMode { + public enum EventLogMode + { Circular = 0, AutoBackup, Retain @@ -50,204 +48,248 @@ namespace System.Diagnostics.Eventing.Reader { /// Provides access to static log information and configures /// log publishing and log file properties. /// - public class EventLogConfiguration : IDisposable { - + public class EventLogConfiguration : IDisposable + { // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // - private EventLogHandle handle = EventLogHandle.Zero; + private EventLogHandle _handle = EventLogHandle.Zero; - private EventLogSession session = null; - private string channelName; + private EventLogSession _session = null; + private string _channelName; public EventLogConfiguration(string logName) : this(logName, null) { } // marked as SecurityCritical because allocates SafeHandles. // marked as Safe because performs Demand check. [System.Security.SecurityCritical] - public EventLogConfiguration(string logName, EventLogSession session) { - + public EventLogConfiguration(string logName, EventLogSession session) + { if (session == null) session = EventLogSession.GlobalSession; - this.session = session; - this.channelName = logName; - - handle = NativeWrapper.EvtOpenChannelConfig(this.session.Handle, this.channelName, 0); + _session = session; + _channelName = logName; + + _handle = NativeWrapper.EvtOpenChannelConfig(_session.Handle, _channelName, 0); } - public string LogName { - get { - return channelName; + public string LogName + { + get + { + return _channelName; } } - public EventLogType LogType { - get { - return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType)); + public EventLogType LogType + { + get + { + return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType)); } } - public EventLogIsolation LogIsolation { - get { - return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation)); + public EventLogIsolation LogIsolation + { + get + { + return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation)); } } - public bool IsEnabled { - get { - return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled); + public bool IsEnabled + { + get + { + return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value); } } - public bool IsClassicLog { - get { - return (bool)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog); + public bool IsClassicLog + { + get + { + return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog); } } - public string SecurityDescriptor { - get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); + public string SecurityDescriptor + { + get + { + return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value); } } - public string LogFilePath { - get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); + public string LogFilePath + { + get + { + return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value); } } - public long MaximumSizeInBytes { - get { - return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)); + public long MaximumSizeInBytes + { + get + { + return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value); } } - public EventLogMode LogMode { - get { - object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention); - object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup); + public EventLogMode LogMode + { + get + { + object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention); + object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup); bool nativeRetention = nativeRetentionObject == null ? false : (bool)nativeRetentionObject; bool nativeAutoBackup = nativeAutoBackupObject == null ? false : (bool)nativeAutoBackupObject; if (nativeAutoBackup) - return EventLogMode.AutoBackup; + return EventLogMode.AutoBackup; if (nativeRetention) return EventLogMode.Retain; return EventLogMode.Circular; } - set { - - switch (value) { + set + { + switch (value) + { case EventLogMode.Circular: - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false); break; case EventLogMode.AutoBackup: - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true); - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); break; case EventLogMode.Retain: - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); break; } } } - public string OwningProviderName { - get { - return (string)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher); + public string OwningProviderName + { + get + { + return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher); } } - public IEnumerable ProviderNames { - get { - return (string[])NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList); + public IEnumerable ProviderNames + { + get + { + return (string[])NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList); } } - public int? ProviderLevel { - get { - return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel)); + public int? ProviderLevel + { + get + { + return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel)); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value); } } - public long? ProviderKeywords { - get { - return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords)); + public long? ProviderKeywords + { + get + { + return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords)); } - set { - NativeWrapper.EvtSetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value); + set + { + NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value); } } - public int? ProviderBufferSize { - get { - return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize)); + public int? ProviderBufferSize + { + get + { + return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize)); } } - public int? ProviderMinimumNumberOfBuffers { - get { - return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers)); + public int? ProviderMinimumNumberOfBuffers + { + get + { + return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers)); } } - public int? ProviderMaximumNumberOfBuffers { - get { - return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers)); + public int? ProviderMaximumNumberOfBuffers + { + get + { + return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers)); } } - public int? ProviderLatency { - get { - return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency)); + public int? ProviderLatency + { + get + { + return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency)); } } - public Guid? ProviderControlGuid { - get { - return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(this.handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid)); + public Guid? ProviderControlGuid + { + get + { + return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid)); } } - public void SaveChanges() { - - NativeWrapper.EvtSaveChannelConfig(this.handle, 0); + public void SaveChanges() + { + NativeWrapper.EvtSaveChannelConfig(_handle, 0); } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - + [System.Security.SecuritySafeCritical] - protected virtual void Dispose(bool disposing) { - - if ( handle != null && !handle.IsInvalid ) - handle.Dispose(); + protected virtual void Dispose(bool disposing) + { + if (_handle != null && !_handle.IsInvalid) + _handle.Dispose(); } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs index 4b4a5e586..0e21caaec 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogException.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogException ** ** Purpose: ** This public class describes an exception thrown from Event @@ -15,12 +10,15 @@ using System.ComponentModel; -namespace System.Diagnostics.Eventing.Reader { - - public class EventLogException : Exception { - internal static void Throw(int errorCode) { - switch (errorCode) { - case 2: +namespace System.Diagnostics.Eventing.Reader +{ + public class EventLogException : Exception + { + internal static void Throw(int errorCode) + { + switch (errorCode) + { + case 2: case 3: case 15007: case 15027: @@ -33,45 +31,48 @@ namespace System.Diagnostics.Eventing.Reader { throw new EventLogInvalidDataException(errorCode); case 1818: // RPC_S_CALL_CANCELED is converted to ERROR_CANCELLED - case 1223: + case 1223: throw new OperationCanceledException(); - case 15037: + case 15037: throw new EventLogProviderDisabledException(errorCode); - case 5: + case 5: throw new UnauthorizedAccessException(); - case 15011: + case 15011: case 15012: throw new EventLogReadingException(errorCode); - - default: throw new EventLogException(errorCode); + + default: throw new EventLogException(errorCode); } } public EventLogException() { } public EventLogException(string message) : base(message) { } public EventLogException(string message, Exception innerException) : base(message, innerException) { } - protected EventLogException(int errorCode) { this.errorCode = errorCode; } + protected EventLogException(int errorCode) { _errorCode = errorCode; } - public override string Message { + public override string Message + { // marked as SecurityCritical because it uses Win32Exception. // marked as TreatAsSafe because it performs Demand. [System.Security.SecurityCritical] - get { - Win32Exception win32Exception = new Win32Exception(errorCode); + get + { + Win32Exception win32Exception = new Win32Exception(_errorCode); return win32Exception.Message; } } - private int errorCode; + private int _errorCode; } /// /// The object requested by the operation is not found. /// - public class EventLogNotFoundException : EventLogException { + public class EventLogNotFoundException : EventLogException + { public EventLogNotFoundException() { } public EventLogNotFoundException(string message) : base(message) { } public EventLogNotFoundException(string message, Exception innerException) : base(message, innerException) { } @@ -83,7 +84,8 @@ namespace System.Diagnostics.Eventing.Reader { /// that the log has been cleared. User needs to obtain a new reader object if /// they wish to continue navigating result set. /// - public class EventLogReadingException : EventLogException { + public class EventLogReadingException : EventLogException + { public EventLogReadingException() { } public EventLogReadingException(string message) : base(message) { } public EventLogReadingException(string message, Exception innerException) : base(message, innerException) { } @@ -95,7 +97,8 @@ namespace System.Diagnostics.Eventing.Reader { /// Obtain a new ProviderMetadata object, when provider is reinstalled, to continue navigating /// provider's metadata. /// - public class EventLogProviderDisabledException : EventLogException { + public class EventLogProviderDisabledException : EventLogException + { public EventLogProviderDisabledException() { } public EventLogProviderDisabledException(string message) : base(message) { } public EventLogProviderDisabledException(string message, Exception innerException) : base(message, innerException) { } @@ -105,7 +108,8 @@ namespace System.Diagnostics.Eventing.Reader { /// /// Data obtained from the eventlog service, for the current operation, is invalid . /// - public class EventLogInvalidDataException : EventLogException { + public class EventLogInvalidDataException : EventLogException + { public EventLogInvalidDataException() { } public EventLogInvalidDataException(string message) : base(message) { } public EventLogInvalidDataException(string message, Exception innerException) : base(message, innerException) { } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs index 08d1b06b2..9ad8a35c6 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogHandle ** ** Purpose: ** This internal class is a SafeHandle implementation over a @@ -15,8 +10,8 @@ using System.Runtime.InteropServices; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ // // Marked as SecurityCritical due to link demands from inherited // SafeHandle members. @@ -26,24 +21,30 @@ namespace System.Diagnostics.Eventing.Reader { // by this class is NativeWrapper.EvtClose and that is protected // by a full Demand() before doing any work. [System.Security.SecuritySafeCritical] - internal sealed class EventLogHandle : SafeHandle { + internal sealed class EventLogHandle : SafeHandle + { // Called by P/Invoke when returning SafeHandles private EventLogHandle() - : base(IntPtr.Zero, true) { + : base(IntPtr.Zero, true) + { } internal EventLogHandle(IntPtr handle, bool ownsHandle) - : base(IntPtr.Zero, ownsHandle) { + : base(IntPtr.Zero, ownsHandle) + { SetHandle(handle); } - - public override bool IsInvalid { - get { + + public override bool IsInvalid + { + get + { return IsClosed || handle == IntPtr.Zero; } } - protected override bool ReleaseHandle() { + protected override bool ReleaseHandle() + { NativeWrapper.EvtClose(handle); handle = IntPtr.Zero; return true; @@ -51,8 +52,10 @@ namespace System.Diagnostics.Eventing.Reader { // DONT compare EventLogHandle with EventLogHandle.Zero // use IsInvalid instead. Zero is provided where a NULL handle needed - public static EventLogHandle Zero { - get { + public static EventLogHandle Zero + { + get + { return new EventLogHandle(); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs index 0c703babb..ab8df3b2c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogInformation.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogInformation ** ** Purpose: ** The objects of this class allow access to the run-time @@ -14,47 +9,49 @@ ** ============================================================*/ -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the run-time properties of logs and external log files. An instance /// of this class is obtained from EventLogSession. /// - public sealed class EventLogInformation { - DateTime? creationTime; - DateTime? lastAccessTime; - DateTime? lastWriteTime; - long? fileSize; - int? fileAttributes; - long? recordCount; - long? oldestRecordNumber; - bool? isLogFull; + public sealed class EventLogInformation + { + private DateTime? _creationTime; + private DateTime? _lastAccessTime; + private DateTime? _lastWriteTime; + private long? _fileSize; + private int? _fileAttributes; + private long? _recordCount; + private long? _oldestRecordNumber; + private bool? _isLogFull; [System.Security.SecuritySafeCritical] - internal EventLogInformation(EventLogSession session, string channelName, PathType pathType) { - + internal EventLogInformation(EventLogSession session, string channelName, PathType pathType) + { EventLogHandle logHandle = NativeWrapper.EvtOpenLog(session.Handle, channelName, pathType); - using (logHandle) { - creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime); - lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime); - lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime); - fileSize = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize)); - fileAttributes = (int?)((uint?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes)); - recordCount = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords)); - oldestRecordNumber = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber)); - isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull); + using (logHandle) + { + _creationTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogCreationTime); + _lastAccessTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastAccessTime); + _lastWriteTime = (DateTime?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogLastWriteTime); + _fileSize = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFileSize)); + _fileAttributes = (int?)((uint?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogAttributes)); + _recordCount = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogNumberOfLogRecords)); + _oldestRecordNumber = (long?)((ulong?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogOldestRecordNumber)); + _isLogFull = (bool?)NativeWrapper.EvtGetLogInfo(logHandle, UnsafeNativeMethods.EvtLogPropertyId.EvtLogFull); } } - public DateTime? CreationTime { get { return creationTime; } } - public DateTime? LastAccessTime { get { return lastAccessTime; } } - public DateTime? LastWriteTime { get { return lastWriteTime; } } - public long? FileSize { get { return fileSize; } } - public int? Attributes { get { return fileAttributes; } } - public long? RecordCount { get { return recordCount; } } - public long? OldestRecordNumber { get { return oldestRecordNumber; } } - public bool? IsLogFull { get { return isLogFull; } } + public DateTime? CreationTime { get { return _creationTime; } } + public DateTime? LastAccessTime { get { return _lastAccessTime; } } + public DateTime? LastWriteTime { get { return _lastWriteTime; } } + public long? FileSize { get { return _fileSize; } } + public int? Attributes { get { return _fileAttributes; } } + public long? RecordCount { get { return _recordCount; } } + public long? OldestRecordNumber { get { return _oldestRecordNumber; } } + public bool? IsLogFull { get { return _isLogFull; } } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogLink.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogLink.cs index abd798bfb..94168758c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogLink.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogLink.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogLink ** ** Purpose: ** This public class describes the metadata for a specific Log @@ -16,59 +11,66 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the metadata for a specific Log Reference defined /// by a Provider. An instance of this class is obtained from /// a ProviderMetadata object. /// - public sealed class EventLogLink { - private string channelName; - private bool isImported; - private string displayName; - private uint channelId; + public sealed class EventLogLink + { + private string _channelName; + private bool _isImported; + private string _displayName; + private uint _channelId; - private bool dataReady; - ProviderMetadata pmReference; - object syncObject; + private bool _dataReady; + private ProviderMetadata _pmReference; + private object _syncObject; - internal EventLogLink(uint channelId, ProviderMetadata pmReference) { - this.channelId = channelId; - this.pmReference = pmReference; - this.syncObject = new object(); + internal EventLogLink(uint channelId, ProviderMetadata pmReference) + { + _channelId = channelId; + _pmReference = pmReference; + _syncObject = new object(); } - internal EventLogLink(string channelName, bool isImported, string displayName, uint channelId) { - this.channelName = channelName; - this.isImported = isImported; - this.displayName = displayName; - this.channelId = channelId; + internal EventLogLink(string channelName, bool isImported, string displayName, uint channelId) + { + _channelName = channelName; + _isImported = isImported; + _displayName = displayName; + _channelId = channelId; - this.dataReady = true; - this.syncObject = new object(); + _dataReady = true; + _syncObject = new object(); } - private void PrepareData() { - if (dataReady == true) return; + private void PrepareData() + { + if (_dataReady == true) return; - lock (syncObject) { - if (dataReady == true) return; + lock (_syncObject) + { + if (_dataReady == true) return; - IEnumerable result = pmReference.LogLinks; + IEnumerable result = _pmReference.LogLinks; - this.channelName = null; - this.isImported = false; - this.displayName = null; - this.dataReady = true; + _channelName = null; + _isImported = false; + _displayName = null; + _dataReady = true; - foreach (EventLogLink ch in result) { - if (ch.ChannelId == this.channelId) { - this.channelName = ch.LogName; - this.isImported = ch.IsImported; - this.displayName = ch.DisplayName; + foreach (EventLogLink ch in result) + { + if (ch.ChannelId == _channelId) + { + _channelName = ch.LogName; + _isImported = ch.IsImported; + _displayName = ch.DisplayName; - this.dataReady = true; + _dataReady = true; break; } @@ -77,32 +79,39 @@ namespace System.Diagnostics.Eventing.Reader { } - public string LogName { - get { + public string LogName + { + get + { this.PrepareData(); - return this.channelName; + return _channelName; } } - public bool IsImported { - get { + public bool IsImported + { + get + { this.PrepareData(); - return this.isImported; + return _isImported; } } - public string DisplayName { - get { + public string DisplayName + { + get + { this.PrepareData(); - return this.displayName; + return _displayName; } } - internal uint ChannelId { - get { - return channelId; + internal uint ChannelId + { + get + { + return _channelId; } } } - } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogPropertySelector.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogPropertySelector.cs index 340cc6783..f0ec387a5 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogPropertySelector.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogPropertySelector.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogPropertySelector ** ** Purpose: ** Public class that encapsulates the information for fast @@ -18,61 +13,66 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Encapsulates the information for fast access to Event Values /// of an EventLogRecord. An instance of this class is constructed /// and then passed to EventLogRecord.GetEventPropertyValues. /// - public class EventLogPropertySelector : IDisposable { - + public class EventLogPropertySelector : IDisposable + { // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // - private EventLogHandle renderContextHandleValues; + private EventLogHandle _renderContextHandleValues; [System.Security.SecurityCritical] - public EventLogPropertySelector(IEnumerable propertyQueries) { - + public EventLogPropertySelector(IEnumerable propertyQueries) + { if (propertyQueries == null) throw new ArgumentNullException("propertyQueries"); string[] paths; ICollection coll = propertyQueries as ICollection; - if (coll != null) { + if (coll != null) + { paths = new string[coll.Count]; coll.CopyTo(paths, 0); } - else { + else + { List queries; queries = new List(propertyQueries); paths = queries.ToArray(); } - renderContextHandleValues = NativeWrapper.EvtCreateRenderContext(paths.Length, paths, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextValues); + _renderContextHandleValues = NativeWrapper.EvtCreateRenderContext(paths.Length, paths, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextValues); } - internal EventLogHandle Handle { + internal EventLogHandle Handle + { // just returning reference to security critical type, the methods // of that type are protected by SecurityCritical as appropriate. - get { - return renderContextHandleValues; + get + { + return _renderContextHandleValues; } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] - protected virtual void Dispose(bool disposing) { - - if (renderContextHandleValues != null && !renderContextHandleValues.IsInvalid) - renderContextHandleValues.Dispose(); + protected virtual void Dispose(bool disposing) + { + if (_renderContextHandleValues != null && !_renderContextHandleValues.IsInvalid) + _renderContextHandleValues.Dispose(); } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs index 3f00aa273..e822af058 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogQuery.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogQuery ** ** Purpose: ** This public class allows a user to define events of interest. @@ -17,8 +12,8 @@ ** ============================================================*/ -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Allows a user to define events of interest. An instance of this /// class is passed to an EventReader to actually obtain the EventRecords. @@ -26,78 +21,95 @@ namespace System.Diagnostics.Eventing.Reader { /// interest, or it can contain query / xpath expressions that indicate exactly /// what characteristics events should have. /// - public class EventLogQuery { - - private string query; - private string path; - private EventLogSession session; - private PathType pathType; - private bool tolerateErrors = false; - private bool reverseDirection = false; + public class EventLogQuery + { + private string _query; + private string _path; + private EventLogSession _session; + private PathType _pathType; + private bool _tolerateErrors = false; + private bool _reverseDirection = false; public EventLogQuery(string path, PathType pathType) - : this(path, pathType, null) { + : this(path, pathType, null) + { } - public EventLogQuery(string path, PathType pathType, string query) { + public EventLogQuery(string path, PathType pathType, string query) + { + _session = EventLogSession.GlobalSession; + _path = path; // can be null + _pathType = pathType; - this.session = EventLogSession.GlobalSession; - this.path = path; // can be null - this.pathType = pathType; - - if (query == null) { + if (query == null) + { if (path == null) throw new ArgumentNullException("path"); } - else { - this.query = query; + else + { + _query = query; } } - public EventLogSession Session { - get { - return this.session; + public EventLogSession Session + { + get + { + return _session; } - set { - this.session = value; + set + { + _session = value; } } - public bool TolerateQueryErrors { - get { - return this.tolerateErrors; + public bool TolerateQueryErrors + { + get + { + return _tolerateErrors; } - set { - this.tolerateErrors = value; + set + { + _tolerateErrors = value; } } - public bool ReverseDirection { - get { - return this.reverseDirection; + public bool ReverseDirection + { + get + { + return _reverseDirection; } - set { - this.reverseDirection = value; + set + { + _reverseDirection = value; } } - internal string Path { - get { - return this.path; + internal string Path + { + get + { + return _path; } } - internal PathType ThePathType { - get { - return this.pathType; + internal PathType ThePathType + { + get + { + return _pathType; } } - internal string Query { - get { - return this.query; + internal string Query + { + get + { + return _query; } } - } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs index a72bbc115..cd23aef52 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogReader.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogReader ** ** Purpose: ** This public class is used for reading event records from event log. @@ -15,63 +10,66 @@ using System.IO; using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// This public class is used for reading event records from event log. /// - public class EventLogReader : IDisposable { + public class EventLogReader : IDisposable + { + private EventLogQuery _eventQuery; - private EventLogQuery eventQuery; - - private int batchSize; + private int _batchSize; // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // - private EventLogHandle handle; + private EventLogHandle _handle; /// /// events buffer holds batched event (handles). /// - private IntPtr[] eventsBuffer; + private IntPtr[] _eventsBuffer; /// /// The current index where the function GetNextEvent is (inside the eventsBuffer). /// - private int currentIndex; + private int _currentIndex; /// /// The number of events read from the batch into the eventsBuffer /// - private int eventCount; + private int _eventCount; /// /// When the reader finishes (will always return only ERROR_NO_MORE_ITEMS). /// For subscription, this means we need to wait for next event. /// - bool isEof; + private bool _isEof; /// /// Maintains cached display / metadata information returned from /// EventRecords that were obtained from this reader. /// - ProviderMetadataCachedInformation cachedMetadataInformation; + private ProviderMetadataCachedInformation _cachedMetadataInformation; public EventLogReader(string path) - : this(new EventLogQuery(path, PathType.LogName), null) { + : this(new EventLogQuery(path, PathType.LogName), null) + { } public EventLogReader(string path, PathType pathType) - : this(new EventLogQuery(path, pathType), null) { + : this(new EventLogQuery(path, pathType), null) + { } public EventLogReader(EventLogQuery eventQuery) - : this(eventQuery, null) { + : this(eventQuery, null) + { } [System.Security.SecurityCritical] - public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) { - + public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) + { if (eventQuery == null) throw new ArgumentNullException("eventQuery"); @@ -79,58 +77,63 @@ namespace System.Diagnostics.Eventing.Reader { if (eventQuery.ThePathType == PathType.FilePath) logfile = eventQuery.Path; - this.cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50 ); + _cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50); //explicit data - this.eventQuery = eventQuery; + _eventQuery = eventQuery; //implicit - this.batchSize = 64; - this.eventsBuffer = new IntPtr[batchSize]; + _batchSize = 64; + _eventsBuffer = new IntPtr[_batchSize]; // // compute the flag. // int flag = 0; - if (this.eventQuery.ThePathType == PathType.LogName) + if (_eventQuery.ThePathType == PathType.LogName) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath; else flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath; - if (this.eventQuery.ReverseDirection) + if (_eventQuery.ReverseDirection) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryReverseDirection; - if (this.eventQuery.TolerateQueryErrors) + if (_eventQuery.TolerateQueryErrors) flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryTolerateQueryErrors; - - handle = NativeWrapper.EvtQuery(this.eventQuery.Session.Handle, - this.eventQuery.Path, this.eventQuery.Query, + + _handle = NativeWrapper.EvtQuery(_eventQuery.Session.Handle, + _eventQuery.Path, _eventQuery.Query, flag); EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark); - if (!bookmarkHandle.IsInvalid) { - using (bookmarkHandle) { - NativeWrapper.EvtSeek(handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); + if (!bookmarkHandle.IsInvalid) + { + using (bookmarkHandle) + { + NativeWrapper.EvtSeek(_handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); } } } - public int BatchSize { - get { - return batchSize; + public int BatchSize + { + get + { + return _batchSize; } - set { + set + { if (value < 1) throw new ArgumentOutOfRangeException("value"); - batchSize = value; + _batchSize = value; } } [System.Security.SecurityCritical] - private bool GetNextBatch(TimeSpan ts) { - + private bool GetNextBatch(TimeSpan ts) + { int timeout; if (ts == TimeSpan.MaxValue) timeout = -1; @@ -138,156 +141,174 @@ namespace System.Diagnostics.Eventing.Reader { timeout = (int)ts.TotalMilliseconds; // batchSize was changed by user, reallocate buffer. - if (batchSize != eventsBuffer.Length) eventsBuffer = new IntPtr[batchSize]; + if (_batchSize != _eventsBuffer.Length) _eventsBuffer = new IntPtr[_batchSize]; int newEventCount = 0; - bool results = NativeWrapper.EvtNext(handle, batchSize, eventsBuffer, timeout, 0, ref newEventCount); + bool results = NativeWrapper.EvtNext(_handle, _batchSize, _eventsBuffer, timeout, 0, ref newEventCount); - if (!results) { - this.eventCount = 0; - this.currentIndex = 0; + if (!results) + { + _eventCount = 0; + _currentIndex = 0; return false; //no more events in the result set } - this.currentIndex = 0; - this.eventCount = newEventCount; + _currentIndex = 0; + _eventCount = newEventCount; return true; } - public EventRecord ReadEvent() { + public EventRecord ReadEvent() + { return ReadEvent(TimeSpan.MaxValue); } // security critical because allocates SafeHandle. // marked as safe because performs Demand check. [System.Security.SecurityCritical] - public EventRecord ReadEvent(TimeSpan timeout) { - - if (this.isEof) + public EventRecord ReadEvent(TimeSpan timeout) + { + if (_isEof) throw new InvalidOperationException(); - if (this.currentIndex >= this.eventCount) { + if (_currentIndex >= _eventCount) + { // buffer is empty, get next batch. GetNextBatch(timeout); - if (this.currentIndex >= this.eventCount) { - this.isEof = true; + if (_currentIndex >= _eventCount) + { + _isEof = true; return null; } } - EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(this.eventsBuffer[currentIndex], true), this.eventQuery.Session, this.cachedMetadataInformation); - currentIndex++; + EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(_eventsBuffer[_currentIndex], true), _eventQuery.Session, _cachedMetadataInformation); + _currentIndex++; return eventInstance; } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] - protected virtual void Dispose(bool disposing) { - - while (this.currentIndex < this.eventCount) { - NativeWrapper.EvtClose(eventsBuffer[this.currentIndex]); - this.currentIndex++; + protected virtual void Dispose(bool disposing) + { + while (_currentIndex < _eventCount) + { + NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]); + _currentIndex++; } - if (handle != null && !handle.IsInvalid) - handle.Dispose(); + if (_handle != null && !_handle.IsInvalid) + _handle.Dispose(); } [System.Security.SecurityCritical] - internal void SeekReset() { + internal void SeekReset() + { // //close all unread event handles in the buffer // - while (this.currentIndex < this.eventCount) { - NativeWrapper.EvtClose(eventsBuffer[this.currentIndex]); - this.currentIndex++; + while (_currentIndex < _eventCount) + { + NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]); + _currentIndex++; } //reset the indexes used by Next - this.currentIndex = 0; - this.eventCount = 0; - this.isEof = false; + _currentIndex = 0; + _eventCount = 0; + _isEof = false; } // marked as SecurityCritical because it allocates SafeHandle. [System.Security.SecurityCritical] - internal void SeekCommon(long offset) { - + internal void SeekCommon(long offset) + { // // modify offset that we're going to send to service to account for the // fact that we've already read some events in our buffer that the user // hasn't seen yet. // - offset = offset - (this.eventCount - this.currentIndex); + offset = offset - (_eventCount - _currentIndex); SeekReset(); - NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent); + NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent); } - public void Seek(EventBookmark bookmark) { + public void Seek(EventBookmark bookmark) + { Seek(bookmark, 0); } [System.Security.SecurityCritical] - public void Seek(EventBookmark bookmark, long offset) { + public void Seek(EventBookmark bookmark, long offset) + { if (bookmark == null) throw new ArgumentNullException("bookmark"); - + SeekReset(); - using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark)) { - NativeWrapper.EvtSeek(this.handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); + using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark)) + { + NativeWrapper.EvtSeek(_handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark); } } [System.Security.SecurityCritical] - public void Seek(SeekOrigin origin, long offset) { - - switch (origin) { + public void Seek(SeekOrigin origin, long offset) + { + switch (origin) + { case SeekOrigin.Begin: SeekReset(); - NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst); + NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst); return; case SeekOrigin.End: SeekReset(); - NativeWrapper.EvtSeek(this.handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast); + NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast); return; case SeekOrigin.Current: - if (offset >= 0) { + if (offset >= 0) + { //we can reuse elements in the batch. - if (this.currentIndex + offset < this.eventCount) { + if (_currentIndex + offset < _eventCount) + { // // We don't call Seek here, we can reposition within the batch. // // close all event handles between [currentIndex, currentIndex + offset) - int index = this.currentIndex; - while (index < this.currentIndex + offset) { - NativeWrapper.EvtClose(eventsBuffer[index]); + int index = _currentIndex; + while (index < _currentIndex + offset) + { + NativeWrapper.EvtClose(_eventsBuffer[index]); index++; } - this.currentIndex = (int)(this.currentIndex + offset); + _currentIndex = (int)(_currentIndex + offset); //leave the eventCount unchanged //leave the same Eof } - else { + else + { SeekCommon(offset); } } - else { + else + { //if inside the current buffer, we still cannot read the events, as the handles. //may have already been closed. - if (currentIndex + offset >= 0) { + if (_currentIndex + offset >= 0) + { SeekCommon(offset); } else //outside the current buffer @@ -299,18 +320,20 @@ namespace System.Diagnostics.Eventing.Reader { } } - public void CancelReading() { - - NativeWrapper.EvtCancel(handle); + public void CancelReading() + { + NativeWrapper.EvtCancel(_handle); } - - public IList LogStatus { + + public IList LogStatus + { [System.Security.SecurityCritical] - get { + get + { List list = null; string[] channelNames = null; int[] errorStatuses = null; - EventLogHandle queryHandle = this.handle; + EventLogHandle queryHandle = _handle; if (queryHandle.IsInvalid) throw new InvalidOperationException(); @@ -322,12 +345,13 @@ namespace System.Diagnostics.Eventing.Reader { throw new InvalidOperationException(); list = new List(channelNames.Length); - for (int i = 0; i < channelNames.Length; i++) { + for (int i = 0; i < channelNames.Length; i++) + { EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]); list.Add(cs); } return list.AsReadOnly(); } - } + } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs index d5ae84d19..c8d4e6088 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogRecord.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogRecord ** ** Purpose: ** This public class is an EventLog implementation of EventRecord. An @@ -16,10 +11,10 @@ using System.Collections.Generic; using System.Text; -namespace System.Diagnostics.Eventing.Reader { - - public class EventLogRecord : EventRecord { - +namespace System.Diagnostics.Eventing.Reader +{ + public class EventLogRecord : EventRecord + { private const int SYSTEM_PROPERTY_COUNT = 18; // @@ -27,357 +22,431 @@ namespace System.Diagnostics.Eventing.Reader { // invoking methods on it is marked SecurityCritical as appropriate. // [System.Security.SecuritySafeCritical] - private EventLogHandle handle; + private EventLogHandle _handle; - private EventLogSession session; + private EventLogSession _session; - private NativeWrapper.SystemProperties systemProperties; - private string containerChannel; - private int[] matchedQueryIds; + private NativeWrapper.SystemProperties _systemProperties; + private string _containerChannel; + private int[] _matchedQueryIds; //a dummy object which is used only for the locking. - object syncObject; + private object _syncObject; //cached DisplayNames for each instance - private string levelName = null; - private string taskName = null; - private string opcodeName = null; - private IEnumerable keywordsNames = null; + private string _levelName = null; + private string _taskName = null; + private string _opcodeName = null; + private IEnumerable _keywordsNames = null; //cached DisplayNames for each instance - private bool levelNameReady; - private bool taskNameReady; - private bool opcodeNameReady; + private bool _levelNameReady; + private bool _taskNameReady; + private bool _opcodeNameReady; - private ProviderMetadataCachedInformation cachedMetadataInformation; + private ProviderMetadataCachedInformation _cachedMetadataInformation; // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo) { - this.cachedMetadataInformation = cachedMetadataInfo; - this.handle = handle; - this.session = session; - systemProperties = new NativeWrapper.SystemProperties(); - syncObject = new object(); + internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo) + { + _cachedMetadataInformation = cachedMetadataInfo; + _handle = handle; + _session = session; + _systemProperties = new NativeWrapper.SystemProperties(); + _syncObject = new object(); } - internal EventLogHandle Handle { + internal EventLogHandle Handle + { // just returning reference to security critical type, the methods // of that type are protected by SecurityCritical as appropriate. [System.Security.SecuritySafeCritical] - get { - return handle; + get + { + return _handle; } } - internal void PrepareSystemData() { - - if (this.systemProperties.filled) + internal void PrepareSystemData() + { + if (_systemProperties.filled) return; //prepare the System Context, if it is not already initialized. - this.session.SetupSystemContext(); + _session.SetupSystemContext(); - lock (this.syncObject) { - if (this.systemProperties.filled == false) { - NativeWrapper.EvtRenderBufferWithContextSystem(this.session.renderContextHandleSystem, this.handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues, this.systemProperties, SYSTEM_PROPERTY_COUNT); - this.systemProperties.filled = true; + lock (_syncObject) + { + if (_systemProperties.filled == false) + { + NativeWrapper.EvtRenderBufferWithContextSystem(_session.renderContextHandleSystem, _handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues, _systemProperties, SYSTEM_PROPERTY_COUNT); + _systemProperties.filled = true; } } } - public override int Id { - get { + public override int Id + { + get + { PrepareSystemData(); - if (this.systemProperties.Id == null) + if (_systemProperties.Id == null) return 0; - return (int)this.systemProperties.Id; + return (int)_systemProperties.Id; } } - public override byte? Version { - get { + public override byte? Version + { + get + { PrepareSystemData(); - return this.systemProperties.Version; + return _systemProperties.Version; } } - public override int? Qualifiers { - get { + public override int? Qualifiers + { + get + { PrepareSystemData(); - return (int?)(uint?)this.systemProperties.Qualifiers; + return (int?)(uint?)_systemProperties.Qualifiers; } } - public override byte? Level { - get { + public override byte? Level + { + get + { PrepareSystemData(); - return this.systemProperties.Level; + return _systemProperties.Level; } } - public override int? Task { - get { + public override int? Task + { + get + { PrepareSystemData(); - return (int?)(uint?)this.systemProperties.Task; + return (int?)(uint?)_systemProperties.Task; } } - public override short? Opcode { - get { + public override short? Opcode + { + get + { PrepareSystemData(); - return (short?)(ushort?)this.systemProperties.Opcode; + return (short?)(ushort?)_systemProperties.Opcode; } } - public override long? Keywords { - get { + public override long? Keywords + { + get + { PrepareSystemData(); - return (long?)this.systemProperties.Keywords; + return (long?)_systemProperties.Keywords; } } - public override long? RecordId { - get { + public override long? RecordId + { + get + { PrepareSystemData(); - return (long?)this.systemProperties.RecordId; + return (long?)_systemProperties.RecordId; } } - public override string ProviderName { - get { + public override string ProviderName + { + get + { PrepareSystemData(); - return this.systemProperties.ProviderName; + return _systemProperties.ProviderName; } } - public override Guid? ProviderId { - get { + public override Guid? ProviderId + { + get + { PrepareSystemData(); - return this.systemProperties.ProviderId; + return _systemProperties.ProviderId; } } - public override string LogName { - get { + public override string LogName + { + get + { PrepareSystemData(); - return this.systemProperties.ChannelName; + return _systemProperties.ChannelName; } } - public override int? ProcessId { - get { + public override int? ProcessId + { + get + { PrepareSystemData(); - return (int?)this.systemProperties.ProcessId; + return (int?)_systemProperties.ProcessId; } } - public override int? ThreadId { - get { + public override int? ThreadId + { + get + { PrepareSystemData(); - return (int?)this.systemProperties.ThreadId; + return (int?)_systemProperties.ThreadId; } } - public override string MachineName { - get { + public override string MachineName + { + get + { PrepareSystemData(); - return this.systemProperties.ComputerName; + return _systemProperties.ComputerName; } } - public override System.Security.Principal.SecurityIdentifier UserId { - get { + public override System.Security.Principal.SecurityIdentifier UserId + { + get + { PrepareSystemData(); - return this.systemProperties.UserId; + return _systemProperties.UserId; } } - public override DateTime? TimeCreated { - get { + public override DateTime? TimeCreated + { + get + { PrepareSystemData(); - return this.systemProperties.TimeCreated; + return _systemProperties.TimeCreated; } } - public override Guid? ActivityId { - get { + public override Guid? ActivityId + { + get + { PrepareSystemData(); - return this.systemProperties.ActivityId; + return _systemProperties.ActivityId; } } - public override Guid? RelatedActivityId { - get { + public override Guid? RelatedActivityId + { + get + { PrepareSystemData(); - return this.systemProperties.RelatedActivityId; + return _systemProperties.RelatedActivityId; } } - public string ContainerLog { - get { - if (this.containerChannel != null) - return this.containerChannel; - lock (this.syncObject) { - if (this.containerChannel == null) { - this.containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); + public string ContainerLog + { + get + { + if (_containerChannel != null) + return _containerChannel; + lock (_syncObject) + { + if (_containerChannel == null) + { + _containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath); } - return this.containerChannel; + return _containerChannel; } } } - public IEnumerable MatchedQueryIds { - get { - if (this.matchedQueryIds != null) - return this.matchedQueryIds; - lock (this.syncObject) { - if (this.matchedQueryIds == null) { - this.matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); + public IEnumerable MatchedQueryIds + { + get + { + if (_matchedQueryIds != null) + return _matchedQueryIds; + lock (_syncObject) + { + if (_matchedQueryIds == null) + { + _matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs); } - return this.matchedQueryIds; + return _matchedQueryIds; } } } - - public override EventBookmark Bookmark { + + public override EventBookmark Bookmark + { [System.Security.SecuritySafeCritical] - get { - + get + { EventLogHandle bookmarkHandle = NativeWrapper.EvtCreateBookmark(null); - NativeWrapper.EvtUpdateBookmark(bookmarkHandle, this.handle); + NativeWrapper.EvtUpdateBookmark(bookmarkHandle, _handle); string bookmarkText = NativeWrapper.EvtRenderBookmark(bookmarkHandle); return new EventBookmark(bookmarkText); } } - public override string FormatDescription() { - - return this.cachedMetadataInformation.GetFormatDescription(this.ProviderName, this.handle); + public override string FormatDescription() + { + return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, _handle); } - public override string FormatDescription(IEnumerable values) { + public override string FormatDescription(IEnumerable values) + { if (values == null) return this.FormatDescription(); //copy the value IEnumerable to an array. string[] theValues = new string[0]; int i = 0; - foreach (object o in values) { - if ( theValues.Length == i ) - Array.Resize( ref theValues, i+1 ); + foreach (object o in values) + { + if (theValues.Length == i) + Array.Resize(ref theValues, i + 1); theValues[i] = o.ToString(); i++; - } + } - return this.cachedMetadataInformation.GetFormatDescription(this.ProviderName, this.handle, theValues); + return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, _handle, theValues); } - public override string LevelDisplayName { - get { - if ( this.levelNameReady ) - return this.levelName; - lock (this.syncObject) { - if (this.levelNameReady == false) { - this.levelNameReady = true; - this.levelName = this.cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, this.handle); + public override string LevelDisplayName + { + get + { + if (_levelNameReady) + return _levelName; + lock (_syncObject) + { + if (_levelNameReady == false) + { + _levelNameReady = true; + _levelName = _cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, _handle); } - return this.levelName; + return _levelName; } } } - public override string OpcodeDisplayName { - get { - lock (this.syncObject) { - if (this.opcodeNameReady == false) { - this.opcodeNameReady = true; - this.opcodeName = this.cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, this.handle); - + public override string OpcodeDisplayName + { + get + { + lock (_syncObject) + { + if (_opcodeNameReady == false) + { + _opcodeNameReady = true; + _opcodeName = _cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, _handle); } - return this.opcodeName; + return _opcodeName; } } } - public override string TaskDisplayName { - get { - if (this.taskNameReady == true) - return this.taskName; - lock (this.syncObject) { - if (this.taskNameReady == false) { - this.taskNameReady = true; - this.taskName = this.cachedMetadataInformation.GetTaskDisplayName(this.ProviderName, this.handle); + public override string TaskDisplayName + { + get + { + if (_taskNameReady == true) + return _taskName; + lock (_syncObject) + { + if (_taskNameReady == false) + { + _taskNameReady = true; + _taskName = _cachedMetadataInformation.GetTaskDisplayName(this.ProviderName, _handle); } - return this.taskName; + return _taskName; } } } - public override IEnumerable KeywordsDisplayNames { - get { - if (this.keywordsNames != null) - return this.keywordsNames; - lock (this.syncObject) { - if (this.keywordsNames == null) { - this.keywordsNames = this.cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, this.handle); + public override IEnumerable KeywordsDisplayNames + { + get + { + if (_keywordsNames != null) + return _keywordsNames; + lock (_syncObject) + { + if (_keywordsNames == null) + { + _keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, _handle); } - return this.keywordsNames; + return _keywordsNames; } } } - public override IList Properties { - get { - this.session.SetupUserContext(); - IList properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(this.session.renderContextHandleUser, this.handle); + public override IList Properties + { + get + { + _session.SetupUserContext(); + IList properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(_session.renderContextHandleUser, _handle); List list = new List(); - foreach (object value in properties) { + foreach (object value in properties) + { list.Add(new EventProperty(value)); } return list; } } - public IList GetPropertyValues(EventLogPropertySelector propertySelector) { + public IList GetPropertyValues(EventLogPropertySelector propertySelector) + { if (propertySelector == null) throw new ArgumentNullException("propertySelector"); - return NativeWrapper.EvtRenderBufferWithContextUserOrValues(propertySelector.Handle, this.handle); + return NativeWrapper.EvtRenderBufferWithContextUserOrValues(propertySelector.Handle, _handle); } // marked as SecurityCritical because it allocates SafeHandle // marked as TreatAsSafe because it performs Demand. [System.Security.SecuritySafeCritical] - public override string ToXml() { + public override string ToXml() + { StringBuilder renderBuffer = new StringBuilder(2000); - NativeWrapper.EvtRender(EventLogHandle.Zero, this.handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml, renderBuffer); + NativeWrapper.EvtRender(EventLogHandle.Zero, _handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml, renderBuffer); return renderBuffer.ToString(); } [System.Security.SecuritySafeCritical] - protected override void Dispose(bool disposing) { - try { - - if ( this.handle != null && !this.handle.IsInvalid ) - this.handle.Dispose(); + protected override void Dispose(bool disposing) + { + try + { + if (_handle != null && !_handle.IsInvalid) + _handle.Dispose(); } - finally { + finally + { base.Dispose(disposing); } } // marked as SecurityCritical because allocates SafeHandle. [System.Security.SecurityCritical] - internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark bookmark) { + internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark bookmark) + { if (bookmark == null) return EventLogHandle.Zero; EventLogHandle handle = NativeWrapper.EvtCreateBookmark(bookmark.BookmarkText); return handle; } } - } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogSession.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogSession.cs index 5b5d9af71..df7a48be3 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogSession.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogSession.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogSession ** ** Purpose: ** Defines a session for Event Log operations. The session can @@ -17,11 +12,13 @@ using System.Security; using System.Collections.Generic; using System.Globalization; -namespace System.Diagnostics.Eventing.Reader { +namespace System.Diagnostics.Eventing.Reader +{ /// /// Session Login Type /// - public enum SessionAuthentication { + public enum SessionAuthentication + { Default = 0, Negotiate = 1, Kerberos = 2, @@ -36,8 +33,9 @@ namespace System.Diagnostics.Eventing.Reader { LogName = 1, FilePath = 2 } - - public class EventLogSession : IDisposable { + + public class EventLogSession : IDisposable + { // //the two context handles for rendering (for EventLogRecord). //the system and user context handles. They are both common for all the event instances and can be created only once. @@ -48,29 +46,31 @@ namespace System.Diagnostics.Eventing.Reader { internal EventLogHandle renderContextHandleUser = EventLogHandle.Zero; //the dummy sync object for the two contextes. - private object syncObject = null; + private object _syncObject = null; - private string server; - private string user; - private string domain; - private SessionAuthentication logOnType; + private string _server; + private string _user; + private string _domain; + private SessionAuthentication _logOnType; //we do not maintain the password here. // //access to the data member references is safe, while //invoking methods on it is marked SecurityCritical as appropriate. // - private EventLogHandle handle = EventLogHandle.Zero; + private EventLogHandle _handle = EventLogHandle.Zero; //setup the System Context, once for all the EventRecords. [System.Security.SecuritySafeCritical] - internal void SetupSystemContext() { - + internal void SetupSystemContext() + { if (!this.renderContextHandleSystem.IsInvalid) return; - lock (this.syncObject) { - if (this.renderContextHandleSystem.IsInvalid) { + lock (_syncObject) + { + if (this.renderContextHandleSystem.IsInvalid) + { //create the SYSTEM render context //call the EvtCreateRenderContext to get the renderContextHandleSystem, so that we can get the system/values/user properties. this.renderContextHandleSystem = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextSystem); @@ -79,10 +79,12 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecuritySafeCritical] - internal void SetupUserContext() { - - lock (this.syncObject) { - if (this.renderContextHandleUser.IsInvalid) { + internal void SetupUserContext() + { + lock (_syncObject) + { + if (this.renderContextHandleUser.IsInvalid) + { //create the USER render context this.renderContextHandleUser = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextUser); } @@ -92,65 +94,72 @@ namespace System.Diagnostics.Eventing.Reader { // marked as SecurityCritical because allocates SafeHandle. // marked as TreatAsSafe because performs Demand(). [System.Security.SecurityCritical] - public EventLogSession() { + public EventLogSession() + { //handle = EventLogHandle.Zero; - syncObject = new object(); + _syncObject = new object(); } public EventLogSession(string server) : - this(server, null, null, (SecureString)null, SessionAuthentication.Default) { + this(server, null, null, (SecureString)null, SessionAuthentication.Default) + { } // marked as TreatAsSafe because performs Demand(). [System.Security.SecurityCritical] - public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) { - + public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) + { if (server == null) server = "localhost"; - syncObject = new object(); + _syncObject = new object(); - this.server = server; - this.domain = domain; - this.user = user; - this.logOnType = logOnType; + _server = server; + _domain = domain; + _user = user; + _logOnType = logOnType; UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin(); - erLogin.Server = this.server; - erLogin.User = this.user; - erLogin.Domain = this.domain; - erLogin.Flags = (int)this.logOnType; + erLogin.Server = _server; + erLogin.User = _user; + erLogin.Domain = _domain; + erLogin.Flags = (int)_logOnType; erLogin.Password = CoTaskMemUnicodeSafeHandle.Zero; - try { + try + { if (password != null) erLogin.Password.SetMemory(SecureStringMarshal.SecureStringToCoTaskMemUnicode(password)); //open a session using the erLogin structure. - handle = NativeWrapper.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref erLogin, 0, 0); + _handle = NativeWrapper.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref erLogin, 0, 0); } - finally { + finally + { erLogin.Password.Dispose(); } - } - internal EventLogHandle Handle { - get { - return handle; + internal EventLogHandle Handle + { + get + { + return _handle; } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] - protected virtual void Dispose(bool disposing) { - - if (disposing) { - if ( this == globalSession ) + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (this == s_globalSession) throw new InvalidOperationException(); } @@ -162,18 +171,19 @@ namespace System.Diagnostics.Eventing.Reader { !this.renderContextHandleUser.IsInvalid) this.renderContextHandleUser.Dispose(); - if (handle != null && !handle.IsInvalid) - handle.Dispose(); + if (_handle != null && !_handle.IsInvalid) + _handle.Dispose(); } - public void CancelCurrentOperations() { - - NativeWrapper.EvtCancel(handle); + public void CancelCurrentOperations() + { + NativeWrapper.EvtCancel(_handle); } - static EventLogSession globalSession = new EventLogSession(); - public static EventLogSession GlobalSession { - get { return globalSession; } + private static EventLogSession s_globalSession = new EventLogSession(); + public static EventLogSession GlobalSession + { + get { return s_globalSession; } } [System.Security.SecurityCritical] @@ -216,14 +226,16 @@ namespace System.Diagnostics.Eventing.Reader { } } - public EventLogInformation GetLogInformation(string logName, PathType pathType) { + public EventLogInformation GetLogInformation(string logName, PathType pathType) + { if (logName == null) throw new ArgumentNullException("logName"); return new EventLogInformation(this, logName, pathType); } - public void ExportLog(string path, PathType pathType, string query, string targetFilePath) { + public void ExportLog(string path, PathType pathType, string query, string targetFilePath) + { this.ExportLog(path, pathType, query, targetFilePath, false); } @@ -256,10 +268,11 @@ namespace System.Diagnostics.Eventing.Reader { public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath) { - this.ExportLogAndMessages(path, pathType, query, targetFilePath, false, CultureInfo.CurrentCulture ); + this.ExportLogAndMessages(path, pathType, query, targetFilePath, false, CultureInfo.CurrentCulture); } - public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo ) { + public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo) + { if (targetCultureInfo == null) targetCultureInfo = CultureInfo.CurrentCulture; ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogStatus.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogStatus.cs index ccb5c7599..56848142d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogStatus.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogStatus.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventLogStatus ** ** Purpose: ** This public class describes the status of a particular @@ -17,8 +12,8 @@ ** of those logs is. ============================================================*/ -namespace System.Diagnostics.Eventing.Reader{ - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the status of a particular log with respect to /// an instantiated EventLogReader. Since it is possible to @@ -27,21 +22,25 @@ namespace System.Diagnostics.Eventing.Reader{ /// errors in attaching to those logs, this class allows the /// user to determine exactly what the status of those logs is. /// - public sealed class EventLogStatus { - private string channelName; - private int win32ErrorCode; + public sealed class EventLogStatus + { + private string _channelName; + private int _win32ErrorCode; - internal EventLogStatus(string channelName, int win32ErrorCode) { - this.channelName = channelName; - this.win32ErrorCode = win32ErrorCode; + internal EventLogStatus(string channelName, int win32ErrorCode) + { + _channelName = channelName; + _win32ErrorCode = win32ErrorCode; } - public string LogName { - get { return this.channelName; } + public string LogName + { + get { return _channelName; } } - public int StatusCode { - get { return this.win32ErrorCode; } + public int StatusCode + { + get { return _win32ErrorCode; } } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventMetadata.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventMetadata.cs index f7aeacac2..e462000ce 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventMetadata.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventMetadata.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventMetadata ** ** Purpose: ** This public class describes the metadata for a specific event @@ -17,36 +12,39 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing.Reader { +namespace System.Diagnostics.Eventing.Reader +{ /// /// Event Metadata /// - public sealed class EventMetadata { - private long id; - private byte version; - private byte channelId; - private byte level; - private short opcode; - private int task; - private long keywords; - private string template; - private string description; + public sealed class EventMetadata + { + private long _id; + private byte _version; + private byte _channelId; + private byte _level; + private short _opcode; + private int _task; + private long _keywords; + private string _template; + private string _description; - ProviderMetadata pmReference; + private ProviderMetadata _pmReference; internal EventMetadata(uint id, byte version, byte channelId, byte level, byte opcode, short task, long keywords, - string template, string description, ProviderMetadata pmReference) { - this.id = id; - this.version = version; - this.channelId = channelId; - this.level = level; - this.opcode = opcode; - this.task = task; - this.keywords = keywords; - this.template = template; - this.description = description; - this.pmReference = pmReference; + string template, string description, ProviderMetadata pmReference) + { + _id = id; + _version = version; + _channelId = channelId; + _level = level; + _opcode = opcode; + _task = task; + _keywords = keywords; + _template = template; + _description = description; + _pmReference = pmReference; } // @@ -58,58 +56,74 @@ namespace System.Diagnostics.Eventing.Reader { // and rest of the bits of the legacy event id would be stored in // Qualifiers property. // - public long Id { - get { - return this.id; + public long Id + { + get + { + return _id; } } - public byte Version { - get { - return this.version; + public byte Version + { + get + { + return _version; } } - public EventLogLink LogLink { - get { - return new EventLogLink((uint)this.channelId, this.pmReference); + public EventLogLink LogLink + { + get + { + return new EventLogLink((uint)_channelId, _pmReference); } } - public EventLevel Level { - get { - return new EventLevel(this.level, this.pmReference); + public EventLevel Level + { + get + { + return new EventLevel(_level, _pmReference); } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] - public EventOpcode Opcode { - get { - return new EventOpcode(this.opcode, this.pmReference); + public EventOpcode Opcode + { + get + { + return new EventOpcode(_opcode, _pmReference); } } - public EventTask Task { - get { - return new EventTask(this.task, this.pmReference); + public EventTask Task + { + get + { + return new EventTask(_task, _pmReference); } } - public IEnumerable Keywords { - get { + public IEnumerable Keywords + { + get + { List list = new List(); - ulong theKeywords = unchecked((ulong)this.keywords); + ulong theKeywords = unchecked((ulong)_keywords); ulong mask = 0x8000000000000000; //for every bit //for (int i = 0; i < 64 && theKeywords != 0; i++) - for (int i = 0; i < 64; i++) { + for (int i = 0; i < 64; i++) + { //if this bit is set - if ((theKeywords & mask) > 0) { + if ((theKeywords & mask) > 0) + { //the mask is the keyword we will be searching for. - list.Add(new EventKeyword(unchecked((long)mask), this.pmReference)); + list.Add(new EventKeyword(unchecked((long)mask), _pmReference)); //theKeywords = theKeywords - mask; } //modify the mask to check next bit. @@ -120,15 +134,19 @@ namespace System.Diagnostics.Eventing.Reader { } } - public string Template { - get { - return this.template; + public string Template + { + get + { + return _template; } } - public string Description { - get { - return this.description; + public string Description + { + get + { + return _description; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventOpcode.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventOpcode.cs index 1c1f1c979..5831ee6a2 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventOpcode.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventOpcode.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventOpcode ** ** Purpose: ** This public class describes the metadata for a specific Opcode @@ -17,71 +12,84 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] - public sealed class EventOpcode { - private int value; - private string name; - private string displayName; - private bool dataReady; - ProviderMetadata pmReference; - object syncObject; + public sealed class EventOpcode + { + private int _value; + private string _name; + private string _displayName; + private bool _dataReady; + private ProviderMetadata _pmReference; + private object _syncObject; //call from EventMetadata - internal EventOpcode(int value, ProviderMetadata pmReference) { - this.value = value; - this.pmReference = pmReference; - this.syncObject = new object(); + internal EventOpcode(int value, ProviderMetadata pmReference) + { + _value = value; + _pmReference = pmReference; + _syncObject = new object(); } //call from ProviderMetadata - internal EventOpcode(string name, int value, string displayName) { - this.value = value; - this.name = name; - this.displayName = displayName; - this.dataReady = true; - this.syncObject = new object(); + internal EventOpcode(string name, int value, string displayName) + { + _value = value; + _name = name; + _displayName = displayName; + _dataReady = true; + _syncObject = new object(); } - internal void PrepareData() { - lock (syncObject) { - if (dataReady == true) return; + internal void PrepareData() + { + lock (_syncObject) + { + if (_dataReady == true) return; // get the data - IEnumerable result = pmReference.Opcodes; + IEnumerable result = _pmReference.Opcodes; //set the names and display names to null - this.name = null; - this.displayName = null; - this.dataReady = true; - foreach (EventOpcode op in result) { - if (op.Value == this.value) { - this.name = op.Name; - this.displayName = op.DisplayName; - this.dataReady = true; + _name = null; + _displayName = null; + _dataReady = true; + foreach (EventOpcode op in result) + { + if (op.Value == _value) + { + _name = op.Name; + _displayName = op.DisplayName; + _dataReady = true; break; } } } }//End Prepare Data - public string Name { - get { + public string Name + { + get + { PrepareData(); - return this.name; + return _name; } } - public int Value { - get { - return this.value; + public int Value + { + get + { + return _value; } } - public string DisplayName { - get { + public string DisplayName + { + get + { PrepareData(); - return this.displayName; + return _displayName; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventProperty.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventProperty.cs index b62b33759..cd0cf68cf 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventProperty.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventProperty.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventProperty ** ** Purpose: ** This public class defines the methods / properties for the @@ -14,17 +9,22 @@ ** ============================================================*/ -namespace System.Diagnostics.Eventing.Reader { - public sealed class EventProperty { - private object value; +namespace System.Diagnostics.Eventing.Reader +{ + public sealed class EventProperty + { + private object _value; - internal EventProperty(object value) { - this.value = value; + internal EventProperty(object value) + { + _value = value; } - public object Value { - get { - return value; + public object Value + { + get + { + return _value; } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs index bd776bf75..1e29c3b05 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventPropertyContext.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventPropertyContext ** ** Purpose: ** This public abstract class defines the methods / properties @@ -14,13 +9,17 @@ ** ============================================================*/ -namespace System.Diagnostics.Eventing.Reader { - public abstract class EventPropertyContext : IDisposable { - public void Dispose() { +namespace System.Diagnostics.Eventing.Reader +{ + public abstract class EventPropertyContext : IDisposable + { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { + protected virtual void Dispose(bool disposing) + { } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs index 91c1b8a1c..e71841f0d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventRecord.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventRecord ** ** Purpose: ** This public abstract class defines the methods / properties @@ -17,12 +12,13 @@ using System.Collections.Generic; using System.Security.Principal; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Represents an event obtained from an EventReader. /// - public abstract class EventRecord : IDisposable { + public abstract class EventRecord : IDisposable + { public abstract int Id { get; } public abstract byte? Version { get; } public abstract byte? Level { get; } @@ -63,8 +59,9 @@ namespace System.Diagnostics.Eventing.Reader { public abstract IList Properties { get; } public abstract string ToXml(); - - public void Dispose() { + + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventTask.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventTask.cs index 226c308a0..5116a1b65 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventTask.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventTask.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: EventTask ** ** Purpose: ** This public class describes the metadata for a specific Task @@ -16,88 +11,102 @@ using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Describes the metadata for a specific Task defined by a Provider. /// An instance of this class is obtained from a ProviderMetadata object. /// - public sealed class EventTask { - private int value; - private string name; - private string displayName; - private Guid guid; - private bool dataReady; - ProviderMetadata pmReference; - object syncObject; + public sealed class EventTask + { + private int _value; + private string _name; + private string _displayName; + private Guid _guid; + private bool _dataReady; + private ProviderMetadata _pmReference; + private object _syncObject; //called from EventMetadata - internal EventTask(int value, ProviderMetadata pmReference) { - this.value = value; - this.pmReference = pmReference; - this.syncObject = new object(); + internal EventTask(int value, ProviderMetadata pmReference) + { + _value = value; + _pmReference = pmReference; + _syncObject = new object(); } //called from ProviderMetadata - internal EventTask(string name, int value, string displayName, Guid guid) { - this.value = value; - this.name = name; - this.displayName = displayName; - this.guid = guid; - this.dataReady = true; - this.syncObject = new object(); + internal EventTask(string name, int value, string displayName, Guid guid) + { + _value = value; + _name = name; + _displayName = displayName; + _guid = guid; + _dataReady = true; + _syncObject = new object(); } - internal void PrepareData() { - lock (syncObject) { - if (dataReady == true) return; + internal void PrepareData() + { + lock (_syncObject) + { + if (_dataReady == true) return; - IEnumerable result = pmReference.Tasks; + IEnumerable result = _pmReference.Tasks; - this.name = null; - this.displayName = null; - this.guid = Guid.Empty; - this.dataReady = true; + _name = null; + _displayName = null; + _guid = Guid.Empty; + _dataReady = true; - foreach (EventTask task in result) { - if (task.Value == this.value) { - this.name = task.Name; - this.displayName = task.DisplayName; - this.guid = task.EventGuid; - this.dataReady = true; + foreach (EventTask task in result) + { + if (task.Value == _value) + { + _name = task.Name; + _displayName = task.DisplayName; + _guid = task.EventGuid; + _dataReady = true; break; } } } } - public string Name { - get { + public string Name + { + get + { PrepareData(); - return this.name; + return _name; } } - public int Value { - get { - return this.value; + public int Value + { + get + { + return _value; } } - public string DisplayName { - get { + public string DisplayName + { + get + { PrepareData(); - return this.displayName; + return _displayName; } } - public Guid EventGuid { - get { + public Guid EventGuid + { + get + { PrepareData(); - return this.guid; + return _guid; } } } - } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 44f840edc..8b7410d4c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: NativeWrapper ** ** Purpose: ** This internal class contains wrapper methods over the Native @@ -22,10 +17,12 @@ using System.Runtime.InteropServices; using System.Text; using System.Security.Principal; -namespace System.Diagnostics.Eventing.Reader { - internal class NativeWrapper { - - public class SystemProperties { +namespace System.Diagnostics.Eventing.Reader +{ + internal class NativeWrapper + { + public class SystemProperties + { //indicates if the SystemProperties values were already computed (for this event Instance, surely). public bool filled = false; @@ -48,16 +45,18 @@ namespace System.Diagnostics.Eventing.Reader { public Guid? ActivityId = null; public Guid? RelatedActivityId = null; - public SystemProperties() { + public SystemProperties() + { } } - + [System.Security.SecurityCritical] public static EventLogHandle EvtQuery( EventLogHandle session, string path, string query, - int flags) { + int flags) + { EventLogHandle handle = UnsafeNativeMethods.EvtQuery(session, path, query, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) @@ -65,14 +64,15 @@ namespace System.Diagnostics.Eventing.Reader { return handle; } - + [System.Security.SecurityCritical] public static void EvtSeek( EventLogHandle resultSet, long position, EventLogHandle bookmark, int timeout, - UnsafeNativeMethods.EvtSeekFlags flags) { + UnsafeNativeMethods.EvtSeekFlags flags) + { bool status = UnsafeNativeMethods.EvtSeek(resultSet, position, bookmark, timeout, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) @@ -86,7 +86,8 @@ namespace System.Diagnostics.Eventing.Reader { IntPtr[] events, int timeout, int flags, - ref int returned) { + ref int returned) + { bool status = UnsafeNativeMethods.EvtNext(queryHandle, eventSize, events, timeout, flags, ref returned); int win32Error = Marshal.GetLastWin32Error(); if (!status && win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) @@ -95,16 +96,18 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecuritySafeCritical] - public static void EvtCancel(EventLogHandle handle) { - - if (!UnsafeNativeMethods.EvtCancel(handle)) { + public static void EvtCancel(EventLogHandle handle) + { + if (!UnsafeNativeMethods.EvtCancel(handle)) + { int win32Error = Marshal.GetLastWin32Error(); EventLogException.Throw(win32Error); } } - + [System.Security.SecurityCritical] - public static void EvtClose(IntPtr handle) { + public static void EvtClose(IntPtr handle) + { // // purposely don't check and throw - this is // always called in cleanup / finalize / etc.. @@ -118,7 +121,8 @@ namespace System.Diagnostics.Eventing.Reader { string ProviderId, string logFilePath, int locale, - int flags) { + int flags) + { // // ignore locale and pass 0 instead: that way, the thread locale will be retrieved in the API layer // and the "strict rendering" flag will NOT be set. Otherwise, the fall back logic is broken and the descriptions @@ -133,7 +137,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static int EvtGetObjectArraySize(EventLogHandle objectArray) { + public static int EvtGetObjectArraySize(EventLogHandle objectArray) + { int arraySize; bool status = UnsafeNativeMethods.EvtGetObjectArraySize(objectArray, out arraySize); int win32Error = Marshal.GetLastWin32Error(); @@ -143,7 +148,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenEventMetadataEnum(EventLogHandle ProviderMetadata, int flags) { + public static EventLogHandle EvtOpenEventMetadataEnum(EventLogHandle ProviderMetadata, int flags) + { EventLogHandle emEnumHandle = UnsafeNativeMethods.EvtOpenEventMetadataEnum(ProviderMetadata, flags); int win32Error = Marshal.GetLastWin32Error(); if (emEnumHandle.IsInvalid) @@ -153,11 +159,13 @@ namespace System.Diagnostics.Eventing.Reader { // returns null if EOF [System.Security.SecurityCritical] - public static EventLogHandle EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) { + public static EventLogHandle EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) + { EventLogHandle emHandle = UnsafeNativeMethods.EvtNextEventMetadata(eventMetadataEnum, flags); int win32Error = Marshal.GetLastWin32Error(); - if (emHandle.IsInvalid) { + if (emHandle.IsInvalid) + { if (win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) EventLogException.Throw(win32Error); return null; @@ -167,8 +175,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenChannelEnum(EventLogHandle session, int flags) { - + public static EventLogHandle EvtOpenChannelEnum(EventLogHandle session, int flags) + { EventLogHandle channelEnum = UnsafeNativeMethods.EvtOpenChannelEnum(session, flags); int win32Error = Marshal.GetLastWin32Error(); if (channelEnum.IsInvalid) @@ -177,8 +185,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenProviderEnum(EventLogHandle session, int flags) { - + public static EventLogHandle EvtOpenProviderEnum(EventLogHandle session, int flags) + { EventLogHandle pubEnum = UnsafeNativeMethods.EvtOpenPublisherEnum(session, flags); int win32Error = Marshal.GetLastWin32Error(); if (pubEnum.IsInvalid) @@ -187,8 +195,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenChannelConfig(EventLogHandle session, String channelPath, int flags) { - + public static EventLogHandle EvtOpenChannelConfig(EventLogHandle session, String channelPath, int flags) + { EventLogHandle handle = UnsafeNativeMethods.EvtOpenChannelConfig(session, channelPath, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) @@ -197,7 +205,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecuritySafeCritical] - public static void EvtSaveChannelConfig(EventLogHandle channelConfig, int flags) { + public static void EvtSaveChannelConfig(EventLogHandle channelConfig, int flags) + { bool status = UnsafeNativeMethods.EvtSaveChannelConfig(channelConfig, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) @@ -206,8 +215,8 @@ namespace System.Diagnostics.Eventing.Reader { [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenLog(EventLogHandle session, string path, PathType flags) { - + public static EventLogHandle EvtOpenLog(EventLogHandle session, string path, PathType flags) + { EventLogHandle logHandle = UnsafeNativeMethods.EvtOpenLog(session, path, flags); int win32Error = Marshal.GetLastWin32Error(); if (logHandle.IsInvalid) @@ -221,8 +230,8 @@ namespace System.Diagnostics.Eventing.Reader { string channelPath, string query, string targetFilePath, - int flags) { - + int flags) + { bool status; status = UnsafeNativeMethods.EvtExportLog(session, channelPath, query, targetFilePath, flags); int win32Error = Marshal.GetLastWin32Error(); @@ -235,8 +244,8 @@ namespace System.Diagnostics.Eventing.Reader { EventLogHandle session, string logFilePath, int locale, - int flags) { - + int flags) + { bool status; status = UnsafeNativeMethods.EvtArchiveExportedLog(session, logFilePath, locale, flags); int win32Error = Marshal.GetLastWin32Error(); @@ -249,8 +258,8 @@ namespace System.Diagnostics.Eventing.Reader { EventLogHandle session, string channelPath, string targetFilePath, - int flags) { - + int flags) + { bool status; status = UnsafeNativeMethods.EvtClearLog(session, channelPath, targetFilePath, flags); int win32Error = Marshal.GetLastWin32Error(); @@ -262,8 +271,8 @@ namespace System.Diagnostics.Eventing.Reader { public static EventLogHandle EvtCreateRenderContext( Int32 valuePathsCount, String[] valuePaths, - UnsafeNativeMethods.EvtRenderContextFlags flags) { - + UnsafeNativeMethods.EvtRenderContextFlags flags) + { EventLogHandle renderContextHandleValues = UnsafeNativeMethods.EvtCreateRenderContext(valuePathsCount, valuePaths, flags); int win32Error = Marshal.GetLastWin32Error(); if (renderContextHandleValues.IsInvalid) @@ -276,29 +285,32 @@ namespace System.Diagnostics.Eventing.Reader { EventLogHandle context, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flags, - StringBuilder buffer) { - + StringBuilder buffer) + { int buffUsed; int propCount; bool status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { - if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) { + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) + { //reallocate the new RenderBuffer with the right size. buffer.Capacity = buffUsed; status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); win32Error = Marshal.GetLastWin32Error(); } - if (!status) { + if (!status) + { EventLogException.Throw(win32Error); } } } [System.Security.SecurityCritical] - public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass loginClass, ref UnsafeNativeMethods.EvtRpcLogin login, int timeout, int flags) { - + public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass loginClass, ref UnsafeNativeMethods.EvtRpcLogin login, int timeout, int flags) + { EventLogHandle handle = UnsafeNativeMethods.EvtOpenSession(loginClass, ref login, timeout, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) @@ -307,8 +319,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static EventLogHandle EvtCreateBookmark(string bookmarkXml) { - + public static EventLogHandle EvtCreateBookmark(string bookmarkXml) + { EventLogHandle handle = UnsafeNativeMethods.EvtCreateBookmark(bookmarkXml); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) @@ -317,7 +329,8 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static void EvtUpdateBookmark(EventLogHandle bookmark, EventLogHandle eventHandle) { + public static void EvtUpdateBookmark(EventLogHandle bookmark, EventLogHandle eventHandle) + { bool status = UnsafeNativeMethods.EvtUpdateBookmark(bookmark, eventHandle); int win32Error = Marshal.GetLastWin32Error(); if (!status) @@ -325,18 +338,21 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecuritySafeCritical] - public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) { + public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - - try { + + try + { bool status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error == UnsafeNativeMethods.ERROR_SUCCESS) { } else if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) - EventLogException.Throw(error); + EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); @@ -346,22 +362,25 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); - } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecurityCritical] - public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) { + public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded = 0; - try { + try + { bool status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, 0, IntPtr.Zero, ref bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -374,20 +393,24 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecuritySafeCritical] - public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) { + public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - - try { + + try + { bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -400,20 +423,24 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecurityCritical] - internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) { + internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) + { IntPtr buffer = IntPtr.Zero; - try { + try + { int bufferNeeded; bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -433,7 +460,8 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToSafeHandle(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } @@ -441,19 +469,21 @@ namespace System.Diagnostics.Eventing.Reader { // implies UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId flag. [System.Security.SecurityCritical] - public static string EvtFormatMessage(EventLogHandle handle, uint msgId) { - + public static string EvtFormatMessage(EventLogHandle handle, uint msgId) + { int bufferNeeded; StringBuilder sb = new StringBuilder(null); - bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded); + bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); // ERROR_EVT_UNRESOLVED_VALUE_INSERT and its cousins are commonly returned for raw message text. if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT - && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED ) { - switch (error) { + && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) + { + switch (error) + { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: @@ -466,21 +496,24 @@ namespace System.Diagnostics.Eventing.Reader { } sb.EnsureCapacity(bufferNeeded); - status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, sb, out bufferNeeded); + status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT - && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED ) { - switch (error) { + && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) + { + switch (error) + { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: - case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: + case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } - if (error == UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { + if (error == UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { return null; } EventLogException.Throw(error); @@ -489,15 +522,18 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) { + public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - try { + try + { bool status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -510,20 +546,24 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecurityCritical] - public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) { + public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - try { + try + { bool status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } @@ -536,22 +576,25 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecuritySafeCritical] - public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) { + public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - - try { + try + { bool status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } @@ -571,64 +614,74 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecuritySafeCritical] - public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) { - + public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) + { UnsafeNativeMethods.EvtVariant varVal = new UnsafeNativeMethods.EvtVariant(); CoTaskMemSafeHandle taskMem = new CoTaskMemSafeHandle(); - using (taskMem) { - - if (val != null) { - - switch (enumType) { - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: { + using (taskMem) + { + if (val != null) + { + switch (enumType) + { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; varVal.UInteger = (uint)((int)val); } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } break; - case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: { + case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; @@ -638,7 +691,8 @@ namespace System.Diagnostics.Eventing.Reader { throw new InvalidOperationException(); } } - else { + else + { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull; } bool status = UnsafeNativeMethods.EvtSetChannelConfigProperty(handle, enumType, 0, ref varVal); @@ -649,14 +703,17 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) { + public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) + { StringBuilder sb = new StringBuilder(null); int channelNameNeeded; bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, sb, out channelNameNeeded); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { - if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) { + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + { finish = true; return null; } @@ -675,14 +732,17 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) { + public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) + { StringBuilder sb = new StringBuilder(null); int ProviderIdNeeded; bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, sb, out ProviderIdNeeded); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { - if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) { + if (!status) + { + if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) + { finish = true; return null; } @@ -701,14 +761,17 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) { + public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - try { + try + { bool status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } @@ -721,22 +784,26 @@ namespace System.Diagnostics.Eventing.Reader { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(buffer); return ConvertToObject(varVal); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecuritySafeCritical] - public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flag, SystemProperties systemProperties, int SYSTEM_PROPERTY_COUNT) { + public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flag, SystemProperties systemProperties, int SYSTEM_PROPERTY_COUNT) + { IntPtr buffer = IntPtr.Zero; IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; - - try { + + try + { bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); - if (!status) { + if (!status) + { int error = Marshal.GetLastWin32Error(); if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); @@ -753,68 +820,71 @@ namespace System.Diagnostics.Eventing.Reader { pointer = buffer; //read each Variant structure - for (int i = 0; i < propCount; i++) { + for (int i = 0; i < propCount; i++) + { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); - switch (i) { - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderName: + switch (i) + { + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderName: systemProperties.ProviderName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderGuid: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderGuid: systemProperties.ProviderId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventID: systemProperties.Id = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemQualifiers: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemQualifiers: systemProperties.Qualifiers = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemLevel: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemLevel: systemProperties.Level = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTask: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTask: systemProperties.Task = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemOpcode: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemOpcode: systemProperties.Opcode = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemKeywords: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemKeywords: systemProperties.Keywords = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTimeCreated: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTimeCreated: systemProperties.TimeCreated = (DateTime?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventRecordId: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventRecordId: systemProperties.RecordId = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemActivityID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemActivityID: systemProperties.ActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemRelatedActivityID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemRelatedActivityID: systemProperties.RelatedActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProcessID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProcessID: systemProperties.ProcessId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemThreadID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemThreadID: systemProperties.ThreadId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemChannel: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemChannel: systemProperties.ChannelName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemComputer: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemComputer: systemProperties.ComputerName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemUserID: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemUserID: systemProperties.UserId = (SecurityIdentifier)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid); break; - case (int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemVersion: + case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemVersion: systemProperties.Version = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; } pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); } } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } @@ -823,16 +893,19 @@ namespace System.Diagnostics.Eventing.Reader { //EvtRenderContextFlags can be both: EvtRenderContextFlags.EvtRenderContextUser and EvtRenderContextFlags.EvtRenderContextValues //Render with Context = ContextUser or ContextValues (with user defined Xpath query strings) [System.Security.SecuritySafeCritical] - public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) { + public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) + { IntPtr buffer = IntPtr.Zero; IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; - - try { + UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; + + try + { bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); - if (!status) { + if (!status) + { int error = Marshal.GetLastWin32Error(); if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); @@ -845,9 +918,11 @@ namespace System.Diagnostics.Eventing.Reader { EventLogException.Throw(win32Error); List valuesList = new List(propCount); - if (propCount > 0) { + if (propCount > 0) + { pointer = buffer; - for (int i = 0; i < propCount; i++) { + for (int i = 0; i < propCount; i++) + { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); valuesList.Add(ConvertToObject(varVal)); pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); @@ -855,29 +930,32 @@ namespace System.Diagnostics.Eventing.Reader { } return valuesList; } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecuritySafeCritical] - public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { - + public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + { int bufferNeeded; StringBuilder sb = new StringBuilder(null); bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { // // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means // message may have one or more unsubstitued strings. This is // not an exception, but we have no way to convey the partial // success out to enduser. // - switch (error) { + switch (error) + { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: @@ -893,9 +971,10 @@ namespace System.Diagnostics.Eventing.Reader { status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); - if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { - switch (error) { + switch (error) + { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: @@ -911,18 +990,21 @@ namespace System.Diagnostics.Eventing.Reader { //The EvtFormatMessage used for the obtaining of the Keywords names. [System.Security.SecuritySafeCritical] - public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { - + public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; - try { + try + { List keywordsList = new List(); bool status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status) { - switch (error) { + if (!status) + { + switch (error) + { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: @@ -937,7 +1019,8 @@ namespace System.Diagnostics.Eventing.Reader { buffer = Marshal.AllocHGlobal(bufferNeeded * 2); status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: @@ -952,7 +1035,8 @@ namespace System.Diagnostics.Eventing.Reader { IntPtr pointer = buffer; - while (true) { + while (true) + { string s = Marshal.PtrToStringUni(pointer); if (String.IsNullOrEmpty(s)) break; @@ -963,23 +1047,27 @@ namespace System.Diagnostics.Eventing.Reader { return keywordsList.AsReadOnly(); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } [System.Security.SecurityCritical] - public static string EvtRenderBookmark(EventLogHandle eventHandle) { + public static string EvtRenderBookmark(EventLogHandle eventHandle) + { IntPtr buffer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; + UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; - try { + try + { bool status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); int error = Marshal.GetLastWin32Error(); - if (!status) { + if (!status) + { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } @@ -992,7 +1080,8 @@ namespace System.Diagnostics.Eventing.Reader { return Marshal.PtrToStringUni(buffer); } - finally { + finally + { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } @@ -1001,12 +1090,13 @@ namespace System.Diagnostics.Eventing.Reader { //Get the formatted description, using the msgId for FormatDescription(string []) [System.Security.SecuritySafeCritical] - public static string EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string[] values) { - + public static string EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string[] values) + { int bufferNeeded; - UnsafeNativeMethods.EvtStringVariant [] stringVariants = new UnsafeNativeMethods.EvtStringVariant[values.Length]; - for (int i = 0; i < values.Length; i++) { + UnsafeNativeMethods.EvtStringVariant[] stringVariants = new UnsafeNativeMethods.EvtStringVariant[values.Length]; + for (int i = 0; i < values.Length; i++) + { stringVariants[i].Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; stringVariants[i].StringVal = values[i]; } @@ -1015,7 +1105,8 @@ namespace System.Diagnostics.Eventing.Reader { bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); - if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { // // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means // message may have one or more unsubstitued strings. This is @@ -1039,7 +1130,8 @@ namespace System.Diagnostics.Eventing.Reader { status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); - if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { + if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) + { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: @@ -1052,13 +1144,13 @@ namespace System.Diagnostics.Eventing.Reader { EventLogException.Throw(error); } return sb.ToString(); - } [System.Security.SecurityCritical] - private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) { - - switch (val.Type) { + private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) + { + switch (val.Type) + { case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32: return val.UInteger; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32: @@ -1092,92 +1184,94 @@ namespace System.Diagnostics.Eventing.Reader { case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid: return (val.SidVal == IntPtr.Zero) ? null : new SecurityIdentifier(val.SidVal); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid: - return (val.GuidReference == IntPtr.Zero) ? Guid.Empty : Marshal.PtrToStructure(val.GuidReference); + return (val.GuidReference == IntPtr.Zero) ? Guid.Empty : Marshal.PtrToStructure(val.GuidReference); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeEvtHandle: return ConvertToSafeHandle(val); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime: return DateTime.FromFileTime((long)val.FileTime); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime: - UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(val.SystemTime); + UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(val.SystemTime); return new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT: - return val.SizeT; + return val.SizeT; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean: if (val.Bool != 0) return true; else return false; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary: - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte): if (val.Reference == IntPtr.Zero) return new Byte[0]; Byte[] arByte = new Byte[val.Count]; Marshal.Copy(val.Reference, arByte, 0, (int)val.Count); return arByte; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16): if (val.Reference == IntPtr.Zero) return new Int16[0]; Int16[] arInt16 = new Int16[val.Count]; Marshal.Copy(val.Reference, arInt16, 0, (int)val.Count); return arInt16; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32): if (val.Reference == IntPtr.Zero) return new Int32[0]; Int32[] arInt32 = new Int32[val.Count]; Marshal.Copy(val.Reference, arInt32, 0, (int)val.Count); return arInt32; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64): if (val.Reference == IntPtr.Zero) return new Int64[0]; Int64[] arInt64 = new Int64[val.Count]; Marshal.Copy(val.Reference, arInt64, 0, (int)val.Count); - return arInt64; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle): + return arInt64; + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle): if (val.Reference == IntPtr.Zero) return new Single[0]; Single[] arSingle = new Single[val.Count]; Marshal.Copy(val.Reference, arSingle, 0, (int)val.Count); return arSingle; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble): if (val.Reference == IntPtr.Zero) return new Double[0]; Double[] arDouble = new Double[val.Count]; Marshal.Copy(val.Reference, arDouble, 0, (int)val.Count); return arDouble; - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte): return ConvertToArray(val, sizeof(SByte)); // not CLS-compliant - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16): - return ConvertToArray(val, sizeof(UInt16)); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64): - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64): - return ConvertToArray(val, sizeof(UInt64)); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32): - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32): - return ConvertToArray(val, sizeof(UInt32)); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16): + return ConvertToArray(val, sizeof(UInt16)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64): + return ConvertToArray(val, sizeof(UInt64)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32): + return ConvertToArray(val, sizeof(UInt32)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString): return ConvertToStringArray(val, false); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString): - return ConvertToStringArray(val, true); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean): + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString): + return ConvertToStringArray(val, true); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean): return ConvertToBoolArray(val); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid): - return ConvertToArray(val, 16 * sizeof(byte)); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime): - return ConvertToFileTimeArray(val); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime): - return ConvertToSysTimeArray(val); - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary): //both length and count in the manifest: tracrpt supports, Crimson APIs don't - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT): //unused: array of win:pointer is returned as HexIntXX - case ((int) UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid): //unsupported by native APIs + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid): + return ConvertToArray(val, 16 * sizeof(byte)); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime): + return ConvertToFileTimeArray(val); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime): + return ConvertToSysTimeArray(val); + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary): //both length and count in the manifest: tracrpt supports, Crimson APIs don't + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT): //unused: array of win:pointer is returned as HexIntXX + case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid): //unsupported by native APIs default: throw new EventLogInvalidDataException(); } } - [System.Security.SecurityCritical] - public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) { + [System.Security.SecurityCritical] + public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) + { if (val.Type == (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull) return null; if (val.Type != (int)desiredType) throw new EventLogInvalidDataException(); return ConvertToObject(val); - } + } [System.Security.SecurityCritical] - public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) { + public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) + { if (val.StringVal == IntPtr.Zero) return string.Empty; else @@ -1185,16 +1279,18 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecurityCritical] - public static string ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) { + public static string ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) + { if (val.AnsiString == IntPtr.Zero) return string.Empty; else return Marshal.PtrToStringAnsi(val.AnsiString); } - + [System.Security.SecurityCritical] - public static EventLogHandle ConvertToSafeHandle(UnsafeNativeMethods.EvtVariant val) { + public static EventLogHandle ConvertToSafeHandle(UnsafeNativeMethods.EvtVariant val) + { if (val.Handle == IntPtr.Zero) return EventLogHandle.Zero; else @@ -1203,92 +1299,108 @@ namespace System.Diagnostics.Eventing.Reader { [System.Security.SecurityCritical] - public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int size) where T : struct { - IntPtr ptr = val.Reference; - if (ptr == IntPtr.Zero) { + public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int size) where T : struct + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { return Array.CreateInstance(typeof(T), 0); } - else { - Array array = Array.CreateInstance(typeof(T), (int)val.Count); - for (int i = 0; i < val.Count; i++) { + else + { + Array array = Array.CreateInstance(typeof(T), (int)val.Count); + for (int i = 0; i < val.Count; i++) + { array.SetValue(Marshal.PtrToStructure(ptr), i); - ptr = new IntPtr ((Int64)ptr + size); + ptr = new IntPtr((Int64)ptr + size); } - return array; + return array; } } [System.Security.SecurityCritical] - public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) { - - //NOTE: booleans are padded to 4 bytes in ETW - IntPtr ptr = val.Reference; - if (ptr == IntPtr.Zero) { + public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) + { + //NOTE: booleans are padded to 4 bytes in ETW + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { return new bool[0]; } - else { - bool[] array = new bool[val.Count]; - for (int i = 0; i < val.Count; i++) { + else + { + bool[] array = new bool[val.Count]; + for (int i = 0; i < val.Count; i++) + { bool value = (Marshal.ReadInt32(ptr) != 0) ? true : false; array[i] = value; - ptr = new IntPtr ((Int64)ptr + 4); + ptr = new IntPtr((Int64)ptr + 4); } - return array; + return array; } - } + } [System.Security.SecurityCritical] - public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) { - IntPtr ptr = val.Reference; - if (ptr == IntPtr.Zero) { + public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { return new DateTime[0]; } - else { - DateTime[] array = new DateTime[val.Count]; - for (int i = 0; i < val.Count; i++) { + else + { + DateTime[] array = new DateTime[val.Count]; + for (int i = 0; i < val.Count; i++) + { array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); - ptr = new IntPtr((Int64)ptr + 8*sizeof(byte)); // FILETIME values are 8 bytes + ptr = new IntPtr((Int64)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes } - return array; + return array; } - } + } [System.Security.SecurityCritical] - public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) { - IntPtr ptr = val.Reference; - if (ptr == IntPtr.Zero) { + public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) + { + IntPtr ptr = val.Reference; + if (ptr == IntPtr.Zero) + { return new DateTime[0]; } - else { - DateTime[] array = new DateTime[val.Count]; - for (int i = 0; i < val.Count; i++) { - - UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(ptr); + else + { + DateTime[] array = new DateTime[val.Count]; + for (int i = 0; i < val.Count; i++) + { + UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure(ptr); array[i] = new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); - ptr = new IntPtr((Int64)ptr + 16*sizeof(byte)); // SystemTime values are 16 bytes - + ptr = new IntPtr((Int64)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes } - return array; + return array; } - } - + } + [System.Security.SecurityCritical] - public static string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) { - if (val.Reference == IntPtr.Zero) { + public static string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) + { + if (val.Reference == IntPtr.Zero) + { return new string[0]; } - else { + else + { IntPtr ptr = val.Reference; IntPtr[] pointersToString = new IntPtr[val.Count]; - Marshal.Copy(ptr, pointersToString, 0, (int)val.Count); + Marshal.Copy(ptr, pointersToString, 0, (int)val.Count); string[] stringArray = new string[val.Count]; - for (int i = 0; i < val.Count; i++) { + for (int i = 0; i < val.Count; i++) + { stringArray[i] = ansi ? Marshal.PtrToStringAnsi(pointersToString[i]) : Marshal.PtrToStringUni(pointersToString[i]); } return stringArray; } } - } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs index 8319789e7..5a524bf27 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadata.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: ProviderMetadata ** ** Purpose: ** This public class exposes all the metadata for a specific @@ -18,252 +13,281 @@ using System.Globalization; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ /// /// Exposes all the metadata for a specific event Provider. An instance /// of this class is obtained from EventLogManagement and is scoped to a /// single Locale. /// - public class ProviderMetadata : IDisposable { - + public class ProviderMetadata : IDisposable + { // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // - private EventLogHandle handle = EventLogHandle.Zero; + private EventLogHandle _handle = EventLogHandle.Zero; - private EventLogHandle defaultProviderHandle = EventLogHandle.Zero; + private EventLogHandle _defaultProviderHandle = EventLogHandle.Zero; - private EventLogSession session = null; + private EventLogSession _session = null; - private string providerName; - private CultureInfo cultureInfo; - private string logFilePath; + private string _providerName; + private CultureInfo _cultureInfo; + private string _logFilePath; //caching of the IEnumerable, , , on the ProviderMetadata //they do not change with every call. - private IList levels = null; - private IList opcodes = null; - private IList tasks = null; - private IList keywords = null; - private IList standardLevels = null; - private IList standardOpcodes = null; - private IList standardTasks = null; - private IList standardKeywords = null; - private IList channelReferences = null; + private IList _levels = null; + private IList _opcodes = null; + private IList _tasks = null; + private IList _keywords = null; + private IList _standardLevels = null; + private IList _standardOpcodes = null; + private IList _standardTasks = null; + private IList _standardKeywords = null; + private IList _channelReferences = null; - private object syncObject; + private object _syncObject; public ProviderMetadata(string providerName) - : this(providerName, null, null, null) { + : this(providerName, null, null, null) + { } public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo) - : this(providerName, session, targetCultureInfo, null) { + : this(providerName, session, targetCultureInfo, null) + { } // SecurityCritical since it allocates SafeHandles. // Marked TreatAsSafe since we perform the Demand check. [System.Security.SecuritySafeCritical] - internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) { - + internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) + { if (targetCultureInfo == null) targetCultureInfo = CultureInfo.CurrentCulture; if (session == null) session = EventLogSession.GlobalSession; - this.session = session; - this.providerName = providerName; - this.cultureInfo = targetCultureInfo; - this.logFilePath = logFilePath; + _session = session; + _providerName = providerName; + _cultureInfo = targetCultureInfo; + _logFilePath = logFilePath; - handle = NativeWrapper.EvtOpenProviderMetadata(this.session.Handle, this.providerName, this.logFilePath, 0, 0); + _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0); - this.syncObject = new object(); + _syncObject = new object(); } - internal EventLogHandle Handle { - get { - return handle; + internal EventLogHandle Handle + { + get + { + return _handle; } } - public string Name { - get { return providerName; } + public string Name + { + get { return _providerName; } } - public Guid Id { - get { - return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid); + public Guid Id + { + get + { + return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid); } } - public string MessageFilePath { - get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath); + public string MessageFilePath + { + get + { + return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath); } } - public string ResourceFilePath { - get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath); + public string ResourceFilePath + { + get + { + return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath); } } - public string ParameterFilePath { - get { - return (string)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath); + public string ParameterFilePath + { + get + { + return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath); } } - public Uri HelpLink { - get { - string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); - if ( helpLinkStr == null || helpLinkStr.Length == 0 ) + public Uri HelpLink + { + get + { + string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); + if (helpLinkStr == null || helpLinkStr.Length == 0) return null; - return new Uri(helpLinkStr); + return new Uri(helpLinkStr); } } - private uint ProviderMessageID { - get { - return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID); + private uint ProviderMessageID + { + get + { + return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID); } } - public string DisplayName { + public string DisplayName + { [System.Security.SecurityCritical] - get { - + get + { uint msgId = (uint)this.ProviderMessageID; - if ( msgId == 0xffffffff ) + if (msgId == 0xffffffff) return null; - return NativeWrapper.EvtFormatMessage(this.handle, msgId); + return NativeWrapper.EvtFormatMessage(_handle, msgId); } } - public IList LogLinks { + public IList LogLinks + { [System.Security.SecurityCritical] - get { - + get + { EventLogHandle elHandle = EventLogHandle.Zero; - try { - lock (syncObject) { + try + { + lock (_syncObject) + { + if (_channelReferences != null) + return _channelReferences; - if (this.channelReferences != null) - return this.channelReferences; - - elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences); + elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences); int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle); List channelList = new List(arraySize); - for (int index = 0; index < arraySize; index++) { + for (int index = 0; index < arraySize; index++) + { + string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath); - string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int) UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath); + uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID); - uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int) UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID); - - uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int) UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags); + uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags); bool isImported; - if (flag == (int) UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported) isImported = true; + if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported) isImported = true; else isImported = false; - int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int) UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID))); + int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID))); string channelRefDisplayName; //if channelRefMessageId == -1, we do not have anything in the message table. - if (channelRefMessageId == -1) { + if (channelRefMessageId == -1) + { channelRefDisplayName = null; } - else { - channelRefDisplayName = NativeWrapper.EvtFormatMessage(this.handle, unchecked((uint)channelRefMessageId)); + else + { + channelRefDisplayName = NativeWrapper.EvtFormatMessage(_handle, unchecked((uint)channelRefMessageId)); } - if (channelRefDisplayName == null && isImported) { - - if (String.Compare(channelName, "Application", StringComparison.OrdinalIgnoreCase ) == 0) + if (channelRefDisplayName == null && isImported) + { + if (String.Compare(channelName, "Application", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 256; - else if ( String.Compare(channelName, "System", StringComparison.OrdinalIgnoreCase ) == 0) + else if (String.Compare(channelName, "System", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 258; - else if ( String.Compare(channelName, "Security", StringComparison.OrdinalIgnoreCase ) == 0) + else if (String.Compare(channelName, "Security", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 257; else channelRefMessageId = -1; - if ( channelRefMessageId != -1 ) { - - if ( this.defaultProviderHandle.IsInvalid ) { - this.defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(this.session.Handle, null, null, 0, 0); + if (channelRefMessageId != -1) + { + if (_defaultProviderHandle.IsInvalid) + { + _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); } - channelRefDisplayName = NativeWrapper.EvtFormatMessage(this.defaultProviderHandle, unchecked((uint)channelRefMessageId)); + channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId)); } } - + channelList.Add(new EventLogLink(channelName, isImported, channelRefDisplayName, channelId)); } - this.channelReferences = channelList.AsReadOnly(); + _channelReferences = channelList.AsReadOnly(); } - return this.channelReferences; + return _channelReferences; } - finally { + finally + { elHandle.Dispose(); } } } - internal enum ObjectTypeName { + internal enum ObjectTypeName + { Level = 0, Opcode = 1, Task = 2, Keyword = 3 } - internal string FindStandardLevelDisplayName(string name, uint value) { - - if( this.standardLevels == null ) - this.standardLevels = (List)GetProviderListProperty(this.defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); - foreach (EventLevel standardLevel in this.standardLevels){ + internal string FindStandardLevelDisplayName(string name, uint value) + { + if (_standardLevels == null) + _standardLevels = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); + foreach (EventLevel standardLevel in _standardLevels) + { if (standardLevel.Name == name && standardLevel.Value == value) return standardLevel.DisplayName; - } - return null; + } + return null; } - internal string FindStandardOpcodeDisplayName(string name, uint value){ - - if ( this.standardOpcodes == null ) - this.standardOpcodes = (List)GetProviderListProperty(this.defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); - foreach (EventOpcode standardOpcode in this.standardOpcodes){ + internal string FindStandardOpcodeDisplayName(string name, uint value) + { + if (_standardOpcodes == null) + _standardOpcodes = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); + foreach (EventOpcode standardOpcode in _standardOpcodes) + { if (standardOpcode.Name == name && standardOpcode.Value == value) return standardOpcode.DisplayName; } return null; } - internal string FindStandardKeywordDisplayName(string name, long value) { - - if ( this.standardKeywords == null ) - this.standardKeywords = (List)GetProviderListProperty(this.defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); - foreach (EventKeyword standardKeyword in this.standardKeywords){ + internal string FindStandardKeywordDisplayName(string name, long value) + { + if (_standardKeywords == null) + _standardKeywords = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); + foreach (EventKeyword standardKeyword in _standardKeywords) + { if (standardKeyword.Name == name && standardKeyword.Value == value) return standardKeyword.DisplayName; } return null; } - internal string FindStandardTaskDisplayName(string name, uint value) { - - if ( this.standardTasks == null ) - this.standardTasks = (List)GetProviderListProperty(this.defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); - foreach (EventTask standardTask in this.standardTasks) { + internal string FindStandardTaskDisplayName(string name, uint value) + { + if (_standardTasks == null) + _standardTasks = (List)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + foreach (EventTask standardTask in _standardTasks) + { if (standardTask.Name == name && standardTask.Value == value) return standardTask.DisplayName; } @@ -271,13 +295,15 @@ namespace System.Diagnostics.Eventing.Reader { } [System.Security.SecuritySafeCritical] - internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty) { + internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty) + { EventLogHandle elHandle = EventLogHandle.Zero; - try { - UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName; - UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue; - UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId; + try + { + UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName; + UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue; + UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId; ObjectTypeName objectTypeName; List levelList = null; @@ -289,35 +315,36 @@ namespace System.Diagnostics.Eventing.Reader { int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle); - switch (metadataProperty) { - case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels: - propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName; - propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue; - propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID; + switch (metadataProperty) + { + case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels: + propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName; + propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue; + propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID; objectTypeName = ObjectTypeName.Level; levelList = new List(arraySize); break; - case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes: - propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName; - propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue; - propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID; + case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes: + propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName; + propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue; + propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID; objectTypeName = ObjectTypeName.Opcode; opcodeList = new List(arraySize); break; - case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords: - propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName; - propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue; - propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID; + case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords: + propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName; + propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue; + propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID; objectTypeName = ObjectTypeName.Keyword; keywordList = new List(arraySize); break; - case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks: - propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName; - propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue; - propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID; + case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks: + propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName; + propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue; + propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID; objectTypeName = ObjectTypeName.Task; taskList = new List(arraySize); break; @@ -325,16 +352,18 @@ namespace System.Diagnostics.Eventing.Reader { default: return null; } - for (int index = 0; index < arraySize; index++) { - + for (int index = 0; index < arraySize; index++) + { string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName); uint generalValue = 0; long generalValueKeyword = 0; - if (objectTypeName != ObjectTypeName.Keyword) { + if (objectTypeName != ObjectTypeName.Keyword) + { generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue); } - else { + else + { generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue))); } @@ -342,27 +371,28 @@ namespace System.Diagnostics.Eventing.Reader { string generalDisplayName = null; - if (generalMessageId == -1) { - - if (providerHandle != this.defaultProviderHandle) { - - if (this.defaultProviderHandle.IsInvalid) { - this.defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(this.session.Handle, null, null, 0, 0); + if (generalMessageId == -1) + { + if (providerHandle != _defaultProviderHandle) + { + if (_defaultProviderHandle.IsInvalid) + { + _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); } - switch (objectTypeName) { - + switch (objectTypeName) + { case ObjectTypeName.Level: - generalDisplayName = FindStandardLevelDisplayName( generalName, generalValue ); + generalDisplayName = FindStandardLevelDisplayName(generalName, generalValue); break; case ObjectTypeName.Opcode: - generalDisplayName = FindStandardOpcodeDisplayName( generalName, generalValue>>16 ); + generalDisplayName = FindStandardOpcodeDisplayName(generalName, generalValue >> 16); break; case ObjectTypeName.Keyword: generalDisplayName = FindStandardKeywordDisplayName(generalName, generalValueKeyword); break; case ObjectTypeName.Task: - generalDisplayName = FindStandardTaskDisplayName(generalName, generalValue); + generalDisplayName = FindStandardTaskDisplayName(generalName, generalValue); break; default: generalDisplayName = null; @@ -370,23 +400,25 @@ namespace System.Diagnostics.Eventing.Reader { } } } - else { + else + { generalDisplayName = NativeWrapper.EvtFormatMessage(providerHandle, unchecked((uint)generalMessageId)); } - switch (objectTypeName) { + switch (objectTypeName) + { case ObjectTypeName.Level: levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName)); break; case ObjectTypeName.Opcode: - opcodeList.Add(new EventOpcode(generalName, (int)(generalValue>>16), generalDisplayName)); + opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName)); break; case ObjectTypeName.Keyword: keywordList.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName)); break; case ObjectTypeName.Task: - Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int) UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid); + Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid); taskList.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid)); break; default: @@ -394,7 +426,8 @@ namespace System.Diagnostics.Eventing.Reader { } } - switch (objectTypeName) { + switch (objectTypeName) + { case ObjectTypeName.Level: return levelList; case ObjectTypeName.Opcode: @@ -406,87 +439,105 @@ namespace System.Diagnostics.Eventing.Reader { } return null; } - finally { + finally + { elHandle.Dispose(); } } - public IList Levels { - get { + public IList Levels + { + get + { List el; - lock (syncObject) { - if (this.levels != null) - return this.levels; + lock (_syncObject) + { + if (_levels != null) + return _levels; - el = (List)this.GetProviderListProperty( this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); - this.levels = el.AsReadOnly(); + el = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); + _levels = el.AsReadOnly(); } - return this.levels; + return _levels; } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcodes", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] - public IList Opcodes { - get { + public IList Opcodes + { + get + { List eo; - lock (syncObject) { - if (this.opcodes != null) - return this.opcodes; + lock (_syncObject) + { + if (_opcodes != null) + return _opcodes; - eo = (List)this.GetProviderListProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); - this.opcodes = eo.AsReadOnly(); + eo = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); + _opcodes = eo.AsReadOnly(); } - return this.opcodes; + return _opcodes; } } - public IList Keywords { - get { + public IList Keywords + { + get + { List ek; - lock (syncObject) { - if (this.keywords != null) - return this.keywords; + lock (_syncObject) + { + if (_keywords != null) + return _keywords; - ek = (List)this.GetProviderListProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); - this.keywords = ek.AsReadOnly(); + ek = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); + _keywords = ek.AsReadOnly(); } - return this.keywords; + return _keywords; } } - public IList Tasks { - get { + public IList Tasks + { + get + { List et; - lock (syncObject) { - if (this.tasks != null) - return this.tasks; + lock (_syncObject) + { + if (_tasks != null) + return _tasks; - et = (List)this.GetProviderListProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); - this.tasks = et.AsReadOnly(); + et = (List)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + _tasks = et.AsReadOnly(); } - return this.tasks; + return _tasks; } } - - public IEnumerable Events { - [System.Security.SecurityCritical] - get { + public IEnumerable Events + { + [System.Security.SecurityCritical] + get + { List emList = new List(); - EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(handle, 0); + EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(_handle, 0); - using (emEnumHandle) { - while (true) { + using (emEnumHandle) + { + while (true) + { EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0); if (emHandle == null) break; - using (emHandle) { - unchecked { + using (emHandle) + { + unchecked + { uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID); byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion))); byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel)); @@ -498,8 +549,8 @@ namespace System.Diagnostics.Eventing.Reader { int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID)); string emMessage = (messageId == -1) - ? null - : NativeWrapper.EvtFormatMessage(this.handle, (uint)messageId); + ? null + : NativeWrapper.EvtFormatMessage(_handle, (uint)messageId); EventMetadata em = new EventMetadata(emId, emVersion, emChannelId, emLevel, emOpcode, emTask, emKeywords, emTemplate, emMessage, this); emList.Add(em); @@ -513,22 +564,25 @@ namespace System.Diagnostics.Eventing.Reader { // throws if Provider metadata has been uninstalled since this object was created. - internal void CheckReleased() { - lock (syncObject) { - this.GetProviderListProperty(this.handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); + internal void CheckReleased() + { + lock (_syncObject) + { + this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); } } - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] - protected virtual void Dispose(bool disposing) { - - if (handle != null && !handle.IsInvalid) - handle.Dispose(); + protected virtual void Dispose(bool disposing) + { + if (_handle != null && !_handle.IsInvalid) + _handle.Dispose(); } } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs index fdfc0e624..d975eaaad 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/ProviderMetadataCachedInformation.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** Class: ProviderMetadataCachedInformation ** ** Purpose: ** This internal class exposes a limited set of cached Provider @@ -16,129 +11,150 @@ using System.Globalization; using System.Collections.Generic; -namespace System.Diagnostics.Eventing.Reader { - +namespace System.Diagnostics.Eventing.Reader +{ // // this class does not expose underlying Provider metadata objects. Instead it // exposes a limited set of Provider metadata information from the cache. The reason // for this is so the cache can easily Dispose the metadata object without worrying // about who is using it. // - internal class ProviderMetadataCachedInformation { + internal class ProviderMetadataCachedInformation + { + private Dictionary _cache; + private int _maximumCacheSize; + private EventLogSession _session; + private string _logfile; - private Dictionary cache; - private int maximumCacheSize; - private EventLogSession session; - private string logfile; + private class ProviderMetadataId + { + private string _providerName; + private CultureInfo _cultureInfo; - private class ProviderMetadataId { - private string providerName; - private CultureInfo cultureInfo; - - public ProviderMetadataId(string providerName, CultureInfo cultureInfo) { - this.providerName = providerName; - this.cultureInfo = cultureInfo; + public ProviderMetadataId(string providerName, CultureInfo cultureInfo) + { + _providerName = providerName; + _cultureInfo = cultureInfo; } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { ProviderMetadataId rhs = obj as ProviderMetadataId; if (rhs == null) return false; - if (this.providerName.Equals(rhs.providerName) && (cultureInfo == rhs.cultureInfo)) + if (_providerName.Equals(rhs._providerName) && (_cultureInfo == rhs._cultureInfo)) return true; return false; } - public override int GetHashCode() { - - return this.providerName.GetHashCode() ^ cultureInfo.GetHashCode(); - + public override int GetHashCode() + { + return _providerName.GetHashCode() ^ _cultureInfo.GetHashCode(); } - public string ProviderName { - get { - return providerName; + public string ProviderName + { + get + { + return _providerName; } } - public CultureInfo TheCultureInfo { - get { - return cultureInfo; + public CultureInfo TheCultureInfo + { + get + { + return _cultureInfo; } } } - private class CacheItem { - private ProviderMetadata pm; - private DateTime theTime; + private class CacheItem + { + private ProviderMetadata _pm; + private DateTime _theTime; - public CacheItem(ProviderMetadata pm) { - this.pm = pm; - theTime = DateTime.Now; + public CacheItem(ProviderMetadata pm) + { + _pm = pm; + _theTime = DateTime.Now; } - public DateTime TheTime { - get { - return theTime; + public DateTime TheTime + { + get + { + return _theTime; } - set { - theTime = value; + set + { + _theTime = value; } } - public ProviderMetadata ProviderMetadata { - get { - return pm; + public ProviderMetadata ProviderMetadata + { + get + { + return _pm; } } } - public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) { + public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) + { Debug.Assert(session != null); - this.session = session; - this.logfile = logfile; - cache = new Dictionary(); - this.maximumCacheSize = maximumCacheSize; + _session = session; + _logfile = logfile; + _cache = new Dictionary(); + _maximumCacheSize = maximumCacheSize; } - private bool IsCacheFull() { - return cache.Count == maximumCacheSize; + private bool IsCacheFull() + { + return _cache.Count == _maximumCacheSize; } - private bool IsProviderinCache(ProviderMetadataId key) { - return cache.ContainsKey(key); + private bool IsProviderinCache(ProviderMetadataId key) + { + return _cache.ContainsKey(key); } - private void DeleteCacheEntry(ProviderMetadataId key) { + private void DeleteCacheEntry(ProviderMetadataId key) + { if (!IsProviderinCache(key)) return; - CacheItem value = cache[key]; - cache.Remove(key); + CacheItem value = _cache[key]; + _cache.Remove(key); value.ProviderMetadata.Dispose(); } - private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) { + private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) + { if (IsCacheFull()) FlushOldestEntry(); CacheItem value = new CacheItem(pm); - cache.Add(key, value); + _cache.Add(key, value); return; } - private void FlushOldestEntry() { + private void FlushOldestEntry() + { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; ProviderMetadataId keyToDelete = null; //get the entry in the cache which was not accessed for the longest time. - foreach (KeyValuePair kvp in cache) { + foreach (KeyValuePair kvp in _cache) + { //the time difference (in ms) between the timeNow and the last used time of each entry TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime); //for the "unused" items (with ReferenceCount == 0) -> can possible be deleted. - if (timeDifference.TotalMilliseconds >= maxPassedTime) { + if (timeDifference.TotalMilliseconds >= maxPassedTime) + { maxPassedTime = timeDifference.TotalMilliseconds; keyToDelete = kvp.Key; } @@ -148,24 +164,30 @@ namespace System.Diagnostics.Eventing.Reader { DeleteCacheEntry(keyToDelete); } - private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) { + private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) + { cacheItem.TheTime = DateTime.Now; } - private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { - if (!IsProviderinCache(key)) { + private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) + { + if (!IsProviderinCache(key)) + { ProviderMetadata pm; - try { - pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo, this.logfile); + try + { + pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } - catch (EventLogNotFoundException) { - pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo); + catch (EventLogNotFoundException) + { + pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); return pm; } - else { - CacheItem cacheItem = cache[key]; + else + { + CacheItem cacheItem = _cache[key]; ProviderMetadata pm = cacheItem.ProviderMetadata; @@ -174,17 +196,21 @@ namespace System.Diagnostics.Eventing.Reader { // uninstalled since last time it was used. // - try { + try + { pm.CheckReleased(); UpdateCacheValueInfoForHit(cacheItem); } - catch (EventLogException) { + catch (EventLogException) + { DeleteCacheEntry(key); - try { - pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo, this.logfile); + try + { + pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } - catch (EventLogNotFoundException) { - pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo); + catch (EventLogNotFoundException) + { + pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); } @@ -195,30 +221,36 @@ namespace System.Diagnostics.Eventing.Reader { // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { - - lock (this) { + public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); - try { + try + { ProviderMetadata pm = GetProviderMetadata(key); - return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); + return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); } - catch (EventLogNotFoundException) { + catch (EventLogNotFoundException) + { return null; } } } - public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) { - - lock (this) { + public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); - try { + try + { return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values); } - catch (EventLogNotFoundException) { + catch (EventLogNotFoundException) + { return null; } } @@ -226,43 +258,50 @@ namespace System.Diagnostics.Eventing.Reader { // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { - lock (this) { + public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); - return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); + return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { - lock (this) { + public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); - return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); + return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { - lock (this) { + public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); - return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); + return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] - public IEnumerable GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { - lock (this) { + public IEnumerable GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) + { + lock (this) + { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); - return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); + return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); } } } - } \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/Winmeta.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/Winmeta.cs index 94b5380d6..4d4ae476a 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/Winmeta.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/Winmeta.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + /*============================================================ ** -** File: winmeta.cs ** ** Purpose: ** Contains eventing constants defined by the Windows @@ -15,11 +10,13 @@ using System.Diagnostics.CodeAnalysis; -namespace System.Diagnostics.Eventing.Reader { +namespace System.Diagnostics.Eventing.Reader +{ /// /// WindowsEventLevel /// - public enum StandardEventLevel { + public enum StandardEventLevel + { /// /// Log always /// @@ -48,7 +45,8 @@ namespace System.Diagnostics.Eventing.Reader { /// /// WindowsEventTask /// - public enum StandardEventTask { + public enum StandardEventTask + { /// /// Undefined task /// @@ -58,8 +56,9 @@ namespace System.Diagnostics.Eventing.Reader { /// /// EventOpcode /// - [SuppressMessage("Microsoft.Naming","CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="Opcode", Justification="matell: Shipped public in 3.5, breaking change to fix now.")] - public enum StandardEventOpcode { + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] + public enum StandardEventOpcode + { /// /// An informational event /// @@ -110,7 +109,8 @@ namespace System.Diagnostics.Eventing.Reader { /// EventOpcode /// [Flags] - public enum StandardEventKeywords : long { + public enum StandardEventKeywords : long + { /// /// Wild card value /// diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 826762d09..8abc918c5 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -1,13 +1,4 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== -/*============================================================ -** -** Class: UnsafeNativeMethods -** -============================================================*/ + namespace System.Diagnostics.Eventing { @@ -16,13 +7,13 @@ namespace System.Diagnostics.Eventing using System.Security; using System.Text; using System.Diagnostics.Eventing.Reader; - + internal static class UnsafeNativeMethods { private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll"; private const string EventProviderDllName = "api-ms-win-eventing-provider-l1-1-0.dll"; private const string WEVTAPI = "wevtapi.dll"; - private static readonly IntPtr NULL = IntPtr.Zero; + private static readonly IntPtr s_NULL = IntPtr.Zero; // WinError.h codes: @@ -67,7 +58,7 @@ namespace System.Diagnostics.Eventing // The event size is larger than the allowed maximum (64k - header). internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534 internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815 - + // Event log specific codes: internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027; @@ -101,7 +92,7 @@ namespace System.Diagnostics.Eventing StringBuilder sb = new StringBuilder(512); int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, - UnsafeNativeMethods.NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.NULL); + UnsafeNativeMethods.s_NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.s_NULL); if (result != 0) { // result is the # of characters copied to the StringBuilder on NT, diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertFromSecureStringActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertFromSecureStringActivity.cs index 122347504..590fce01f 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertFromSecureStringActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertFromSecureStringActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\ConvertFrom-SecureString"; } } - + // Arguments - + /// /// Provides access to the SecureString parameter. /// @@ -54,10 +55,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -71,18 +72,18 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(SecureString.Expression != null) + + if (SecureString.Expression != null) { targetCommand.AddParameter("SecureString", SecureString.Get(context)); } - if(SecureKey.Expression != null) + if (SecureKey.Expression != null) { targetCommand.AddParameter("SecureKey", SecureKey.Get(context)); } - if(Key.Expression != null) + if (Key.Expression != null) { targetCommand.AddParameter("Key", Key.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertToSecureStringActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertToSecureStringActivity.cs index f813194b6..ef0f169cc 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertToSecureStringActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/ConvertToSecureStringActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\ConvertTo-SecureString"; } } - + // Arguments - + /// /// Provides access to the String parameter. /// @@ -68,10 +69,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -85,28 +86,28 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(String.Expression != null) + + if (String.Expression != null) { targetCommand.AddParameter("String", String.Get(context)); } - if(AsPlainText.Expression != null) + if (AsPlainText.Expression != null) { targetCommand.AddParameter("AsPlainText", AsPlainText.Get(context)); } - if(Force.Expression != null) + if (Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } - if(SecureKey.Expression != null) + if (SecureKey.Expression != null) { targetCommand.AddParameter("SecureKey", SecureKey.Get(context)); } - if(Key.Expression != null) + if (Key.Expression != null) { targetCommand.AddParameter("Key", Key.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/GetAclActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/GetAclActivity.cs index 379797019..64de426bf 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/GetAclActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/GetAclActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Get-Acl"; } } - + // Arguments - + /// /// Provides access to the Path parameter. /// @@ -89,10 +90,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -106,43 +107,43 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Path.Expression != null) + + if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } - if(InputObject.Expression != null) + if (InputObject.Expression != null) { targetCommand.AddParameter("InputObject", InputObject.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } - if(Audit.Expression != null) + if (Audit.Expression != null) { targetCommand.AddParameter("Audit", Audit.Get(context)); } - if(AllCentralAccessPolicies.Expression != null) + if (AllCentralAccessPolicies.Expression != null) { targetCommand.AddParameter("AllCentralAccessPolicies", AllCentralAccessPolicies.Get(context)); } - if(Filter.Expression != null) + if (Filter.Expression != null) { targetCommand.AddParameter("Filter", Filter.Get(context)); } - if(Include.Expression != null) + if (Include.Expression != null) { targetCommand.AddParameter("Include", Include.Get(context)); } - if(Exclude.Expression != null) + if (Exclude.Expression != null) { targetCommand.AddParameter("Exclude", Exclude.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/GetAuthenticodeSignatureActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/GetAuthenticodeSignatureActivity.cs index 0796389c5..5e366bc48 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/GetAuthenticodeSignatureActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/GetAuthenticodeSignatureActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Get-AuthenticodeSignature"; } } - + // Arguments - + /// /// Provides access to the FilePath parameter. /// @@ -47,10 +48,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -64,13 +65,13 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(FilePath.Expression != null) + + if (FilePath.Expression != null) { targetCommand.AddParameter("FilePath", FilePath.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/GetCmsMessageActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/GetCmsMessageActivity.cs index 8a8fe2c8e..87d81e387 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/GetCmsMessageActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/GetCmsMessageActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Get-CmsMessage"; } } - + // Arguments - + /// /// Provides access to the Content parameter. /// @@ -54,10 +55,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -71,18 +72,18 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Content.Expression != null) + + if (Content.Expression != null) { targetCommand.AddParameter("Content", Content.Get(context)); } - if(Path.Expression != null) + if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/GetExecutionPolicyActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/GetExecutionPolicyActivity.cs index 2228cbe27..6dde07031 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/GetExecutionPolicyActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/GetExecutionPolicyActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Get-ExecutionPolicy"; } } - + // Arguments - + /// /// Provides access to the Scope parameter. /// @@ -47,10 +48,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -64,13 +65,13 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Scope.Expression != null) + + if (Scope.Expression != null) { targetCommand.AddParameter("Scope", Scope.Get(context)); } - if(List.Expression != null) + if (List.Expression != null) { targetCommand.AddParameter("List", List.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/GetPfxCertificateActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/GetPfxCertificateActivity.cs index 032c9ba1c..586c2e71c 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/GetPfxCertificateActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/GetPfxCertificateActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Get-PfxCertificate"; } } - + // Arguments - + /// /// Provides access to the FilePath parameter. /// @@ -47,10 +48,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -64,13 +65,13 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(FilePath.Expression != null) + + if (FilePath.Expression != null) { targetCommand.AddParameter("FilePath", FilePath.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/ProtectCmsMessageActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/ProtectCmsMessageActivity.cs index d1371a227..c5ce71e39 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/ProtectCmsMessageActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/ProtectCmsMessageActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Protect-CmsMessage"; } } - + // Arguments - + /// /// Provides access to the To parameter. /// @@ -68,10 +69,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -85,28 +86,28 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(To.Expression != null) + + if (To.Expression != null) { targetCommand.AddParameter("To", To.Get(context)); } - if(Content.Expression != null) + if (Content.Expression != null) { targetCommand.AddParameter("Content", Content.Get(context)); } - if(Path.Expression != null) + if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } - if(OutFile.Expression != null) + if (OutFile.Expression != null) { targetCommand.AddParameter("OutFile", OutFile.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/SetAclActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/SetAclActivity.cs index dcacc23c5..662c1fffa 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/SetAclActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/SetAclActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Set-Acl"; } } - + // Arguments - + /// /// Provides access to the Path parameter. /// @@ -65,7 +66,7 @@ namespace Microsoft.PowerShell.Security.Activities [ParameterSpecificCategory] [DefaultValue(null)] public InArgument SecurityDescriptor { get; set; } - + /// /// Provides access to the CentralAccessPolicy parameter. /// @@ -110,10 +111,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -127,58 +128,58 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Path.Expression != null) + + if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } - if(InputObject.Expression != null) + if (InputObject.Expression != null) { targetCommand.AddParameter("InputObject", InputObject.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } - if(AclObject.Expression != null) + if (AclObject.Expression != null) { targetCommand.AddParameter("AclObject", AclObject.Get(context)); } - if(SecurityDescriptor.Expression != null) + if (SecurityDescriptor.Expression != null) { targetCommand.AddParameter("SecurityDescriptor", SecurityDescriptor.Get(context)); } - if(CentralAccessPolicy.Expression != null) + if (CentralAccessPolicy.Expression != null) { targetCommand.AddParameter("CentralAccessPolicy", CentralAccessPolicy.Get(context)); } - if(ClearCentralAccessPolicy.Expression != null) + if (ClearCentralAccessPolicy.Expression != null) { targetCommand.AddParameter("ClearCentralAccessPolicy", ClearCentralAccessPolicy.Get(context)); } - if(Passthru.Expression != null) + if (Passthru.Expression != null) { targetCommand.AddParameter("Passthru", Passthru.Get(context)); } - if(Filter.Expression != null) + if (Filter.Expression != null) { targetCommand.AddParameter("Filter", Filter.Get(context)); } - if(Include.Expression != null) + if (Include.Expression != null) { targetCommand.AddParameter("Include", Include.Get(context)); } - if(Exclude.Expression != null) + if (Exclude.Expression != null) { targetCommand.AddParameter("Exclude", Exclude.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/SetAuthenticodeSignatureActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/SetAuthenticodeSignatureActivity.cs index 6659f6709..72020622e 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/SetAuthenticodeSignatureActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/SetAuthenticodeSignatureActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Set-AuthenticodeSignature"; } } - + // Arguments - + /// /// Provides access to the Certificate parameter. /// @@ -82,10 +83,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -99,38 +100,38 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Certificate.Expression != null) + + if (Certificate.Expression != null) { targetCommand.AddParameter("Certificate", Certificate.Get(context)); } - if(IncludeChain.Expression != null) + if (IncludeChain.Expression != null) { targetCommand.AddParameter("IncludeChain", IncludeChain.Get(context)); } - if(TimestampServer.Expression != null) + if (TimestampServer.Expression != null) { targetCommand.AddParameter("TimestampServer", TimestampServer.Get(context)); } - if(HashAlgorithm.Expression != null) + if (HashAlgorithm.Expression != null) { targetCommand.AddParameter("HashAlgorithm", HashAlgorithm.Get(context)); } - if(Force.Expression != null) + if (Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } - if(FilePath.Expression != null) + if (FilePath.Expression != null) { targetCommand.AddParameter("FilePath", FilePath.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/SetExecutionPolicyActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/SetExecutionPolicyActivity.cs index 2a04b30fe..b365942ad 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/SetExecutionPolicyActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/SetExecutionPolicyActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Set-ExecutionPolicy"; } } - + // Arguments - + /// /// Provides access to the ExecutionPolicy parameter. /// @@ -54,10 +55,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -71,18 +72,18 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(ExecutionPolicy.Expression != null) + + if (ExecutionPolicy.Expression != null) { targetCommand.AddParameter("ExecutionPolicy", ExecutionPolicy.Get(context)); } - if(Scope.Expression != null) + if (Scope.Expression != null) { targetCommand.AddParameter("Scope", Scope.Get(context)); } - if(Force.Expression != null) + if (Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security.Activities/Generated/UnprotectCmsMessageActivity.cs b/src/Microsoft.PowerShell.Security.Activities/Generated/UnprotectCmsMessageActivity.cs index 71452d781..3dc5c9f78 100644 --- a/src/Microsoft.PowerShell.Security.Activities/Generated/UnprotectCmsMessageActivity.cs +++ b/src/Microsoft.PowerShell.Security.Activities/Generated/UnprotectCmsMessageActivity.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; @@ -28,9 +29,9 @@ namespace Microsoft.PowerShell.Security.Activities /// Gets the fully qualified name of the command invoked by this activity. /// public override string PSCommandName { get { return "Microsoft.PowerShell.Security\\Unprotect-CmsMessage"; } } - + // Arguments - + /// /// Provides access to the Content parameter. /// @@ -75,10 +76,10 @@ namespace Microsoft.PowerShell.Security.Activities // Module defining this command - + // Optional custom code for this activity - + /// /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. @@ -92,33 +93,33 @@ namespace Microsoft.PowerShell.Security.Activities System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments - - if(Content.Expression != null) + + if (Content.Expression != null) { targetCommand.AddParameter("Content", Content.Get(context)); } - if(EventLogRecord.Expression != null) + if (EventLogRecord.Expression != null) { targetCommand.AddParameter("EventLogRecord", EventLogRecord.Get(context)); } - if(Path.Expression != null) + if (Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } - if(LiteralPath.Expression != null) + if (LiteralPath.Expression != null) { targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context)); } - if(IncludeContext.Expression != null) + if (IncludeContext.Expression != null) { targetCommand.AddParameter("IncludeContext", IncludeContext.Get(context)); } - if(To.Expression != null) + if (To.Expression != null) { targetCommand.AddParameter("To", To.Get(context)); } diff --git a/src/Microsoft.PowerShell.Security/AssemblyInfo.cs b/src/Microsoft.PowerShell.Security/AssemblyInfo.cs index 8be322935..dd4e8f282 100644 --- a/src/Microsoft.PowerShell.Security/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.Security/AssemblyInfo.cs @@ -1,8 +1,8 @@ using System.Reflection; using System.Resources; -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersionAttribute("3.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 055e685d4..a82c9af8e 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -9,7 +9,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Management.Automation; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Management.Automation.Security; using System.Security.AccessControl; using System.Security.Principal; @@ -28,7 +28,6 @@ using System.Reflection; namespace Microsoft.PowerShell.Commands { - /// /// Defines the base class from which all Security Descriptor commands /// are derived. @@ -44,12 +43,12 @@ namespace Microsoft.PowerShell.Commands { get { - return filter; + return _filter; } set { - filter = value; + _filter = value; } } @@ -62,12 +61,12 @@ namespace Microsoft.PowerShell.Commands { get { - return include; + return _include; } set { - include = value; + _include = value; } } @@ -80,12 +79,12 @@ namespace Microsoft.PowerShell.Commands { get { - return exclude; + return _exclude; } set { - exclude = value; + _exclude = value; } } @@ -121,8 +120,8 @@ namespace Microsoft.PowerShell.Commands /// of security descriptor /// static internal void AddBrokeredProperties( - Collection results, - bool audit, + Collection results, + bool audit, bool allCentralAccessPolicies) { foreach (PSObject result in results) @@ -186,7 +185,7 @@ namespace Microsoft.PowerShell.Commands /// public static string GetPath(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -194,11 +193,11 @@ namespace Microsoft.PowerShell.Commands { // These are guaranteed to not be null, but even checking // them for null causes a presharp warning - #pragma warning disable 56506 +#pragma warning disable 56506 //Get path return instance.Properties["PSPath"].Value.ToString(); - #pragma warning enable 56506 +#pragma warning enable 56506 } } @@ -213,13 +212,13 @@ namespace Microsoft.PowerShell.Commands /// public static string GetOwner(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if(sd == null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -253,13 +252,13 @@ namespace Microsoft.PowerShell.Commands /// public static string GetGroup(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if(sd == null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -292,7 +291,7 @@ namespace Microsoft.PowerShell.Commands /// public static AuthorizationRuleCollection GetAccess(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -330,7 +329,7 @@ namespace Microsoft.PowerShell.Commands /// public static AuthorizationRuleCollection GetAudit(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -415,7 +414,7 @@ namespace Microsoft.PowerShell.Commands } pAce += ace.AceSize; } - IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) - + IntPtr pSid = pAce + Marshal.SizeOf(new NativeMethods.SYSTEM_AUDIT_ACE()) - Marshal.SizeOf(new uint()); bool ret = NativeMethods.IsValidSid(pSid); if (!ret) @@ -582,13 +581,13 @@ namespace Microsoft.PowerShell.Commands /// public static string GetSddl(PSObject instance) { - if(instance == null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException("instance"); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if(sd == null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException("instance"); } @@ -602,24 +601,24 @@ namespace Microsoft.PowerShell.Commands /// /// The filter to be used to when globbing to get the item. /// - private string filter; + private string _filter; /// /// The glob string used to determine which items are included. /// - private string[] include = new string[0]; + private string[] _include = new string[0]; /// /// The glob string used to determine which items are excluded. /// - private string[] exclude = new string[0]; + private string[] _exclude = new string[0]; } /// /// Defines the implementation of the 'get-acl' cmdlet. /// This cmdlet gets the security descriptor of an item at the specified path. /// - [Cmdlet(VerbsCommon.Get, "Acl", SupportsTransactions = true, DefaultParameterSetName="ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113305")] + [Cmdlet(VerbsCommon.Get, "Acl", SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113305")] public sealed class GetAclCommand : SecurityDescriptorCommandsBase { /// @@ -629,33 +628,33 @@ namespace Microsoft.PowerShell.Commands public GetAclCommand() { //Default for path is the current location - path = new string[] { "." }; + _path = new string[] { "." }; } #region parameters - private string[] path; + private string[] _path; /// /// Gets or sets the path of the item for which to obtain the /// security descriptor. Default is the current location. /// - [Parameter(Position = 0, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty()] public string[] Path { get { - return path; + return _path; } set { - path = value; + _path = value; } } - private PSObject inputObject = null; - + private PSObject _inputObject = null; + /// /// InputObject Parameter /// Gets or sets the inputObject for which to obtain the security descriptor @@ -665,12 +664,12 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; } } @@ -686,16 +685,16 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Gets or sets the audit flag of the command. This flag @@ -706,15 +705,15 @@ namespace Microsoft.PowerShell.Commands { get { - return audit; + return _audit; } set { - audit = value; + _audit = value; } } - SwitchParameter audit; + private SwitchParameter _audit; #if CORECLR /// @@ -744,7 +743,7 @@ namespace Microsoft.PowerShell.Commands allCentralAccessPolicies = value; } } - SwitchParameter allCentralAccessPolicies; + private SwitchParameter allCentralAccessPolicies; #endif #endregion @@ -761,14 +760,14 @@ namespace Microsoft.PowerShell.Commands AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access; - if (audit) + if (_audit) { sections |= AccessControlSections.Audit; } - if (inputObject != null) + if (_inputObject != null) { - PSMethodInfo methodInfo = inputObject.Methods["GetSecurityDescriptor"]; + PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"]; if (methodInfo != null) { @@ -821,7 +820,7 @@ namespace Microsoft.PowerShell.Commands string currentPath = null; try { - if (isLiteralPath) + if (_isLiteralPath) { pathsToProcess.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } @@ -842,7 +841,7 @@ namespace Microsoft.PowerShell.Commands CmdletProviderContext context = new CmdletProviderContext(this.Context); context.SuppressWildcardExpansion = true; - if (!InvokeProvider.Item.Exists(rp, false, isLiteralPath)) + if (!InvokeProvider.Item.Exists(rp, false, _isLiteralPath)) { ErrorRecord er = SecurityUtils.CreatePathNotFoundErrorRecord( @@ -860,8 +859,8 @@ namespace Microsoft.PowerShell.Commands if (sd != null) { AddBrokeredProperties( - sd, - audit, + sd, + _audit, AllCentralAccessPolicies); WriteObject(sd, true); } @@ -898,11 +897,11 @@ namespace Microsoft.PowerShell.Commands /// Defines the implementation of the 'set-acl' cmdlet. /// This cmdlet sets the security descriptor of an item at the specified path. /// - [Cmdlet(VerbsCommon.Set, "Acl", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName="ByPath", + [Cmdlet(VerbsCommon.Set, "Acl", SupportsShouldProcess = true, SupportsTransactions = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113389")] public sealed class SetAclCommand : SecurityDescriptorCommandsBase { - private string[] path; + private string[] _path; /// /// Gets or sets the path of the item for which to set the @@ -913,16 +912,16 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; + _path = value; } } - private PSObject inputObject = null; + private PSObject _inputObject = null; /// /// InputObject Parameter @@ -933,15 +932,15 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; } } - + /// /// Gets or sets the literal path of the item for which to set the /// security descriptor. @@ -953,18 +952,18 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; - private object securityDescriptor; + private object _securityDescriptor; /// /// Gets or sets the security descriptor object to be @@ -977,12 +976,12 @@ namespace Microsoft.PowerShell.Commands { get { - return securityDescriptor; + return _securityDescriptor; } set { - securityDescriptor = PSObject.Base(value); + _securityDescriptor = PSObject.Base(value); } } @@ -1018,7 +1017,7 @@ namespace Microsoft.PowerShell.Commands } #endif - SwitchParameter clearCentralAccessPolicy; + private SwitchParameter _clearCentralAccessPolicy; /// /// Clears the central access policy applied on the target item(s). @@ -1029,16 +1028,16 @@ namespace Microsoft.PowerShell.Commands { get { - return clearCentralAccessPolicy; + return _clearCentralAccessPolicy; } set { - clearCentralAccessPolicy = value; + _clearCentralAccessPolicy = value; } } - SwitchParameter passthru; + private SwitchParameter _passthru; /// /// Gets or sets the Passthru flag for the operation. @@ -1050,12 +1049,12 @@ namespace Microsoft.PowerShell.Commands { get { - return passthru; + return _passthru; } set { - passthru = value; + _passthru = value; } } @@ -1244,7 +1243,7 @@ namespace Microsoft.PowerShell.Commands /// by calling NativeMethods.CloseHandle. /// private IntPtr GetTokenWithEnabledPrivilege( - string privilege, + string privilege, NativeMethods.TOKEN_PRIVILEGE previousState) { IntPtr pToken = IntPtr.Zero; @@ -1323,15 +1322,15 @@ namespace Microsoft.PowerShell.Commands /// Access Control List (ACL). protected override void ProcessRecord() { - ObjectSecurity aclObjectSecurity = securityDescriptor as ObjectSecurity; + ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity; - if (inputObject != null) + if (_inputObject != null) { - PSMethodInfo methodInfo = inputObject.Methods["SetSecurityDescriptor"]; + PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"]; if (methodInfo != null) { - CommonSecurityDescriptor aclCommonSD = securityDescriptor as CommonSecurityDescriptor; + CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) @@ -1473,7 +1472,7 @@ namespace Microsoft.PowerShell.Commands CmdletProviderContext context = this.CmdletProviderContext; context.PassThru = Passthru; - if (isLiteralPath) + if (_isLiteralPath) { ProviderInfo Provider = null; PSDriveInfo Drive = null; diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index 46ba8b97c..78814710d 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -6,7 +6,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Management.Automation; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; using System.Collections; using System.IO; using System.Management.Automation.Provider; @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Commands /// Defines the base class from which all catalog commands are derived. /// public abstract class CatalogCommandsBase : PSCmdlet - { + { /// /// Path of folder/file to generate or validate the catalog file /// @@ -57,7 +57,7 @@ namespace Microsoft.PowerShell.Commands // // name of this command // - string commandName; + private string commandName; /// /// Initializes a new instance of the CatalogCommandsBase class, @@ -71,7 +71,7 @@ namespace Microsoft.PowerShell.Commands commandName = name; } - private CatalogCommandsBase() : base() {} + private CatalogCommandsBase() : base() { } /// /// Processes records from the input pipeline. @@ -90,7 +90,7 @@ namespace Microsoft.PowerShell.Commands Collection paths = new Collection(); if (Path != null) - { + { foreach (string p in Path) { foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) @@ -100,15 +100,15 @@ namespace Microsoft.PowerShell.Commands } } - string drive = null; + string drive = null; // resolve catalog destination Path if (!SessionState.Path.IsPSAbsolute(catalogFilePath, out drive) && !System.IO.Path.IsPathRooted(catalogFilePath)) - { - catalogFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(catalogFilePath); + { + catalogFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(catalogFilePath); } - PerformAction(paths, catalogFilePath); + PerformAction(paths, catalogFilePath); } /// @@ -136,7 +136,7 @@ namespace Microsoft.PowerShell.Commands /// Initializes a new instance of the New-FileCatalog class. /// public NewFileCatalogCommand() : base("New-FileCatalog") { } - + /// /// Catalog version /// @@ -149,12 +149,12 @@ namespace Microsoft.PowerShell.Commands } set { - catalogVersion = value; + catalogVersion = value; } } - + // Based on the Catalog version we will decide which hashing Algorithm to use - private int catalogVersion = 1; + private int catalogVersion = 1; /// /// Generate the Catalog for the Path @@ -168,8 +168,8 @@ namespace Microsoft.PowerShell.Commands /// /// True if able to Create Catalog or else False /// - protected override void PerformAction(Collection path,string catalogFilePath) - { + protected override void PerformAction(Collection path, string catalogFilePath) + { if (path.Count == 0) { // if user has not provided the path use current directory to generate catalog @@ -182,9 +182,9 @@ namespace Microsoft.PowerShell.Commands // parent Directory exists other wise CryptoAPI fails to create a .cat file if (catalogFileInfo.Extension.Equals(".cat", StringComparison.Ordinal)) { - System.IO.Directory.CreateDirectory(catalogFileInfo.Directory.FullName); + System.IO.Directory.CreateDirectory(catalogFileInfo.Directory.FullName); } - else + else { // This only creates Directory if it does not exists, Append a default name System.IO.Directory.CreateDirectory(catalogFilePath); @@ -197,7 +197,7 @@ namespace Microsoft.PowerShell.Commands { WriteObject(catalogFile); } - } + } } /// @@ -228,8 +228,8 @@ namespace Microsoft.PowerShell.Commands /// /// Patterns used to exclude files from DiskPaths and Catalog /// - [Parameter()] - public string[] FilesToSkip + [Parameter()] + public string[] FilesToSkip { get { @@ -245,7 +245,7 @@ namespace Microsoft.PowerShell.Commands } } } - string[] filesToSkip = null; + private string[] filesToSkip = null; internal WildcardPattern[] excludedPatterns = null; /// @@ -277,10 +277,9 @@ namespace Microsoft.PowerShell.Commands else { WriteObject(catalogInfo.Status); - } + } } } - } #endif diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index e40496766..5d4d5f7c7 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; using System.Collections; using System.Collections.Generic; using System.IO; @@ -27,20 +27,20 @@ namespace Microsoft.PowerShell.Commands /// Gets or sets the path of the item for which to obtain the /// certificate. /// - [Parameter(Position=0, ValueFromPipeline=true, ValueFromPipelineByPropertyName = true, Mandatory=true, ParameterSetName = "ByPath")] + [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByPath")] public string[] FilePath { get { - return path; + return _path; } - + set { - path = value; + _path = value; } } - private string[] path; + private string[] _path; /// /// Gets or sets the literal path of the item for which to obtain the @@ -53,21 +53,21 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } - private bool isLiteralPath = false; + private bool _isLiteralPath = false; // // list of files that were not found // - ArrayList filesNotFound = new ArrayList(); + private ArrayList _filesNotFound = new ArrayList(); /// @@ -99,7 +99,7 @@ namespace Microsoft.PowerShell.Commands List paths = new List(); // Expand wildcard characters - if (isLiteralPath) + if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } @@ -114,7 +114,7 @@ namespace Microsoft.PowerShell.Commands } catch (ItemNotFoundException) { - filesNotFound.Add(p); + _filesNotFound.Add(p); } } @@ -126,7 +126,7 @@ namespace Microsoft.PowerShell.Commands if (resolvedProviderPath == null) { - filesNotFound.Add(p); + _filesNotFound.Add(p); } else { @@ -178,9 +178,9 @@ namespace Microsoft.PowerShell.Commands } } - if (filesNotFound.Count > 0) + if (_filesNotFound.Count > 0) { - if (filesNotFound.Count == FilePath.Length) + if (_filesNotFound.Count == FilePath.Length) { ErrorRecord er = SecurityUtils.CreateFileNotFoundErrorRecord( @@ -195,7 +195,7 @@ namespace Microsoft.PowerShell.Commands // we found some files but not others. // Write error for each missing file // - foreach (string f in filesNotFound) + foreach (string f in _filesNotFound) { ErrorRecord er = SecurityUtils.CreateFileNotFoundErrorRecord( @@ -234,8 +234,6 @@ namespace Microsoft.PowerShell.Commands return cert; } - - } } diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 5a24d97de..4a65e92e2 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -23,7 +23,7 @@ using System.Diagnostics.CodeAnalysis; using System.Xml; using System.Xml.XPath; using System.Security; -using DWORD = System.UInt32; +using DWORD = System.UInt32; namespace Microsoft.PowerShell.Commands { @@ -45,49 +45,49 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter CodeSigningCert { - get { return codeSigningCert; } - set { codeSigningCert = value; } - } + get { return _codeSigningCert; } + set { _codeSigningCert = value; } + } - private SwitchParameter codeSigningCert = new SwitchParameter(); + private SwitchParameter _codeSigningCert = new SwitchParameter(); } /// /// Defines the type of DNS string /// The structure contains punycode name and unicode name /// - [SuppressMessage("Microsoft.Performance","CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] + [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] public struct DnsNameRepresentation { /// /// punycode version of DNS name /// - private string punycodeName; + private string _punycodeName; /// /// Unicode version of DNS name /// - private string unicodeName; - + private string _unicodeName; + /// /// ambiguous constructor of a DnsNameRepresentation /// public DnsNameRepresentation(string inputDnsName) { - punycodeName = inputDnsName; - unicodeName = inputDnsName; + _punycodeName = inputDnsName; + _unicodeName = inputDnsName; } /// /// specific constructor of a DnsNameRepresentation /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId="Punycode")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")] public DnsNameRepresentation( string inputPunycodeName, string inputUnicodeName) { - punycodeName = inputPunycodeName; - unicodeName = inputUnicodeName; + _punycodeName = inputPunycodeName; + _unicodeName = inputUnicodeName; } /// @@ -96,18 +96,18 @@ namespace Microsoft.PowerShell.Commands public bool Equals(DnsNameRepresentation dnsName) { bool match = false; - - if (unicodeName != null && dnsName.unicodeName != null) + + if (_unicodeName != null && dnsName._unicodeName != null) { if (String.Equals( - unicodeName, - dnsName.unicodeName, + _unicodeName, + dnsName._unicodeName, StringComparison.OrdinalIgnoreCase)) { match = true; } } - else if (unicodeName == null && dnsName.unicodeName == null) + else if (_unicodeName == null && dnsName._unicodeName == null) { match = true; } @@ -117,12 +117,12 @@ namespace Microsoft.PowerShell.Commands /// /// get property of Punycode /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId="Punycode")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")] public string Punycode { get { - return punycodeName; + return _punycodeName; } } @@ -133,7 +133,7 @@ namespace Microsoft.PowerShell.Commands { get { - return unicodeName; + return _unicodeName; } } @@ -146,10 +146,10 @@ namespace Microsoft.PowerShell.Commands // We don't ever expect to see the punycode and unicode strings // to differ only by upper/lower case. If they do, that's really // a code bug, and the effect is to just display both strings. - - return String.Equals(punycodeName, unicodeName)? - punycodeName : - unicodeName + " (" + punycodeName + ")"; + + return String.Equals(_punycodeName, _unicodeName) ? + _punycodeName : + _unicodeName + " (" + _punycodeName + ")"; } } @@ -187,12 +187,13 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter CodeSigningCert { - get { return codeSigningCert; } + get { return _codeSigningCert; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { codeSigningCert = value; } - } - private SwitchParameter codeSigningCert = new SwitchParameter(); + set + { _codeSigningCert = value; } + } + private SwitchParameter _codeSigningCert = new SwitchParameter(); /// /// switch that controls whether we only return @@ -201,12 +202,13 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter DocumentEncryptionCert { - get { return documentEncryptionCert; } + get { return _documentEncryptionCert; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { documentEncryptionCert = value; } + set + { _documentEncryptionCert = value; } } - private SwitchParameter documentEncryptionCert = new SwitchParameter(); + private SwitchParameter _documentEncryptionCert = new SwitchParameter(); /// /// switch that controls whether we only return @@ -215,13 +217,14 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public SwitchParameter SSLServerAuthentication { - get { return sslServerAuthentication; } + get { return _sslServerAuthentication; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { sslServerAuthentication = value; } - } + set + { _sslServerAuthentication = value; } + } - private SwitchParameter sslServerAuthentication = new SwitchParameter(); + private SwitchParameter _sslServerAuthentication = new SwitchParameter(); /// /// string to filter certs by DNSName @@ -231,13 +234,14 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public DnsNameRepresentation DnsName { - get { return dnsName; } + get { return _dnsName; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { dnsName = value; } - } - - private DnsNameRepresentation dnsName; + set + { _dnsName = value; } + } + + private DnsNameRepresentation _dnsName; /// /// string to filter certs by EKU @@ -248,13 +252,14 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public string[] Eku { - get { return eku; } + get { return _eku; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { eku = value; } - } - - private string[] eku = null; + set + { _eku = value; } + } + + private string[] _eku = null; /// /// string to filter certs by the number of valid days @@ -266,13 +271,14 @@ namespace Microsoft.PowerShell.Commands [Parameter()] public int ExpiringInDays { - get { return expiringInDays; } + get { return _expiringInDays; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This method is used by command line processing")] - set { expiringInDays = value; } - } - - private int expiringInDays = -1; + set + { _expiringInDays = value; } + } + + private int _expiringInDays = -1; } /// @@ -294,20 +300,20 @@ namespace Microsoft.PowerShell.Commands get { { - return deleteKey; + return _deleteKey; } } - + set { { - deleteKey = value; + _deleteKey = value; } } } - private SwitchParameter deleteKey = new SwitchParameter(); - } + private SwitchParameter _deleteKey = new SwitchParameter(); + } /// /// Defines the safe handle class for native cert store handles, @@ -392,126 +398,126 @@ namespace Microsoft.PowerShell.Commands /// public X509NativeStore(X509StoreLocation StoreLocation, string StoreName) { - storeLocation = StoreLocation; - storeName = StoreName; + _storeLocation = StoreLocation; + _storeName = StoreName; } public void Open(bool includeArchivedCerts) { - if (storeHandle != null && archivedCerts != includeArchivedCerts) + if (_storeHandle != null && _archivedCerts != includeArchivedCerts) { - storeHandle = null; // release the old handle + _storeHandle = null; // release the old handle } - if (storeHandle == null) + if (_storeHandle == null) { - valid = false; - open = false; - + _valid = false; + _open = false; + Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_STORE_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_CONTEXT_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG; - + if (includeArchivedCerts) { StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG; } - - switch (storeLocation.Location) + + switch (_storeLocation.Location) { - case StoreLocation.LocalMachine: - StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; - break; - - case StoreLocation.CurrentUser: - StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; - break; - - default: - //ThrowItemNotFound(storeLocation.ToString(), CertificateProviderItem.StoreLocation); - break; + case StoreLocation.LocalMachine: + StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + break; + + case StoreLocation.CurrentUser: + StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + break; + + default: + //ThrowItemNotFound(storeLocation.ToString(), CertificateProviderItem.StoreLocation); + break; } - + IntPtr hCertStore = Security.NativeMethods.CertOpenStore( Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, IntPtr.Zero, // hCryptProv StoreFlags, - storeName); + _storeName); if (IntPtr.Zero == hCertStore) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } - - storeHandle = new CertificateStoreHandle(); - storeHandle.Handle = hCertStore; + + _storeHandle = new CertificateStoreHandle(); + _storeHandle.Handle = hCertStore; //we only do CertControlStore for stores other than UserDS if (!String.Equals( - storeName, + _storeName, "UserDS", StringComparison.OrdinalIgnoreCase)) - { + { if (!Security.NativeMethods.CertControlStore( - storeHandle.Handle, + _storeHandle.Handle, 0, Security.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, IntPtr.Zero)) { - storeHandle = null; + _storeHandle = null; throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } } - valid = true; - open = true; - archivedCerts = includeArchivedCerts; + _valid = true; + _open = true; + _archivedCerts = includeArchivedCerts; } } public IntPtr GetFirstCert( CertificateFilterInfo filter) { - filterHandle = null; + _filterHandle = null; if (DownLevelHelper.NativeFilteringSupported() && filter != null) { IntPtr hFilter = IntPtr.Zero; - filterHandle = new CertificateFilterHandle(); + _filterHandle = new CertificateFilterHandle(); int hr = Security.NativeMethods.CCFindCertificateBuildFilter( filter.FilterString, ref hFilter); if (hr != Security.NativeConstants.S_OK) { - filterHandle = null; + _filterHandle = null; throw new System.ComponentModel.Win32Exception(hr); } - filterHandle.Handle = hFilter; + _filterHandle.Handle = hFilter; } return GetNextCert(IntPtr.Zero); } public IntPtr GetNextCert(IntPtr certContext) { - if (!open) + if (!_open) { throw Marshal.GetExceptionForHR( Security.NativeMethods.CRYPT_E_NOT_FOUND); } if (Valid) { - if (filterHandle != null) + if (_filterHandle != null) { certContext = Security.NativeMethods.CCFindCertificateFromFilter( - storeHandle.Handle, - filterHandle.Handle, + _storeHandle.Handle, + _filterHandle.Handle, certContext); } else { certContext = Security.NativeMethods.CertEnumCertificatesInStore( - storeHandle.Handle, + _storeHandle.Handle, certContext); } } @@ -526,7 +532,7 @@ namespace Microsoft.PowerShell.Commands { IntPtr certContext = IntPtr.Zero; - if (!open) + if (!_open) { throw Marshal.GetExceptionForHR( Security.NativeMethods.CRYPT_E_NOT_FOUND); @@ -536,7 +542,7 @@ namespace Microsoft.PowerShell.Commands if (DownLevelHelper.HashLookupSupported()) { certContext = Security.NativeMethods.CertFindCertificateInStore( - storeHandle.Handle, + _storeHandle.Handle, Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, 0, // dwFindFlags Security.NativeMethods.CertFindType.CERT_FIND_HASH_STR, @@ -551,7 +557,7 @@ namespace Microsoft.PowerShell.Commands // We have to iterate through all certs to find // what we want. // - + while (true) { certContext = GetNextCert(certContext); @@ -586,7 +592,7 @@ namespace Microsoft.PowerShell.Commands { get { - return storeHandle.Handle; + return _storeHandle.Handle; } } @@ -597,7 +603,7 @@ namespace Microsoft.PowerShell.Commands { get { - return storeLocation; + return _storeLocation; } } @@ -608,7 +614,7 @@ namespace Microsoft.PowerShell.Commands { get { - return storeName; + return _storeName; } } @@ -620,24 +626,24 @@ namespace Microsoft.PowerShell.Commands { get { - return valid; + return _valid; } } - private bool archivedCerts = false; - private X509StoreLocation storeLocation = null; - private string storeName = null; - private CertificateStoreHandle storeHandle = null; - private CertificateFilterHandle filterHandle = null; - private bool valid = false; - private bool open = false; + private bool _archivedCerts = false; + private X509StoreLocation _storeLocation = null; + private string _storeName = null; + private CertificateStoreHandle _storeHandle = null; + private CertificateFilterHandle _filterHandle = null; + private bool _valid = false; + private bool _open = false; } /// /// Defines the types of items /// supported by the certificate provider. /// - enum CertificateProviderItem + internal enum CertificateProviderItem { /// /// An unknown item. @@ -679,9 +685,9 @@ namespace Microsoft.PowerShell.Commands /// /// tracer for certificate provider /// - [TraceSource( "CertificateProvider", + [TraceSource("CertificateProvider", "The core command provider for certificates")] - private readonly static PSTraceSource tracer = PSTraceSource.GetTracer ("CertificateProvider", + private readonly static PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider", "The core command provider for certificates"); #endregion tracer @@ -696,14 +702,14 @@ namespace Microsoft.PowerShell.Commands /// -- storeLocations /// -- pathCache /// - private static object staticLock = new object(); + private static object s_staticLock = new object(); /// /// list of store locations. They do not change once initialized. /// /// Synchronized on staticLock /// - private static List storeLocations = null; + private static List s_storeLocations = null; /// /// cache that stores paths and their associated objects. @@ -713,22 +719,22 @@ namespace Microsoft.PowerShell.Commands /// /// Synchronized on staticLock /// - private static Hashtable pathCache = null; + private static Hashtable s_pathCache = null; /// /// we allow either / or \ to be the path separator /// - private static readonly char[] pathSeparators = new char[] { '/', '\\' }; + private static readonly char[] s_pathSeparators = new char[] { '/', '\\' }; /// /// regex pattern that defines a valid cert path /// private const string certPathPattern = @"^\\((?CurrentUser|LocalMachine)(\\(?[a-zA-Z]+)(\\(?[0-9a-f]{40}))?)?)?$"; - + /// /// Cache the store handle to avoid repeated CertOpenStore calls. /// - private static X509NativeStore storeCache = null; + private static X509NativeStore s_storeCache = null; /// /// On demand create the Regex to avoid a hit to startup perf. @@ -741,24 +747,24 @@ namespace Microsoft.PowerShell.Commands /// this property. /// /// - private static Regex certPathRegex = null; + private static Regex s_certPathRegex = null; private static Regex CertPathRegex { get { - lock (staticLock) + lock (s_staticLock) { - if (certPathRegex == null) + if (s_certPathRegex == null) { RegexOptions options = RegexOptions.IgnoreCase; #if !CORECLR options |= RegexOptions.Compiled; #endif - certPathRegex = new Regex(certPathPattern, options); + s_certPathRegex = new Regex(certPathPattern, options); } } - return certPathRegex; + return s_certPathRegex; } } @@ -766,17 +772,17 @@ namespace Microsoft.PowerShell.Commands /// Initializes a new instance of the CertificateProvider class. /// This initializes the default certificate store locations. /// - public CertificateProvider() - { + public CertificateProvider() + { // // initialize storeLocations list and also update the cache // - lock (staticLock) + lock (s_staticLock) { - if (storeLocations == null) + if (s_storeLocations == null) { - pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase); - storeLocations = + s_pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase); + s_storeLocations = new List(); // @@ -784,7 +790,7 @@ namespace Microsoft.PowerShell.Commands // X509StoreLocation user = new X509StoreLocation(StoreLocation.CurrentUser); - storeLocations.Add(user); + s_storeLocations.Add(user); AddItemToCache(StoreLocation.CurrentUser.ToString(), user); @@ -793,14 +799,13 @@ namespace Microsoft.PowerShell.Commands // X509StoreLocation machine = new X509StoreLocation(StoreLocation.LocalMachine); - storeLocations.Add(machine); + s_storeLocations.Add(machine); AddItemToCache(StoreLocation.LocalMachine.ToString(), machine); - AddItemToCache("", storeLocations); - } + AddItemToCache("", s_storeLocations); + } } - } // constructor @@ -824,11 +829,11 @@ namespace Microsoft.PowerShell.Commands /// path is null or empty. /// destination is null or empty. /// - + protected override void RemoveItem( string path, bool recurse) - { + { path = NormalizePath(path); bool isContainer = false; bool fDeleteKey = false; @@ -836,19 +841,19 @@ namespace Microsoft.PowerShell.Commands object outObj = GetItemAtPath(path, false, out isContainer); string[] pathElements = GetPathElements(path); - bool fUserContext = String.Equals(pathElements[0],"CurrentUser",StringComparison.OrdinalIgnoreCase); + bool fUserContext = String.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase); // isContainer = true means not a valid certificate - + // if source store is user root store and UI is not allowed // we raise invalid operation if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero && fUserContext && - String.Equals(pathElements[1],"ROOT", StringComparison.OrdinalIgnoreCase)) + String.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.UINotAllowed; string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); - } + } if (DynamicParameters != null) { @@ -862,7 +867,7 @@ namespace Microsoft.PowerShell.Commands } } } - + if (isContainer) { if (pathElements.Length == 2) //is a store @@ -882,18 +887,18 @@ namespace Microsoft.PowerShell.Commands { string message = CertificateProviderStrings.CannotRemoveContainer; string errorId = "CannotRemoveContainer"; - ThrowInvalidOperation(errorId, message); - } + ThrowInvalidOperation(errorId, message); + } } else //certificate { //do remove X509Certificate2 certificate = outObj as X509Certificate2; RemoveCertItem(certificate, fDeleteKey, !fUserContext, path); - return; + return; } } - + /// /// Gets the dynamic parameters for remove-item on the Certificate /// Provider. We currently only support one dynamic parameter, @@ -915,10 +920,9 @@ namespace Microsoft.PowerShell.Commands /// protected override object RemoveItemDynamicParameters(string path, bool recurse) { - return new ProviderRemoveItemDynamicParameters(); } - + /// /// Moves an item at the specified path to the given destination. /// @@ -939,19 +943,19 @@ namespace Microsoft.PowerShell.Commands /// path is null or empty. /// destination is null or empty. /// - + protected override void MoveItem( string path, string destination) - { + { //normalize path path = NormalizePath(path); destination = NormalizePath(destination); //get elements from the path string[] pathElements = GetPathElements(path); - string[] destElements = GetPathElements(destination); - + string[] destElements = GetPathElements(destination); + bool isContainer = false; object cert = GetItemAtPath(path, false, out isContainer); @@ -969,7 +973,7 @@ namespace Microsoft.PowerShell.Commands { //if the destination leads to the same thumbprint if (destElements.Length == 3 && - (String.Equals(pathElements[2],destElements[2], StringComparison.OrdinalIgnoreCase))) + (String.Equals(pathElements[2], destElements[2], StringComparison.OrdinalIgnoreCase))) { //in this case we think of destination path as vaild //and strip the thumbprint part @@ -986,29 +990,29 @@ namespace Microsoft.PowerShell.Commands //the second element is store location //we do not allow cross context move //we do not allow the destination store is the same as source - - if (!String.Equals(pathElements[0],destElements[0], StringComparison.OrdinalIgnoreCase)) + + if (!String.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveCrossContext; string errorId = "CannotMoveCrossContext"; ThrowInvalidOperation(errorId, message); } - if (String.Equals(pathElements[1],destElements[1], StringComparison.OrdinalIgnoreCase)) + if (String.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveToSameStore; string errorId = "CannotMoveToSameStore"; ThrowInvalidOperation(errorId, message); } - + // if source or destination store is user root store and UI is not allowed // we raise invalid operation - if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero) + if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero) { - if ((String.Equals(pathElements[0],"CurrentUser",StringComparison.OrdinalIgnoreCase) && - String.Equals(pathElements[1],"ROOT", StringComparison.OrdinalIgnoreCase)) || - (String.Equals(destElements[0],"CurrentUser",StringComparison.OrdinalIgnoreCase) && - String.Equals(destElements[1],"ROOT", StringComparison.OrdinalIgnoreCase))) + if ((String.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) && + String.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) || + (String.Equals(destElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) && + String.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))) { string message = CertificateProviderStrings.UINotAllowed; string errorId = "UINotAllowed"; @@ -1028,13 +1032,13 @@ namespace Microsoft.PowerShell.Commands if (certstore != null) { certstore.Open(true); - - string action = CertificateProviderStrings.Action_Move; + + string action = CertificateProviderStrings.Action_Move; string resource = String.Format( CultureInfo.CurrentCulture, CertificateProviderStrings.MoveItemTemplate, path, - destination); + destination); if (ShouldProcess(resource, action)) { DoMove(destination, certificate, certstore, path); @@ -1044,10 +1048,9 @@ namespace Microsoft.PowerShell.Commands else { ThrowItemNotFound(path, CertificateProviderItem.Certificate); - } - + } } - + /// /// Creates a certificate store with the given path. /// @@ -1121,7 +1124,7 @@ namespace Microsoft.PowerShell.Commands Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; - + //Create new store IntPtr hCertStore = Security.NativeMethods.CertOpenStore( Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, @@ -1143,7 +1146,6 @@ namespace Microsoft.PowerShell.Commands pathElements[1], StoreLocation.LocalMachine); WriteItemObject(outStore, path, true); - } #region DriveCmdletProvider overrides @@ -1159,7 +1161,7 @@ namespace Microsoft.PowerShell.Commands { string providerDescription = CertificateProviderStrings.CertProvidername; - PSDriveInfo drive = + PSDriveInfo drive = new PSDriveInfo( "Cert", // drive name ProviderInfo,// provider name @@ -1202,7 +1204,6 @@ namespace Microsoft.PowerShell.Commands /// protected override bool HasChildItems(string path) { - bool result = false; Utils.CheckArgForNull(path, "path"); @@ -1239,7 +1240,6 @@ namespace Microsoft.PowerShell.Commands } } } - } return result; } @@ -1310,7 +1310,7 @@ namespace Microsoft.PowerShell.Commands /// -- etc /// /// - protected override bool ItemExists(string path) + protected override bool ItemExists(string path) { if (!_hasAttemptedToLoadPkiModule) { @@ -1323,7 +1323,7 @@ namespace Microsoft.PowerShell.Commands bool isContainer = false; object item = null; - path = NormalizePath(path); + path = NormalizePath(path); if (path.Length == 0) { @@ -1340,7 +1340,7 @@ namespace Microsoft.PowerShell.Commands { item = GetItemAtPath(path, true, out isContainer); } - catch(ProviderInvocationException e) + catch (ProviderInvocationException e) { // // if the item is not found, we get ProviderInvocationException @@ -1354,10 +1354,10 @@ namespace Microsoft.PowerShell.Commands } } - result = (bool) item; + result = (bool)item; } - tracer.WriteLine("result = {0}", result); + s_tracer.WriteLine("result = {0}", result); return result; } // ItemExists @@ -1386,10 +1386,10 @@ namespace Microsoft.PowerShell.Commands /// -- etc /// /// - protected override void GetItem(string path) - { + protected override void GetItem(string path) + { bool isContainer = false; - + path = NormalizePath(path); object item = GetItemAtPath(path, false, out isContainer); CertificateFilterInfo filter = GetFilter(); @@ -1431,7 +1431,7 @@ namespace Microsoft.PowerShell.Commands X509StoreLocation storeLocation = item as X509StoreLocation; if (storeLocation != null) //store location { - WriteItemObject(item, path, isContainer); + WriteItemObject(item, path, isContainer); } else //store { @@ -1444,7 +1444,7 @@ namespace Microsoft.PowerShell.Commands store.Location.Location); WriteItemObject(outStore, path, isContainer); } - } + } } } } @@ -1507,12 +1507,12 @@ namespace Microsoft.PowerShell.Commands if (Runspaces.Runspace.DefaultRunspace == null) { - // - // Requires default runspace. Only import the module. - // when a default runspace is available. - // + // + // Requires default runspace. Only import the module. + // when a default runspace is available. + // - return; + return; } @@ -1522,7 +1522,7 @@ namespace Microsoft.PowerShell.Commands typeof(Microsoft.PowerShell.Commands.ImportModuleCommand)); Runspaces.Command importModuleCommand = new Runspaces.Command(commandInfo); - tracer.WriteLine("Attempting to load module: {0}", moduleName); + s_tracer.WriteLine("Attempting to load module: {0}", moduleName); try { @@ -1569,7 +1569,7 @@ namespace Microsoft.PowerShell.Commands if (separatorIndex == -1) { result = path; - } + } else { result = path.Substring(separatorIndex + 1); @@ -1592,7 +1592,7 @@ namespace Microsoft.PowerShell.Commands string certmgr = "certmgr.msc"; string certPath = System.IO.Path.Combine( System.Environment.ExpandEnvironmentVariables("%windir%"), "system32"); - + if (ShouldProcess(path, action)) { System.Diagnostics.Process.Start(System.IO.Path.Combine(certPath, certmgr)); @@ -1620,7 +1620,7 @@ namespace Microsoft.PowerShell.Commands result = StringLiterals.DefaultPathSeparator + path; } - tracer.WriteLine("result = {0}", result); + s_tracer.WriteLine("result = {0}", result); return result; } // EnsureDriveIsRooted @@ -1636,21 +1636,21 @@ namespace Microsoft.PowerShell.Commands // switch (itemType) { - case CertificateProviderItem.Certificate: - message = CertificateProviderStrings.CertificateNotFound; - break; + case CertificateProviderItem.Certificate: + message = CertificateProviderStrings.CertificateNotFound; + break; - case CertificateProviderItem.Store: - message = CertificateProviderStrings.CertificateStoreNotFound; - break; + case CertificateProviderItem.Store: + message = CertificateProviderStrings.CertificateStoreNotFound; + break; - case CertificateProviderItem.StoreLocation: - message = CertificateProviderStrings.CertificateStoreLocationNotFound; - break; + case CertificateProviderItem.StoreLocation: + message = CertificateProviderStrings.CertificateStoreLocationNotFound; + break; - default: - message = CertificateProviderStrings.InvalidPath; - break; + default: + message = CertificateProviderStrings.InvalidPath; + break; } message = String.Format( @@ -1663,21 +1663,21 @@ namespace Microsoft.PowerShell.Commands // switch (itemType) { - case CertificateProviderItem.Certificate: + case CertificateProviderItem.Certificate: e = new CertificateNotFoundException(message); - break; + break; - case CertificateProviderItem.Store: - e = new CertificateStoreNotFoundException(message); - break; + case CertificateProviderItem.Store: + e = new CertificateStoreNotFoundException(message); + break; - case CertificateProviderItem.StoreLocation: - e = new CertificateStoreLocationNotFoundException(message); - break; + case CertificateProviderItem.StoreLocation: + e = new CertificateStoreLocationNotFoundException(message); + break; - default: - e = new ArgumentException(message); - break; + default: + e = new ArgumentException(message); + break; } ErrorRecord er = @@ -1687,7 +1687,7 @@ namespace Microsoft.PowerShell.Commands null); er.ErrorDetails = ed; - + return er; } @@ -1707,7 +1707,6 @@ namespace Microsoft.PowerShell.Commands "RemotingFailure", ErrorCategory.NotSpecified, null)); - } else { @@ -1715,7 +1714,7 @@ namespace Microsoft.PowerShell.Commands } } - private void ThrowInvalidOperation(string errorId,string message) + private void ThrowInvalidOperation(string errorId, string message) { ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(message), @@ -1725,14 +1724,14 @@ namespace Microsoft.PowerShell.Commands errorRecord.ErrorDetails = new ErrorDetails(message); ThrowTerminatingError(errorRecord); - return; - } - + return; + } + private void ThrowItemNotFound(string path, - CertificateProviderItem itemType) + CertificateProviderItem itemType) { ErrorRecord er = CreateErrorRecord(path, itemType); - + ThrowTerminatingError(er); } @@ -1740,11 +1739,11 @@ namespace Microsoft.PowerShell.Commands { if (path.Length > 0) { - char lastChar = path[path.Length-1]; + char lastChar = path[path.Length - 1]; if ((lastChar == '/') || (lastChar == '\\')) { - path = path.Substring(0, path.Length-1); + path = path.Substring(0, path.Length - 1); } string[] elts = GetPathElements(path); @@ -1757,10 +1756,10 @@ namespace Microsoft.PowerShell.Commands static private string[] GetPathElements(string path) { - string[] allElts = path.Split(pathSeparators); + string[] allElts = path.Split(s_pathSeparators); string[] result = null; - Stack elts = new Stack(); + Stack elts = new Stack(); foreach (string e in allElts) { @@ -1795,14 +1794,14 @@ namespace Microsoft.PowerShell.Commands /// /// no return - [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId="System.Management.Automation.Security.NativeMethods.NCryptSetProperty(System.IntPtr,System.String,System.Void*,System.Int32,System.Int32)")] - [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId="System.Management.Automation.Security.NativeMethods.NCryptFreeObject(System.IntPtr)")] + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptSetProperty(System.IntPtr,System.String,System.Void*,System.Int32,System.Int32)")] + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptFreeObject(System.IntPtr)")] private void DoDeleteKey(IntPtr pProvInfo) { IntPtr hProv = IntPtr.Zero; - Security.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo = + Security.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo = ClrFacade.PtrToStructure(pProvInfo); - + IntPtr hWnd = DetectUIHelper.GetOwnerWindow(Host); if (keyProvInfo.dwProvType != 0) //legacy @@ -1818,7 +1817,7 @@ namespace Microsoft.PowerShell.Commands { unsafe { - void * pWnd = hWnd.ToPointer(); + void* pWnd = hWnd.ToPointer(); Security.NativeMethods.CryptSetProvParam( hProv, Security.NativeMethods.ProviderParam.PP_CLIENT_HWND, @@ -1834,7 +1833,7 @@ namespace Microsoft.PowerShell.Commands keyProvInfo.pwszContainerName, keyProvInfo.pwszProvName, (int)keyProvInfo.dwProvType, - keyProvInfo.dwFlags | (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET | + keyProvInfo.dwFlags | (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET | (hWnd == IntPtr.Zero ? (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT : 0))) { ThrowErrorRemoting(Marshal.GetLastWin32Error()); @@ -1844,7 +1843,7 @@ namespace Microsoft.PowerShell.Commands { uint cngKeyFlag = 0; int result = 0; - + IntPtr hCNGProv = IntPtr.Zero; IntPtr hCNGKey = IntPtr.Zero; @@ -1854,7 +1853,7 @@ namespace Microsoft.PowerShell.Commands } if (hWnd == IntPtr.Zero || - (keyProvInfo.dwFlags & (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0 ) + (keyProvInfo.dwFlags & (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0) { cngKeyFlag |= (uint)Security.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG; } @@ -1870,13 +1869,13 @@ namespace Microsoft.PowerShell.Commands { ThrowErrorRemoting(stat); } - + stat = Security.NativeMethods.NCryptOpenKey( hCNGProv, ref hCNGKey, keyProvInfo.pwszContainerName, keyProvInfo.dwKeySpec, - cngKeyFlag); + cngKeyFlag); if (stat != 0) { ThrowErrorRemoting(stat); @@ -1897,7 +1896,7 @@ namespace Microsoft.PowerShell.Commands } stat = Security.NativeMethods.NCryptDeleteKey(hCNGKey, 0); - if (stat != 0 ) + if (stat != 0) { ThrowErrorRemoting(stat); } @@ -1953,7 +1952,7 @@ namespace Microsoft.PowerShell.Commands RemoveCertItem(cert, fDeleteKey, true, certPath); certContext = store.GetNextCert(certContext); - } + } //remove the cert store Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | @@ -1961,7 +1960,7 @@ namespace Microsoft.PowerShell.Commands Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DELETE_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; - + //delete store IntPtr hCertStore = Security.NativeMethods.CertOpenStore( Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, @@ -2007,7 +2006,7 @@ namespace Microsoft.PowerShell.Commands { action = CertificateProviderStrings.Action_Remove; } - + string resource = String.Format( CultureInfo.CurrentCulture, CertificateProviderStrings.RemoveItemTemplate, @@ -2015,11 +2014,11 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(resource, action)) { - DoRemove(cert, fDeleteKey, fMachine, sourcePath); + DoRemove(cert, fDeleteKey, fMachine, sourcePath); } } } - + /// /// Delete the cert from the store; if -DeleteKey is specified, we also delete /// the associated private key @@ -2042,16 +2041,16 @@ namespace Microsoft.PowerShell.Commands int provSize = 0; IntPtr pProvInfo = IntPtr.Zero; bool fHasPrivateKey = false; - + try - { + { if (fDeleteKey) { //it is fine if below call fails - if(Security.NativeMethods.CertGetCertificateContextProperty( + if (Security.NativeMethods.CertGetCertificateContextProperty( cert.Handle, Security.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, - IntPtr.Zero, + IntPtr.Zero, ref provSize)) { pProvInfo = Marshal.AllocHGlobal((int)provSize); @@ -2059,18 +2058,18 @@ namespace Microsoft.PowerShell.Commands if (Security.NativeMethods.CertGetCertificateContextProperty( cert.Handle, Security.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, - pProvInfo, + pProvInfo, ref provSize)) { fHasPrivateKey = true; } } - + if (!fHasPrivateKey) { //raise a verbose message //we should not use WriteWarning here - string verboseNoPrivatekey = CertificateProviderStrings.VerboseNoPrivateKey; + string verboseNoPrivatekey = CertificateProviderStrings.VerboseNoPrivateKey; WriteVerbose(verboseNoPrivatekey); } } @@ -2078,18 +2077,18 @@ namespace Microsoft.PowerShell.Commands //do remove certifiate //should not use the original handle - if(!Security.NativeMethods.CertDeleteCertificateFromStore( + if (!Security.NativeMethods.CertDeleteCertificateFromStore( Security.NativeMethods.CertDuplicateCertificateContext(cert.Handle))) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); - } + } //commit the change to physical store - if(sourcePath.Contains("UserDS")) + if (sourcePath.Contains("UserDS")) { Security.NativeMethods.CERT_CONTEXT context = ClrFacade.PtrToStructure(cert.Handle); - + CommitUserDS(context.hCertStore); } @@ -2110,7 +2109,7 @@ namespace Microsoft.PowerShell.Commands Marshal.FreeHGlobal(pProvInfo); } } - + /// /// Commit store for UserDS store /// @@ -2147,7 +2146,7 @@ namespace Microsoft.PowerShell.Commands /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] private void DoMove(string destination, X509Certificate2 cert, X509NativeStore store, string sourcePath) - { + { IntPtr dupCert = IntPtr.Zero; //should not free this IntPtr outCert = IntPtr.Zero; @@ -2160,7 +2159,6 @@ namespace Microsoft.PowerShell.Commands } else { - if (!Security.NativeMethods.CertAddCertificateContextToStore( store.StoreHandle, cert.Handle, @@ -2168,9 +2166,9 @@ namespace Microsoft.PowerShell.Commands ref outCert)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); - } - - if(!Security.NativeMethods.CertDeleteCertificateFromStore(dupCert)) + } + + if (!Security.NativeMethods.CertDeleteCertificateFromStore(dupCert)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } @@ -2195,20 +2193,20 @@ namespace Microsoft.PowerShell.Commands CommitUserDS(store.StoreHandle); } - if(sourcePath.Contains("UserDS")) + if (sourcePath.Contains("UserDS")) { Security.NativeMethods.CERT_CONTEXT context = ClrFacade.PtrToStructure(cert.Handle); - + CommitUserDS(context.hCertStore); } - + //get the output object X509Certificate2 outObj = new X509Certificate2(outCert); string certName = GetCertName(outObj); string certPath = MakePath(destination, certName); WriteItemObject((object)outObj, certPath, false); } - + /// /// fetches the store-location/store/certificate at the /// specified path. @@ -2221,13 +2219,13 @@ namespace Microsoft.PowerShell.Commands /// /// item at the path /// - private object GetItemAtPath(string path, bool test, out bool isContainer) - { + private object GetItemAtPath(string path, bool test, out bool isContainer) + { Utils.CheckArgForNull(path, "path"); object item = null; string[] pathElements = GetPathElements(path); - + // // certs have a fixed depth hierarchy. // @@ -2351,7 +2349,7 @@ namespace Microsoft.PowerShell.Commands } } - if((item != null) && test) + if ((item != null) && test) { item = true; } @@ -2386,8 +2384,8 @@ namespace Microsoft.PowerShell.Commands /// -- etc /// /// - protected override void GetChildItems(string path, bool recurse) - { + protected override void GetChildItems(string path, bool recurse) + { path = NormalizePath(path); GetChildItemsOrNames(path, recurse, ReturnContainers.ReturnAllContainers, false, GetFilter()); @@ -2423,7 +2421,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void GetChildNames( string path, - ReturnContainers returnContainers) + ReturnContainers returnContainers) { path = NormalizePath(path); GetChildItemsOrNames(path, false, returnContainers, true, GetFilter()); @@ -2455,7 +2453,7 @@ namespace Microsoft.PowerShell.Commands /// -- etc /// /// - protected override bool IsItemContainer(string path) + protected override bool IsItemContainer(string path) { path = NormalizePath(path); Utils.CheckArgForNull(path, "path"); @@ -2478,7 +2476,7 @@ namespace Microsoft.PowerShell.Commands GetItemAtPath(path, true, out isContainer); } - tracer.WriteLine("result = {0}", isContainer); + s_tracer.WriteLine("result = {0}", isContainer); return isContainer; } // IsItemContainer @@ -2509,7 +2507,7 @@ namespace Microsoft.PowerShell.Commands { return new CertificateProviderCodeSigningDynamicParameters(); } - } + } /// /// Gets the dynamic parameters for get-childitem on the Certificate @@ -2541,7 +2539,7 @@ namespace Microsoft.PowerShell.Commands { return new CertificateProviderCodeSigningDynamicParameters(); } - } + } #endregion DriveCmdletProvider overrides @@ -2574,8 +2572,8 @@ namespace Microsoft.PowerShell.Commands bool recurse, ReturnContainers returnContainers, bool returnNames, - CertificateFilterInfo filter) - { + CertificateFilterInfo filter) + { object thingToReturn = null; string childPath = null; @@ -2588,10 +2586,10 @@ namespace Microsoft.PowerShell.Commands // if (path.Length == 0) { - foreach (X509StoreLocation l in storeLocations) + foreach (X509StoreLocation l in s_storeLocations) { thingToReturn = returnNames ? - (object) l.LocationName : (object) l; + (object)l.LocationName : (object)l; // 'returnNames' is true only when called from // GetChildNames(), in which case 'recurse' will always be @@ -2701,10 +2699,10 @@ namespace Microsoft.PowerShell.Commands /// /// Does not return a value /// - private void GetCertificatesOrNames( string path, + private void GetCertificatesOrNames(string path, string[] pathElements, bool returnNames, - CertificateFilterInfo filter ) + CertificateFilterInfo filter) { object thingToReturn = null; string certPath = null; @@ -2733,7 +2731,7 @@ namespace Microsoft.PowerShell.Commands if (returnNames) { - thingToReturn = (object) certName; + thingToReturn = (object)certName; } else { @@ -2744,7 +2742,7 @@ namespace Microsoft.PowerShell.Commands X509Certificate2 cert2 = new X509Certificate2(cert); #endif PSObject myPsObj = new PSObject(cert2); - thingToReturn = (object) myPsObj; + thingToReturn = (object)myPsObj; } WriteItemObject(thingToReturn, certPath, false); } @@ -2829,24 +2827,24 @@ namespace Microsoft.PowerShell.Commands { ThrowItemNotFound(storePath, CertificateProviderItem.Store); } - if (storeCache != null) + if (s_storeCache != null) { - if (storeCache.Location != storeLocation || + if (s_storeCache.Location != storeLocation || !String.Equals( - storeCache.StoreName, + s_storeCache.StoreName, storeName, StringComparison.OrdinalIgnoreCase)) { - storeCache = null; + s_storeCache = null; } } - if (storeCache == null ) + if (s_storeCache == null) { - storeCache = new X509NativeStore(storeLocation, storeName); + s_storeCache = new X509NativeStore(storeLocation, storeName); } - return storeCache; + return s_storeCache; } /// @@ -2869,7 +2867,7 @@ namespace Microsoft.PowerShell.Commands string path, bool recurse, bool returnNames, - CertificateFilterInfo filter ) + CertificateFilterInfo filter) { object thingToReturn = null; @@ -2961,7 +2959,7 @@ namespace Microsoft.PowerShell.Commands if (dp != null) { bool filterSpecified = false; - + filter = new CertificateFilterInfo(); if (dp.CodeSigningCert) { @@ -3045,22 +3043,22 @@ namespace Microsoft.PowerShell.Commands switch (filter.Purpose) { - case CertificatePurpose.CodeSigning: - if (SecuritySupport.CertIsGoodForSigning(cert)) - { - return true; - } - break; + case CertificatePurpose.CodeSigning: + if (SecuritySupport.CertIsGoodForSigning(cert)) + { + return true; + } + break; - case CertificatePurpose.DocumentEncryption: - if (SecuritySupport.CertIsGoodForEncryption(cert)) - { - return true; - } - break; + case CertificatePurpose.DocumentEncryption: + if (SecuritySupport.CertIsGoodForEncryption(cert)) + { + return true; + } + break; - default: - break; + default: + break; } return false; @@ -3070,12 +3068,12 @@ namespace Microsoft.PowerShell.Commands { object item = null; - lock (staticLock) + lock (s_staticLock) { - if (pathCache.ContainsKey(path)) + if (s_pathCache.ContainsKey(path)) { - item = pathCache[path]; - Dbg.Diagnostics.Assert( item != null, "GetCachedItem"); + item = s_pathCache[path]; + Dbg.Diagnostics.Assert(item != null, "GetCachedItem"); } } @@ -3084,11 +3082,11 @@ namespace Microsoft.PowerShell.Commands private static void AddItemToCache(string path, object item) { - lock (staticLock) + lock (s_staticLock) { - if ((item != null) && (!pathCache.ContainsKey(path))) + if ((item != null) && (!s_pathCache.ContainsKey(path))) { - pathCache.Add(path, item); + s_pathCache.Add(path, item); } } } @@ -3148,7 +3146,7 @@ namespace Microsoft.PowerShell.Commands #if !CORECLR settings.XmlResolver = null; #endif - XmlReader reader = XmlReader.Create(fullHelpPath, settings); + XmlReader reader = XmlReader.Create(fullHelpPath, settings); document.Load(reader); // Add the "command" namespace from the MAML schema @@ -3168,34 +3166,34 @@ namespace Microsoft.PowerShell.Commands XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr); if (result != null) { - return result.OuterXml; + return result.OuterXml; } } - catch(XmlException) + catch (XmlException) { return String.Empty; } - catch(PathTooLongException) + catch (PathTooLongException) { return String.Empty; } - catch(IOException) + catch (IOException) { return String.Empty; } - catch(UnauthorizedAccessException) + catch (UnauthorizedAccessException) { return String.Empty; } - catch(NotSupportedException) + catch (NotSupportedException) { return String.Empty; } - catch(SecurityException) + catch (SecurityException) { return String.Empty; } - catch(XPathException) + catch (XPathException) { return String.Empty; } @@ -3204,8 +3202,6 @@ namespace Microsoft.PowerShell.Commands } #endregion - - } // CertificateProvider /// @@ -3222,7 +3218,7 @@ namespace Microsoft.PowerShell.Commands { get { - return location.ToString(); + return _location.ToString(); } } @@ -3234,15 +3230,15 @@ namespace Microsoft.PowerShell.Commands { get { - return location; + return _location; } - + set { - location = value; + _location = value; } } - private StoreLocation location = StoreLocation.CurrentUser; + private StoreLocation _location = StoreLocation.CurrentUser; /// /// Gets the list of stores at this location. @@ -3257,7 +3253,7 @@ namespace Microsoft.PowerShell.Commands // since there is no managed support to obtain store names, // we use pinvoke to get it ourselves. - List names = Crypt32Helpers.GetStoreNamesAtLocation(location); + List names = Crypt32Helpers.GetStoreNamesAtLocation(_location); foreach (string name in names) { storeNames.Add(name, true); @@ -3265,7 +3261,7 @@ namespace Microsoft.PowerShell.Commands return storeNames; } - } + } /// /// Initializes a new instance of the X509StoreLocation class. @@ -3280,29 +3276,29 @@ namespace Microsoft.PowerShell.Commands /// Defines the type of EKU string /// The structure contains friendly name and EKU oid /// - [SuppressMessage("Microsoft.Performance","CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] + [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] public struct EnhancedKeyUsageRepresentation { /// /// Localized friendly name of EKU /// - private string friendlyName; - + private string _friendlyName; + /// /// OID of EKU /// - private string oid; + private string _oid; /// /// constructor of an EnhancedKeyUsageRepresentation /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId="Oid")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oid")] public EnhancedKeyUsageRepresentation(string inputFriendlyName, string inputOid) { - friendlyName = inputFriendlyName; - oid = inputOid; + _friendlyName = inputFriendlyName; + _oid = inputOid; } /// @@ -3311,17 +3307,17 @@ namespace Microsoft.PowerShell.Commands public bool Equals(EnhancedKeyUsageRepresentation keyUsage) { bool match = false; - - if (oid != null && keyUsage.oid != null) + + if (_oid != null && keyUsage._oid != null) { // OID strings only contain numbers and periods - - if (String.Equals(oid, keyUsage.oid, StringComparison.Ordinal)) + + if (String.Equals(_oid, keyUsage._oid, StringComparison.Ordinal)) { match = true; } } - else if (oid == null && keyUsage.oid == null) + else if (_oid == null && keyUsage._oid == null) { match = true; } @@ -3335,7 +3331,7 @@ namespace Microsoft.PowerShell.Commands { get { - return friendlyName; + return _friendlyName; } } @@ -3346,7 +3342,7 @@ namespace Microsoft.PowerShell.Commands { get { - return oid; + return _oid; } } @@ -3355,9 +3351,9 @@ namespace Microsoft.PowerShell.Commands /// public override string ToString() { - return String.IsNullOrEmpty(friendlyName)? - oid : - friendlyName + " (" + oid + ")"; + return String.IsNullOrEmpty(_friendlyName) ? + _oid : + _friendlyName + " (" + _oid + ")"; } } @@ -3381,10 +3377,10 @@ namespace Microsoft.PowerShell.Commands int propSize = 0; //try to get the property //it is fine if fail for not there - if(Security.NativeMethods.CertGetCertificateContextProperty( + if (Security.NativeMethods.CertGetCertificateContextProperty( cert.Handle, Security.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, - IntPtr.Zero, + IntPtr.Zero, ref propSize)) { //we have the property @@ -3394,9 +3390,9 @@ namespace Microsoft.PowerShell.Commands { //if fail int error = Marshal.GetLastWin32Error(); - if ( error != Security.NativeMethods.CRYPT_E_NOT_FOUND) + if (error != Security.NativeMethods.CRYPT_E_NOT_FOUND) { - throw new System.ComponentModel.Win32Exception(error); + throw new System.ComponentModel.Win32Exception(error); } } } @@ -3414,7 +3410,7 @@ namespace Microsoft.PowerShell.Commands if (DownLevelHelper.TrustedIssuerSupported()) { IntPtr propertyPtr = IntPtr.Zero; - Security.NativeMethods.CRYPT_DATA_BLOB dataBlob = new Security.NativeMethods.CRYPT_DATA_BLOB(); + Security.NativeMethods.CRYPT_DATA_BLOB dataBlob = new Security.NativeMethods.CRYPT_DATA_BLOB(); dataBlob.cbData = 0; dataBlob.pbData = IntPtr.Zero; X509Certificate certFromStore = null; @@ -3426,7 +3422,7 @@ namespace Microsoft.PowerShell.Commands //try to open the store and get the cert out //in case the store handle is already released string[] pathElements = GetPathElements(certPath); - + //certpath is in the format: Microsoft.Powershell.Security\ //Certificate::CurrentUser(LocalMachine)\my\HashID //obtained pathElements[0] is Microsoft.Powershell.Security @@ -3434,8 +3430,8 @@ namespace Microsoft.PowerShell.Commands //obtained pathElements[2] is MY //obtained pathElements[3] is HashID - bool fUserContext = String.Equals(pathElements[1],"Certificate::CurrentUser",StringComparison.OrdinalIgnoreCase); - + bool fUserContext = String.Equals(pathElements[1], "Certificate::CurrentUser", StringComparison.OrdinalIgnoreCase); + X509StoreLocation storeLocation = new X509StoreLocation(fUserContext ? StoreLocation.CurrentUser : StoreLocation.LocalMachine); @@ -3446,7 +3442,7 @@ namespace Microsoft.PowerShell.Commands store.Open(true); //including archival flag IntPtr certContext = store.GetCertByName(pathElements[3]); - + if (certContext != IntPtr.Zero) { certFromStore = new X509Certificate2(certContext); @@ -3484,14 +3480,13 @@ namespace Microsoft.PowerShell.Commands } } - private static readonly char[] separators = new char[] { '/', '\\' }; + private static readonly char[] s_separators = new char[] { '/', '\\' }; static private string[] GetPathElements(string path) { - - string[] allElts = path.Split(separators); + string[] allElts = path.Split(s_separators); string[] result = null; - Stack elts = new Stack(); + Stack elts = new Stack(); foreach (string e in allElts) { @@ -3524,9 +3519,9 @@ namespace Microsoft.PowerShell.Commands public sealed class EnhancedKeyUsageProperty { - private List ekuList = new List(); - - + private List _ekuList = new List(); + + /// /// get property of EKUList /// @@ -3534,11 +3529,11 @@ namespace Microsoft.PowerShell.Commands { get { - return ekuList; + return _ekuList; } } - /// + /// /// constructor for EnhancedKeyUsageProperty /// public EnhancedKeyUsageProperty(X509Certificate2 cert) @@ -3546,30 +3541,30 @@ namespace Microsoft.PowerShell.Commands if (DownLevelHelper.NativeFilteringSupported()) { Collection ekuCollection = System.Management.Automation.Internal.SecuritySupport.GetCertEKU(cert); - + foreach (string oidString in ekuCollection) { - if (! String.IsNullOrEmpty(oidString)) + if (!String.IsNullOrEmpty(oidString)) { IntPtr stringAnsi = (IntPtr)Marshal.StringToHGlobalAnsi(oidString); - + EnhancedKeyUsageRepresentation ekuString; IntPtr oidPtr = Security.NativeMethods.CryptFindOIDInfo( Security.NativeConstants.CRYPT_OID_INFO_OID_KEY, stringAnsi, 0); - if (oidPtr != IntPtr.Zero) + if (oidPtr != IntPtr.Zero) { Security.NativeMethods.CRYPT_OID_INFO oidInfo = ClrFacade.PtrToStructure(oidPtr); - ekuString = new EnhancedKeyUsageRepresentation(oidInfo.pwszName,oidString); + ekuString = new EnhancedKeyUsageRepresentation(oidInfo.pwszName, oidString); } else //if oidInfo is not available { - ekuString = new EnhancedKeyUsageRepresentation(null,oidString); + ekuString = new EnhancedKeyUsageRepresentation(null, oidString); } - ekuList.Add(ekuString); + _ekuList.Add(ekuString); } } } @@ -3582,8 +3577,8 @@ namespace Microsoft.PowerShell.Commands public sealed class DnsNameProperty { - private List dnsList = new List(); - + private List _dnsList = new List(); + /// /// get property of DnsNameList /// @@ -3591,7 +3586,7 @@ namespace Microsoft.PowerShell.Commands { get { - return dnsList; + return _dnsList; } } @@ -3605,8 +3600,8 @@ namespace Microsoft.PowerShell.Commands if (cert != null) { //need to get subject alternative name from the certificate context - dnsList = GetCertNames( - cert.Handle, + _dnsList = GetCertNames( + cert.Handle, Security.NativeMethods.AltNameType.CERT_ALT_NAME_DNS_NAME); } } @@ -3684,62 +3679,62 @@ namespace Microsoft.PowerShell.Commands /// internal static class DownLevelHelper { - private static bool IsWin8Set = false; - private static bool IsWin8 = false; + private static bool s_isWin8Set = false; + private static bool s_isWin8 = false; internal static bool IsWin8AndAbove() { - if (!IsWin8Set) + if (!s_isWin8Set) { #if CORECLR - IsWin8 = true; + s_isWin8 = true; #else 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))) { - IsWin8 = true; + s_isWin8 = true; } #endif - IsWin8Set = true; + s_isWin8Set = true; } - return IsWin8; + return s_isWin8; } - private static bool NativeFilteringSet = false; - private static bool NativeFiltering = false; + private static bool s_nativeFilteringSet = false; + private static bool s_nativeFiltering = false; internal static bool NativeFilteringSupported() { - if (!NativeFilteringSet) + if (!s_nativeFilteringSet) { if (IsWin8AndAbove() && Security.NativeMethods.IsSystem32DllPresent("certca.dll")) { - NativeFiltering = true; + s_nativeFiltering = true; } - NativeFilteringSet = true; + s_nativeFilteringSet = true; } - return NativeFiltering; + return s_nativeFiltering; } - private static bool LogChangesSet = false; - private static bool LogChanges = false; + private static bool s_logChangesSet = false; + private static bool s_logChanges = false; internal static bool LogCertChangeSupported() { - if (!LogChangesSet) + if (!s_logChangesSet) { if (IsWin8AndAbove() && Security.NativeMethods.IsSystem32DllPresent("certenroll.dll")) { - LogChanges = true; + s_logChanges = true; } - LogChangesSet = true; + s_logChangesSet = true; } - return LogChanges; + return s_logChanges; } internal static bool TrustedIssuerSupported() @@ -3751,8 +3746,8 @@ namespace Microsoft.PowerShell.Commands { return IsWin8AndAbove(); } - } - + } + /// /// Check in UI is allowed /// @@ -3797,7 +3792,7 @@ namespace Microsoft.PowerShell.Commands { if (host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase)) return false; - + uint SessionId; uint ProcessId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; if (!Security.NativeMethods.ProcessIdToSessionId(ProcessId, out SessionId)) @@ -3836,9 +3831,9 @@ namespace Microsoft.PowerShell.Commands /// lock that guards access to the following static members /// -- storeNames /// - private static object staticLock = new object(); + private static object s_staticLock = new object(); - internal static List storeNames = new List(); + internal static List storeNames = new List(); /// /// get a list of store names at the specified location @@ -3849,19 +3844,19 @@ namespace Microsoft.PowerShell.Commands Security.NativeMethods.CertStoreFlags locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; - switch(location) + switch (location) { - case StoreLocation.CurrentUser: - locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; - break; + case StoreLocation.CurrentUser: + locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + break; - case StoreLocation.LocalMachine: - locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; - break; + case StoreLocation.LocalMachine: + locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + break; - default: - Diagnostics.Assert(false, "GetStoreNamesAtLocation: invalid location value"); - break; + default: + Diagnostics.Assert(false, "GetStoreNamesAtLocation: invalid location value"); + break; } Security.NativeMethods.CertEnumSystemStoreCallBackProto callBack = @@ -3871,10 +3866,10 @@ namespace Microsoft.PowerShell.Commands // Return a new list to avoid synchronization issues. List names = new List(); - lock (staticLock) + lock (s_staticLock) { storeNames.Clear(); - + Security.NativeMethods.CertEnumSystemStore(locationFlag, IntPtr.Zero, IntPtr.Zero, callBack); foreach (string name in storeNames) @@ -3886,7 +3881,7 @@ namespace Microsoft.PowerShell.Commands return names; } - + /// /// call back function used by CertEnumSystemStore /// @@ -3897,7 +3892,7 @@ namespace Microsoft.PowerShell.Commands /// Each time this callback is called, we add the passed store name /// to the list of stores /// - internal static bool CertEnumSystemStoreCallBack( string storeName, + internal static bool CertEnumSystemStoreCallBack(string storeName, DWORD dwFlagsNotUsed, IntPtr notUsed1, IntPtr notUsed2, @@ -3906,6 +3901,5 @@ namespace Microsoft.PowerShell.Commands storeNames.Add(storeName); return true; } - } } diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 48df4fc3c..57dea14c3 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -50,7 +50,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - PSDataCollection inputObjects = new PSDataCollection(); + private PSDataCollection _inputObjects = new PSDataCollection(); /// /// Gets or sets the content of the CMS Message by path. @@ -71,7 +71,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - private string resolvedPath = null; + private string _resolvedPath = null; /// /// Emits the protected message to a file path. @@ -82,7 +82,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - private string resolvedOutFile = null; + private string _resolvedOutFile = null; /// /// Validate / convert arguments @@ -107,20 +107,20 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(error); } - resolvedPath = resolvedPaths[0]; + _resolvedPath = resolvedPaths[0]; } if (!String.IsNullOrEmpty(LiteralPath)) { // Validate that the path exists SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); - resolvedPath = LiteralPath; + _resolvedPath = LiteralPath; } // Validate OutFile if (!String.IsNullOrEmpty(OutFile)) { - resolvedOutFile = GetUnresolvedProviderPathFromPSPath(OutFile); + _resolvedOutFile = GetUnresolvedProviderPathFromPSPath(OutFile); } } @@ -133,7 +133,7 @@ namespace Microsoft.PowerShell.Commands { if (String.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { - inputObjects.Add(Content); + _inputObjects.Add(Content); } } @@ -144,16 +144,16 @@ namespace Microsoft.PowerShell.Commands { byte[] contentBytes = null; - if (inputObjects.Count > 0) + if (_inputObjects.Count > 0) { StringBuilder outputString = new StringBuilder(); Collection output = System.Management.Automation.PowerShell.Create(). AddCommand("Microsoft.PowerShell.Utility\\Out-String"). AddParameter("Stream"). - Invoke(inputObjects); + Invoke(_inputObjects); - foreach(PSObject outputObject in output) + foreach (PSObject outputObject in output) { if (outputString.Length > 0) { @@ -167,7 +167,7 @@ namespace Microsoft.PowerShell.Commands } else { - contentBytes = System.IO.File.ReadAllBytes(resolvedPath); + contentBytes = System.IO.File.ReadAllBytes(_resolvedPath); } ErrorRecord terminatingError = null; @@ -178,13 +178,13 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(terminatingError); } - if (String.IsNullOrEmpty(resolvedOutFile)) + if (String.IsNullOrEmpty(_resolvedOutFile)) { WriteObject(encodedContent); } else { - System.IO.File.WriteAllText(resolvedOutFile, encodedContent); + System.IO.File.WriteAllText(_resolvedOutFile, encodedContent); } } } @@ -210,7 +210,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - StringBuilder contentBuffer = new StringBuilder(); + private StringBuilder _contentBuffer = new StringBuilder(); /// /// Gets or sets the CMS Message by path. @@ -231,7 +231,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - private string resolvedPath = null; + private string _resolvedPath = null; /// @@ -257,14 +257,14 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(error); } - resolvedPath = resolvedPaths[0]; + _resolvedPath = resolvedPaths[0]; } if (!String.IsNullOrEmpty(LiteralPath)) { // Validate that the path exists SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); - resolvedPath = LiteralPath; + _resolvedPath = LiteralPath; } } @@ -277,12 +277,12 @@ namespace Microsoft.PowerShell.Commands { if (String.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { - if (contentBuffer.Length > 0) + if (_contentBuffer.Length > 0) { - contentBuffer.Append(Environment.NewLine); + _contentBuffer.Append(Environment.NewLine); } - contentBuffer.Append(Content); + _contentBuffer.Append(Content); } } @@ -296,11 +296,11 @@ namespace Microsoft.PowerShell.Commands // Read in the content if (String.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { - actualContent = contentBuffer.ToString(); + actualContent = _contentBuffer.ToString(); } else { - actualContent = System.IO.File.ReadAllText(resolvedPath); + actualContent = System.IO.File.ReadAllText(_resolvedPath); } // Extract out the bytes and Base64 decode them @@ -353,7 +353,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - private StringBuilder contentBuffer = new StringBuilder(); + private StringBuilder _contentBuffer = new StringBuilder(); /// /// Gets or sets the Windows Event Log Message with contents to be decrypted. @@ -385,7 +385,7 @@ namespace Microsoft.PowerShell.Commands get; set; } - private string resolvedPath = null; + private string _resolvedPath = null; /// /// Determines whether to include the decrypted content in its original context, @@ -432,14 +432,14 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(error); } - resolvedPath = resolvedPaths[0]; + _resolvedPath = resolvedPaths[0]; } if (!String.IsNullOrEmpty(LiteralPath)) { // Validate that the path exists SessionState.InvokeProvider.Item.Get(new string[] { LiteralPath }, false, true); - resolvedPath = LiteralPath; + _resolvedPath = LiteralPath; } } @@ -454,12 +454,12 @@ namespace Microsoft.PowerShell.Commands // If we're process by content, collect it. if (String.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { - if (contentBuffer.Length > 0) + if (_contentBuffer.Length > 0) { - contentBuffer.Append(Environment.NewLine); + _contentBuffer.Append(Environment.NewLine); } - contentBuffer.Append(Content); + _contentBuffer.Append(Content); } // If we're processing event log records, decrypt those inline. @@ -497,11 +497,11 @@ namespace Microsoft.PowerShell.Commands // Read in the content if (String.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { - actualContent = contentBuffer.ToString(); + actualContent = _contentBuffer.ToString(); } else { - actualContent = System.IO.File.ReadAllText(resolvedPath); + actualContent = System.IO.File.ReadAllText(_resolvedPath); } string decrypted = Decrypt(actualContent); diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index c6dea58e2..717153d1c 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -16,7 +16,7 @@ namespace Microsoft.PowerShell.Commands /// operations involving security. /// [Cmdlet(VerbsCommon.Get, "Credential", DefaultParameterSetName = GetCredentialCommand.credentialSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113311")] - [OutputType(typeof(PSCredential), ParameterSetName = new string[] { GetCredentialCommand.credentialSet, GetCredentialCommand.messageSet})] + [OutputType(typeof(PSCredential), ParameterSetName = new string[] { GetCredentialCommand.credentialSet, GetCredentialCommand.messageSet })] public sealed class GetCredentialCommand : PSCmdlet { /// @@ -40,15 +40,15 @@ namespace Microsoft.PowerShell.Commands { get { - return cred; + return _cred; } - + set { - cred = value; + _cred = value; } } - private PSCredential cred; + private PSCredential _cred; /// /// Gets and sets the user supplied message providing description about which script/function is @@ -57,10 +57,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, ParameterSetName = messageSet)] public string Message { - get { return message; } - set { message = value; } + get { return _message; } + set { _message = value; } } - private string message = null; + private string _message = null; /// /// Gets and sets the user supplied username to be used while creating the PSCredential. @@ -68,10 +68,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = false, ParameterSetName = messageSet)] public string UserName { - get { return userName; } - set { userName = value; } + get { return _userName; } + set { _userName = value; } } - private string userName = null; + private string _userName = null; /// /// Initializes a new instance of the GetCredentialCommand @@ -79,7 +79,6 @@ namespace Microsoft.PowerShell.Commands /// public GetCredentialCommand() : base() { - } /// @@ -94,7 +93,7 @@ namespace Microsoft.PowerShell.Commands try { - Credential = this.Host.UI.PromptForCredential(caption, message, userName, string.Empty); + Credential = this.Host.UI.PromptForCredential(caption, message, _userName, string.Empty); } catch (ArgumentException exception) { diff --git a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs index 7aaf1886a..3c9d7f7eb 100644 --- a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs @@ -3,6 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #region Using directives + using System; // System.Management.Automation is the namespace which contains the types and // methods pertaining to the Microsoft Command Shell @@ -34,11 +35,11 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true)] public ExecutionPolicyScope Scope { - get { return executionPolicyScope; } - set { executionPolicyScope = value; scopeSpecified = true; } + get { return _executionPolicyScope; } + set { _executionPolicyScope = value; _scopeSpecified = true; } } - private ExecutionPolicyScope executionPolicyScope = ExecutionPolicyScope.LocalMachine; - private bool scopeSpecified = false; + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; + private bool _scopeSpecified = false; /// /// Gets or sets the List parameter, which lists all scopes and their execution @@ -47,17 +48,17 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = false)] public SwitchParameter List { - get { return list; } - set { list = value; } + get { return _list; } + set { _list = value; } } - private bool list; + private bool _list; /// /// Outputs the execution policy. /// protected override void BeginProcessing() { - if (list && scopeSpecified) + if (_list && _scopeSpecified) { string message = ExecutionPolicyCommands.ListAndScopeSpecified; @@ -75,7 +76,7 @@ namespace Microsoft.PowerShell.Commands string shellId = base.Context.ShellID; - if (list) + if (_list) { foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences) { @@ -91,11 +92,10 @@ namespace Microsoft.PowerShell.Commands WriteObject(outputObject); } - } - else if (scopeSpecified) + else if (_scopeSpecified) { - WriteObject(SecuritySupport.GetExecutionPolicy(shellId, executionPolicyScope)); + WriteObject(SecuritySupport.GetExecutionPolicy(shellId, _executionPolicyScope)); } else { @@ -122,10 +122,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] public ExecutionPolicy ExecutionPolicy { - get { return executionPolicy; } - set { executionPolicy = value; } + get { return _executionPolicy; } + set { _executionPolicy = value; } } - private ExecutionPolicy executionPolicy; + private ExecutionPolicy _executionPolicy; /// /// Gets or sets the scope of the execution policy. @@ -133,10 +133,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true)] public ExecutionPolicyScope Scope { - get { return executionPolicyScope; } - set { executionPolicyScope = value; } + get { return _executionPolicyScope; } + set { _executionPolicyScope = value; } } - private ExecutionPolicyScope executionPolicyScope = ExecutionPolicyScope.LocalMachine; + private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine; /// /// Specifies whether to force the execution policy change. @@ -147,14 +147,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private SwitchParameter force; + private SwitchParameter _force; /// /// Sets the execution policy (validation). @@ -162,8 +162,8 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // Verify they've specified a valid scope - if ((executionPolicyScope == ExecutionPolicyScope.UserPolicy) || - (executionPolicyScope == ExecutionPolicyScope.MachinePolicy)) + if ((_executionPolicyScope == ExecutionPolicyScope.UserPolicy) || + (_executionPolicyScope == ExecutionPolicyScope.MachinePolicy)) { string message = ExecutionPolicyCommands.CantSetGroupPolicy; @@ -192,7 +192,7 @@ namespace Microsoft.PowerShell.Commands { try { - SecuritySupport.SetExecutionPolicy(executionPolicyScope, ExecutionPolicy, shellId); + SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId); } catch (UnauthorizedAccessException exception) { @@ -240,16 +240,16 @@ namespace Microsoft.PowerShell.Commands #else private bool ShouldProcessPolicyChange(string localPreference) { - if(ShouldProcess(localPreference)) + if (ShouldProcess(localPreference)) { // See if we're being invoked directly at the // command line. In that case, give a warning. - if(! Force) + if (!Force) { // We don't give this warning if we're in a script, or // if we don't have a window handle // (i.e.: PowerShell -command Set-ExecutionPolicy Unrestricted) - if(IsProcessInteractive()) + if (IsProcessInteractive()) { string query = ExecutionPolicyCommands.SetExecutionPolicyQuery; string caption = ExecutionPolicyCommands.SetExecutionPolicyCaption; @@ -288,7 +288,7 @@ namespace Microsoft.PowerShell.Commands private bool IsProcessInteractive() { // CommandOrigin != Runspace means it is in a script - if(MyInvocation.CommandOrigin != CommandOrigin.Runspace) + if (MyInvocation.CommandOrigin != CommandOrigin.Runspace) return false; // If we don't own the window handle, we've been invoked @@ -305,10 +305,10 @@ namespace Microsoft.PowerShell.Commands TimeSpan timeSinceStart = DateTime.Now - currentProcess.StartTime; TimeSpan idleTime = timeSinceStart - currentProcess.TotalProcessorTime; - if(idleTime.TotalSeconds > 1) + if (idleTime.TotalSeconds > 1) return true; } - catch(System.ComponentModel.Win32Exception) + catch (System.ComponentModel.Win32Exception) { // Don't have access to the properties return false; @@ -332,5 +332,4 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(errorRecord); } }//End Class - }//End namespace diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 1cd607f9d..fe88daf73 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -9,7 +9,7 @@ using System.Security; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Globalization; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands /// public abstract class SecureStringCommandBase : PSCmdlet { - private SecureString ss; + private SecureString _ss; /// /// Gets or sets the secure string to be used by the get- and set- @@ -27,14 +27,14 @@ namespace Microsoft.PowerShell.Commands /// protected SecureString SecureStringData { - get { return ss; } - set { ss = value; } + get { return _ss; } + set { _ss = value; } } // // name of this command // - string commandName; + private string _commandName; /// /// Intitializes a new instance of the SecureStringCommandBase @@ -46,10 +46,10 @@ namespace Microsoft.PowerShell.Commands /// protected SecureStringCommandBase(string name) : base() { - commandName = name; + _commandName = name; } - private SecureStringCommandBase() : base() {} + private SecureStringCommandBase() : base() { } } /// @@ -64,24 +64,24 @@ namespace Microsoft.PowerShell.Commands /// protected ConvertFromToSecureStringCommandBase(string name) : base(name) { } - private SecureString secureKey = null; - private byte[] key; + private SecureString _secureKey = null; + private byte[] _key; /// /// Gets or sets the SecureString version of the encryption /// key used by the SecureString cmdlets. /// - [Parameter(Position=1, ParameterSetName="Secure")] + [Parameter(Position = 1, ParameterSetName = "Secure")] public SecureString SecureKey { get { - return secureKey; + return _secureKey; } set { - secureKey = value; + _secureKey = value; } } @@ -94,12 +94,12 @@ namespace Microsoft.PowerShell.Commands { get { - return key; + return _key; } - + set { - key = value; + _key = value; } } } @@ -120,7 +120,7 @@ namespace Microsoft.PowerShell.Commands /// /// Initializes a new instance of the ExportSecureStringCommand class /// - public ConvertFromSecureStringCommand() : base("ConvertFrom-SecureString") {} + public ConvertFromSecureStringCommand() : base("ConvertFrom-SecureString") { } /// /// Gets or sets the secure string to be exported. @@ -132,7 +132,7 @@ namespace Microsoft.PowerShell.Commands { return SecureStringData; } - + set { SecureStringData = value; @@ -170,7 +170,7 @@ namespace Microsoft.PowerShell.Commands exportedString = SecureStringHelper.Protect(SecureString); } - if(encryptionResult != null) + if (encryptionResult != null) { // The formatted string is Algorithm Version, // Initialization Vector, Encrypted Data @@ -217,66 +217,66 @@ namespace Microsoft.PowerShell.Commands /// /// Initializes a new instance of the ImportSecureStringCommand class. /// - public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") {} + public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") { } /// /// Gets or sets the unsecured string to be imported. /// /// - [Parameter(Position=0, ValueFromPipeline = true, Mandatory=true)] + [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] public String String { get { - return s; + return _s; } - + set { - s = value; + _s = value; } } - private string s; + private string _s; /// /// Gets or sets the flag that marks the unsecured string as a plain /// text string. /// /// - [Parameter(Position=1, ParameterSetName="PlainText")] + [Parameter(Position = 1, ParameterSetName = "PlainText")] public SwitchParameter AsPlainText { get { - return asPlainText; + return _asPlainText; } - + set { - asPlainText = value; + _asPlainText = value; } } - private bool asPlainText; + private bool _asPlainText; /// /// Gets or sets the flag that will force the import of a plaintext /// unsecured string. /// /// - [Parameter(Position=2, ParameterSetName="PlainText")] + [Parameter(Position = 2, ParameterSetName = "PlainText")] public SwitchParameter Force { get { - return force; + return _force; } - + set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// @@ -288,7 +288,7 @@ namespace Microsoft.PowerShell.Commands { SecureString importedString = null; - Utils.CheckArgForNullOrEmpty(s, "String"); + Utils.CheckArgForNullOrEmpty(_s, "String"); try { @@ -296,7 +296,7 @@ namespace Microsoft.PowerShell.Commands byte[] iv = null; // If this is a V2 package - if(String.IndexOf(SecureStringHelper.SecureStringExportHeader, + if (String.IndexOf(SecureStringHelper.SecureStringExportHeader, StringComparison.OrdinalIgnoreCase) == 0) { try @@ -313,13 +313,13 @@ namespace Microsoft.PowerShell.Commands string dataPackage = System.Text.Encoding.Unicode.GetString(inputBytes); string[] dataElements = dataPackage.Split(Utils.Separators.Pipe); - if(dataElements.Length == 3) + if (dataElements.Length == 3) { encryptedContent = dataElements[2]; iv = Convert.FromBase64String(dataElements[1]); } } - catch(FormatException) + catch (FormatException) { // Will be raised if we can't convert the // input from a Base64 string. This means @@ -338,17 +338,17 @@ namespace Microsoft.PowerShell.Commands { importedString = SecureStringHelper.Decrypt(encryptedContent, Key, iv); } - else if(! AsPlainText) + else if (!AsPlainText) { importedString = SecureStringHelper.Unprotect(String); } else { - if(! Force) + if (!Force) { String error = SecureStringCommands.ForceRequired; - Exception e = new ArgumentException (error); + Exception e = new ArgumentException(error); WriteError(new ErrorRecord(e, "ImportSecureString_ForceRequired", ErrorCategory.InvalidArgument, null)); } else @@ -358,7 +358,7 @@ namespace Microsoft.PowerShell.Commands // -AsPlainText and -Force flags, they consciously have made the decision to be OK // with that. importedString = new SecureString(); - foreach(char currentChar in String) { importedString.AppendChar(currentChar); } + foreach (char currentChar in String) { importedString.AppendChar(currentChar); } } } } diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 971edd0f2..f7ecc4154 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -6,7 +6,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Management.Automation; using System.Management.Automation.Internal; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; using System.Collections.Generic; using System.Collections; using System.IO; @@ -17,7 +17,7 @@ using System.Runtime.InteropServices; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; -using DWORD = System.UInt32; +using DWORD = System.UInt32; namespace Microsoft.PowerShell.Commands { @@ -36,15 +36,15 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } - + set { - path = value; + _path = value; } } - private string[] path; + private string[] _path; /// /// Gets or sets the literal path to the file for which to get or set the @@ -57,16 +57,16 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; - isLiteralPath = true; + _path = value; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Gets or sets the digital signature to be written to @@ -74,10 +74,10 @@ namespace Microsoft.PowerShell.Commands /// protected Signature Signature { - get { return signature; } - set { signature = value; } + get { return _signature; } + set { _signature = value; } } - private Signature signature; + private Signature _signature; /// /// Gets or sets the file type of the byte array containing the content with @@ -118,7 +118,7 @@ namespace Microsoft.PowerShell.Commands // // name of this command // - string commandName; + private string _commandName; /// /// Initializes a new instance of the SignatureCommandsBase class, @@ -130,13 +130,13 @@ namespace Microsoft.PowerShell.Commands /// protected SignatureCommandsBase(string name) : base() { - commandName = name; + _commandName = name; } // // hide default ctor // - private SignatureCommandsBase() : base() {} + private SignatureCommandsBase() : base() { } /// /// Processes records from the input pipeline. @@ -160,7 +160,7 @@ namespace Microsoft.PowerShell.Commands Collection paths = new Collection(); // Expand wildcard characters - if (isLiteralPath) + if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } @@ -208,7 +208,7 @@ namespace Microsoft.PowerShell.Commands { WriteObject(Signature); } - } + } } } @@ -217,7 +217,7 @@ namespace Microsoft.PowerShell.Commands WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.CannotRetrieveFromContainer, "SignatureCommandsBaseCannotRetrieveFromContainer")); - } + } } } else @@ -320,15 +320,15 @@ namespace Microsoft.PowerShell.Commands { get { - return certificate; + return _certificate; } set { - certificate = value; + _certificate = value; } } - private X509Certificate2 certificate; + private X509Certificate2 _certificate; /// /// Gets or sets the additional certificates to @@ -347,15 +347,15 @@ namespace Microsoft.PowerShell.Commands { get { - return includeChain; + return _includeChain; } set { - includeChain = value; + _includeChain = value; } } - private string includeChain = "notroot"; + private string _includeChain = "notroot"; /// /// Gets or sets the Url of the time stamping server. @@ -367,7 +367,7 @@ namespace Microsoft.PowerShell.Commands { get { - return timestampServer; + return _timestampServer; } set @@ -376,10 +376,10 @@ namespace Microsoft.PowerShell.Commands { value = String.Empty; } - timestampServer = value; + _timestampServer = value; } } - private string timestampServer = ""; + private string _timestampServer = ""; /// /// Gets or sets the hash algorithm used for signing. @@ -391,15 +391,15 @@ namespace Microsoft.PowerShell.Commands { get { - return hashAlgorithm; + return _hashAlgorithm; } set { - hashAlgorithm = value; + _hashAlgorithm = value; } } - private string hashAlgorithm = null; + private string _hashAlgorithm = null; /// /// Property that sets force parameter. @@ -409,14 +409,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Sets the digital signature on the specified file. @@ -559,7 +559,7 @@ namespace Microsoft.PowerShell.Commands filePath, Certificate, TimestampServer, - hashAlgorithm); + _hashAlgorithm); } finally { @@ -595,7 +595,7 @@ namespace Microsoft.PowerShell.Commands /// association between SigningOption.* values and the /// corresponding string names. /// - private static readonly SigningOptionInfo[] sigOptionInfo = + private static readonly SigningOptionInfo[] s_sigOptionInfo = { new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"), new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"), @@ -612,7 +612,7 @@ namespace Microsoft.PowerShell.Commands /// private static SigningOption GetSigningOption(string optionName) { - foreach (SigningOptionInfo si in sigOptionInfo) + foreach (SigningOptionInfo si in s_sigOptionInfo) { if (String.Equals(optionName, si.optionName, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.PowerShell.Security/security/Utils.cs b/src/Microsoft.PowerShell.Security/security/Utils.cs index 966e9ad4e..04a73f829 100644 --- a/src/Microsoft.PowerShell.Security/security/Utils.cs +++ b/src/Microsoft.PowerShell.Security/security/Utils.cs @@ -17,8 +17,8 @@ using System.Security.Cryptography.X509Certificates; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; -using DWORD = System.UInt32; -using BOOL = System.UInt32; +using DWORD = System.UInt32; +using BOOL = System.UInt32; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Microsoft.PowerShell diff --git a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs index d3225f72b..523ba9fb0 100644 --- a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs +++ b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Runtime.Serialization; using System.Reflection; @@ -26,7 +26,7 @@ namespace Microsoft.PowerShell.Commands /// Initializes a new instance of the CertificateProviderItemNotFoundException /// class with the default message. /// - public CertificateProviderItemNotFoundException () : base() + public CertificateProviderItemNotFoundException() : base() { } @@ -82,7 +82,7 @@ namespace Microsoft.PowerShell.Commands /// The inner exception to be included in the exception. /// internal CertificateProviderItemNotFoundException(Exception innerException) - : base (innerException.Message, innerException) + : base(innerException.Message, innerException) { } } @@ -157,7 +157,7 @@ namespace Microsoft.PowerShell.Commands /// The inner exception to be included in the exception. /// internal CertificateNotFoundException(Exception innerException) - : base (innerException.Message, innerException) + : base(innerException.Message, innerException) { } } @@ -232,7 +232,7 @@ namespace Microsoft.PowerShell.Commands /// The inner exception to be included in the exception. /// internal CertificateStoreNotFoundException(Exception innerException) - : base (innerException.Message, innerException) + : base(innerException.Message, innerException) { } } @@ -307,7 +307,7 @@ namespace Microsoft.PowerShell.Commands /// The inner exception to be included in the exception. /// internal CertificateStoreLocationNotFoundException(Exception innerException) - : base (innerException.Message, innerException) + : base(innerException.Message, innerException) { } } diff --git a/src/System.Management.Automation/AssemblyInfo.cs b/src/System.Management.Automation/AssemblyInfo.cs index 56edb3836..11c405de5 100644 --- a/src/System.Management.Automation/AssemblyInfo.cs +++ b/src/System.Management.Automation/AssemblyInfo.cs @@ -2,13 +2,13 @@ using System.Runtime.CompilerServices; using System.Reflection; using System.Resources; -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersionAttribute("3.0.0.0")] +[assembly: AssemblyVersion("3.0.0.0")] -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] -[assembly:InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("Microsoft.Test.Management.Automation.GPowershell.Analyzers,PublicKey=00240000048000009400000006020000002400005253413100040000010001003f8c902c8fe7ac83af7401b14c1bd103973b26dfafb2b77eda478a2539b979b56ce47f36336741b4ec52bbc51fecd51ba23810cec47070f3e29a2261a2d1d08e4b2b4b457beaa91460055f78cc89f21cd028377af0cc5e6c04699b6856a1e49d5fad3ef16d3c3d6010f40df0a7d6cc2ee11744b5cfb42e0f19a52b8a29dc31b0")] @@ -29,19 +29,19 @@ using System.Resources; [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Editor")] [assembly: InternalsVisibleTo(@"powershell_ise")] #else -[assembly: InternalsVisibleTo(@"System.Management.Automation.Help"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Utility"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Management"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Security"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Export-Command"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.PowerShellLanguageService"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.GraphicalHost"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.GPowerShell"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ISECommon"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Editor"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo(@"powershell_ise"+@",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"System.Management.Automation.Help" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Utility" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Management" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Security" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Export-Command" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.PowerShellLanguageService" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.GraphicalHost" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.GPowerShell" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ISECommon" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Editor" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo(@"powershell_ise" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #endif namespace System.Management.Automation @@ -50,8 +50,8 @@ namespace System.Management.Automation { internal const int PRODUCTMAJORVERSION = 10; internal const int PRODUCTMINORVERSION = 0; - internal const int PRODUCTBUILD = 10032; - internal const int PRODUCTBUILD_QFE = 0; - internal const int PACKAGEBUILD_QFE = 814; + internal const int PRODUCTBUILD = 10032; + internal const int PRODUCTBUILD_QFE = 0; + internal const int PACKAGEBUILD_QFE = 814; } } diff --git a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs index 94e35a3ac..9b6aad4e0 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsExtensions.cs @@ -16,9 +16,9 @@ using Microsoft.Win32; namespace System.Management.Automation { -#region Reflection and Type related extensions + #region Reflection and Type related extensions -#region Enums + #region Enums [Flags] internal enum MemberTypes @@ -31,7 +31,7 @@ namespace System.Management.Automation All = 0xbf, } -#endregion Enums + #endregion Enums /// /// The type extension methods within this partial class are only used for CoreCLR powershell. @@ -42,17 +42,17 @@ namespace System.Management.Automation /// internal static partial class PSTypeExtensions { -#region Miscs + #region Miscs internal static bool IsSubclassOf(this Type targetType, Type type) { return targetType.GetTypeInfo().IsSubclassOf(type); } -#endregion Miscs + #endregion Miscs + + #region Interface -#region Interface - internal static Type GetInterface(this Type type, string name) { // The search is case-sensitive, as it's in the full CLR version @@ -66,10 +66,10 @@ namespace System.Management.Automation implementedInterface => String.Equals(name, implementedInterface.Name, stringComparison)); } -#endregion Interface + #endregion Interface + + #region Member -#region Member - internal static MemberInfo[] GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingAttr) { if (bindingAttr == 0) @@ -105,10 +105,10 @@ namespace System.Management.Automation return members.ToArray(); } -#endregion Member + #endregion Member + + #region Field -#region Field - internal static FieldInfo[] GetFields(this Type type, string name, BindingFlags bindingFlags) { return GetFields(type, name, bindingFlags, false); @@ -188,10 +188,10 @@ namespace System.Management.Automation return fields.ToArray(); } -#endregion Field + #endregion Field + + #region Property -#region Property - internal static PropertyInfo[] GetProperties(this Type type, string name, BindingFlags bindingFlags) { return GetProperties(type, name, bindingFlags, false); @@ -272,7 +272,7 @@ namespace System.Management.Automation return properties.ToArray(); } -#region Property Helper Methods + #region Property Helper Methods private static bool IsInstanceProperty(PropertyInfo property) { @@ -364,11 +364,11 @@ namespace System.Management.Automation return true; } -#endregion Property Helper Methods + #endregion Property Helper Methods -#endregion Property + #endregion Property -#region Constructor + #region Constructor /// /// Search for a constructor that matches the specified bindingFlags and parameter types @@ -389,7 +389,7 @@ namespace System.Management.Automation return results != null ? GetMatchingConstructor(results, types) : null; } - internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed, + internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, string binderNotUsed, CallingConventions callConvention, Type[] types, string modifiersNotUsed) { if (binderNotUsed != null || modifiersNotUsed != null) @@ -523,9 +523,9 @@ namespace System.Management.Automation return ctors.ToArray(); } -#endregion Constructor + #endregion Constructor -#region Method + #region Method internal static MethodInfo GetMethod(this Type targetType, string name, BindingFlags bindingFlags, string binderNotUsed, Type[] types, string modifierNotUsed) { @@ -696,11 +696,11 @@ namespace System.Management.Automation return methods.ToArray(); } -#endregion Method + #endregion Method -#region TypeCode + #region TypeCode - private static readonly Dictionary TypeCodeMap = + private static readonly Dictionary s_typeCodeMap = new Dictionary() { // 'DBNull = 2' is removed from 'System.TypeCode' in CoreCLR. We return @@ -720,7 +720,7 @@ namespace System.Management.Automation {typeof(Double),TypeCode.Double}, {typeof(string),TypeCode.String}, {typeof(Decimal),TypeCode.Decimal}, - {typeof(DateTime),TypeCode.DateTime}, + {typeof(DateTime),TypeCode.DateTime}, }; [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -728,19 +728,19 @@ namespace System.Management.Automation { if (type == null) return TypeCode.Empty; - if (TypeCodeMap.ContainsKey(type)) - return TypeCodeMap[type]; + if (s_typeCodeMap.ContainsKey(type)) + return s_typeCodeMap[type]; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return TypeCode.Object; } -#endregion TypeCode + #endregion TypeCode } -#endregion Reflection and Type related extensions + #endregion Reflection and Type related extensions -#region Environment Extensions + #region Environment Extensions // TODO:CORECLR - Environment Extensions need serious work to refine. internal enum EnvironmentVariableTarget { @@ -751,13 +751,13 @@ namespace System.Management.Automation internal static partial class Environment { -#region Forward_To_System.Environment + #region Forward_To_System.Environment -#region Properties + #region Properties public static int CurrentManagedThreadId - { - get + { + get { return System.Environment.CurrentManagedThreadId; } @@ -803,9 +803,9 @@ namespace System.Management.Automation } } -#endregion Properties + #endregion Properties -#region Methods + #region Methods public static string ExpandEnvironmentVariables(string name) { @@ -867,19 +867,19 @@ namespace System.Management.Automation System.Environment.SetEnvironmentVariable(variable, value); } -#endregion Methods + #endregion Methods + + #endregion Forward_To_System.Environment -#endregion Forward_To_System.Environment - private const int MaxMachineNameLength = 256; - private static string[] commandLineArgs = new string[0]; + private static string[] s_commandLineArgs = new string[0]; public static string[] GetCommandLineArgs() { - return commandLineArgs; + return s_commandLineArgs; } -#region EnvironmentVariable_Extensions + #region EnvironmentVariable_Extensions /// /// The code is mostly copied from the .NET implementation. @@ -982,9 +982,9 @@ namespace System.Management.Automation #endif } -#endregion EnvironmentVariable_Extensions + #endregion EnvironmentVariable_Extensions -#region Property_Extensions + #region Property_Extensions internal static string WinGetUserDomainName() { @@ -1028,7 +1028,7 @@ namespace System.Management.Automation } } } - + internal static string WinGetUserName() { StringBuilder domainName = new StringBuilder(1024); @@ -1083,11 +1083,11 @@ namespace System.Management.Automation { get { - if (m_os == null) + if (s_os == null) { if (Platform.IsWindows) { - m_os = WinOSVersion; + s_os = WinOSVersion; } else { @@ -1096,13 +1096,13 @@ namespace System.Management.Automation // Porting note: cannot put this in CorePsPlatform since // System.Management.Automation.Environment only exists in CoreCLR // builds of monad. - m_os = new Environment.OperatingSystem(new Version(1,0,0,0),""); + s_os = new Environment.OperatingSystem(new Version(1, 0, 0, 0), ""); } } - return m_os; + return s_os; } } - private static volatile OperatingSystem m_os; + private static volatile OperatingSystem s_os; /// /// Windows OSVersion implementation @@ -1123,10 +1123,10 @@ namespace System.Management.Automation return new OperatingSystem(v, osviex.CSDVersion); } } - -#endregion Property_Extensions -#region SpecialFolder_Extensions + #endregion Property_Extensions + + #region SpecialFolder_Extensions /// /// The code is copied from the .NET implementation. @@ -1223,9 +1223,9 @@ namespace System.Management.Automation return folderPath ?? string.Empty; } -#endregion SpecialFolder_Extensions + #endregion SpecialFolder_Extensions -#region NativeMethods + #region NativeMethods /// /// DllImport uses the ApiSet dll that is available on CSS, since this code @@ -1244,7 +1244,7 @@ namespace System.Management.Automation internal static extern byte GetUserNameEx(int format, [Out] StringBuilder domainName, ref uint domainNameLen); [DllImport("api-ms-win-core-localization-l1-2-1.dll", CharSet = CharSet.Unicode)] - internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, + internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments); @@ -1291,9 +1291,9 @@ namespace System.Management.Automation } } -#endregion NativeMethods + #endregion NativeMethods -#region NestedTypes + #region NestedTypes // Porting note: MyDocuments does not exist on .NET Core, but Personal does, and // they both point to your "documents repository," which on linux, is just the @@ -1367,12 +1367,12 @@ namespace System.Management.Automation } } -#endregion NestedTypes + #endregion NestedTypes } -#endregion Environment Extensions + #endregion Environment Extensions -#region Non-generic collection extensions + #region Non-generic collection extensions /// /// Add the AttributeCollection type with stripped functionalities for powershell on CoreCLR. @@ -1388,7 +1388,7 @@ namespace System.Management.Automation /// public static readonly AttributeCollection Empty = new AttributeCollection(null); -#region Constructors + #region Constructors /// /// AttributeCollection protected constructor @@ -1396,7 +1396,7 @@ namespace System.Management.Automation protected AttributeCollection() { } - + /// /// AttributeCollection public constructor /// @@ -1408,7 +1408,7 @@ namespace System.Management.Automation attributes = new Attribute[0]; } - this._attributes = attributes; + _attributes = attributes; for (int i = 0; i < attributes.Length; i++) { if (attributes[i] == null) @@ -1418,9 +1418,9 @@ namespace System.Management.Automation } } -#endregion Constructors + #endregion Constructors -#region Methods + #region Methods /// /// Copies the collection to an array, starting at the specified index. @@ -1446,9 +1446,9 @@ namespace System.Management.Automation return this.GetEnumerator(); } -#endregion Methods + #endregion Methods -#region Properties + #region Properties private readonly Attribute[] _attributes; /// @@ -1459,7 +1459,7 @@ namespace System.Management.Automation { get { - return this._attributes; + return _attributes; } } @@ -1511,12 +1511,12 @@ namespace System.Management.Automation } } -#endregion Properties + #endregion Properties } -#endregion Non-generic collection extensions + #endregion Non-generic collection extensions -#region Misc extensions + #region Misc extensions /// /// Add the Pointer type with stripped functionalities for PowerShell on CoreCLR. @@ -1531,7 +1531,7 @@ namespace System.Management.Automation { } -#region Methods + #region Methods /// /// Boxes the supplied unmanaged memory pointer and the type associated with that pointer into a managed Pointer wrapper object. @@ -1572,7 +1572,7 @@ namespace System.Management.Automation return ((Pointer)ptr)._ptr; } -#endregion Methods + #endregion Methods } internal static class ListExtensions @@ -1609,7 +1609,7 @@ namespace System.Management.Automation } } -#endregion Misc extensions + #endregion Misc extensions } @@ -1631,7 +1631,7 @@ namespace Microsoft.PowerShell.CoreCLR public static Assembly LoadFrom(string assemblyPath) { return ClrFacade.LoadFrom(assemblyPath); - } + } /// /// Load an assembly given its byte stream diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index f20d88679..2d56cea1b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -21,7 +21,6 @@ using SpecialFolder = System.Management.Automation.Environment.SpecialFolder; namespace System.Management.Automation { - /// /// These are platform abstractions and platform specific implementations /// @@ -30,7 +29,6 @@ namespace System.Management.Automation /// public static class Platform { - /// /// True if the current platform is Linux. /// @@ -38,11 +36,11 @@ namespace System.Management.Automation { get { - #if CORECLR +#if CORECLR return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); - #else +#else return false; - #endif +#endif } } @@ -53,11 +51,11 @@ namespace System.Management.Automation { get { - #if CORECLR +#if CORECLR return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - #else +#else return false; - #endif +#endif } } @@ -68,11 +66,11 @@ namespace System.Management.Automation { get { - #if CORECLR +#if CORECLR return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - #else +#else return true; - #endif +#endif } } @@ -83,11 +81,11 @@ namespace System.Management.Automation { get { - #if CORECLR +#if CORECLR return true; - #else +#else return false; - #endif +#endif } } @@ -127,20 +125,20 @@ namespace System.Management.Automation /// /// function for choosing directory location of PowerShell for profile loading /// - public static string SelectProductNameForDirectory (Platform.XDG_Type dirpath) + public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) { - //TODO: XDG_DATA_DIRS implementation as per GitHub issue #1060 string xdgconfighome = System.Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); string xdgdatahome = System.Environment.GetEnvironmentVariable("XDG_DATA_HOME"); string xdgcachehome = System.Environment.GetEnvironmentVariable("XDG_CACHE_HOME"); - string xdgConfigHomeDefault = Path.Combine ( System.Environment.GetEnvironmentVariable("HOME"), ".config", "powershell"); - string xdgDataHomeDefault = Path.Combine( System.Environment.GetEnvironmentVariable("HOME"), ".local", "share", "powershell"); - string xdgModuleDefault = Path.Combine ( xdgDataHomeDefault, "Modules"); - string xdgCacheDefault = Path.Combine (System.Environment.GetEnvironmentVariable("HOME"), ".cache", "powershell"); + string xdgConfigHomeDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".config", "powershell"); + string xdgDataHomeDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".local", "share", "powershell"); + string xdgModuleDefault = Path.Combine(xdgDataHomeDefault, "Modules"); + string xdgCacheDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".cache", "powershell"); - switch (dirpath){ + switch (dirpath) + { case Platform.XDG_Type.CONFIG: //the user has set XDG_CONFIG_HOME corrresponding to profile path if (String.IsNullOrEmpty(xdgconfighome)) @@ -156,8 +154,8 @@ namespace System.Management.Automation case Platform.XDG_Type.DATA: //the user has set XDG_DATA_HOME corresponding to module path - if (String.IsNullOrEmpty(xdgdatahome)){ - + if (String.IsNullOrEmpty(xdgdatahome)) + { // create the xdg folder if needed if (!Directory.Exists(xdgDataHomeDefault)) { @@ -172,8 +170,8 @@ namespace System.Management.Automation case Platform.XDG_Type.MODULES: //the user has set XDG_DATA_HOME corresponding to module path - if (String.IsNullOrEmpty(xdgdatahome)){ - + if (String.IsNullOrEmpty(xdgdatahome)) + { //xdg values have not been set if (!Directory.Exists(xdgModuleDefault)) //module folder not always guaranteed to exist { @@ -218,18 +216,18 @@ namespace System.Management.Automation //This folder is the default in the event of all other failures for data storage if (!Directory.Exists(xdgConfigHomeDefault)) { - try { + try + { Directory.CreateDirectory(xdgConfigHomeDefault); } - catch{ - + catch + { Console.Error.WriteLine("Failed to create default data directory: " + xdgConfigHomeDefault); } } return xdgConfigHomeDefault; } - } // Platform methods prefixed NonWindows are: @@ -273,12 +271,12 @@ namespace System.Management.Automation return Unix.NativeMethods.GetUserFromPid(path); } - #if CORECLR +#if CORECLR internal static string NonWindowsGetFolderPath(SpecialFolder folder) { return Unix.GetFolderPath(folder); } - #endif +#endif internal static string NonWindowsInternalGetLinkType(FileSystemInfo fileInfo) { @@ -371,21 +369,21 @@ namespace System.Management.Automation internal static class Unix { - private static string _userName; + private static string s_userName; public static string UserName { get { - if (string.IsNullOrEmpty(_userName)) + if (string.IsNullOrEmpty(s_userName)) { - _userName = NativeMethods.GetUserName(); - if (string.IsNullOrEmpty(_userName)) + s_userName = NativeMethods.GetUserName(); + if (string.IsNullOrEmpty(s_userName)) { int lastError = Marshal.GetLastWin32Error(); throw new InvalidOperationException("Unix.UserName error: " + lastError); } } - return _userName; + return s_userName; } } @@ -408,7 +406,7 @@ namespace System.Management.Automation } } - #if CORECLR +#if CORECLR public static string GetFolderPath(SpecialFolder folder) { string s = null; @@ -441,7 +439,7 @@ namespace System.Management.Automation } return s; } - #endif +#endif public static bool IsHardLink(ref IntPtr handle) { @@ -469,7 +467,6 @@ namespace System.Management.Automation int lastError = Marshal.GetLastWin32Error(); throw new InvalidOperationException("Unix.IsHardLink error: " + lastError); } - } public static void SetDate(SetDateInfoInternal info) @@ -521,7 +518,7 @@ namespace System.Management.Automation internal static class NativeMethods { - const string psLib = "libpsl-native"; + private const string psLib = "libpsl-native"; // Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and OS X @@ -573,8 +570,6 @@ namespace System.Management.Automation [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool IsDirectory([MarshalAs(UnmanagedType.LPStr)]string filePath); - } } - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 7dda497c8..e9c67bd9d 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -24,7 +24,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs // We create some stub attribute types to make some attribute markers work in CoreCLR. // The purpose of this is to avoid #if/def in powershell code as much as possible. -#region Attribute_Related + #region Attribute_Related /// /// Stub for SpecialNameAttribute @@ -34,7 +34,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public SpecialNameAttribute() {} + public SpecialNameAttribute() { } } /// @@ -45,7 +45,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public SerializableAttribute() {} + public SerializableAttribute() { } } /// @@ -56,7 +56,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public NonSerializedAttribute() {} + public NonSerializedAttribute() { } } /// @@ -76,9 +76,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// public sealed class SecurityPermissionAttribute : Attribute { - public SecurityPermissionAttribute(SecurityAction action) {} + public SecurityPermissionAttribute(SecurityAction action) { } public bool SerializationFormatter { get; set; } - + public bool UnmanagedCode { get; set; } } @@ -91,7 +91,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public TypeLibTypeAttribute(short flags) {} + public TypeLibTypeAttribute(short flags) { } } /// @@ -105,23 +105,24 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// public sealed class HostProtectionAttribute : Attribute { - public HostProtectionAttribute(SecurityAction action) {} + public HostProtectionAttribute(SecurityAction action) { } public bool MayLeakOnAbort { get; set; } } - + /// /// Stub for ResourceExposureAttribute /// public sealed class ResourceExposureAttribute : Attribute { private ResourceScope _resourceExposureLevel; - + public ResourceExposureAttribute(ResourceScope exposureLevel) { _resourceExposureLevel = exposureLevel; } - - public ResourceScope ResourceExposureLevel { + + public ResourceScope ResourceExposureLevel + { get { return _resourceExposureLevel; } } } @@ -133,12 +134,12 @@ namespace Microsoft.PowerShell.CoreClr.Stubs { None = 0, // Resource type - Machine = 0x1, - Process = 0x2, + Machine = 0x1, + Process = 0x2, AppDomain = 0x4, - Library = 0x8, + Library = 0x8, // Visibility - Private = 0x10, // Private to this one class. + Private = 0x10, // Private to this one class. Assembly = 0x20, // Assembly-level, like C#'s "internal" } @@ -202,9 +203,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs WillNotCorruptState } -#endregion Attribute_Related + #endregion Attribute_Related -#region Serialization_Related + #region Serialization_Related /// /// Stub for SerializationInfo @@ -214,7 +215,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public SerializationInfo() {} + public SerializationInfo() { } /// /// @@ -242,7 +243,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// /// - public void AddValue(string name, Object value, Type type) + public void AddValue(string name, Object value, Type type) { throw new NotImplementedException("AddValue(string name, Object value, Type type)"); } @@ -318,9 +319,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs } } -#endregion Serialization_Related + #endregion Serialization_Related -#region Interface_Related + #region Interface_Related /// /// Stub for ISerializable @@ -378,9 +379,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs object this[int index] { get; set; } } -#endregion Interface_Related + #endregion Interface_Related -#region Exception_Related + #region Exception_Related /// /// Stub for SystemException @@ -391,33 +392,33 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// SystemException constructor /// public SystemException() : base() { } - + /// /// SystemException constructor /// /// public SystemException(string message) : base(message) { } - + /// /// SystemException constructor /// /// /// - public SystemException(string message, Exception innerException) : base(message, innerException) {} - + public SystemException(string message, Exception innerException) : base(message, innerException) { } + /// /// SystemException constructor /// /// /// protected SystemException(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - + /// /// SystemException constructor /// /// /// - public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) {} + public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } /// @@ -429,33 +430,33 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// AccessViolationException constructor /// public AccessViolationException() : base() { } - + /// /// AccessViolationException constructor /// /// public AccessViolationException(string message) : base(message) { } - + /// /// AccessViolationException constructor /// /// /// - public AccessViolationException(string message, Exception innerException) : base(message, innerException) {} - + public AccessViolationException(string message, Exception innerException) : base(message, innerException) { } + /// /// AccessViolationException constructor /// /// /// protected AccessViolationException(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - + /// /// AccessViolationException constructor /// /// /// - public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) {} + public virtual void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } /// @@ -472,9 +473,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs { } -#endregion Exception_Related + #endregion Exception_Related -#region SafeHandle_Related + #region SafeHandle_Related /// /// Stub for SafeHandleZeroOrMinusOneIsInvalid @@ -484,7 +485,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// /// Constructor /// - protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) + protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { } @@ -501,9 +502,9 @@ namespace Microsoft.PowerShell.CoreClr.Stubs } } -#endregion SafeHandle_Related + #endregion SafeHandle_Related -#region Misc_Types + #region Misc_Types /// /// Stub for SecurityZone @@ -524,12 +525,12 @@ namespace Microsoft.PowerShell.CoreClr.Stubs /// public class MailAddress { - public MailAddress(string address) {} + public MailAddress(string address) { } } -#endregion Misc_Types + #endregion Misc_Types -#region SystemManagementStubs + #region SystemManagementStubs // Summary: // Describes the authentication level to be used to connect to WMI. This is @@ -602,7 +603,7 @@ namespace Microsoft.PowerShell.CoreClr.Stubs Delegate = 4, } -#endregion + #endregion } @@ -676,7 +677,7 @@ namespace System.Security int strLen = str.Length; int index; // Pointer into the string that indicates the location of the current '&' character int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed). - + do { index = str.IndexOfAny(s_escapeChars, newIndex); @@ -731,7 +732,7 @@ namespace System.Security namespace System.Management.Automation { -#region PSTransaction + #region PSTransaction /// /// We don't need PSTransaction related types on CSS because System.Transactions @@ -765,9 +766,9 @@ namespace System.Management.Automation Never } -#endregion PSTransaction + #endregion PSTransaction -#region CMS + #region CMS internal static class CmsUtils { @@ -790,9 +791,9 @@ namespace System.Management.Automation } } -#endregion CMS + #endregion CMS -#region ApartmentState + #region ApartmentState internal enum ApartmentState { @@ -810,7 +811,7 @@ namespace System.Management.Automation Unknown = 2 } -#endregion ApartmentState + #endregion ApartmentState } namespace System.Management.Automation.Internal @@ -829,7 +830,7 @@ namespace System.Management.Automation.Internal /// internal bool HasTransaction { - get + get { return false; } @@ -888,7 +889,7 @@ namespace System.Management.Automation.Internal throw new NotImplementedException("Rollback"); } - public void Dispose() {} + public void Dispose() { } } } @@ -1144,7 +1145,7 @@ namespace Microsoft.PowerShell.Commands.Internal using System.Security.AccessControl; using System.Security.Principal; -#region TransactedRegistryKey + #region TransactedRegistryKey internal abstract class TransactedRegistryKey : IDisposable { @@ -1279,12 +1280,13 @@ namespace Microsoft.PowerShell.Commands.Internal } } -#endregion TransactedRegistryKey + #endregion TransactedRegistryKey } #endregion PS_STUBS -#region TEMPORARY -- Will port the actual PS component [update: Not necessarily porting all PS components listed here] +// -- Will port the actual PS component [update: Not necessarily porting all PS components listed here] +#region TEMPORARY namespace System.Management.Automation.Internal { @@ -1308,7 +1310,7 @@ namespace System.Management.Automation { using Microsoft.Win32; -#region RegistryStringResourceIndirect + #region RegistryStringResourceIndirect internal sealed class RegistryStringResourceIndirect : IDisposable { @@ -1343,10 +1345,10 @@ namespace System.Management.Automation } } -#endregion + #endregion + + #region Environment -#region Environment - internal static partial class Environment { //TODO:CORECLR Need to be removed once we decide what will be the replacement @@ -1354,8 +1356,8 @@ namespace System.Management.Automation { } } - -#endregion Environment + + #endregion Environment } namespace System.Management.Automation.Security @@ -1366,7 +1368,7 @@ namespace System.Management.Automation.Security /// internal sealed class SystemPolicy { - private SystemPolicy() {} + private SystemPolicy() { } /// /// Gets the system lockdown policy @@ -1381,7 +1383,7 @@ namespace System.Management.Automation.Security /// Gets lockdown policy as applied to a file /// /// Always return SystemEnforcementMode.None in CSS (trusted) - public static SystemEnforcementMode GetLockdownPolicy(string path, System.Runtime.InteropServices.SafeHandle handle) + public static SystemEnforcementMode GetLockdownPolicy(string path, System.Runtime.InteropServices.SafeHandle handle) { return SystemEnforcementMode.None; } @@ -1465,13 +1467,13 @@ namespace System.Management.Automation.Tracing { } static internal void LogAnalyticVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } static internal void SetActivityIdForCurrentThread(Guid newActivityId) { } - static internal void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } - static internal void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + static internal void LogOperationalVerbose(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void LogOperationalWarning(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } static internal void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { } static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } - static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { } - static internal void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } - static internal void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args){ } + static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { } + static internal void LogAnalyticInformational(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } + static internal void LogOperationalInformation(PSEventId id, PSOpcode opcode, PSTask task, PSKeyword keyword, params object[] args) { } } public enum PowerShellTraceTask @@ -1505,9 +1507,9 @@ namespace System.Management.Automation.Tracing /// /// Defines Keywords. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028")] [Flags] - public enum PowerShellTraceKeywords : ulong + public enum PowerShellTraceKeywords : ulong { /// /// None @@ -1575,16 +1577,16 @@ namespace System.Management.Automation.Tracing UseAlwaysAnalytic = 0x4000000000000000, } - public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity + public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity { - static Tracer() {} - + static Tracer() { } + public void EndpointRegistered(string endpointName, string endpointType, string registeredBy) { } public void EndpointUnregistered(string endpointName, string unregisteredBy) - { + { } public void EndpointDisabled(string endpointName, string disabledBy) @@ -1600,35 +1602,35 @@ namespace System.Management.Automation.Tracing } public void BeginContainerParentJobExecution(Guid containerParentJobInstanceId) - { + { } - + public void BeginProxyJobExecution(Guid proxyJobInstanceId) - { + { } public void ProxyJobRemoteJobAssociation(Guid proxyJobInstanceId, Guid containerParentJobInstanceId) - { + { } - + public void EndProxyJobExecution(Guid proxyJobInstanceId) - { + { } - + public void BeginProxyJobEventHandler(Guid proxyJobInstanceId) - { + { } - + public void EndProxyJobEventHandler(Guid proxyJobInstanceId) - { + { } - + public void BeginProxyChildJobEventHandler(Guid proxyChildJobInstanceId) - { + { } - + public void EndContainerParentJobExecution(Guid containerParentJobInstanceId) - { + { } } @@ -1655,7 +1657,7 @@ namespace System.Management.Automation.Tracing /// public bool WriteMessage(string message1, string message2) { - return false; + return false; } /// @@ -1666,7 +1668,7 @@ namespace System.Management.Automation.Tracing /// public bool WriteMessage(string message, Guid instanceId) { - return false; + return false; } @@ -1681,7 +1683,7 @@ namespace System.Management.Automation.Tracing /// public void WriteMessage(string className, string methodName, Guid workflowId, string message, params string[] parameters) { - return ; + return; } /// @@ -1696,16 +1698,16 @@ namespace System.Management.Automation.Tracing /// public void WriteMessage(string className, string methodName, Guid workflowId, Job job, string message, params string[] parameters) { - return; + return; } - public bool TraceException(Exception exception) + public bool TraceException(Exception exception) { - return false; + return false; } } - /// + /// /// TraceSourceFactory will return an instance of TraceSource every time GetTraceSource method is called. /// public static class PowerShellTraceSourceFactory @@ -1757,8 +1759,8 @@ namespace Microsoft.PowerShell { internal static class NativeCultureResolver { - internal static void SetThreadUILanguage(Int16 langId) {} - + internal static void SetThreadUILanguage(Int16 langId) { } + internal static CultureInfo UICulture { get @@ -1779,7 +1781,7 @@ namespace Microsoft.PowerShell #endregion TEMPORARY - + #region Timer namespace System @@ -1801,29 +1803,29 @@ namespace System // // isTerminating: // true if the runtime is terminating; otherwise, false. - public UnhandledExceptionEventArgs(object exception, bool isTerminating) {} + public UnhandledExceptionEventArgs(object exception, bool isTerminating) { } // Summary: // Gets the unhandled exception object. // // Returns: // The unhandled exception object. - public object ExceptionObject - { + public object ExceptionObject + { get - { + { return null; } } - + // // Summary: // Indicates whether the common language runtime is terminating. // // Returns: // true if the runtime is terminating; otherwise, false. - public bool IsTerminating - { + public bool IsTerminating + { get { return false; diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 40103c0f2..a1725bff0 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -60,13 +60,13 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } else { - Exception innerException = null; + Exception innerException = null; if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0) { innerException = powerShell.Streams.Error[0].Exception; } errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InstantiatePSClassObjectFailed, className); - var invalidOperationException = new InvalidOperationException(errorMessage,innerException); + var invalidOperationException = new InvalidOperationException(errorMessage, innerException); throw invalidOperationException; } } @@ -74,12 +74,11 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal foreach (var property in instance.CimInstanceProperties) { if (property.Value != null) - { - + { MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance); - + // verify property exists in corresponding class type - if (memberInfo == null || memberInfo.Length > 1 || !(memberInfo[0] is PropertyInfo || memberInfo[0] is FieldInfo)) + if (memberInfo == null || memberInfo.Length > 1 || !(memberInfo[0] is PropertyInfo || memberInfo[0] is FieldInfo)) { errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.PropertyNotDeclaredInPSClass, new object[] { property.Name, className }); var invalidOperationException = new InvalidOperationException(errorMessage); @@ -99,7 +98,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal var cimPropertyInstance = property.Value as CimInstance; if (cimPropertyInstance != null && cimPropertyInstance.CimClass != null && - cimPropertyInstance.CimClass.CimSystemProperties != null && + cimPropertyInstance.CimClass.CimSystemProperties != null && String.Equals( cimPropertyInstance.CimClass.CimSystemProperties.ClassName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase)) @@ -318,15 +317,15 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration /// internal class CimDSCParser { - private CimMofDeserializer deserializer; - private CimMofDeserializer.OnClassNeeded onClassNeeded; - /// + private CimMofDeserializer _deserializer; + private CimMofDeserializer.OnClassNeeded _onClassNeeded; + /// /// /// internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded) { - deserializer = CimMofDeserializer.Create(); - this.onClassNeeded = onClassNeeded; + _deserializer = CimMofDeserializer.Create(); + _onClassNeeded = onClassNeeded; } /// @@ -334,9 +333,9 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration /// internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded, Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption validationOptions) { - deserializer = CimMofDeserializer.Create(); - deserializer.SchemaValidationOption = validationOptions; - this.onClassNeeded = onClassNeeded; + _deserializer = CimMofDeserializer.Create(); + _deserializer.SchemaValidationOption = validationOptions; + _onClassNeeded = onClassNeeded; } /// @@ -351,7 +350,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration var buffer = GetFileContent(filePath); try { - var result = new List(deserializer.DeserializeInstances(buffer, ref offset, onClassNeeded, null)); + var result = new List(_deserializer.DeserializeInstances(buffer, ref offset, _onClassNeeded, null)); return result; } catch (CimException exception) @@ -393,7 +392,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration { uint offset = 0; var buffer = Encoding.Unicode.GetBytes(mof); - var result = new List(deserializer.DeserializeClasses(buffer, ref offset, null, null, null, onClassNeeded, null)); + var result = new List(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null)); return result; } @@ -403,7 +402,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration /// /// [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things. Wrapping those 2 things in a class will result in a more, not less complexity")] - internal List ParseSchemaMof(string filePath) + internal List ParseSchemaMof(string filePath) { uint offset = 0; var buffer = GetFileContent(filePath); @@ -415,7 +414,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration { fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex); } - var result = new List(deserializer.DeserializeClasses(buffer, ref offset, null, null, null, onClassNeeded, null)); + var result = new List(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null)); foreach (CimClass c in result) { string superClassName = c.CimSuperClassName; @@ -430,7 +429,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration throw e; } } - } return result; @@ -463,9 +461,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration bytes = System.Text.Encoding.Unicode.GetBytes(classText); } - deserializer.DeserializeInstances(bytes, ref offset, onClassNeeded, null); + _deserializer.DeserializeInstances(bytes, ref offset, _onClassNeeded, null); } - } } @@ -483,15 +480,15 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal private const string reservedProperties = "^(Require|Trigger|Notify|Before|After|Subscribe)$"; - private static PSTraceSource tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); // Constants for items in the module qualified name (Module\Version\ClassName) - const int IndexModuleName = 0; - const int IndexModuleVersion = 1; - const int IndexClassName = 2; + private const int IndexModuleName = 0; + private const int IndexModuleVersion = 1; + private const int IndexClassName = 2; //Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1 - private static readonly string[] hiddenResourceList = + private static readonly string[] s_hiddenResourceList = { "MSFT_BaseConfigurationProviderRegistration", "MSFT_CimConfigurationProviderRegistration", @@ -499,89 +496,90 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal }; //Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1) - private static readonly HashSet hiddenResourceCache = new HashSet(hiddenResourceList, + private static readonly HashSet s_hiddenResourceCache = new HashSet(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase); //a collection to hold current importing script based resource file //this prevent circular importing case when the script resource exising in the same module with resources it import-dscresource - private static readonly HashSet CurrentImportingScriptFiles = new HashSet(StringComparer.OrdinalIgnoreCase); - + private static readonly HashSet s_currentImportingScriptFiles = new HashSet(StringComparer.OrdinalIgnoreCase); + /// /// DSC class cache for this runspace. /// Cache stores the DSCRunAsBehavior for the class along with actual cim class. /// - static Dictionary> ClassCache + private static Dictionary> ClassCache { get { - if (_classCache == null) + if (t_classCache == null) { - _classCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); + t_classCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } - return _classCache; + return t_classCache; } } [ThreadStatic] - private static Dictionary> _classCache; + private static Dictionary> t_classCache; /// /// DSC classname to source module mapper /// - static Dictionary> ByClassModuleCache + private static Dictionary> ByClassModuleCache { get { - if (_byClassModuleCache == null) + if (t_byClassModuleCache == null) { - _byClassModuleCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); + t_byClassModuleCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } - return _byClassModuleCache; + return t_byClassModuleCache; } } - [ThreadStatic] private static Dictionary> _byClassModuleCache; + [ThreadStatic] + private static Dictionary> t_byClassModuleCache; /// /// DSC filename to defined class mapper /// - static Dictionary> ByFileClassCache + private static Dictionary> ByFileClassCache { get { - if (_byFileClassCache == null) + if (t_byFileClassCache == null) { - _byFileClassCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); + t_byFileClassCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } - return _byFileClassCache; + return t_byFileClassCache; } } [ThreadStatic] - private static Dictionary> _byFileClassCache; + private static Dictionary> t_byFileClassCache; /// /// Filenames from which we have imported script dynamic keywords /// - static HashSet ScriptKeywordFileCache + private static HashSet ScriptKeywordFileCache { get { - if (_scriptKeywordFileCache == null) + if (t_scriptKeywordFileCache == null) { - _scriptKeywordFileCache = new HashSet(StringComparer.OrdinalIgnoreCase); + t_scriptKeywordFileCache = new HashSet(StringComparer.OrdinalIgnoreCase); } - return _scriptKeywordFileCache; + return t_scriptKeywordFileCache; } } [ThreadStatic] - private static HashSet _scriptKeywordFileCache; + private static HashSet t_scriptKeywordFileCache; /// /// Default ModuleName and ModuleVersion to use /// - private static readonly Tuple DefaultModuleInfoForResource = new Tuple("PSDesiredStateConfiguration", new Version("1.1")); + private static readonly Tuple s_defaultModuleInfoForResource = new Tuple("PSDesiredStateConfiguration", new Version("1.1")); /// /// Default ModuleName and ModuleVersion to use for meta configuration resources @@ -601,16 +599,16 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// because the Mof serializer does not support deserialization of classes with different versions. /// [ThreadStatic] - private static bool _cacheResourcesFromMultipleModuleVersions; + private static bool t_cacheResourcesFromMultipleModuleVersions; private static bool CacheResourcesFromMultipleModuleVersions { get { - return _cacheResourcesFromMultipleModuleVersions; + return t_cacheResourcesFromMultipleModuleVersions; } set { - _cacheResourcesFromMultipleModuleVersions = value; + t_cacheResourcesFromMultipleModuleVersions = value; } } @@ -638,7 +636,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// List of module path from where DSC PS modules will be loaded public static void Initialize(Collection errors, List modulePathList) { - tracer.WriteLine("Initializing DSC class cache force={0}"); + s_tracer.WriteLine("Initializing DSC class cache force={0}"); if (System.Management.Automation.Platform.IsLinux) { @@ -655,10 +653,10 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal Debug.Assert(Directory.Exists(dscConfigurationDirectory), dscConfigurationDirectory + " does not exist."); var resourceBaseFile = Path.Combine(dscConfigurationDirectory, "baseregistration/baseresource.schema.mof"); - ImportClasses(resourceBaseFile, DefaultModuleInfoForResource, errors); + ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors); var metaConfigFile = Path.Combine(dscConfigurationDirectory, "baseregistration/MSFT_DSCMetaConfiguration.mof"); - ImportClasses(metaConfigFile, DefaultModuleInfoForResource, errors); + ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors); var allResourceRoots = new string[] { dscConfigurationDirectory }; @@ -675,7 +673,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) { - ImportClasses(schemaFile, DefaultModuleInfoForResource, errors); + ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); } } @@ -698,10 +696,10 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal // ClearCache(); var resourceBaseFile = Path.Combine(systemResourceRoot, "BaseRegistration\\BaseResource.Schema.mof"); - ImportClasses(resourceBaseFile, DefaultModuleInfoForResource, errors); + ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors); var metaConfigFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_DSCMetaConfiguration.mof"); - ImportClasses(metaConfigFile, DefaultModuleInfoForResource, errors); + ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors); var metaConfigExtensionFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_MetaConfigurationExtensionClasses.Schema.mof"); ImportClasses(metaConfigExtensionFile, DefaultModuleInfoForMetaConfigResource, errors); @@ -719,7 +717,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) { - ImportClasses(schemaFile, DefaultModuleInfoForResource, errors); + ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); } } @@ -808,7 +806,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// Indicate a internal DSC module /// /// - static Tuple GetModuleInfoHelper(string moduleFolderPath, bool isInboxResource, bool isPsProviderModule) + private static Tuple GetModuleInfoHelper(string moduleFolderPath, bool isInboxResource, bool isPsProviderModule) { string moduleName = "PsDesiredStateConfiguration"; if (!isInboxResource) @@ -816,7 +814,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal moduleName = Path.GetFileName(moduleFolderPath); } string manifestPath = Path.Combine(moduleFolderPath, moduleName + ".psd1"); - tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath); + s_tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath); if (!File.Exists(manifestPath)) { @@ -828,7 +826,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } else { - tracer.WriteLine("DSC GetModuleVersion: Manifest file '{0}' not exist.", manifestPath); + s_tracer.WriteLine("DSC GetModuleVersion: Manifest file '{0}' not exist.", manifestPath); return null; } } @@ -850,21 +848,21 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } else { - tracer.WriteLine( + s_tracer.WriteLine( "DSC GetModuleVersion: ModuleVersion value '{0}' cannot be converted to System.Version. Skip the module '{1}'.", versionValue, moduleName); } } else { - tracer.WriteLine( + s_tracer.WriteLine( "DSC GetModuleVersion: Manifest file '{0}' does not contain ModuleVersion. Skip the module '{1}'.", manifestPath, moduleName); } } catch (PSInvalidOperationException ex) { - tracer.WriteLine( + s_tracer.WriteLine( "DSC GetModuleVersion: Error evaluating module manifest file '{0}', with error '{1}'. Skip the module '{2}'.", manifestPath, ex, moduleName); } @@ -873,10 +871,10 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } //Callback implementation... - static CimClass MyClassCallback(string serverName, string namespaceName, string className) - { + private static CimClass MyClassCallback(string serverName, string namespaceName, string className) + { foreach (KeyValuePair> cimClass in ClassCache) - { + { string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName]; if (string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0) { @@ -901,7 +899,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal throw PSTraceSource.NewArgumentNullException("path"); } - tracer.WriteLine("DSC ClassCache: importing file: {0}", path); + s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path); var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback); @@ -913,7 +911,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal catch (PSInvalidOperationException e) { // Ignore modules with invalid schemas. - tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e); + s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e); if (errors != null) { errors.Add(e); @@ -927,8 +925,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal // Only add the class once... var className = c.CimSystemProperties.ClassName; string moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleInfo.Item1, moduleInfo.Item2.ToString(), className); - Tuple cimClassInfo; - + Tuple cimClassInfo; + if (ClassCache.TryGetValue(moduleQualifiedResourceName, out cimClassInfo)) { CimClass cimClass = cimClassInfo.Item2; @@ -947,7 +945,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } } } - if (hiddenResourceCache.Contains(className)) + if (s_hiddenResourceCache.Contains(className)) { continue; } @@ -960,7 +958,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal ClassCache.Remove(resourceList[0].Key); } } - ClassCache[moduleQualifiedResourceName] = new Tuple(DSCResourceRunAsCredential.Default, c); + ClassCache[moduleQualifiedResourceName] = new Tuple(DSCResourceRunAsCredential.Default, c); ByClassModuleCache[className] = moduleInfo; } @@ -971,11 +969,11 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal sb.Append(","); } - tracer.WriteLine("DSC ClassCache: loading file '{0}' added the following classes to the cache: {1}", path, sb.ToString()); + s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added the following classes to the cache: {1}", path, sb.ToString()); } else { - tracer.WriteLine("DSC ClassCache: loading file '{0}' added no classes to the cache."); + s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added no classes to the cache."); } ByFileClassCache[path] = classes; @@ -1010,8 +1008,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// public static void ClearCache() { - tracer.WriteLine("DSC class: clearing the cache and associated keywords."); - ClassCache.Clear(); + s_tracer.WriteLine("DSC class: clearing the cache and associated keywords."); + ClassCache.Clear(); ByClassModuleCache.Clear(); ByFileClassCache.Clear(); ScriptKeywordFileCache.Clear(); @@ -1038,11 +1036,13 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// List of found resources in the form of Dictionary{moduleQualifiedName, cimClass}, otherwise empty list. private static List>> FindResourceInCache(string moduleName, string className) { - return (from cacheEntry in ClassCache let splittedName = cacheEntry.Key.Split(Utils.Separators.Backslash) + return (from cacheEntry in ClassCache + let splittedName = cacheEntry.Key.Split(Utils.Separators.Backslash) let cachedClassName = splittedName[IndexClassName] let cachedModuleName = splittedName[IndexModuleName] where string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0 - && string.Compare(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase) == 0 select cacheEntry).ToList(); + && string.Compare(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase) == 0 + select cacheEntry).ToList(); } /// @@ -1065,7 +1065,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal var moduleQualifiedName = String.Format(CultureInfo.InvariantCulture, "{0}\\{1}", module.Name, module.Version.ToString()); foreach (var pair in ClassCache) { - if(pair.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase)) + if (pair.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase)) { cachedClasses.Add(pair.Value.Item2); } @@ -1233,12 +1233,12 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal string[] splittedName = cachedClass.Key.Split(Utils.Separators.Backslash); string moduleName = splittedName[IndexModuleName]; string moduleVersion = splittedName[IndexModuleVersion]; - + var keyword = CreateKeywordFromCimClass(moduleName, Version.Parse(moduleVersion), cachedClass.Value.Item2, null, cachedClass.Value.Item1); if (keyword != null) { - keywords.Add(keyword); - } + keywords.Add(keyword); + } } return keywords; } @@ -1251,7 +1251,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// If true, don't define the keywords, just create the functions. /// To Specify RunAsBehavior of the class - static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) + private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) { var keyword = CreateKeywordFromCimClass(moduleName, moduleVersion, cimClass, functionsToDefine, runAsBehavior); if (keyword == null) @@ -1289,7 +1289,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// If true, don't define the keywords, just create the functions. /// To specify RunAs behavior of the class - static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) + private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) { var resourceName = cimClass.CimSystemProperties.ClassName; string alias = GetFriendlyName(cimClass); @@ -1440,7 +1440,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { if (valueMap.Length != keyProp.Values.Count) { - tracer.WriteLine( + s_tracer.WriteLine( "DSC CreateDynamicKeywordFromClass: the count of values for qualifier 'Values' and 'ValueMap' doesn't match. count of 'Values': {0}, count of 'ValueMap': {1}. Skip the keyword '{2}'.", keyProp.Values.Count, valueMap.Length, keyword.Keyword); return null; @@ -1453,7 +1453,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal if (keyProp.ValueMap.ContainsKey(key)) { - tracer.WriteLine( + s_tracer.WriteLine( "DSC CreateDynamicKeywordFromClass: same string value '{0}' appears more than once in qualifier 'Values'. Skip the keyword '{1}'.", key, keyword.Keyword); return null; @@ -1571,7 +1571,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal CacheResourcesFromMultipleModuleVersions = cacheResourcesFromMultipleModuleVersions; foreach (var cimClass in GetCachedClasses()) - { + { var className = cimClass.Item2.CimSystemProperties.ClassName; var moduleInfo = ByClassModuleCache[className]; CreateAndRegisterKeywordFromCimClass(moduleInfo.Item1, moduleInfo.Item2, cimClass.Item2, functionsToDefine, cimClass.Item1); @@ -1584,8 +1584,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal var nodeKeyword = new DynamicKeyword() { BodyMode = DynamicKeywordBodyMode.ScriptBlock, - ImplementingModule = DefaultModuleInfoForResource.Item1, - ImplementingModuleVersion = DefaultModuleInfoForResource.Item2, + ImplementingModule = s_defaultModuleInfoForResource.Item1, + ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2, NameMode = DynamicKeywordNameMode.NameRequired, Keyword = "Node", }; @@ -1599,8 +1599,8 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal var nodeKeyword = new DynamicKeyword() { BodyMode = DynamicKeywordBodyMode.Command, - ImplementingModule = DefaultModuleInfoForResource.Item1, - ImplementingModuleVersion = DefaultModuleInfoForResource.Item2, + ImplementingModule = s_defaultModuleInfoForResource.Item1, + ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2, NameMode = DynamicKeywordNameMode.NoName, Keyword = "Import-DscResource", MetaStatement = true, @@ -1780,7 +1780,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { moduleSpecifications[0].Version = moduleVersion; } - } else { @@ -1947,17 +1946,16 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { errorList.Add(new ParseError(scriptExtent, "MultipleModuleEntriesFoundDuringParse", - string.Format(CultureInfo.CurrentCulture, + string.Format(CultureInfo.CurrentCulture, ParserStrings.MultipleModuleEntriesFoundDuringParse, moduleToImport.Name))); - } else { string moduleString = moduleToImport.Version == null ? moduleToImport.Name : string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>", moduleToImport.Name, moduleToImport.Version); - + errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse", string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString))); } @@ -2035,7 +2033,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal try { - foundScriptSchema = ImportScriptKeywordsFromModule(moduleInfo, resourceName, out schemaScriptFilePath); } catch (FileNotFoundException) @@ -2134,12 +2131,12 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal try { var path = moduleInfo.Path; - + if (moduleInfo.RootModule != null && !Path.GetExtension(moduleInfo.Path).Equals(".dll", StringComparison.OrdinalIgnoreCase)) { path = moduleInfo.ModuleBase + "\\" + moduleInfo.RootModule; } - + assembly = Assembly.ReflectionOnlyLoadFrom(path); } catch { } @@ -2165,7 +2162,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { scriptPath = Path.Combine(moduleInfo.ModuleBase, moduleInfo.RootModule); } - else if(moduleInfo.Path != null) + else if (moduleInfo.Path != null) { scriptPath = moduleInfo.Path; } @@ -2276,7 +2273,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal return "string"; } - static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List embeddedInstanceTypes) + private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List embeddedInstanceTypes) { var className = typeAst.Name; sb.AppendFormat(CultureInfo.InvariantCulture, "[ClassVersion(\"1.0.0\"), FriendlyName(\"{0}\")]\nclass {0}", className); @@ -2285,7 +2282,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { sb.Append(" : OMI_BaseResource"); } - sb.Append("\n{\n"); + sb.Append("\n{\n"); ProcessMembers(sb, embeddedInstanceTypes, typeAst, className); @@ -2476,7 +2473,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal mofType, member.Name, arrayAffix); - } + } } /// @@ -2487,7 +2484,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// /// - private static bool GetResourceDefinitionsFromModule (string fileName, out IEnumerable resourceDefinitions, List errorList, IScriptExtent extent) + private static bool GetResourceDefinitionsFromModule(string fileName, out IEnumerable resourceDefinitions, List errorList, IScriptExtent extent) { resourceDefinitions = null; @@ -2558,10 +2555,10 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// /// - static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo module, ICollection resourcesToImport, ICollection resourcesFound, Dictionary functionsToDefine, List errorList, IScriptExtent extent) + private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo module, ICollection resourcesToImport, ICollection resourcesFound, Dictionary functionsToDefine, List errorList, IScriptExtent extent) { IEnumerable resourceDefinitions; - if(!GetResourceDefinitionsFromModule(fileName, out resourceDefinitions, errorList, extent)) + if (!GetResourceDefinitionsFromModule(fileName, out resourceDefinitions, errorList, extent)) { return false; } @@ -2599,20 +2596,20 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal foreach (var attr in resourceDefnAst.Attributes) { if (attr.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) - { + { foreach (var na in attr.NamedArguments) { if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) { - var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; + var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; if (dscResourceAttribute != null) - { - runAsBehavior = dscResourceAttribute.RunAsCredential; - } + { + runAsBehavior = dscResourceAttribute.RunAsCredential; + } } } } - } + } var mof = GenerateMofForAst(resourceDefnAst); @@ -2622,7 +2619,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal return result; } - private static readonly Dictionary mapPrimitiveDotNetTypeToMof = new Dictionary() + private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new Dictionary() { { typeof(sbyte), "sint8" }, { typeof(byte) , "uint8"}, @@ -2640,32 +2637,31 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { typeof(PSCredential), "string" }, { typeof(char), "char16" }, }; - + private static bool AreQualifiersSame(CimReadOnlyKeyedCollection oldQualifier, CimReadOnlyKeyedCollection newQualifiers) { - if(oldQualifier.Count != newQualifiers.Count) + if (oldQualifier.Count != newQualifiers.Count) { return false; } - foreach(var qual in oldQualifier) + foreach (var qual in oldQualifier) { // Find the qualifier in new class var newQual = newQualifiers[qual.Name]; - if( newQual == null) + if (newQual == null) { return false; } - if( (qual.CimType != newQual.CimType) || + if ((qual.CimType != newQual.CimType) || (qual.Flags != newQual.Flags)) { - return false; } - if( (qual.Value == null && newQual.Value != null) || + if ((qual.Value == null && newQual.Value != null) || (qual.Value != null && newQual.Value == null) || - (qual.Value != null && newQual.Value != null && - !string.Equals(qual.Value.ToString(), newQual.Value.ToString(), StringComparison.OrdinalIgnoreCase ) + (qual.Value != null && newQual.Value != null && + !string.Equals(qual.Value.ToString(), newQual.Value.ToString(), StringComparison.OrdinalIgnoreCase) ) ) { @@ -2676,51 +2672,51 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } private static bool ArePropertiesSame(CimReadOnlyKeyedCollection oldProperties, CimReadOnlyKeyedCollection newProperties) { - if(oldProperties.Count != newProperties.Count) + if (oldProperties.Count != newProperties.Count) { return false; } - foreach(var prop in oldProperties) + foreach (var prop in oldProperties) { // Find the property in new class var newProp = newProperties[prop.Name]; - if( newProp == null) + if (newProp == null) { return false; } // flags and type should match - if( (prop.CimType != newProp.CimType) || - (prop.Flags != newProp.Flags) ) + if ((prop.CimType != newProp.CimType) || + (prop.Flags != newProp.Flags)) { return false; } - if(!AreQualifiersSame(prop.Qualifiers, newProp.Qualifiers)) + if (!AreQualifiersSame(prop.Qualifiers, newProp.Qualifiers)) { return false; } } return true; - } + } private static bool IsSameNestedObject(CimClass oldClass, CimClass newClass) { // #1 both the classes should be nested class and not DSC resource - if( (oldClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", oldClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase) ) || - (newClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", newClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase) )) + if ((oldClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", oldClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase)) || + (newClass.CimSuperClassName != null && string.Equals("OMI_BaseResource", newClass.CimSuperClassName, StringComparison.OrdinalIgnoreCase))) { return false; } // #2 qualifier count, names, values and types should be same - if( !AreQualifiersSame(oldClass.CimClassQualifiers, newClass.CimClassQualifiers) ) + if (!AreQualifiersSame(oldClass.CimClassQualifiers, newClass.CimClassQualifiers)) { return false; - } + } // #3 property count, names, values, qualifiers and types should be same - if( !ArePropertiesSame(oldClass.CimClassProperties, newClass.CimClassProperties) ) + if (!ArePropertiesSame(oldClass.CimClassProperties, newClass.CimClassProperties)) { return false; - } + } return true; } @@ -2766,7 +2762,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal else { string cimType; - if (mapPrimitiveDotNetTypeToMof.TryGetValue(type, out cimType)) + if (s_mapPrimitiveDotNetTypeToMof.TryGetValue(type, out cimType)) { embeddedInstanceType = null; return cimType; @@ -2778,7 +2774,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal bool missingDefaultConstructor = false; if (type.GetTypeInfo().IsValueType) { - if (mapPrimitiveDotNetTypeToMof.ContainsKey(type)) + if (s_mapPrimitiveDotNetTypeToMof.ContainsKey(type)) { supported = true; } @@ -2932,7 +2928,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal private static void ProcessEmbeddedInstanceTypes(List embeddedInstanceTypes, List visitedInstances, StringBuilder sb) { StringBuilder nestedSb = null; - + while (embeddedInstanceTypes.Count > 0) { if (nestedSb == null) @@ -2966,7 +2962,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } } - static void GenerateMofForType(Type type, StringBuilder sb, List embeddedInstanceTypes) + private static void GenerateMofForType(Type type, StringBuilder sb, List embeddedInstanceTypes) { var className = type.Name; // Friendly name is required by module validator to verify resource instance against the exclusive resource name list. @@ -2995,7 +2991,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal var propertyInfo = member as PropertyInfo; if (propertyInfo == null) { - var fieldInfo = (FieldInfo) member; + var fieldInfo = (FieldInfo)member; memberType = fieldInfo.FieldType; } else @@ -3068,11 +3064,11 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { foreach (var c in parser.ParseSchemaMofFileBuffer(mof)) { - var className = c.CimSystemProperties.ClassName; + var className = c.CimSystemProperties.ClassName; if (!CacheResourcesFromMultipleModuleVersions) { // Find & remove the previous version of the resource. - List>> resourceList = + List>> resourceList = FindResourceInCache(module.Name, className); if (resourceList.Count > 0 && !string.IsNullOrEmpty(resourceList[0].Key)) @@ -3081,7 +3077,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } } var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className); - ClassCache[moduleQualifiedResourceName] = new Tuple(runAsBehavior, c); + ClassCache[moduleQualifiedResourceName] = new Tuple(runAsBehavior, c); ByClassModuleCache[className] = new Tuple(module.Name, module.Version); resourcesFound.Add(className); CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, runAsBehavior); @@ -3175,7 +3171,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal // // search if class'es friendly name is the given resourceName // - foreach(var c in classes) + foreach (var c in classes) { var alias = GetFriendlyName(c); if (String.Equals(alias, resourceName, StringComparison.OrdinalIgnoreCase)) @@ -3230,7 +3226,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal schemaFilePath = Path.Combine(Path.Combine(Path.Combine(module.ModuleBase, "DSCResources"), resourceName), resourceName + ".Schema.psm1"); - if (File.Exists(schemaFilePath) && !CurrentImportingScriptFiles.Contains(schemaFilePath)) + if (File.Exists(schemaFilePath) && !s_currentImportingScriptFiles.Contains(schemaFilePath)) { // If script dynamic keywords has already been loaded from the file, don't load them again. // The ScriptKeywordFile cache is always initialized from scratch by the top-level @@ -3241,9 +3237,9 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal //BUGBUG - need to fix up how the module gets set. //BUGBUG - should fail somehow if errors is not empty Token[] tokens; ParseError[] errors; - CurrentImportingScriptFiles.Add(schemaFilePath); + s_currentImportingScriptFiles.Add(schemaFilePath); Parser.ParseFile(schemaFilePath, out tokens, out errors); - CurrentImportingScriptFiles.Remove(schemaFilePath); + s_currentImportingScriptFiles.Remove(schemaFilePath); ScriptKeywordFileCache.Add(schemaFilePath); } @@ -3417,16 +3413,16 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal e.SetErrorId("DebugModeShouldHaveOneValue"); return e.ErrorRecord; } - + /// - /// Return an error to indicate a value is out of range for a dynamic keyword property - /// - /// - /// - /// - /// - /// - /// + /// Return an error to indicate a value is out of range for a dynamic keyword property + /// + /// + /// + /// + /// + /// + /// public static ErrorRecord ValueNotInRangeErrorRecord(string property, string name, int providedValue, int lower, int upper) { PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( @@ -3476,28 +3472,28 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { // Name must be present and simple non-empty bare word case DynamicKeywordNameMode.SimpleNameRequired: - usageString = new StringBuilder(keyword.Keyword + " [string] # Resource Name"); - break; + usageString = new StringBuilder(keyword.Keyword + " [string] # Resource Name"); + break; // Name must be present but can also be an expression case DynamicKeywordNameMode.NameRequired: - usageString = new StringBuilder(keyword.Keyword + " [string[]] # Name List"); - break; + usageString = new StringBuilder(keyword.Keyword + " [string[]] # Name List"); + break; // Name may be optionally present, but if it is present, it must be a non-empty bare word. case DynamicKeywordNameMode.SimpleOptionalName: - usageString = new StringBuilder(keyword.Keyword + " [ [string] ] # Optional Name"); - break; + usageString = new StringBuilder(keyword.Keyword + " [ [string] ] # Optional Name"); + break; // Name may be optionally present, expression or bare word case DynamicKeywordNameMode.OptionalName: - usageString = new StringBuilder(keyword.Keyword + " [ [string[]] ] # Optional NameList"); - break; + usageString = new StringBuilder(keyword.Keyword + " [ [string[]] ] # Optional NameList"); + break; // Does not take a name default: - usageString = new StringBuilder(keyword.Keyword); - break; + usageString = new StringBuilder(keyword.Keyword); + break; } usageString.Append("\n{\n"); @@ -3505,7 +3501,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal bool listKeyProperties = true; while (true) { - foreach (var prop in keyword.Properties.OrderBy( ob => ob.Key)) + foreach (var prop in keyword.Properties.OrderBy(ob => ob.Key)) { if (string.Equals(prop.Key, "ResourceId", StringComparison.OrdinalIgnoreCase)) { @@ -3513,9 +3509,9 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal } var propVal = prop.Value; - if (listKeyProperties && propVal.IsKey || ! listKeyProperties && ! propVal.IsKey) + if (listKeyProperties && propVal.IsKey || !listKeyProperties && !propVal.IsKey) { - usageString.Append(propVal.Mandatory ? " " : " [ "); + usageString.Append(propVal.Mandatory ? " " : " [ "); usageString.Append(prop.Key); usageString.Append(" = "); usageString.Append(FormatCimPropertyType(propVal, !propVal.Mandatory)); @@ -3543,7 +3539,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// /// - static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty) + private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty) { string cimTypeName = prop.TypeConstraint; StringBuilder formattedTypeString = new StringBuilder(); @@ -3573,7 +3569,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal if (prop.ValueMap != null && prop.ValueMap.Count > 0) { formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.OrderBy(x => x)) + " }"); - } // We prepend optional property with "[" so close out it here. This way it is shown with [ ] to indication optional @@ -3582,7 +3577,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal formattedTypeString.Append("]"); } - formattedTypeString.Append( "\n" ); + formattedTypeString.Append("\n"); return formattedTypeString; } @@ -3590,20 +3585,20 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal /// /// The scriptblock that implementes the CIM keyword functionality. /// - static ScriptBlock CimKeywordImlementationFunction + private static ScriptBlock CimKeywordImlementationFunction { get { - if (_cimKeywordImlementationFunction == null) + if (s_cimKeywordImlementationFunction == null) { // The scriptblock cache will handle mutual exclusion - _cimKeywordImlementationFunction = ScriptBlock.Create(CimKeywordImlementationFunctionText); + s_cimKeywordImlementationFunction = ScriptBlock.Create(CimKeywordImlementationFunctionText); } - return _cimKeywordImlementationFunction; + return s_cimKeywordImlementationFunction; } } - static ScriptBlock _cimKeywordImlementationFunction; - const string CimKeywordImlementationFunctionText = @" + private static ScriptBlock s_cimKeywordImlementationFunction; + private const string CimKeywordImlementationFunctionText = @" param ( [Parameter(Mandatory)] $KeywordData, @@ -3962,7 +3957,6 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal Write-Debug ""${debugPrefix} RESOURCE PROCESSING COMPLETED. TOTAL ERROR COUNT: $(Get-ConfigurationErrorCount)"" "; - } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index ced5d6b98..d07c1621b 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -23,8 +23,8 @@ namespace Microsoft.PowerShell.Cmdletization return mb; } - private static Lazy _moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); - private static object _moduleBuilderUsageLock = new object(); + private static Lazy s_moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); + private static object s_moduleBuilderUsageLock = new object(); internal static string GetEnumFullName(EnumMetadataEnum enumMetadata) { @@ -45,9 +45,9 @@ namespace Microsoft.PowerShell.Cmdletization underlyingType = typeof(Int32); } - ModuleBuilder mb = _moduleBuilder.Value; + ModuleBuilder mb = s_moduleBuilder.Value; EnumBuilder eb; - lock (_moduleBuilderUsageLock) + lock (s_moduleBuilderUsageLock) { eb = mb.DefineEnum(fullEnumName, TypeAttributes.Public, underlyingType); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index ef155bfab..83a2ef840 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -26,8 +26,8 @@ namespace Microsoft.PowerShell.Cmdletization if (parameters == null) throw new ArgumentNullException("parameters"); // returnValue can be null - this.methodName = name; - this.returnValue = returnValue; + _methodName = name; + _returnValue = returnValue; KeyedCollection mpk = new MethodParametersCollection(); foreach (var parameter in parameters) @@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Cmdletization mpk.Add(parameter); } - this.parameters = mpk; + _parameters = mpk; } /// @@ -43,29 +43,29 @@ namespace Microsoft.PowerShell.Cmdletization /// public string MethodName { - get { return this.methodName; } + get { return _methodName; } } - private readonly string methodName; + private readonly string _methodName; /// /// Method parameters /// public KeyedCollection Parameters { - get { return this.parameters; } + get { return _parameters; } } - private readonly KeyedCollection parameters; + private readonly KeyedCollection _parameters; /// /// Return value of the method. Can be null if the method doesn't return anything. /// public MethodParameter ReturnValue { - get { return this.returnValue; } + get { return _returnValue; } } - private readonly MethodParameter returnValue; + private readonly MethodParameter _returnValue; - internal IEnumerable GetArgumentsOfType() where T: class + internal IEnumerable GetArgumentsOfType() where T : class { List result = new List(); foreach (var methodParameter in this.Parameters) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index de96eb58f..b1b054bba 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Cmdletization /// For example - CimCmdletAdapter knows how to invoke a static method "Foo" in the CIM OM. /// /// Type that represents instances of objects from the wrapped object model - public abstract class CmdletAdapter + public abstract class CmdletAdapter where TObjectInstance : class { internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) @@ -35,10 +35,10 @@ namespace Microsoft.PowerShell.Cmdletization throw new ArgumentNullException("privateData"); } - this.cmdlet = cmdlet; - this.className = className; - this.classVersion = classVersion; - this.privateData = privateData; + _cmdlet = cmdlet; + _className = className; + _classVersion = classVersion; + _privateData = privateData; var compiledScript = this.Cmdlet as PSScriptCmdlet; if (compiledScript != null) @@ -52,7 +52,7 @@ namespace Microsoft.PowerShell.Cmdletization { disposable.Dispose(); } - }; + }; } } @@ -66,7 +66,7 @@ namespace Microsoft.PowerShell.Cmdletization /// public void Initialize(PSCmdlet cmdlet, string className, string classVersion, Version moduleVersion, IDictionary privateData) { - this.moduleVersion = moduleVersion; + _moduleVersion = moduleVersion; Initialize(cmdlet, className, classVersion, privateData); } @@ -137,7 +137,7 @@ namespace Microsoft.PowerShell.Cmdletization /// Query parameters /// Method invocation details /// true if successful method invocations should emit downstream the object instance being operated on - public virtual void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) + public virtual void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) { throw new NotImplementedException(); } @@ -146,7 +146,7 @@ namespace Microsoft.PowerShell.Cmdletization /// Invokes a static method in the object model. /// /// Method invocation details - public virtual void ProcessRecord( + public virtual void ProcessRecord( MethodInvocationInfo methodInvocationInfo) { throw new NotImplementedException(); @@ -159,10 +159,10 @@ namespace Microsoft.PowerShell.Cmdletization { get { - return this.cmdlet; + return _cmdlet; } } - private PSCmdlet cmdlet; + private PSCmdlet _cmdlet; /// /// Name of the class (from the object model handled by this ObjectModelWrapper) that is wrapped by the currently executing cmdlet @@ -171,10 +171,10 @@ namespace Microsoft.PowerShell.Cmdletization { get { - return this.className; + return _className; } } - private string className; + private string _className; /// /// Name of the class (from the object model handled by this ObjectModelWrapper) that is wrapped by the currently executing cmdlet. @@ -184,10 +184,10 @@ namespace Microsoft.PowerShell.Cmdletization { get { - return this.classVersion; + return _classVersion; } } - private string classVersion; + private string _classVersion; /// /// Module version @@ -196,10 +196,10 @@ namespace Microsoft.PowerShell.Cmdletization { get { - return this.moduleVersion; + return _moduleVersion; } } - private Version moduleVersion; + private Version _moduleVersion; /// /// Private data from Cmdlet Definition XML (from <ObjectModelWrapperPrivateData> element) @@ -208,9 +208,9 @@ namespace Microsoft.PowerShell.Cmdletization { get { - return this.privateData; + return _privateData; } } - private IDictionary privateData; + private IDictionary _privateData; } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index cab6e8179..1d208fcd4 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -36,38 +36,38 @@ namespace Microsoft.PowerShell.Cmdletization { #region Static code reused for reading cmdletization xml - private static readonly XmlReaderSettings xmlReaderSettings; + private static readonly XmlReaderSettings s_xmlReaderSettings; static ScriptWriter() { // // XmlReaderSettings // - ScriptWriter.xmlReaderSettings = new XmlReaderSettings(); + ScriptWriter.s_xmlReaderSettings = new XmlReaderSettings(); // general settings - ScriptWriter.xmlReaderSettings.CheckCharacters = true; - ScriptWriter.xmlReaderSettings.CloseInput = false; - ScriptWriter.xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document; - ScriptWriter.xmlReaderSettings.IgnoreComments = true; - ScriptWriter.xmlReaderSettings.IgnoreProcessingInstructions = true; - ScriptWriter.xmlReaderSettings.IgnoreWhitespace = false; - ScriptWriter.xmlReaderSettings.MaxCharactersFromEntities = 16384; // generous guess for the upper bound - ScriptWriter.xmlReaderSettings.MaxCharactersInDocument = 128 * 1024 * 1024; // generous guess for the upper bound + ScriptWriter.s_xmlReaderSettings.CheckCharacters = true; + ScriptWriter.s_xmlReaderSettings.CloseInput = false; + ScriptWriter.s_xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document; + ScriptWriter.s_xmlReaderSettings.IgnoreComments = true; + ScriptWriter.s_xmlReaderSettings.IgnoreProcessingInstructions = true; + ScriptWriter.s_xmlReaderSettings.IgnoreWhitespace = false; + ScriptWriter.s_xmlReaderSettings.MaxCharactersFromEntities = 16384; // generous guess for the upper bound + ScriptWriter.s_xmlReaderSettings.MaxCharactersInDocument = 128 * 1024 * 1024; // generous guess for the upper bound #if CORECLR // XmlReaderSettings doesn't have XmlResolver and Schema Validation related members in CoreCLR. - ScriptWriter.xmlReaderSettings.DtdProcessing = DtdProcessing.Ignore; // DtdProcessing.Parse is not in CoreCLR, so we ignore DTDs in OneCore powershell + ScriptWriter.s_xmlReaderSettings.DtdProcessing = DtdProcessing.Ignore; // DtdProcessing.Parse is not in CoreCLR, so we ignore DTDs in OneCore powershell #else - ScriptWriter.xmlReaderSettings.DtdProcessing = DtdProcessing.Parse; // Allowing DTD parsing with limits of MaxCharactersFromEntities/MaxCharactersInDocument - ScriptWriter.xmlReaderSettings.XmlResolver = null; // do not fetch external documents + ScriptWriter.s_xmlReaderSettings.DtdProcessing = DtdProcessing.Parse; // Allowing DTD parsing with limits of MaxCharactersFromEntities/MaxCharactersInDocument + ScriptWriter.s_xmlReaderSettings.XmlResolver = null; // do not fetch external documents // xsd schema related settings - ScriptWriter.xmlReaderSettings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | + ScriptWriter.s_xmlReaderSettings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings; - ScriptWriter.xmlReaderSettings.ValidationType = ValidationType.Schema; + ScriptWriter.s_xmlReaderSettings.ValidationType = ValidationType.Schema; string cmdletizationXsd = CmdletizationCoreResources.Xml_cmdletsOverObjectsXsd; - XmlReader cmdletizationSchemaReader = XmlReader.Create(new StringReader(cmdletizationXsd), ScriptWriter.xmlReaderSettings); - ScriptWriter.xmlReaderSettings.Schemas = new XmlSchemaSet(); - ScriptWriter.xmlReaderSettings.Schemas.Add(null, cmdletizationSchemaReader); - ScriptWriter.xmlReaderSettings.Schemas.XmlResolver = null; // do not fetch external documents + XmlReader cmdletizationSchemaReader = XmlReader.Create(new StringReader(cmdletizationXsd), ScriptWriter.s_xmlReaderSettings); + ScriptWriter.s_xmlReaderSettings.Schemas = new XmlSchemaSet(); + ScriptWriter.s_xmlReaderSettings.Schemas.Add(null, cmdletizationSchemaReader); + ScriptWriter.s_xmlReaderSettings.Schemas.XmlResolver = null; // do not fetch external documents #endif } @@ -83,12 +83,12 @@ namespace Microsoft.PowerShell.Cmdletization HelpXml = 4, } - private readonly PowerShellMetadata cmdletizationMetadata; - private readonly string moduleName; - private readonly Type objectModelWrapper; - private readonly Type objectInstanceType; - private readonly InvocationInfo invocationInfo; - private readonly GenerationOptions generationOptions; + private readonly PowerShellMetadata _cmdletizationMetadata; + private readonly string _moduleName; + private readonly Type _objectModelWrapper; + private readonly Type _objectInstanceType; + private readonly InvocationInfo _invocationInfo; + private readonly GenerationOptions _generationOptions; internal ScriptWriter( TextReader cmdletizationXmlReader, @@ -102,11 +102,11 @@ namespace Microsoft.PowerShell.Cmdletization Dbg.Assert(invocationInfo != null, "Caller should verify that invocationInfo != null"); Dbg.Assert(!string.IsNullOrEmpty(defaultObjectModelWrapper), "Caller should verify that defaultObjectModelWrapper != null"); - XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, ScriptWriter.xmlReaderSettings); + XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, ScriptWriter.s_xmlReaderSettings); try { var xmlSerializer = new PowerShellMetadataSerializer(); - this.cmdletizationMetadata = (PowerShellMetadata)xmlSerializer.Deserialize(xmlReader); + _cmdletizationMetadata = (PowerShellMetadata)xmlSerializer.Deserialize(xmlReader); } catch (InvalidOperationException e) { @@ -137,9 +137,9 @@ namespace Microsoft.PowerShell.Cmdletization throw; } - string objectModelWrapperName = this.cmdletizationMetadata.Class.CmdletAdapter ?? defaultObjectModelWrapper; - this.objectModelWrapper = (Type)LanguagePrimitives.ConvertTo(objectModelWrapperName, typeof(Type), CultureInfo.InvariantCulture); - TypeInfo objectModelWrapperTypeInfo = this.objectModelWrapper.GetTypeInfo(); + string objectModelWrapperName = _cmdletizationMetadata.Class.CmdletAdapter ?? defaultObjectModelWrapper; + _objectModelWrapper = (Type)LanguagePrimitives.ConvertTo(objectModelWrapperName, typeof(Type), CultureInfo.InvariantCulture); + TypeInfo objectModelWrapperTypeInfo = _objectModelWrapper.GetTypeInfo(); if (objectModelWrapperTypeInfo.IsGenericType) { string message = string.Format( @@ -148,7 +148,7 @@ namespace Microsoft.PowerShell.Cmdletization objectModelWrapperName); throw new XmlException(message); } - Type baseType = this.objectModelWrapper; + Type baseType = _objectModelWrapper; TypeInfo baseTypeInfo = objectModelWrapperTypeInfo; while ((!baseTypeInfo.IsGenericType) || baseTypeInfo.GetGenericTypeDefinition() != typeof(CmdletAdapter<>)) { @@ -164,11 +164,11 @@ namespace Microsoft.PowerShell.Cmdletization } baseTypeInfo = baseType.GetTypeInfo(); } - this.objectInstanceType = baseType.GetGenericArguments()[0]; + _objectInstanceType = baseType.GetGenericArguments()[0]; - this.moduleName = moduleName; - this.invocationInfo = invocationInfo; - this.generationOptions = generationOptions; + _moduleName = moduleName; + _invocationInfo = invocationInfo; + _generationOptions = generationOptions; } #endregion Constructors / setup code @@ -196,14 +196,14 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function @() { output.WriteLine( ScriptWriter.HeaderTemplate, - CodeGeneration.EscapeSingleQuotedStringContent(this.cmdletizationMetadata.Class.ClassName), - CodeGeneration.EscapeSingleQuotedStringContent(this.cmdletizationMetadata.Class.ClassVersion ?? string.Empty), - CodeGeneration.EscapeSingleQuotedStringContent(new Version(this.cmdletizationMetadata.Class.Version).ToString()), - CodeGeneration.EscapeSingleQuotedStringContent(this.objectModelWrapper.FullName)); + CodeGeneration.EscapeSingleQuotedStringContent(_cmdletizationMetadata.Class.ClassName), + CodeGeneration.EscapeSingleQuotedStringContent(_cmdletizationMetadata.Class.ClassVersion ?? string.Empty), + CodeGeneration.EscapeSingleQuotedStringContent(new Version(_cmdletizationMetadata.Class.Version).ToString()), + CodeGeneration.EscapeSingleQuotedStringContent(_objectModelWrapper.FullName)); - if (this.cmdletizationMetadata.Class.CmdletAdapterPrivateData != null) + if (_cmdletizationMetadata.Class.CmdletAdapterPrivateData != null) { - foreach (ClassMetadataData data in this.cmdletizationMetadata.Class.CmdletAdapterPrivateData) + foreach (ClassMetadataData data in _cmdletizationMetadata.Class.CmdletAdapterPrivateData) { output.WriteLine( "$script:PrivateData.Add('{0}', '{1}')", @@ -241,13 +241,13 @@ function __cmdletization_BindCommonParameters private string GetCmdletName(CommonCmdletMetadata cmdletMetadata) { - string noun = cmdletMetadata.Noun ?? this.cmdletizationMetadata.Class.DefaultNoun; + string noun = cmdletMetadata.Noun ?? _cmdletizationMetadata.Class.DefaultNoun; string verb = cmdletMetadata.Verb; return verb + "-" + noun; } - private readonly List aliasesToExport = new List(); - private readonly List functionsToExport = new List(); + private readonly List _aliasesToExport = new List(); + private readonly List _functionsToExport = new List(); private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { @@ -256,7 +256,7 @@ function __cmdletization_BindCommonParameters if (cmdletMetadata.Aliases != null) { attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); - this.aliasesToExport.AddRange(cmdletMetadata.Aliases); + _aliasesToExport.AddRange(cmdletMetadata.Aliases); } if (cmdletMetadata.Obsolete != null) @@ -274,7 +274,7 @@ function __cmdletization_BindCommonParameters { Dictionary commonParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - InternalParameterMetadata internalParameterMetadata = new InternalParameterMetadata(this.objectModelWrapper, false); + InternalParameterMetadata internalParameterMetadata = new InternalParameterMetadata(_objectModelWrapper, false); foreach (CompiledCommandParameter compiledCommandParameter in internalParameterMetadata.BindableParameters.Values) { ParameterMetadata parameterMetadata = new ParameterMetadata(compiledCommandParameter); @@ -285,7 +285,7 @@ function __cmdletization_BindCommonParameters string message = string.Format( CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperUsesIgnoredParameterMetadata, - this.objectModelWrapper.FullName, + _objectModelWrapper.FullName, parameterMetadata.Name, "ValueFromPipeline"); throw new XmlException(message); @@ -296,7 +296,7 @@ function __cmdletization_BindCommonParameters string message = string.Format( CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperUsesIgnoredParameterMetadata, - this.objectModelWrapper.FullName, + _objectModelWrapper.FullName, parameterMetadata.Name, "ValueFromPipelineByPropertyName"); throw new XmlException(message); @@ -307,7 +307,7 @@ function __cmdletization_BindCommonParameters string message = string.Format( CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperUsesIgnoredParameterMetadata, - this.objectModelWrapper.FullName, + _objectModelWrapper.FullName, parameterMetadata.Name, "ValueFromRemainingArguments"); throw new XmlException(message); @@ -326,7 +326,7 @@ function __cmdletization_BindCommonParameters string message = string.Format( CultureInfo.InvariantCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperDefinesMultipleParameterSets, - this.objectModelWrapper.FullName); + _objectModelWrapper.FullName); throw new XmlException(message); } foreach (ParameterMetadata parameter in commonParameters.Values) @@ -405,10 +405,10 @@ function __cmdletization_BindCommonParameters Dbg.Assert(methodMetadata != null, "Caller should verify that instanceMethod != null"); int uniqueId; - if (!this._staticMethodMetadataToUniqueId.TryGetValue(methodMetadata, out uniqueId)) + if (!_staticMethodMetadataToUniqueId.TryGetValue(methodMetadata, out uniqueId)) { - uniqueId = this._staticMethodMetadataToUniqueId.Count; - this._staticMethodMetadataToUniqueId.Add(methodMetadata, uniqueId); + uniqueId = _staticMethodMetadataToUniqueId.Count; + _staticMethodMetadataToUniqueId.Add(methodMetadata, uniqueId); } return methodMetadata.MethodName + uniqueId; @@ -429,10 +429,10 @@ function __cmdletization_BindCommonParameters { if (instanceCmdlet == null) { - if ((this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) && - (this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters != null)) + if ((_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) && + (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters != null)) { - return this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters; + return _cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters; } } else @@ -443,7 +443,7 @@ function __cmdletization_BindCommonParameters } } - return this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdletParameters; + return _cmdletizationMetadata.Class.InstanceCmdlets.GetCmdletParameters; } private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet) @@ -527,10 +527,10 @@ function __cmdletization_BindCommonParameters Dbg.Assert(typeMetadata != null, "Caller should verify typeMetadata != null"); string psTypeText; - List matchingEnums = (this.cmdletizationMetadata.Enums ?? Enumerable.Empty()) + List matchingEnums = (_cmdletizationMetadata.Enums ?? Enumerable.Empty()) .Where(e => Regex.IsMatch( - typeMetadata.PSType, - string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(e.EnumName)), + typeMetadata.PSType, + string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(e.EnumName)), RegexOptions.CultureInvariant)) .ToList(); EnumMetadataEnum matchingEnum = matchingEnums.Count == 1 ? matchingEnums[0] : null; @@ -548,11 +548,11 @@ function __cmdletization_BindCommonParameters } private ParameterMetadata GetParameter( - string parameterSetName, - string objectModelParameterName, - TypeMetadata parameterTypeMetadata, - CmdletParameterMetadata parameterCmdletization, - bool isValueFromPipeline, + string parameterSetName, + string objectModelParameterName, + TypeMetadata parameterTypeMetadata, + CmdletParameterMetadata parameterCmdletization, + bool isValueFromPipeline, bool isValueFromPipelineByPropertyName) { string parameterName; @@ -661,10 +661,9 @@ function __cmdletization_BindCommonParameters } parameterMetadata.Attributes.Add(new ValidateSetAttribute(allowedValues.ToArray())); } - } - int position = int.MinValue; + int position = int.MinValue; ParameterSetMetadata.ParameterFlags parameterFlags = 0; if (parameterCmdletization != null) { @@ -692,31 +691,31 @@ function __cmdletization_BindCommonParameters } private ParameterMetadata GetParameter( - string parameterSetName, - string objectModelParameterName, - TypeMetadata parameterType, + string parameterSetName, + string objectModelParameterName, + TypeMetadata parameterType, CmdletParameterMetadataForInstanceMethodParameter parameterCmdletization) { return GetParameter( - parameterSetName, - objectModelParameterName, - parameterType, - parameterCmdletization, + parameterSetName, + objectModelParameterName, + parameterType, + parameterCmdletization, false, /* isValueFromPipeline */ parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); } - + private ParameterMetadata GetParameter( IEnumerable queryParameterSets, - string objectModelParameterName, - TypeMetadata parameterType, + string objectModelParameterName, + TypeMetadata parameterType, CmdletParameterMetadataForGetCmdletParameter parameterCmdletization) { ParameterMetadata result = GetParameter( - ParameterAttribute.AllParameterSets, - objectModelParameterName, - parameterType, - parameterCmdletization, + ParameterAttribute.AllParameterSets, + objectModelParameterName, + parameterType, + parameterCmdletization, parameterCmdletization != null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); @@ -738,19 +737,19 @@ function __cmdletization_BindCommonParameters return result; } - + private ParameterMetadata GetParameter( - string parameterSetName, - string objectModelParameterName, - TypeMetadata parameterType, + string parameterSetName, + string objectModelParameterName, + TypeMetadata parameterType, CmdletParameterMetadataForStaticMethodParameter parameterCmdletization) { return GetParameter( - parameterSetName, - objectModelParameterName, - parameterType, - parameterCmdletization, - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, + parameterSetName, + objectModelParameterName, + parameterType, + parameterCmdletization, + parameterCmdletization != null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); } @@ -770,7 +769,7 @@ function __cmdletization_BindCommonParameters CmdletizationCoreResources.ScriptWriter_ParameterNameConflictsWithCommonParameters, parameter.Key, commandMetadata.Name, - this.objectModelWrapper.FullName); + _objectModelWrapper.FullName); throw new XmlException(message); } else @@ -945,14 +944,14 @@ function __cmdletization_BindCommonParameters foreach (ParameterMetadata parameter in parameters.Values) { - List> oldParameterSets = new List>(parameter.ParameterSets); + List> oldParameterSets = new List>(parameter.ParameterSets); parameter.ParameterSets.Clear(); foreach (KeyValuePair oldParameterSet in oldParameterSets) { foreach (List combination in combinations) { - string[] formattingArray = new string[otherParameterSets.Length+1]; + string[] formattingArray = new string[otherParameterSets.Length + 1]; formattingArray[0] = oldParameterSet.Key; combination.CopyTo(formattingArray, 1); string newParameterSetName = string.Format(CultureInfo.InvariantCulture, parameterSetNameTemplate, formattingArray); @@ -1213,8 +1212,8 @@ function __cmdletization_BindCommonParameters MethodParameterBindings methodParameterBindings = GetMethodParameterKind(methodParameter); Type dotNetTypeOfParameter = GetDotNetType(methodParameter.Type); GenerateSingleMethodParameterProcessing( - output, - " ", + output, + " ", cmdletParameterName, dotNetTypeOfParameter, methodParameter.Type.ETSType, @@ -1257,7 +1256,7 @@ function __cmdletization_BindCommonParameters } output.WriteLine( - " $__cmdletization_methodInvocationInfo = [Microsoft.PowerShell.Cmdletization.MethodInvocationInfo]::new('{0}', $__cmdletization_methodParameters, $__cmdletization_returnValue)", + " $__cmdletization_methodInvocationInfo = [Microsoft.PowerShell.Cmdletization.MethodInvocationInfo]::new('{0}', $__cmdletization_methodParameters, $__cmdletization_returnValue)", CodeGeneration.EscapeSingleQuotedStringContent(method.MethodName)); output.WriteLine(" $__cmdletization_objectModelWrapper.ProcessRecord($__cmdletization_methodInvocationInfo)"); @@ -1395,7 +1394,7 @@ function __cmdletization_BindCommonParameters } output.WriteLine( - " $__cmdletization_methodInvocationInfo = [Microsoft.PowerShell.Cmdletization.MethodInvocationInfo]::new('{0}', $__cmdletization_methodParameters, $__cmdletization_returnValue)", + " $__cmdletization_methodInvocationInfo = [Microsoft.PowerShell.Cmdletization.MethodInvocationInfo]::new('{0}', $__cmdletization_methodParameters, $__cmdletization_returnValue)", CodeGeneration.EscapeSingleQuotedStringContent(method.MethodName)); if (typesOfOutParameters.Count == 0) @@ -1441,27 +1440,27 @@ function __cmdletization_BindCommonParameters } private void GenerateIfBoundParameter( - IEnumerable commonParameterSets, - IEnumerable methodParameterSets, - ParameterMetadata cmdletParameterMetadata, + IEnumerable commonParameterSets, + IEnumerable methodParameterSets, + ParameterMetadata cmdletParameterMetadata, TextWriter output) { output.Write(" if ($PSBoundParameters.ContainsKey('{0}') -and (@(", CodeGeneration.EscapeSingleQuotedStringContent(cmdletParameterMetadata.Name)); bool firstParameterSet = true; foreach (string queryParameterSetName in cmdletParameterMetadata.ParameterSets.Keys) - foreach (string parameterSetName in MultiplyParameterSets(queryParameterSetName, InstanceQueryParameterSetTemplate, commonParameterSets, methodParameterSets)) - { - if (!firstParameterSet) output.Write(", "); - firstParameterSet = false; - output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); - } + foreach (string parameterSetName in MultiplyParameterSets(queryParameterSetName, InstanceQueryParameterSetTemplate, commonParameterSets, methodParameterSets)) + { + if (!firstParameterSet) output.Write(", "); + firstParameterSet = false; + output.Write("'{0}'", CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); + } output.WriteLine(") -contains $PSCmdlet.ParameterSetName )) {"); } private ParameterMetadata GenerateQueryClause( - IEnumerable commonParameterSets, - IEnumerable queryParameterSets, - IEnumerable methodParameterSets, + IEnumerable commonParameterSets, + IEnumerable queryParameterSets, + IEnumerable methodParameterSets, string queryBuilderMethodName, PropertyMetadata property, PropertyQuery query, @@ -1513,7 +1512,7 @@ function __cmdletization_BindCommonParameters } else { - bool allowGlobbing = + bool allowGlobbing = (!wildcardablePropertyQuery.AllowGlobbingSpecified && cmdletParameterMetadata.ParameterType.Equals(typeof(string[]))) || (wildcardablePropertyQuery.AllowGlobbingSpecified && wildcardablePropertyQuery.AllowGlobbing); output.WriteLine( @@ -1574,10 +1573,10 @@ function __cmdletization_BindCommonParameters } private ParameterMetadata GenerateOptionClause( - IEnumerable commonParameterSets, - IEnumerable queryParameterSets, - IEnumerable methodParameterSets, - QueryOption queryOptionMetadata, + IEnumerable commonParameterSets, + IEnumerable queryParameterSets, + IEnumerable methodParameterSets, + QueryOption queryOptionMetadata, TextWriter output) { ParameterMetadata cmdletParameterMetadata = GetParameter( @@ -1638,7 +1637,7 @@ function __cmdletization_BindCommonParameters methodName = "NotAValidMethod"; break; } - + ParameterMetadata parameterMetadata = GenerateQueryClause( commonParameterSets, queryParameterSets, methodParameterSets, methodName, property, property.Items[i], output); @@ -1717,7 +1716,7 @@ function __cmdletization_BindCommonParameters if (instanceCmdlet != null) { - ParameterMetadata inputObjectParameter = new ParameterMetadata("InputObject", this.objectInstanceType.MakeArrayType()); + ParameterMetadata inputObjectParameter = new ParameterMetadata("InputObject", _objectInstanceType.MakeArrayType()); ParameterSetMetadata.ParameterFlags inputObjectFlags = ParameterSetMetadata.ParameterFlags.ValueFromPipeline; if (queryParameters.Count > 0) @@ -1726,18 +1725,18 @@ function __cmdletization_BindCommonParameters } string psTypeNameOfInputObjectElements; - if (this.objectModelWrapper.FullName.Equals("Microsoft.PowerShell.Cmdletization.Cim.CimCmdletAdapter")) + if (_objectModelWrapper.FullName.Equals("Microsoft.PowerShell.Cmdletization.Cim.CimCmdletAdapter")) { - int indexOfLastBackslash = this.cmdletizationMetadata.Class.ClassName.LastIndexOf('\\'); - int indexOfLastForwardSlash = this.cmdletizationMetadata.Class.ClassName.LastIndexOf('/'); + int indexOfLastBackslash = _cmdletizationMetadata.Class.ClassName.LastIndexOf('\\'); + int indexOfLastForwardSlash = _cmdletizationMetadata.Class.ClassName.LastIndexOf('/'); int indexOfLastSeparator = Math.Max(indexOfLastBackslash, indexOfLastForwardSlash); - string cimClassName = this.cmdletizationMetadata.Class.ClassName.Substring( - indexOfLastSeparator + 1, - this.cmdletizationMetadata.Class.ClassName.Length - indexOfLastSeparator - 1); + string cimClassName = _cmdletizationMetadata.Class.ClassName.Substring( + indexOfLastSeparator + 1, + _cmdletizationMetadata.Class.ClassName.Length - indexOfLastSeparator - 1); psTypeNameOfInputObjectElements = string.Format( CultureInfo.InvariantCulture, "{0}#{1}", - this.objectInstanceType.FullName, + _objectInstanceType.FullName, cimClassName); } else @@ -1745,8 +1744,8 @@ function __cmdletization_BindCommonParameters psTypeNameOfInputObjectElements = string.Format( CultureInfo.InvariantCulture, "{0}#{1}", - this.objectInstanceType.FullName, - this.cmdletizationMetadata.Class.ClassName); + _objectInstanceType.FullName, + _cmdletizationMetadata.Class.ClassName); } inputObjectParameter.Attributes.Add(new PSTypeNameAttribute(psTypeNameOfInputObjectElements)); @@ -1851,12 +1850,12 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' { StringBuilder output = new StringBuilder(); - if (GenerationOptions.HelpXml == (this.generationOptions & GenerationOptions.HelpXml)) + if (GenerationOptions.HelpXml == (_generationOptions & GenerationOptions.HelpXml)) { output.AppendFormat( CultureInfo.InvariantCulture, "# .EXTERNALHELP {0}.cdxml-Help.xml", - ScriptWriter.EscapeModuleNameForHelpComment(this.moduleName)); + ScriptWriter.EscapeModuleNameForHelpComment(_moduleName)); } return output.ToString(); @@ -1908,7 +1907,7 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - this.functionsToExport.Add(commandMetadata.Name); + _functionsToExport.Add(commandMetadata.Name); } private static void AddPassThruParameter(IDictionary commonParameters, InstanceCmdletMetadata instanceCmdletMetadata) @@ -1930,7 +1929,7 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' } if (instanceCmdletMetadata.Method.ReturnValue != null) { - if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata != null) && + if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata != null) && (instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata.ErrorCode == null)) { outParametersArePresent = true; @@ -2003,8 +2002,8 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' CmdletEndBlockTemplate, /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - - this.functionsToExport.Add(commandMetadata.Name); + + _functionsToExport.Add(commandMetadata.Name); } private string GetOutputAttributeForGetCmdlet() @@ -2013,29 +2012,29 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' result.AppendFormat( CultureInfo.InvariantCulture, "[OutputType([{0}])]", - CodeGeneration.EscapeSingleQuotedStringContent(this.objectInstanceType.FullName)); + CodeGeneration.EscapeSingleQuotedStringContent(_objectInstanceType.FullName)); result.AppendLine(); result.AppendFormat( CultureInfo.InvariantCulture, "[OutputType('{0}#{1}')]", - CodeGeneration.EscapeSingleQuotedStringContent(this.objectInstanceType.FullName), - CodeGeneration.EscapeSingleQuotedStringContent(this.cmdletizationMetadata.Class.ClassName)); + CodeGeneration.EscapeSingleQuotedStringContent(_objectInstanceType.FullName), + CodeGeneration.EscapeSingleQuotedStringContent(_cmdletizationMetadata.Class.ClassName)); result.AppendLine(); return result.ToString(); } private CommonCmdletMetadata GetGetCmdletMetadata() { - Dbg.Assert(this.cmdletizationMetadata.Class.InstanceCmdlets != null, "Caller should verify presence of instance cmdlets"); + Dbg.Assert(_cmdletizationMetadata.Class.InstanceCmdlets != null, "Caller should verify presence of instance cmdlets"); CommonCmdletMetadata cmdletMetadata; - if (this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) { - cmdletMetadata = this.cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.CmdletMetadata; + cmdletMetadata = _cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.CmdletMetadata; } else { cmdletMetadata = new CommonCmdletMetadata(); - cmdletMetadata.Noun = this.cmdletizationMetadata.Class.DefaultNoun; + cmdletMetadata.Noun = _cmdletizationMetadata.Class.DefaultNoun; cmdletMetadata.Verb = VerbsCommon.Get; } Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); @@ -2089,17 +2088,17 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - this.functionsToExport.Add(commandMetadata.Name); + _functionsToExport.Add(commandMetadata.Name); } - private static object _enumCompilationLock = new object(); + private static object s_enumCompilationLock = new object(); private static void CompileEnum(EnumMetadataEnum enumMetadata) { try { string enumFullName = EnumWriter.GetEnumFullName(enumMetadata); - lock (_enumCompilationLock) + lock (s_enumCompilationLock) { Type alreadyExistingType; if (!LanguagePrimitives.TryConvertTo(enumFullName, CultureInfo.InvariantCulture, out alreadyExistingType)) @@ -2124,28 +2123,28 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' this.WriteModulePreamble(output); this.WriteBindCommonParametersFunction(output); - if (this.cmdletizationMetadata.Enums != null) + if (_cmdletizationMetadata.Enums != null) { - foreach (EnumMetadataEnum enumMetadata in this.cmdletizationMetadata.Enums) + foreach (EnumMetadataEnum enumMetadata in _cmdletizationMetadata.Enums) { CompileEnum(enumMetadata); } } - if (this.cmdletizationMetadata.Class.StaticCmdlets != null) + if (_cmdletizationMetadata.Class.StaticCmdlets != null) { - foreach (StaticCmdletMetadata staticCmdlet in this.cmdletizationMetadata.Class.StaticCmdlets) + foreach (StaticCmdletMetadata staticCmdlet in _cmdletizationMetadata.Class.StaticCmdlets) { this.WriteCmdlet(output, staticCmdlet); } } - if (this.cmdletizationMetadata.Class.InstanceCmdlets != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets != null) { this.WriteGetCmdlet(output); - if (this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) { - foreach (InstanceCmdletMetadata instanceCmdlet in this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet) + foreach (InstanceCmdletMetadata instanceCmdlet in _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet) { this.WriteCmdlet(output, instanceCmdlet); } @@ -2165,11 +2164,11 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' internal void PopulatePSModuleInfo(PSModuleInfo moduleInfo) { moduleInfo.SetModuleType(ModuleType.Cim); - moduleInfo.SetVersion(new Version(this.cmdletizationMetadata.Class.Version)); + moduleInfo.SetVersion(new Version(_cmdletizationMetadata.Class.Version)); Hashtable cmdletizationData = new Hashtable(StringComparer.OrdinalIgnoreCase); - cmdletizationData.Add(PrivateDataKey_ClassName, this.cmdletizationMetadata.Class.ClassName); - cmdletizationData.Add(PrivateDataKey_ObjectModelWrapper, this.objectModelWrapper); + cmdletizationData.Add(PrivateDataKey_ClassName, _cmdletizationMetadata.Class.ClassName); + cmdletizationData.Add(PrivateDataKey_ObjectModelWrapper, _objectModelWrapper); Hashtable privateData = new Hashtable(StringComparer.OrdinalIgnoreCase); privateData.Add(PrivateDataKey_CmdletsOverObjects, cmdletizationData); @@ -2187,24 +2186,24 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' moduleInfo.DeclaredFunctionExports = new Collection(); IEnumerable cmdletMetadatas = Enumerable.Empty(); - if (this.cmdletizationMetadata.Class.InstanceCmdlets != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets != null) { cmdletMetadatas = cmdletMetadatas.Append(this.GetGetCmdletMetadata()); - if (this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) { cmdletMetadatas = cmdletMetadatas.Concat( - this.cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet.Select(c => c.CmdletMetadata)); + _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet.Select(c => c.CmdletMetadata)); } } - if (this.cmdletizationMetadata.Class.StaticCmdlets != null) + if (_cmdletizationMetadata.Class.StaticCmdlets != null) { cmdletMetadatas = cmdletMetadatas.Concat( - this.cmdletizationMetadata.Class.StaticCmdlets.Select(c => c.CmdletMetadata)); + _cmdletizationMetadata.Class.StaticCmdlets.Select(c => c.CmdletMetadata)); } - + foreach (CommonCmdletMetadata cmdletMetadata in cmdletMetadatas) { if (cmdletMetadata.Aliases != null) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index 1bfd80ea7..e03af7836 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -3,6 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ // TODO/FIXME: move this to Microsoft.PowerShell.Cim namespace (and move in source depot folder as well) + namespace Microsoft.PowerShell.Cmdletization.Cim { using System.Management.Automation; @@ -20,8 +21,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class WildcardPatternToCimQueryParser : WildcardPatternParser { - private readonly StringBuilder result = new StringBuilder(); - private bool needClientSideFiltering; + private readonly StringBuilder _result = new StringBuilder(); + private bool _needClientSideFiltering; protected override void AppendLiteralCharacter(char c) { @@ -35,24 +36,24 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.EndBracketExpression(); break; default: - result.Append(c); + _result.Append(c); break; } } protected override void AppendAsterix() { - result.Append('%'); + _result.Append('%'); } protected override void AppendQuestionMark() { - result.Append('_'); + _result.Append('_'); } protected override void BeginBracketExpression() { - result.Append('['); + _result.Append('['); } protected override void AppendLiteralCharacterToBracketExpression(char c) @@ -66,7 +67,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim this.AppendCharacterRangeToBracketExpression(c, c); break; default: - result.Append(c); + _result.Append(c); break; } } @@ -82,12 +83,12 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if ((91 <= startOfCharacterRange) && (startOfCharacterRange <= 94)) { startOfCharacterRange = (char)90; - needClientSideFiltering = true; + _needClientSideFiltering = true; } if ((91 <= endOfCharacterRange) && (endOfCharacterRange <= 94)) { endOfCharacterRange = (char)95; - needClientSideFiltering = true; + _needClientSideFiltering = true; } // 44 = , @@ -96,22 +97,22 @@ namespace Microsoft.PowerShell.Cmdletization.Cim if (startOfCharacterRange == 45) { startOfCharacterRange = (char)44; - needClientSideFiltering = true; + _needClientSideFiltering = true; } if (endOfCharacterRange == 45) { endOfCharacterRange = (char)46; - needClientSideFiltering = true; + _needClientSideFiltering = true; } - result.Append(startOfCharacterRange); - result.Append('-'); - result.Append(endOfCharacterRange); + _result.Append(startOfCharacterRange); + _result.Append('-'); + _result.Append(endOfCharacterRange); } protected override void EndBracketExpression() { - result.Append(']'); + _result.Append(']'); } /// @@ -122,8 +123,8 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { var parser = new WildcardPatternToCimQueryParser(); WildcardPatternParser.Parse(wildcardPattern, parser); - needsClientSideFiltering = parser.needClientSideFiltering; - return parser.result.ToString(); + needsClientSideFiltering = parser._needClientSideFiltering; + return parser._result.ToString(); } } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index 1a24c5bac..4b13a76ff 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -1,13 +1,4 @@ #if CORECLR -// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE -// -// The original file has been generated by admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd -// -// sgen.exe is called within 'generate.ps1' to generate the original file. The generated code cannot work in CoreCLR. -// This file is manually adjusted based on the generated file, so as to make it work in CoreCLR. -// The adjustment for this file is mainly removing the attributes that are not supported in CoreCLR. - #if CORECLR #pragma warning disable @@ -24,545 +15,664 @@ // // This source code was auto-generated by xsd, Version=4.0.30319.17929. // -namespace Microsoft.PowerShell.Cmdletization.Xml { +namespace Microsoft.PowerShell.Cmdletization.Xml +{ using System.Xml.Serialization; - - + + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public ClassMetadata Class + { + get + { + return this._classField; } - set { - this.classField = value; + set + { + this._classField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable=false)] - public EnumMetadataEnum[] Enums { - get { - return this.enumsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)] + public EnumMetadataEnum[] Enums + { + get + { + return this._enumsField; } - set { - this.enumsField = value; + set + { + this._enumsField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public string Version + { + get + { + return this._versionField; } - set { - this.versionField = value; + set + { + this._versionField = value; } } - + /// - public string DefaultNoun { - get { - return this.defaultNounField; + public string DefaultNoun + { + get + { + return this._defaultNounField; } - set { - this.defaultNounField = value; + set + { + this._defaultNounField = value; } } - + /// - public ClassMetadataInstanceCmdlets InstanceCmdlets { - get { - return this.instanceCmdletsField; + public ClassMetadataInstanceCmdlets InstanceCmdlets + { + get + { + return this._instanceCmdletsField; } - set { - this.instanceCmdletsField = value; + set + { + this._instanceCmdletsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable=false)] - public StaticCmdletMetadata[] StaticCmdlets { - get { - return this.staticCmdletsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)] + public StaticCmdletMetadata[] StaticCmdlets + { + get + { + return this._staticCmdletsField; } - set { - this.staticCmdletsField = value; + set + { + this._staticCmdletsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable=false)] - public ClassMetadataData[] CmdletAdapterPrivateData { - get { - return this.cmdletAdapterPrivateDataField; + [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)] + public ClassMetadataData[] CmdletAdapterPrivateData + { + get + { + return this._cmdletAdapterPrivateDataField; } - set { - this.cmdletAdapterPrivateDataField = value; + set + { + this._cmdletAdapterPrivateDataField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletAdapter { - get { - return this.cmdletAdapterField; + public string CmdletAdapter + { + get + { + return this._cmdletAdapterField; } - set { - this.cmdletAdapterField = value; + set + { + this._cmdletAdapterField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassName { - get { - return this.classNameField; + public string ClassName + { + get + { + return this._classNameField; } - set { - this.classNameField = value; + set + { + this._classNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassVersion { - get { - return this.classVersionField; + public string ClassVersion + { + get + { + return this._classVersionField; } - set { - this.classVersionField = value; + set + { + this._classVersionField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + set + { + this._getCmdletParametersField = value; } } - + /// - public GetCmdletMetadata GetCmdlet { - get { - return this.getCmdletField; + public GetCmdletMetadata GetCmdlet + { + get + { + return this._getCmdletField; } - set { - this.getCmdletField = value; + set + { + this._getCmdletField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("Cmdlet")] - public InstanceCmdletMetadata[] Cmdlet { - get { - return this.cmdletField; + public InstanceCmdletMetadata[] Cmdlet + { + get + { + return this._cmdletField; } - set { - this.cmdletField = value; + set + { + this._cmdletField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)] + public PropertyMetadata[] QueryableProperties + { + get + { + return this._queryablePropertiesField; } - set { - this.queryablePropertiesField = value; + set + { + this._queryablePropertiesField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)] - public Association[] QueryableAssociations { - get { - return this.queryableAssociationsField; + [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] + public Association[] QueryableAssociations + { + get + { + return this._queryableAssociationsField; } - set { - this.queryableAssociationsField = value; + set + { + this._queryableAssociationsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable=false)] - public QueryOption[] QueryOptions { - get { - return this.queryOptionsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)] + public QueryOption[] QueryOptions + { + get + { + return this._queryOptionsField; } - set { - this.queryOptionsField = value; + set + { + this._queryOptionsField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet { - get { - return this.defaultCmdletParameterSetField; + public string DefaultCmdletParameterSet + { + get + { + return this._defaultCmdletParameterSetField; } - set { - this.defaultCmdletParameterSetField = value; + set + { + this._defaultCmdletParameterSetField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + 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; + public PropertyQuery[] Items + { + get + { + return this._itemsField; } - set { - this.itemsField = value; + set + { + this._itemsField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] [System.Xml.Serialization.XmlIgnoreAttribute()] - public ItemsChoiceType[] ItemsElementName { - get { - return this.itemsElementNameField; + public ItemsChoiceType[] ItemsElementName + { + get + { + return this._itemsElementNameField; } - set { - this.itemsElementNameField = value; + set + { + this._itemsElementNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PropertyName { - get { - return this.propertyNameField; + public string PropertyName + { + get + { + return this._propertyNameField; } - set { - this.propertyNameField = value; + set + { + this._propertyNameField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public string PSType + { + get + { + return this._pSTypeField; } - set { - this.pSTypeField = value; + set + { + this._pSTypeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ETSType { - get { - return this.eTSTypeField; + public string ETSType + { + get + { + return this._eTSTypeField; } - set { - this.eTSTypeField = value; + set + { + this._eTSTypeField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public AssociationAssociatedInstance AssociatedInstance + { + get + { + return this._associatedInstanceField; } - set { - this.associatedInstanceField = value; + set + { + this._associatedInstanceField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute("Association")] - public string Association1 { - get { - return this.association1Field; + public string Association1 + { + get + { + return this._association1Field; } - set { - this.association1Field = value; + set + { + this._association1Field = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string SourceRole { - get { - return this.sourceRoleField; + public string SourceRole + { + get + { + return this._sourceRoleField; } - set { - this.sourceRoleField = value; + set + { + this._sourceRoleField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ResultRole { - get { - return this.resultRoleField; + public string ResultRole + { + get + { + return this._resultRoleField; } - set { - this.resultRoleField = value; + set + { + this._resultRoleField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata { - get { - return this.cmdletParameterMetadataField; + public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public bool ErrorOnNoMatch + { + get + { + return this._errorOnNoMatchField; } - set { - this.errorOnNoMatchField = value; + set + { + this._errorOnNoMatchField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ErrorOnNoMatchSpecified { - get { - return this.errorOnNoMatchFieldSpecified; + public bool ErrorOnNoMatchSpecified + { + get + { + return this._errorOnNoMatchFieldSpecified; } - set { - this.errorOnNoMatchFieldSpecified = value; + set + { + this._errorOnNoMatchFieldSpecified = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public bool ValueFromPipeline + { + get + { + return this._valueFromPipelineField; } - set { - this.valueFromPipelineField = value; + set + { + this._valueFromPipelineField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified { - get { - return this.valueFromPipelineFieldSpecified; + public bool ValueFromPipelineSpecified + { + get + { + return this._valueFromPipelineFieldSpecified; } - set { - this.valueFromPipelineFieldSpecified = value; + set + { + this._valueFromPipelineFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName { - get { - return this.valueFromPipelineByPropertyNameField; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + set + { + this._valueFromPipelineByPropertyNameFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] CmdletParameterSets { - get { - return this.cmdletParameterSetsField; + public string[] CmdletParameterSets + { + get + { + return this._cmdletParameterSetsField; } - set { - this.cmdletParameterSetsField = value; + set + { + this._cmdletParameterSetsField = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] @@ -570,1156 +680,1406 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public object AllowEmptyCollection + { + get + { + return this._allowEmptyCollectionField; } - set { - this.allowEmptyCollectionField = value; + set + { + this._allowEmptyCollectionField = value; } } - + /// - public object AllowEmptyString { - get { - return this.allowEmptyStringField; + public object AllowEmptyString + { + get + { + return this._allowEmptyStringField; } - set { - this.allowEmptyStringField = value; + set + { + this._allowEmptyStringField = value; } } - + /// - public object AllowNull { - get { - return this.allowNullField; + public object AllowNull + { + get + { + return this._allowNullField; } - set { - this.allowNullField = value; + set + { + this._allowNullField = value; } } - + /// - public object ValidateNotNull { - get { - return this.validateNotNullField; + public object ValidateNotNull + { + get + { + return this._validateNotNullField; } - set { - this.validateNotNullField = value; + set + { + this._validateNotNullField = value; } } - + /// - public object ValidateNotNullOrEmpty { - get { - return this.validateNotNullOrEmptyField; + public object ValidateNotNullOrEmpty + { + get + { + return this._validateNotNullOrEmptyField; } - set { - this.validateNotNullOrEmptyField = value; + set + { + this._validateNotNullOrEmptyField = value; } } - + /// - public CmdletParameterMetadataValidateCount ValidateCount { - get { - return this.validateCountField; + public CmdletParameterMetadataValidateCount ValidateCount + { + get + { + return this._validateCountField; } - set { - this.validateCountField = value; + set + { + this._validateCountField = value; } } - + /// - public CmdletParameterMetadataValidateLength ValidateLength { - get { - return this.validateLengthField; + public CmdletParameterMetadataValidateLength ValidateLength + { + get + { + return this._validateLengthField; } - set { - this.validateLengthField = value; + set + { + this._validateLengthField = value; } } - + /// - public CmdletParameterMetadataValidateRange ValidateRange { - get { - return this.validateRangeField; + public CmdletParameterMetadataValidateRange ValidateRange + { + get + { + return this._validateRangeField; } - set { - this.validateRangeField = value; + set + { + this._validateRangeField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable=false)] - public string[] ValidateSet { - get { - return this.validateSetField; + [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)] + public string[] ValidateSet + { + get + { + return this._validateSetField; } - set { - this.validateSetField = value; + set + { + this._validateSetField = value; } } - + /// - public ObsoleteAttributeMetadata Obsolete { - get { - return this.obsoleteField; + public ObsoleteAttributeMetadata Obsolete + { + get + { + return this._obsoleteField; } - set { - this.obsoleteField = value; + set + { + this._obsoleteField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool IsMandatory { - get { - return this.isMandatoryField; + public bool IsMandatory + { + get + { + return this._isMandatoryField; } - set { - this.isMandatoryField = value; + set + { + this._isMandatoryField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool IsMandatorySpecified { - get { - return this.isMandatoryFieldSpecified; + public bool IsMandatorySpecified + { + get + { + return this._isMandatoryFieldSpecified; } - set { - this.isMandatoryFieldSpecified = value; + set + { + this._isMandatoryFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases { - get { - return this.aliasesField; + public string[] Aliases + { + get + { + return this._aliasesField; } - set { - this.aliasesField = value; + set + { + this._aliasesField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName { - get { - return this.pSNameField; + public string PSName + { + get + { + return this._pSNameField; } - set { - this.pSNameField = value; + set + { + this._pSNameField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Position { - get { - return this.positionField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Position + { + get + { + return this._positionField; } - set { - this.positionField = value; + set + { + this._positionField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + set + { + this._maxField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + set + { + this._maxField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="integer")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + set + { + this._maxField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ObsoleteAttributeMetadata { - - private string messageField; - + [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; + public string Message + { + get + { + return this._messageField; } - set { - this.messageField = value; + set + { + this._messageField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + set + { + this._valueFromPipelineByPropertyNameFieldSpecified = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public bool ValueFromPipeline + { + get + { + return this._valueFromPipelineField; } - set { - this.valueFromPipelineField = value; + set + { + this._valueFromPipelineField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified { - get { - return this.valueFromPipelineFieldSpecified; + public bool ValueFromPipelineSpecified + { + get + { + return this._valueFromPipelineFieldSpecified; } - set { - this.valueFromPipelineFieldSpecified = value; + set + { + this._valueFromPipelineFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName { - get { - return this.valueFromPipelineByPropertyNameField; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + set + { + this._valueFromPipelineByPropertyNameFieldSpecified = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata { - get { - return this.cmdletParameterMetadataField; + public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string OptionName { - get { - return this.optionNameField; + public string OptionName + { + get + { + return this._optionNameField; } - set { - this.optionNameField = value; + set + { + this._optionNameField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class GetCmdletMetadata { - - private CommonCmdletMetadata cmdletMetadataField; - - private GetCmdletParameters getCmdletParametersField; - + [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; + public CommonCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// - public GetCmdletParameters GetCmdletParameters { - get { - return this.getCmdletParametersField; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + set + { + this._getCmdletParametersField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public ObsoleteAttributeMetadata Obsolete + { + get + { + return this._obsoleteField; } - set { - this.obsoleteField = value; + set + { + this._obsoleteField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string Verb { - get { - return this.verbField; + public string Verb + { + get + { + return this._verbField; } - set { - this.verbField = value; + set + { + this._verbField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string Noun { - get { - return this.nounField; + public string Noun + { + get + { + return this._nounField; } - set { - this.nounField = value; + set + { + this._nounField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases { - get { - return this.aliasesField; + public string[] Aliases + { + get + { + return this._aliasesField; } - set { - this.aliasesField = value; + set + { + this._aliasesField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public ConfirmImpact ConfirmImpact { - get { - return this.confirmImpactField; + public ConfirmImpact ConfirmImpact + { + get + { + return this._confirmImpactField; } - set { - this.confirmImpactField = value; + set + { + this._confirmImpactField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ConfirmImpactSpecified { - get { - return this.confirmImpactFieldSpecified; + public bool ConfirmImpactSpecified + { + get + { + return this._confirmImpactFieldSpecified; } - set { - this.confirmImpactFieldSpecified = value; + set + { + this._confirmImpactFieldSpecified = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")] - public string HelpUri { - get { - return this.helpUriField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")] + public string HelpUri + { + get + { + return this._helpUriField; } - set { - this.helpUriField = value; + set + { + this._helpUriField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - public enum ConfirmImpact { - + [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.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticCmdletMetadata { - - private StaticCmdletMetadataCmdletMetadata cmdletMetadataField; - - private StaticMethodMetadata[] methodField; - + [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; + public StaticCmdletMetadataCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("Method")] - public StaticMethodMetadata[] Method { - get { - return this.methodField; + public StaticMethodMetadata[] Method + { + get + { + return this._methodField; } - set { - this.methodField = value; + set + { + this._methodField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public string DefaultCmdletParameterSet + { + get + { + return this._defaultCmdletParameterSetField; } - set { - this.defaultCmdletParameterSetField = value; + set + { + this._defaultCmdletParameterSetField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + public StaticMethodParameterMetadata[] Parameters + { + get + { + return this._parametersField; } - set { - this.parametersField = value; + set + { + this._parametersField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletParameterSet { - get { - return this.cmdletParameterSetField; + public string CmdletParameterSet + { + get + { + return this._cmdletParameterSetField; } - set { - this.cmdletParameterSetField = value; + set + { + this._cmdletParameterSetField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + set + { + this._cmdletOutputMetadataField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletOutputMetadata { - - private object errorCodeField; - - private string pSNameField; - + [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; + public object ErrorCode + { + get + { + return this._errorCodeField; } - set { - this.errorCodeField = value; + set + { + this._errorCodeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName { - get { - return this.pSNameField; + public string PSName + { + get + { + return this._pSNameField; } - set { - this.pSNameField = value; + 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.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ParameterName { - get { - return this.parameterNameField; + public string ParameterName + { + get + { + return this._parameterNameField; } - set { - this.parameterNameField = value; + set + { + this._parameterNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultValue { - get { - return this.defaultValueField; + public string DefaultValue + { + get + { + return this._defaultValueField; } - set { - this.defaultValueField = value; + set + { + this._defaultValueField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + 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.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodMetadata { - - private CommonMethodMetadataReturnValue returnValueField; - - private string methodNameField; - + [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; + public CommonMethodMetadataReturnValue ReturnValue + { + get + { + return this._returnValueField; } - set { - this.returnValueField = value; + set + { + this._returnValueField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string MethodName { - get { - return this.methodNameField; + public string MethodName + { + get + { + return this._methodNameField; } - set { - this.methodNameField = value; + set + { + this._methodNameField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + set + { + this._cmdletOutputMetadataField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + public InstanceMethodParameterMetadata[] Parameters + { + get + { + return this._parametersField; } - set { - this.parametersField = value; + set + { + this._parametersField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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; - + [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; + public CommonCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// - public InstanceMethodMetadata Method { - get { - return this.methodField; + public InstanceMethodMetadata Method + { + get + { + return this._methodField; } - set { - this.methodField = value; + set + { + this._methodField = value; } } - + /// - public GetCmdletParameters GetCmdletParameters { - get { - return this.getCmdletParametersField; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + set + { + this._getCmdletParametersField = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class PropertyQuery { - - private CmdletParameterMetadataForGetCmdletFilteringParameter cmdletParameterMetadataField; - + [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; + public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public bool AllowGlobbing + { + get + { + return this._allowGlobbingField; } - set { - this.allowGlobbingField = value; + set + { + this._allowGlobbingField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool AllowGlobbingSpecified { - get { - return this.allowGlobbingFieldSpecified; + public bool AllowGlobbingSpecified + { + get + { + return this._allowGlobbingFieldSpecified; } - set { - this.allowGlobbingFieldSpecified = value; + set + { + this._allowGlobbingFieldSpecified = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema=false)] - public enum ItemsChoiceType { - + [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.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public string Name + { + get + { + return this._nameField; } - set { - this.nameField = value; + set + { + this._nameField = value; } } - + /// [System.Xml.Serialization.XmlTextAttribute()] - public string Value { - get { - return this.valueField; + public string Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + set + { + this._valueField = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public EnumMetadataEnumValue[] Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + set + { + this._valueField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string EnumName { - get { - return this.enumNameField; + public string EnumName + { + get + { + return this._enumNameField; } - set { - this.enumNameField = value; + set + { + this._enumNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string UnderlyingType { - get { - return this.underlyingTypeField; + public string UnderlyingType + { + get + { + return this._underlyingTypeField; } - set { - this.underlyingTypeField = value; + set + { + this._underlyingTypeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool BitwiseFlags { - get { - return this.bitwiseFlagsField; + public bool BitwiseFlags + { + get + { + return this._bitwiseFlagsField; } - set { - this.bitwiseFlagsField = value; + set + { + this._bitwiseFlagsField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool BitwiseFlagsSpecified { - get { - return this.bitwiseFlagsFieldSpecified; + public bool BitwiseFlagsSpecified + { + get + { + return this._bitwiseFlagsFieldSpecified; } - set { - this.bitwiseFlagsFieldSpecified = value; + set + { + this._bitwiseFlagsFieldSpecified = value; } } } - + /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [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.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; + public string Name + { + get + { + return this._nameField; } - set { - this.nameField = value; + set + { + this._nameField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="integer")] - public string Value { - get { - return this.valueField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + set + { + this._valueField = value; } } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index fdbae2d56..eef66f047 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -1,22 +1,11 @@ #if CORECLR -// THIS FILE IS MANUALLY CHANGED BASED ON THE GENERATED FILE -// -// The original file has been generated by admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd -// -// sgen.exe is called within 'generate.ps1' to generate the original file. The generated code cannot work in CoreCLR. -// This file is manually adjusted based on the generated file, so as to make it work in CoreCLR. -// The adjustment for this file includes: -// 1. We only need deseriliazation to import CDXML modules, so the serialization related code is removed. -// 2. The generated code uses XmlSerializationReader for most of its deseriliazation logic. This type is not in CoreCLR, -// so we need to copy the code/APIs that we depends on from .NET source code (see the Copy_From_XmlSerializationReader region below). - #if CORECLR #pragma warning disable -namespace Microsoft.PowerShell.Cmdletization.Xml { +namespace Microsoft.PowerShell.Cmdletization.Xml +{ using System; using System.Collections; @@ -42,29 +31,29 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { internal XmlSerializationReader1(XmlReader reader) { - this.r = reader; - this.d = null; + _r = reader; + _d = null; - schemaNsID = r.NameTable.Add("http://www.w3.org/2001/XMLSchema"); - schemaNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema"); - schemaNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema"); - schemaNonXsdTypesNsID = r.NameTable.Add("http://microsoft.com/wsdl/types/"); - instanceNsID = r.NameTable.Add("http://www.w3.org/2001/XMLSchema-instance"); - instanceNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema-instance"); - instanceNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema-instance"); - soapNsID = r.NameTable.Add("http://schemas.xmlsoap.org/soap/encoding/"); - soap12NsID = r.NameTable.Add("http://www.w3.org/2003/05/soap-encoding"); - schemaID = r.NameTable.Add("schema"); - wsdlNsID = r.NameTable.Add("http://schemas.xmlsoap.org/wsdl/"); - wsdlArrayTypeID = r.NameTable.Add("arrayType"); - nullID = r.NameTable.Add("null"); - nilID = r.NameTable.Add("nil"); - typeID = r.NameTable.Add("type"); - arrayTypeID = r.NameTable.Add("arrayType"); - itemTypeID = r.NameTable.Add("itemType"); - arraySizeID = r.NameTable.Add("arraySize"); - arrayID = r.NameTable.Add("Array"); - urTypeID = r.NameTable.Add("anyType"); + _schemaNsID = _r.NameTable.Add("http://www.w3.org/2001/XMLSchema"); + _schemaNs2000ID = _r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema"); + _schemaNs1999ID = _r.NameTable.Add("http://www.w3.org/1999/XMLSchema"); + _schemaNonXsdTypesNsID = _r.NameTable.Add("http://microsoft.com/wsdl/types/"); + _instanceNsID = _r.NameTable.Add("http://www.w3.org/2001/XMLSchema-instance"); + _instanceNs2000ID = _r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema-instance"); + _instanceNs1999ID = _r.NameTable.Add("http://www.w3.org/1999/XMLSchema-instance"); + _soapNsID = _r.NameTable.Add("http://schemas.xmlsoap.org/soap/encoding/"); + _soap12NsID = _r.NameTable.Add("http://www.w3.org/2003/05/soap-encoding"); + _schemaID = _r.NameTable.Add("schema"); + _wsdlNsID = _r.NameTable.Add("http://schemas.xmlsoap.org/wsdl/"); + _wsdlArrayTypeID = _r.NameTable.Add("arrayType"); + _nullID = _r.NameTable.Add("null"); + _nilID = _r.NameTable.Add("nil"); + _typeID = _r.NameTable.Add("type"); + _arrayTypeID = _r.NameTable.Add("arrayType"); + _itemTypeID = _r.NameTable.Add("itemType"); + _arraySizeID = _r.NameTable.Add("arraySize"); + _arrayID = _r.NameTable.Add("Array"); + _urTypeID = _r.NameTable.Add("anyType"); InitIDs(); } @@ -73,86 +62,86 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { #region "Field Definition" - XmlReader r; - XmlDocument d; + XmlReader _r; + XmlDocument _d; - bool soap12; - bool isReturnValue; - bool decodeName = true; + bool _soap12; + bool _isReturnValue; + bool _decodeName = true; - string schemaNsID; - string schemaNs1999ID; - string schemaNs2000ID; - string schemaNonXsdTypesNsID; - string instanceNsID; - string instanceNs2000ID; - string instanceNs1999ID; - string soapNsID; - string soap12NsID; - string schemaID; - string wsdlNsID; - string wsdlArrayTypeID; - string nullID; - string nilID; - string typeID; - string arrayTypeID; - string itemTypeID; - string arraySizeID; - string arrayID; - string urTypeID; - string stringID; - string intID; - string booleanID; - string shortID; - string longID; - string floatID; - string doubleID; - string decimalID; - string dateTimeID; - string qnameID; - string dateID; - string timeID; - string hexBinaryID; - string base64BinaryID; - string base64ID; - string unsignedByteID; - string byteID; - string unsignedShortID; - string unsignedIntID; - string unsignedLongID; - string oldDecimalID; - string oldTimeInstantID; + string _schemaNsID; + string _schemaNs1999ID; + string _schemaNs2000ID; + string _schemaNonXsdTypesNsID; + string _instanceNsID; + string _instanceNs2000ID; + string _instanceNs1999ID; + string _soapNsID; + string _soap12NsID; + string _schemaID; + string _wsdlNsID; + string _wsdlArrayTypeID; + string _nullID; + string _nilID; + string _typeID; + string _arrayTypeID; + string _itemTypeID; + string _arraySizeID; + string _arrayID; + string _urTypeID; + string _stringID; + string _intID; + string _booleanID; + string _shortID; + string _longID; + string _floatID; + string _doubleID; + string _decimalID; + string _dateTimeID; + string _qnameID; + string _dateID; + string _timeID; + string _hexBinaryID; + string _base64BinaryID; + string _base64ID; + string _unsignedByteID; + string _byteID; + string _unsignedShortID; + string _unsignedIntID; + string _unsignedLongID; + string _oldDecimalID; + string _oldTimeInstantID; - string anyURIID; - string durationID; - string ENTITYID; - string ENTITIESID; - string gDayID; - string gMonthID; - string gMonthDayID; - string gYearID; - string gYearMonthID; - string IDID; - string IDREFID; - string IDREFSID; - string integerID; - string languageID; - string NameID; - string NCNameID; - string NMTOKENID; - string NMTOKENSID; - string negativeIntegerID; - string nonPositiveIntegerID; - string nonNegativeIntegerID; - string normalizedStringID; - string NOTATIONID; - string positiveIntegerID; - string tokenID; + string _anyURIID; + string _durationID; + string _ENTITYID; + string _ENTITIESID; + string _gDayID; + string _gMonthID; + string _gMonthDayID; + string _gYearID; + string _gYearMonthID; + string _IDID; + string _IDREFID; + string _IDREFSID; + string _integerID; + string _languageID; + string _nameID; + string _NCNameID; + string _NMTOKENID; + string _NMTOKENSID; + string _negativeIntegerID; + string _nonPositiveIntegerID; + string _nonNegativeIntegerID; + string _normalizedStringID; + string _NOTATIONID; + string _positiveIntegerID; + string _tokenID; - string charID; - string guidID; + string _charID; + string _guidID; - static object PrimitiveTypedObject = new object(); + static object s_primitiveTypedObject = new object(); #endregion "Field Definition" @@ -163,7 +152,7 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { { get { - return r; + return _r; } } @@ -186,11 +175,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { { get { - return decodeName; + return _decodeName; } set { - decodeName = value; + _decodeName = value; } } @@ -198,11 +187,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { { get { - if (d == null) + if (_d == null) { - d = new XmlDocument(r.NameTable); + _d = new XmlDocument(_r.NameTable); } - return d; + return _d; } } @@ -213,61 +202,61 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { internal void InitPrimitiveIDs() { - if (tokenID != null) return; + if (_tokenID != null) return; - object ns = r.NameTable.Add("http://www.w3.org/2001/XMLSchema"); - object ns2 = r.NameTable.Add("http://microsoft.com/wsdl/types/"); + object ns = _r.NameTable.Add("http://www.w3.org/2001/XMLSchema"); + object ns2 = _r.NameTable.Add("http://microsoft.com/wsdl/types/"); - stringID = r.NameTable.Add("string"); - intID = r.NameTable.Add("int"); - booleanID = r.NameTable.Add("boolean"); - shortID = r.NameTable.Add("short"); - longID = r.NameTable.Add("long"); - floatID = r.NameTable.Add("float"); - doubleID = r.NameTable.Add("double"); - decimalID = r.NameTable.Add("decimal"); - dateTimeID = r.NameTable.Add("dateTime"); - qnameID = r.NameTable.Add("QName"); - dateID = r.NameTable.Add("date"); - timeID = r.NameTable.Add("time"); - hexBinaryID = r.NameTable.Add("hexBinary"); - base64BinaryID = r.NameTable.Add("base64Binary"); - unsignedByteID = r.NameTable.Add("unsignedByte"); - byteID = r.NameTable.Add("byte"); - unsignedShortID = r.NameTable.Add("unsignedShort"); - unsignedIntID = r.NameTable.Add("unsignedInt"); - unsignedLongID = r.NameTable.Add("unsignedLong"); - oldDecimalID = r.NameTable.Add("decimal"); - oldTimeInstantID = r.NameTable.Add("timeInstant"); - charID = r.NameTable.Add("char"); - guidID = r.NameTable.Add("guid"); - base64ID = r.NameTable.Add("base64"); + _stringID = _r.NameTable.Add("string"); + _intID = _r.NameTable.Add("int"); + _booleanID = _r.NameTable.Add("boolean"); + _shortID = _r.NameTable.Add("short"); + _longID = _r.NameTable.Add("long"); + _floatID = _r.NameTable.Add("float"); + _doubleID = _r.NameTable.Add("double"); + _decimalID = _r.NameTable.Add("decimal"); + _dateTimeID = _r.NameTable.Add("dateTime"); + _qnameID = _r.NameTable.Add("QName"); + _dateID = _r.NameTable.Add("date"); + _timeID = _r.NameTable.Add("time"); + _hexBinaryID = _r.NameTable.Add("hexBinary"); + _base64BinaryID = _r.NameTable.Add("base64Binary"); + _unsignedByteID = _r.NameTable.Add("unsignedByte"); + _byteID = _r.NameTable.Add("byte"); + _unsignedShortID = _r.NameTable.Add("unsignedShort"); + _unsignedIntID = _r.NameTable.Add("unsignedInt"); + _unsignedLongID = _r.NameTable.Add("unsignedLong"); + _oldDecimalID = _r.NameTable.Add("decimal"); + _oldTimeInstantID = _r.NameTable.Add("timeInstant"); + _charID = _r.NameTable.Add("char"); + _guidID = _r.NameTable.Add("guid"); + _base64ID = _r.NameTable.Add("base64"); - anyURIID = r.NameTable.Add("anyURI"); - durationID = r.NameTable.Add("duration"); - ENTITYID = r.NameTable.Add("ENTITY"); - ENTITIESID = r.NameTable.Add("ENTITIES"); - gDayID = r.NameTable.Add("gDay"); - gMonthID = r.NameTable.Add("gMonth"); - gMonthDayID = r.NameTable.Add("gMonthDay"); - gYearID = r.NameTable.Add("gYear"); - gYearMonthID = r.NameTable.Add("gYearMonth"); - IDID = r.NameTable.Add("ID"); - IDREFID = r.NameTable.Add("IDREF"); - IDREFSID = r.NameTable.Add("IDREFS"); - integerID = r.NameTable.Add("integer"); - languageID = r.NameTable.Add("language"); - NameID = r.NameTable.Add("Name"); - NCNameID = r.NameTable.Add("NCName"); - NMTOKENID = r.NameTable.Add("NMTOKEN"); - NMTOKENSID = r.NameTable.Add("NMTOKENS"); - negativeIntegerID = r.NameTable.Add("negativeInteger"); - nonNegativeIntegerID = r.NameTable.Add("nonNegativeInteger"); - nonPositiveIntegerID = r.NameTable.Add("nonPositiveInteger"); - normalizedStringID = r.NameTable.Add("normalizedString"); - NOTATIONID = r.NameTable.Add("NOTATION"); - positiveIntegerID = r.NameTable.Add("positiveInteger"); - tokenID = r.NameTable.Add("token"); + _anyURIID = _r.NameTable.Add("anyURI"); + _durationID = _r.NameTable.Add("duration"); + _ENTITYID = _r.NameTable.Add("ENTITY"); + _ENTITIESID = _r.NameTable.Add("ENTITIES"); + _gDayID = _r.NameTable.Add("gDay"); + _gMonthID = _r.NameTable.Add("gMonth"); + _gMonthDayID = _r.NameTable.Add("gMonthDay"); + _gYearID = _r.NameTable.Add("gYear"); + _gYearMonthID = _r.NameTable.Add("gYearMonth"); + _IDID = _r.NameTable.Add("ID"); + _IDREFID = _r.NameTable.Add("IDREF"); + _IDREFSID = _r.NameTable.Add("IDREFS"); + _integerID = _r.NameTable.Add("integer"); + _languageID = _r.NameTable.Add("language"); + _nameID = _r.NameTable.Add("Name"); + _NCNameID = _r.NameTable.Add("NCName"); + _NMTOKENID = _r.NameTable.Add("NMTOKEN"); + _NMTOKENSID = _r.NameTable.Add("NMTOKENS"); + _negativeIntegerID = _r.NameTable.Add("negativeInteger"); + _nonNegativeIntegerID = _r.NameTable.Add("nonNegativeInteger"); + _nonPositiveIntegerID = _r.NameTable.Add("nonPositiveInteger"); + _normalizedStringID = _r.NameTable.Add("normalizedString"); + _NOTATIONID = _r.NameTable.Add("NOTATION"); + _positiveIntegerID = _r.NameTable.Add("positiveInteger"); + _tokenID = _r.NameTable.Add("token"); } protected void CheckReaderCount(ref int whileIterations, ref int readerCount) @@ -276,14 +265,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { private string CurrentTag() { - switch (r.NodeType) + switch (_r.NodeType) { case XmlNodeType.Element: - return "<" + r.LocalName + " xmlns='" + r.NamespaceURI + "'>"; + return "<" + _r.LocalName + " xmlns='" + _r.NamespaceURI + "'>"; case XmlNodeType.EndElement: return ">"; case XmlNodeType.Text: - return r.Value; + return _r.Value; case XmlNodeType.CDATA: return "CDATA"; case XmlNodeType.Comment: @@ -353,27 +342,27 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { protected void UnknownNode(object o, string qnames) { - if (r.NodeType == XmlNodeType.None || r.NodeType == XmlNodeType.Whitespace) + if (_r.NodeType == XmlNodeType.None || _r.NodeType == XmlNodeType.Whitespace) { - r.Read(); + _r.Read(); return; } - if (r.NodeType == XmlNodeType.EndElement) + if (_r.NodeType == XmlNodeType.EndElement) return; - - if (r.NodeType == XmlNodeType.Attribute) + + if (_r.NodeType == XmlNodeType.Attribute) { return; } - else if (r.NodeType == XmlNodeType.Element) + else if (_r.NodeType == XmlNodeType.Element) { - r.Skip(); + _r.Skip(); return; } else { - UnknownNode(Document.ReadNode(r), o, qnames); + UnknownNode(Document.ReadNode(_r), o, qnames); } } @@ -388,9 +377,9 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { protected void ReadEndElement() { - while (r.NodeType == XmlNodeType.Whitespace) r.Skip(); - if (r.NodeType == XmlNodeType.None) r.Skip(); - else r.ReadEndElement(); + while (_r.NodeType == XmlNodeType.Whitespace) _r.Skip(); + if (_r.NodeType == XmlNodeType.None) _r.Skip(); + else _r.ReadEndElement(); } protected string ReadString(string value, bool trim) @@ -403,7 +392,7 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { // XmlNodeType.SignificantWhitespace // In this case, we use 'ReadContentAsString()' to read the text content at the current position. // We cannot use 'ReadElementContentAsString()'. It will fail because the XmlReader is not positioned on an Element start node. - string str = r.ReadContentAsString(); + string str = _r.ReadContentAsString(); if (str != null && trim) str = str.Trim(); if (value == null || value.Length == 0) @@ -429,17 +418,17 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } if (prefix == null || prefix.Length == 0) { - return new XmlQualifiedName(r.NameTable.Add(value), r.LookupNamespace(String.Empty)); + return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(String.Empty)); } else { - string ns = r.LookupNamespace(prefix); + string ns = _r.LookupNamespace(prefix); if (ns == null) { // Namespace prefix '{0}' is not defined. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUndefinedAlias. Prefix: {0}", prefix)); } - return new XmlQualifiedName(r.NameTable.Add(localName), ns); + return new XmlQualifiedName(_r.NameTable.Add(localName), ns); } } @@ -451,13 +440,13 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { /// protected XmlQualifiedName GetXsiType() { - string type = r.GetAttribute(typeID, instanceNsID); + string type = _r.GetAttribute(_typeID, _instanceNsID); if (type == null) { - type = r.GetAttribute(typeID, instanceNs2000ID); + type = _r.GetAttribute(_typeID, _instanceNs2000ID); if (type == null) { - type = r.GetAttribute(typeID, instanceNs1999ID); + type = _r.GetAttribute(_typeID, _instanceNs1999ID); if (type == null) return null; } @@ -467,14 +456,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { protected bool GetNullAttr() { - string isNull = r.GetAttribute(nilID, instanceNsID); + string isNull = _r.GetAttribute(_nilID, _instanceNsID); if (isNull == null) - isNull = r.GetAttribute(nullID, instanceNsID); + isNull = _r.GetAttribute(_nullID, _instanceNsID); if (isNull == null) { - isNull = r.GetAttribute(nullID, instanceNs2000ID); + isNull = _r.GetAttribute(_nullID, _instanceNs2000ID); if (isNull == null) - isNull = r.GetAttribute(nullID, instanceNs1999ID); + isNull = _r.GetAttribute(_nullID, _instanceNs1999ID); } if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false; return true; @@ -483,15 +472,15 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { protected bool ReadNull() { if (!GetNullAttr()) return false; - if (r.IsEmptyElement) + if (_r.IsEmptyElement) { - r.Skip(); + _r.Skip(); return true; } - r.ReadStartElement(); + _r.ReadStartElement(); int whileIterations = 0; int readerCount = ReaderCount; - while (r.NodeType != XmlNodeType.EndElement) + while (_r.NodeType != XmlNodeType.EndElement) { UnknownNode(null); CheckReaderCount(ref whileIterations, ref readerCount); @@ -502,12 +491,12 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { bool IsPrimitiveNamespace(string ns) { - return (object)ns == (object)schemaNsID || - (object)ns == (object)schemaNonXsdTypesNsID || - (object)ns == (object)soapNsID || - (object)ns == (object)soap12NsID || - (object)ns == (object)schemaNs2000ID || - (object)ns == (object)schemaNs1999ID; + return (object)ns == (object)_schemaNsID || + (object)ns == (object)_schemaNonXsdTypesNsID || + (object)ns == (object)_soapNsID || + (object)ns == (object)_soap12NsID || + (object)ns == (object)_schemaNs2000ID || + (object)ns == (object)_schemaNs1999ID; } protected object ReadTypedPrimitive(XmlQualifiedName type) @@ -519,8 +508,8 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { // ValidateNotNull, AllowNull, AllEmptyString, ErrorCode and etc. e.g. , . // We don't actually use the value, only check if the value is null, so as to decide whether the tag element // is specified in CDXML file. - if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)urTypeID) - return PrimitiveTypedObject; + if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) + return s_primitiveTypedObject; // CDXML files are all under the namespace 'http://schemas.microsoft.com/cmdlets-over-objects/2009/11', so // they will never fall into the following namespaces: @@ -548,685 +537,883 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { #endregion Copy_From_XmlSerializationReader - public object Read50_PowerShellMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); } return (object)o; } - public object Read51_ClassMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadata"); } return (object)o; } - public object Read52_ClassMetadataInstanceCmdlets() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadataInstanceCmdlets"); } return (object)o; } - public object Read53_GetCmdletParameters() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":GetCmdletParameters"); } return (object)o; } - public object Read54_PropertyMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":PropertyMetadata"); } return (object)o; } - public object Read55_TypeMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":TypeMetadata"); } return (object)o; } - public object Read56_Association() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":Association"); } return (object)o; } - public object Read57_AssociationAssociatedInstance() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":AssociationAssociatedInstance"); } return (object)o; } - public object Read58_CmdletParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadata"); } return (object)o; } - public object Read59_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); } return (object)o; } - public object Read60_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); } return (object)o; } - public object Read61_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateCount"); } return (object)o; } - public object Read62_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateLength"); } return (object)o; } - public object Read63_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateRange"); } return (object)o; } - public object Read64_ObsoleteAttributeMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ObsoleteAttributeMetadata"); } return (object)o; } - public object Read65_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); } return (object)o; } - public object Read66_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); } return (object)o; } - public object Read67_QueryOption() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":QueryOption"); } return (object)o; } - public object Read68_GetCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":GetCmdletMetadata"); } return (object)o; } - public object Read69_CommonCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonCmdletMetadata"); } return (object)o; } - public object Read70_ConfirmImpact() { + 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)) { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { + if (((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) + { { o = Read20_ConfirmImpact(Reader.ReadElementContentAsString()); } } - else { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ConfirmImpact"); } return (object)o; } - public object Read71_StaticCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticCmdletMetadata"); } return (object)o; } - public object Read72_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); } return (object)o; } - public object Read73_CommonMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodMetadata"); } return (object)o; } - public object Read74_StaticMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticMethodMetadata"); } return (object)o; } - public object Read75_CommonMethodParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodParameterMetadata"); } return (object)o; } - public object Read76_StaticMethodParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticMethodParameterMetadata"); } return (object)o; } - public object Read77_CmdletOutputMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletOutputMetadata"); } return (object)o; } - public object Read78_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceMethodParameterMetadata"); } return (object)o; } - public object Read79_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodMetadataReturnValue"); } return (object)o; } - public object Read80_InstanceMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceMethodMetadata"); } return (object)o; } - public object Read81_InstanceCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceCmdletMetadata"); } return (object)o; } - public object Read82_PropertyQuery() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":PropertyQuery"); } return (object)o; } - public object Read83_WildcardablePropertyQuery() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":WildcardablePropertyQuery"); } return (object)o; } - public object Read84_ItemsChoiceType() { + 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)) { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { + if (((object)Reader.LocalName == (object)_id37_ItemsChoiceType && (object)Reader.NamespaceURI == (object)_id4_Item)) + { { o = Read3_ItemsChoiceType(Reader.ReadElementContentAsString()); } } - else { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ItemsChoiceType"); } return (object)o; } - public object Read85_ClassMetadataData() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadataData"); } return (object)o; } - public object Read86_EnumMetadataEnum() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":EnumMetadataEnum"); } return (object)o; } - public object Read87_EnumMetadataEnumValue() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":EnumMetadataEnumValue"); } return (object)o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read49_EnumMetadataEnumValue(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name, :Value"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1234,11 +1421,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1248,15 +1438,18 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read48_EnumMetadataEnum(bool isNullable, bool checkType) { + 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 (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; @@ -1264,26 +1457,32 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + 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; @@ -1292,16 +1491,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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); + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } } - else { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } Reader.MoveToContent(); @@ -1312,35 +1516,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read37_EnumMetadataEnumValue(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name, :Value"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1348,11 +1560,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1362,31 +1577,38 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read47_ClassMetadataData(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1394,19 +1616,23 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Reader.MoveToContent(); int whileIterations3 = 0; int readerCount3 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - 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) { + 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 { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1416,8 +1642,10 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType Read3_ItemsChoiceType(string s) { - switch (s) { + 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; @@ -1426,32 +1654,39 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } } - global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery Read13_WildcardablePropertyQuery(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":AllowGlobbing"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1459,17 +1694,22 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } } - else { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } Reader.MoveToContent(); @@ -1479,15 +1719,18 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter Read12_Item(bool isNullable, bool checkType) { + 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 (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; @@ -1499,55 +1742,68 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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]; + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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]; + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + 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); @@ -1557,83 +1813,105 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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()) { + 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)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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)) { + 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.ReadElementContentAsString(); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations6, ref readerCount6); } - ReadEndElement(); + 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)) { + 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 { + 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 { + 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(); @@ -1645,31 +1923,38 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata Read7_ObsoleteAttributeMetadata(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Message"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1677,11 +1962,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1691,35 +1979,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read6_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1727,11 +2023,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1741,35 +2040,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read5_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1777,11 +2084,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1791,35 +2101,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read4_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -1827,11 +2145,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -1841,403 +2162,490 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::System.Object Read1_Object(bool isNullable, bool checkType) { + 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 (checkType) + { + if (isNull) + { if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } - if (xsiType == 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) { + 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.ReadElementContentAsString())); ReadEndElement(); return e; } - else if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id69_ArrayOfString && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { + 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()) { + if (!ReadNull()) + { global::System.String[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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)) { + 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.ReadElementContentAsString(); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations11, ref readerCount11); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations12, ref readerCount12); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.Association[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations13, ref readerCount13); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations14, ref readerCount14); } - ReadEndElement(); + 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)) { + 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.ReadElementContentAsString())); ReadEndElement(); return e; } - else if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id75_Item && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations15, ref readerCount15); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations16, ref readerCount16); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations17, ref readerCount17); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations18, ref readerCount18); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations19, ref readerCount19); } - ReadEndElement(); + ReadEndElement(); } a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } @@ -2245,3036 +2653,3673 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } else return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); + } + if (isNull) return null; + global::System.Object o; + o = new global::System.Object(); + bool[] paramsRead = new bool[0]; + while (Reader.MoveToNextAttribute()) + { + if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o); } - if (isNull) return null; - global::System.Object o; - o = new global::System.Object(); - bool[] paramsRead = new bool[0]; - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations20, ref readerCount20); - } - ReadEndElement(); + } + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations20, ref readerCount20); + } + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@UnderlyingType = Reader.Value; + paramsRead[2] = true; } - 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; + 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; } - 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 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 { + 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; + 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; + } - 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)) { + 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; } - 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; + 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, @""); + } + 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, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations22, ref readerCount22); + } + ReadEndElement(); + return o; + } + + 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 (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":Name"); + 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); } - } - 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, @""); - } - 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, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations22, ref readerCount22); - } - ReadEndElement(); - return o; - } - - 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 { + 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; + 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; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id87_CmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@CmdletParameterSet = Reader.Value; + paramsRead[3] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); } - 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"); - } + } + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations25, ref readerCount25); } - ReadEndElement(); + else + { + UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations25, ref readerCount25); } - o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); + ReadEndElement(); } - } - else { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); + o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); } } - else { + 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; + 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; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@DefaultValue = Reader.Value; + paramsRead[2] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o, @":ParameterName, :DefaultValue"); } - 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"); - } + } + 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 { + 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"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations26, ref readerCount26); } - ReadEndElement(); - return o; + 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; + } - 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)) { + 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; } - 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"); - } + 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"); - } + } + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations27, ref readerCount27); - } - ReadEndElement(); - return o; - } - - 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); + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); } - 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.ReadElementContentAsString(); - } - } - 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; + CheckReaderCount(ref whileIterations27, ref readerCount27); } + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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; + 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)id95_ETSType && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@ETSType = Reader.Value; + 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 (!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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations30, ref readerCount30); - } - ReadEndElement(); - return o; - } - - 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; - } - - 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; + 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 (((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; - } - - 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)); - } - } - - 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; - } - - 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.ReadElementContentAsString(); - } - } - 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; - } - - 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; - } - - 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.ReadElementContentAsString(); - } - } - 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; - } - - 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; + 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 (!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; - } - - 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; - } - - 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; - } - - 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; - } - - 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.ReadElementContentAsString(); - } - } - 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; - } - - 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; - } - - 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; + 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)id98_HelpUri && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@HelpUri = CollapseWhitespace(Reader.Value); + 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)id99_DefaultCmdletParameterSet && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@DefaultCmdletParameterSet = Reader.Value; + 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 (!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; - } - - 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; - } - - 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; - } - - 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; - } - - 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; - } - - 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; - } - - 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; - } - - 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; + 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 (!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)) { + 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)) { - o.@Version = Reader.ReadElementContentAsString(); + Reader.Skip(); } - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id116_DefaultNoun && (object) Reader.NamespaceURI == (object)id2_Item)) { + else { - o.@DefaultNoun = Reader.ReadElementContentAsString(); - } - 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"); + 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.ReadElementContentAsString(); } } - 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:AllowedValue"); } - 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); + else + { + UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } - ReadEndElement(); + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations29, ref readerCount29); } - o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); + ReadEndElement(); } - } - 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"); + o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), 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 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"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations57, ref readerCount57); - } - ReadEndElement(); - return o; - } - - 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); + { + 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"); } - 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; + CheckReaderCount(ref whileIterations28, ref readerCount28); } + o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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); - } + else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id95_ETSType && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@ETSType = Reader.Value; + paramsRead[1] = true; } - 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; + 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, @""); + } + else + { + UnknownNode((object)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; + CheckReaderCount(ref whileIterations30, ref readerCount30); } + ReadEndElement(); + return o; + } - 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)) { + 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); } - 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - 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); + 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)id68_Max && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@Max = CollapseWhitespace(Reader.Value); + 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 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations63, ref readerCount63); - } - ReadEndElement(); - return o; - } - - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations64, ref readerCount64); - } - ReadEndElement(); - return o; - } - - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations65, ref readerCount65); - } - ReadEndElement(); - return o; - } - - 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 { + 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; + 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; + } - 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)) { + 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; } - 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); + 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]; } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + 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; } - 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); + else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@HelpUri = CollapseWhitespace(Reader.Value); + paramsRead[5] = true; } - ReadEndElement(); + 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; + } - string id72_ArrayOfAssociation; - string id46_AllowGlobbing; - string id6_GetCmdletParameters; - string id25_Item; - string id62_ValidateRange; - string id118_StaticCmdlets; - string id58_ValidateNotNull; - string id17_ObsoleteAttributeMetadata; - string id49_PSName; - string id116_DefaultNoun; - string id38_ClassMetadataData; - string id114_ClassVersion; - string id66_Message; - string id65_Obsolete; - string id51_ValueFromPipeline; - string id108_MinValueQuery; - string id119_CmdletAdapterPrivateData; - string id21_GetCmdletMetadata; - string id120_GetCmdlet; - string id67_Min; - string id56_AllowEmptyString; - string id30_CmdletOutputMetadata; - string id106_RegularQuery; - string id74_Option; - string id75_Item; - string id23_ConfirmImpact; - string id117_InstanceCmdlets; - string id83_Enum; - string id40_EnumMetadataEnumValue; - string id111_QueryOptions; - string id34_InstanceCmdletMetadata; - string id60_ValidateCount; - string id45_BitwiseFlags; - string id81_Data; - string id31_Item; - string id1_PowerShellMetadata; - string id98_HelpUri; - string id91_DefaultValue; - string id4_Item; - string id32_Item; - string id43_EnumName; - string id122_Enums; - string id82_ArrayOfEnumMetadataEnum; - string id14_Item; - string id48_Aliases; - string id115_Version; - string id11_CmdletParameterMetadata; - string id70_ArrayOfPropertyMetadata; - string id9_Association; - string id102_ResultRole; - string id29_StaticMethodParameterMetadata; - string id97_Noun; - string id47_IsMandatory; - string id35_PropertyQuery; - string id54_ErrorOnNoMatch; - string id3_ClassMetadata; - string id77_Item; - string id2_Item; - string id22_CommonCmdletMetadata; - string id37_ItemsChoiceType; - string id36_WildcardablePropertyQuery; - string id113_ClassName; - string id64_AllowedValue; - string id52_Item; - string id55_AllowEmptyCollection; - string id13_Item; - string id76_Parameter; - string id19_Item; - string id105_MaxValueQuery; - string id101_SourceRole; - string id5_ClassMetadataInstanceCmdlets; - string id112_CmdletAdapter; - string id10_AssociationAssociatedInstance; - string id93_ErrorCode; - string id41_Name; - string id68_Max; - string id50_Position; - string id100_OptionName; - string id84_CmdletMetadata; - string id87_CmdletParameterSet; - string id104_PropertyName; - string id28_CommonMethodParameterMetadata; - string id107_ExcludeQuery; - string id92_Type; - string id33_InstanceMethodMetadata; - string id63_ValidateSet; - string id53_CmdletParameterSets; - string id15_Item; - string id109_QueryableProperties; - string id57_AllowNull; - string id80_ArrayOfClassMetadataData; - string id99_DefaultCmdletParameterSet; - string id20_QueryOption; - string id89_Parameters; - string id90_ParameterName; - string id61_ValidateLength; - string id78_ArrayOfStaticCmdletMetadata; - string id16_Item; - string id39_EnumMetadataEnum; - string id7_PropertyMetadata; - string id110_QueryableAssociations; - string id86_MethodName; - string id8_TypeMetadata; - string id71_Property; - string id27_StaticMethodMetadata; - string id94_PSType; - string id44_UnderlyingType; - string id103_AssociatedInstance; - string id79_Cmdlet; - string id18_Item; - string id85_Method; - string id95_ETSType; - string id26_CommonMethodMetadata; - string id88_ReturnValue; - string id69_ArrayOfString; - string id24_StaticCmdletMetadata; - string id59_ValidateNotNullOrEmpty; - string id96_Verb; - string id121_Class; - string id73_ArrayOfQueryOption; - string id12_Item; - string id42_Value; - - private 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(@""); - 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"); + 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)); } } - internal sealed class PowerShellMetadataSerializer + 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; + } + + 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.ReadElementContentAsString(); + } + } + 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; + } + + 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; + } + + 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.ReadElementContentAsString(); + } + } + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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.ReadElementContentAsString(); + } + } + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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.ReadElementContentAsString(); + } + paramsRead[0] = true; + } + else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id116_DefaultNoun && (object)Reader.NamespaceURI == (object)_id2_Item)) + { + { + o.@DefaultNoun = Reader.ReadElementContentAsString(); + } + 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; + } + + 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; + } + + 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; + } + + 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; + } + + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations63, ref readerCount63); + } + ReadEndElement(); + return o; + } + + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations64, ref readerCount64); + } + ReadEndElement(); + return o; + } + + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations65, ref readerCount65); + } + ReadEndElement(); + return o; + } + + 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; + } + + 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; + } + + string _id72_ArrayOfAssociation; + string _id46_AllowGlobbing; + string _id6_GetCmdletParameters; + string _id25_Item; + string _id62_ValidateRange; + string _id118_StaticCmdlets; + string _id58_ValidateNotNull; + string _id17_ObsoleteAttributeMetadata; + string _id49_PSName; + string _id116_DefaultNoun; + string _id38_ClassMetadataData; + string _id114_ClassVersion; + string _id66_Message; + string _id65_Obsolete; + string _id51_ValueFromPipeline; + string _id108_MinValueQuery; + string _id119_CmdletAdapterPrivateData; + string _id21_GetCmdletMetadata; + string _id120_GetCmdlet; + string _id67_Min; + string _id56_AllowEmptyString; + string _id30_CmdletOutputMetadata; + string _id106_RegularQuery; + string _id74_Option; + string _id75_Item; + string _id23_ConfirmImpact; + string _id117_InstanceCmdlets; + string _id83_Enum; + string _id40_EnumMetadataEnumValue; + string _id111_QueryOptions; + string _id34_InstanceCmdletMetadata; + string _id60_ValidateCount; + string _id45_BitwiseFlags; + string _id81_Data; + string _id31_Item; + string _id1_PowerShellMetadata; + string _id98_HelpUri; + string _id91_DefaultValue; + string _id4_Item; + string _id32_Item; + string _id43_EnumName; + string _id122_Enums; + string _id82_ArrayOfEnumMetadataEnum; + string _id14_Item; + string _id48_Aliases; + string _id115_Version; + string _id11_CmdletParameterMetadata; + string _id70_ArrayOfPropertyMetadata; + string _id9_Association; + string _id102_ResultRole; + string _id29_StaticMethodParameterMetadata; + string _id97_Noun; + string _id47_IsMandatory; + string _id35_PropertyQuery; + string _id54_ErrorOnNoMatch; + string _id3_ClassMetadata; + string _id77_Item; + string _id2_Item; + string _id22_CommonCmdletMetadata; + string _id37_ItemsChoiceType; + string _id36_WildcardablePropertyQuery; + string _id113_ClassName; + string _id64_AllowedValue; + string _id52_Item; + string _id55_AllowEmptyCollection; + string _id13_Item; + string _id76_Parameter; + string _id19_Item; + string _id105_MaxValueQuery; + string _id101_SourceRole; + string _id5_ClassMetadataInstanceCmdlets; + string _id112_CmdletAdapter; + string _id10_AssociationAssociatedInstance; + string _id93_ErrorCode; + string _id41_Name; + string _id68_Max; + string _id50_Position; + string _id100_OptionName; + string _id84_CmdletMetadata; + string _id87_CmdletParameterSet; + string _id104_PropertyName; + string _id28_CommonMethodParameterMetadata; + string _id107_ExcludeQuery; + string _id92_Type; + string _id33_InstanceMethodMetadata; + string _id63_ValidateSet; + string _id53_CmdletParameterSets; + string _id15_Item; + string _id109_QueryableProperties; + string _id57_AllowNull; + string _id80_ArrayOfClassMetadataData; + string _id99_DefaultCmdletParameterSet; + string _id20_QueryOption; + string _id89_Parameters; + string _id90_ParameterName; + string _id61_ValidateLength; + string _id78_ArrayOfStaticCmdletMetadata; + string _id16_Item; + string _id39_EnumMetadataEnum; + string _id7_PropertyMetadata; + string _id110_QueryableAssociations; + string _id86_MethodName; + string _id8_TypeMetadata; + string _id71_Property; + string _id27_StaticMethodMetadata; + string _id94_PSType; + string _id44_UnderlyingType; + string _id103_AssociatedInstance; + string _id79_Cmdlet; + string _id18_Item; + string _id85_Method; + string _id95_ETSType; + string _id26_CommonMethodMetadata; + string _id88_ReturnValue; + string _id69_ArrayOfString; + string _id24_StaticCmdletMetadata; + string _id59_ValidateNotNullOrEmpty; + string _id96_Verb; + string _id121_Class; + string _id73_ArrayOfQueryOption; + string _id12_Item; + string _id42_Value; + + private 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(@""); + _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"); + } + } + + internal sealed class PowerShellMetadataSerializer { internal object Deserialize(XmlReader reader) { 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 index e013baef1..d31dab66f 100644 --- 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 @@ -2,7 +2,6 @@ // // This file has been generated // by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd // // Generation timestamp: 10/21/2013 18:29:23 @@ -20,565 +19,675 @@ // // This source code was auto-generated by xsd, Version=4.0.30319.17929. // -namespace Microsoft.PowerShell.Cmdletization.Xml { + +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; - + [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; + public ClassMetadata Class + { + get + { + return this._classField; } - set { - this.classField = value; + set + { + this._classField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable=false)] - public EnumMetadataEnum[] Enums { - get { - return this.enumsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)] + public EnumMetadataEnum[] Enums + { + get + { + return this._enumsField; } - set { - this.enumsField = value; + 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; - + [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; + public string Version + { + get + { + return this._versionField; } - set { - this.versionField = value; + set + { + this._versionField = value; } } - + /// - public string DefaultNoun { - get { - return this.defaultNounField; + public string DefaultNoun + { + get + { + return this._defaultNounField; } - set { - this.defaultNounField = value; + set + { + this._defaultNounField = value; } } - + /// - public ClassMetadataInstanceCmdlets InstanceCmdlets { - get { - return this.instanceCmdletsField; + public ClassMetadataInstanceCmdlets InstanceCmdlets + { + get + { + return this._instanceCmdletsField; } - set { - this.instanceCmdletsField = value; + set + { + this._instanceCmdletsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable=false)] - public StaticCmdletMetadata[] StaticCmdlets { - get { - return this.staticCmdletsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)] + public StaticCmdletMetadata[] StaticCmdlets + { + get + { + return this._staticCmdletsField; } - set { - this.staticCmdletsField = value; + set + { + this._staticCmdletsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable=false)] - public ClassMetadataData[] CmdletAdapterPrivateData { - get { - return this.cmdletAdapterPrivateDataField; + [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)] + public ClassMetadataData[] CmdletAdapterPrivateData + { + get + { + return this._cmdletAdapterPrivateDataField; } - set { - this.cmdletAdapterPrivateDataField = value; + set + { + this._cmdletAdapterPrivateDataField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletAdapter { - get { - return this.cmdletAdapterField; + public string CmdletAdapter + { + get + { + return this._cmdletAdapterField; } - set { - this.cmdletAdapterField = value; + set + { + this._cmdletAdapterField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassName { - get { - return this.classNameField; + public string ClassName + { + get + { + return this._classNameField; } - set { - this.classNameField = value; + set + { + this._classNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassVersion { - get { - return this.classVersionField; + public string ClassVersion + { + get + { + return this._classVersionField; } - set { - this.classVersionField = value; + 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; - + [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; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + set + { + this._getCmdletParametersField = value; } } - + /// - public GetCmdletMetadata GetCmdlet { - get { - return this.getCmdletField; + public GetCmdletMetadata GetCmdlet + { + get + { + return this._getCmdletField; } - set { - this.getCmdletField = value; + set + { + this._getCmdletField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("Cmdlet")] - public InstanceCmdletMetadata[] Cmdlet { - get { - return this.cmdletField; + public InstanceCmdletMetadata[] Cmdlet + { + get + { + return this._cmdletField; } - set { - this.cmdletField = value; + 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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)] + public PropertyMetadata[] QueryableProperties + { + get + { + return this._queryablePropertiesField; } - set { - this.queryablePropertiesField = value; + set + { + this._queryablePropertiesField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)] - public Association[] QueryableAssociations { - get { - return this.queryableAssociationsField; + [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] + public Association[] QueryableAssociations + { + get + { + return this._queryableAssociationsField; } - set { - this.queryableAssociationsField = value; + set + { + this._queryableAssociationsField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable=false)] - public QueryOption[] QueryOptions { - get { - return this.queryOptionsField; + [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)] + public QueryOption[] QueryOptions + { + get + { + return this._queryOptionsField; } - set { - this.queryOptionsField = value; + set + { + this._queryOptionsField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet { - get { - return this.defaultCmdletParameterSetField; + public string DefaultCmdletParameterSet + { + get + { + return this._defaultCmdletParameterSetField; } - set { - this.defaultCmdletParameterSetField = value; + 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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + 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; + public PropertyQuery[] Items + { + get + { + return this._itemsField; } - set { - this.itemsField = value; + set + { + this._itemsField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] [System.Xml.Serialization.XmlIgnoreAttribute()] - public ItemsChoiceType[] ItemsElementName { - get { - return this.itemsElementNameField; + public ItemsChoiceType[] ItemsElementName + { + get + { + return this._itemsElementNameField; } - set { - this.itemsElementNameField = value; + set + { + this._itemsElementNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PropertyName { - get { - return this.propertyNameField; + public string PropertyName + { + get + { + return this._propertyNameField; } - set { - this.propertyNameField = value; + 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.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; + public string PSType + { + get + { + return this._pSTypeField; } - set { - this.pSTypeField = value; + set + { + this._pSTypeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ETSType { - get { - return this.eTSTypeField; + public string ETSType + { + get + { + return this._eTSTypeField; } - set { - this.eTSTypeField = value; + 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; - + [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; + public AssociationAssociatedInstance AssociatedInstance + { + get + { + return this._associatedInstanceField; } - set { - this.associatedInstanceField = value; + set + { + this._associatedInstanceField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute("Association")] - public string Association1 { - get { - return this.association1Field; + public string Association1 + { + get + { + return this._association1Field; } - set { - this.association1Field = value; + set + { + this._association1Field = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string SourceRole { - get { - return this.sourceRoleField; + public string SourceRole + { + get + { + return this._sourceRoleField; } - set { - this.sourceRoleField = value; + set + { + this._sourceRoleField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ResultRole { - get { - return this.resultRoleField; + public string ResultRole + { + get + { + return this._resultRoleField; } - set { - this.resultRoleField = value; + 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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata { - get { - return this.cmdletParameterMetadataField; + public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + 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.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; + public bool ErrorOnNoMatch + { + get + { + return this._errorOnNoMatchField; } - set { - this.errorOnNoMatchField = value; + set + { + this._errorOnNoMatchField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ErrorOnNoMatchSpecified { - get { - return this.errorOnNoMatchFieldSpecified; + public bool ErrorOnNoMatchSpecified + { + get + { + return this._errorOnNoMatchFieldSpecified; } - set { - this.errorOnNoMatchFieldSpecified = value; + 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.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; + public bool ValueFromPipeline + { + get + { + return this._valueFromPipelineField; } - set { - this.valueFromPipelineField = value; + set + { + this._valueFromPipelineField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified { - get { - return this.valueFromPipelineFieldSpecified; + public bool ValueFromPipelineSpecified + { + get + { + return this._valueFromPipelineFieldSpecified; } - set { - this.valueFromPipelineFieldSpecified = value; + set + { + this._valueFromPipelineFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName { - get { - return this.valueFromPipelineByPropertyNameField; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + set + { + this._valueFromPipelineByPropertyNameFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] CmdletParameterSets { - get { - return this.cmdletParameterSetsField; + public string[] CmdletParameterSets + { + get + { + return this._cmdletParameterSetsField; } - set { - this.cmdletParameterSetsField = value; + set + { + this._cmdletParameterSetsField = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] @@ -588,774 +697,921 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { [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; - + [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; + public object AllowEmptyCollection + { + get + { + return this._allowEmptyCollectionField; } - set { - this.allowEmptyCollectionField = value; + set + { + this._allowEmptyCollectionField = value; } } - + /// - public object AllowEmptyString { - get { - return this.allowEmptyStringField; + public object AllowEmptyString + { + get + { + return this._allowEmptyStringField; } - set { - this.allowEmptyStringField = value; + set + { + this._allowEmptyStringField = value; } } - + /// - public object AllowNull { - get { - return this.allowNullField; + public object AllowNull + { + get + { + return this._allowNullField; } - set { - this.allowNullField = value; + set + { + this._allowNullField = value; } } - + /// - public object ValidateNotNull { - get { - return this.validateNotNullField; + public object ValidateNotNull + { + get + { + return this._validateNotNullField; } - set { - this.validateNotNullField = value; + set + { + this._validateNotNullField = value; } } - + /// - public object ValidateNotNullOrEmpty { - get { - return this.validateNotNullOrEmptyField; + public object ValidateNotNullOrEmpty + { + get + { + return this._validateNotNullOrEmptyField; } - set { - this.validateNotNullOrEmptyField = value; + set + { + this._validateNotNullOrEmptyField = value; } } - + /// - public CmdletParameterMetadataValidateCount ValidateCount { - get { - return this.validateCountField; + public CmdletParameterMetadataValidateCount ValidateCount + { + get + { + return this._validateCountField; } - set { - this.validateCountField = value; + set + { + this._validateCountField = value; } } - + /// - public CmdletParameterMetadataValidateLength ValidateLength { - get { - return this.validateLengthField; + public CmdletParameterMetadataValidateLength ValidateLength + { + get + { + return this._validateLengthField; } - set { - this.validateLengthField = value; + set + { + this._validateLengthField = value; } } - + /// - public CmdletParameterMetadataValidateRange ValidateRange { - get { - return this.validateRangeField; + public CmdletParameterMetadataValidateRange ValidateRange + { + get + { + return this._validateRangeField; } - set { - this.validateRangeField = value; + set + { + this._validateRangeField = value; } } - + /// - [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable=false)] - public string[] ValidateSet { - get { - return this.validateSetField; + [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)] + public string[] ValidateSet + { + get + { + return this._validateSetField; } - set { - this.validateSetField = value; + set + { + this._validateSetField = value; } } - + /// - public ObsoleteAttributeMetadata Obsolete { - get { - return this.obsoleteField; + public ObsoleteAttributeMetadata Obsolete + { + get + { + return this._obsoleteField; } - set { - this.obsoleteField = value; + set + { + this._obsoleteField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool IsMandatory { - get { - return this.isMandatoryField; + public bool IsMandatory + { + get + { + return this._isMandatoryField; } - set { - this.isMandatoryField = value; + set + { + this._isMandatoryField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool IsMandatorySpecified { - get { - return this.isMandatoryFieldSpecified; + public bool IsMandatorySpecified + { + get + { + return this._isMandatoryFieldSpecified; } - set { - this.isMandatoryFieldSpecified = value; + set + { + this._isMandatoryFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases { - get { - return this.aliasesField; + public string[] Aliases + { + get + { + return this._aliasesField; } - set { - this.aliasesField = value; + set + { + this._aliasesField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName { - get { - return this.pSNameField; + public string PSName + { + get + { + return this._pSNameField; } - set { - this.pSNameField = value; + set + { + this._pSNameField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Position { - get { - return this.positionField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Position + { + get + { + return this._positionField; } - set { - this.positionField = value; + 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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + 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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="nonNegativeInteger")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + 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.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; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Min + { + get + { + return this._minField; } - set { - this.minField = value; + set + { + this._minField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="integer")] - public string Max { - get { - return this.maxField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Max + { + get + { + return this._maxField; } - set { - this.maxField = value; + 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.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; + public string Message + { + get + { + return this._messageField; } - set { - this.messageField = value; + 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.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; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + 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.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; + public bool ValueFromPipeline + { + get + { + return this._valueFromPipelineField; } - set { - this.valueFromPipelineField = value; + set + { + this._valueFromPipelineField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified { - get { - return this.valueFromPipelineFieldSpecified; + public bool ValueFromPipelineSpecified + { + get + { + return this._valueFromPipelineFieldSpecified; } - set { - this.valueFromPipelineFieldSpecified = value; + set + { + this._valueFromPipelineFieldSpecified = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName { - get { - return this.valueFromPipelineByPropertyNameField; + public bool ValueFromPipelineByPropertyName + { + get + { + return this._valueFromPipelineByPropertyNameField; } - set { - this.valueFromPipelineByPropertyNameField = value; + set + { + this._valueFromPipelineByPropertyNameField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified { - get { - return this.valueFromPipelineByPropertyNameFieldSpecified; + public bool ValueFromPipelineByPropertyNameSpecified + { + get + { + return this._valueFromPipelineByPropertyNameFieldSpecified; } - set { - this.valueFromPipelineByPropertyNameFieldSpecified = value; + 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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata { - get { - return this.cmdletParameterMetadataField; + public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string OptionName { - get { - return this.optionNameField; + public string OptionName + { + get + { + return this._optionNameField; } - set { - this.optionNameField = value; + 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; - + [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; + public CommonCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// - public GetCmdletParameters GetCmdletParameters { - get { - return this.getCmdletParametersField; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + 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; - + [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; + public ObsoleteAttributeMetadata Obsolete + { + get + { + return this._obsoleteField; } - set { - this.obsoleteField = value; + set + { + this._obsoleteField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string Verb { - get { - return this.verbField; + public string Verb + { + get + { + return this._verbField; } - set { - this.verbField = value; + set + { + this._verbField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string Noun { - get { - return this.nounField; + public string Noun + { + get + { + return this._nounField; } - set { - this.nounField = value; + set + { + this._nounField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases { - get { - return this.aliasesField; + public string[] Aliases + { + get + { + return this._aliasesField; } - set { - this.aliasesField = value; + set + { + this._aliasesField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public ConfirmImpact ConfirmImpact { - get { - return this.confirmImpactField; + public ConfirmImpact ConfirmImpact + { + get + { + return this._confirmImpactField; } - set { - this.confirmImpactField = value; + set + { + this._confirmImpactField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ConfirmImpactSpecified { - get { - return this.confirmImpactFieldSpecified; + public bool ConfirmImpactSpecified + { + get + { + return this._confirmImpactFieldSpecified; } - set { - this.confirmImpactFieldSpecified = value; + set + { + this._confirmImpactFieldSpecified = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")] - public string HelpUri { - get { - return this.helpUriField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")] + public string HelpUri + { + get + { + return this._helpUriField; } - set { - this.helpUriField = value; + 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 { - + [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; - + [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; + public StaticCmdletMetadataCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// [System.Xml.Serialization.XmlElementAttribute("Method")] - public StaticMethodMetadata[] Method { - get { - return this.methodField; + public StaticMethodMetadata[] Method + { + get + { + return this._methodField; } - set { - this.methodField = value; + 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.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; + public string DefaultCmdletParameterSet + { + get + { + return this._defaultCmdletParameterSetField; } - set { - this.defaultCmdletParameterSetField = value; + 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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + public StaticMethodParameterMetadata[] Parameters + { + get + { + return this._parametersField; } - set { - this.parametersField = value; + set + { + this._parametersField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletParameterSet { - get { - return this.cmdletParameterSetField; + public string CmdletParameterSet + { + get + { + return this._cmdletParameterSetField; } - set { - this.cmdletParameterSetField = value; + 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; - + [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; + public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + 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; - + [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; + public object ErrorCode + { + get + { + return this._errorCodeField; } - set { - this.errorCodeField = value; + set + { + this._errorCodeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName { - get { - return this.pSNameField; + public string PSName + { + get + { + return this._pSNameField; } - set { - this.pSNameField = value; + set + { + this._pSNameField = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))] @@ -1363,81 +1619,96 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { [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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string ParameterName { - get { - return this.parameterNameField; + public string ParameterName + { + get + { + return this._parameterNameField; } - set { - this.parameterNameField = value; + set + { + this._parameterNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultValue { - get { - return this.defaultValueField; + public string DefaultValue + { + get + { + return this._defaultValueField; } - set { - this.defaultValueField = value; + 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; - + [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; + public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + set + { + this._cmdletParameterMetadataField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + set + { + this._cmdletOutputMetadataField = value; } } } - + /// [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))] @@ -1445,351 +1716,411 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { [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; - + [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; + public CommonMethodMetadataReturnValue ReturnValue + { + get + { + return this._returnValueField; } - set { - this.returnValueField = value; + set + { + this._returnValueField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string MethodName { - get { - return this.methodNameField; + public string MethodName + { + get + { + return this._methodNameField; } - set { - this.methodNameField = value; + 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; - + [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; + public TypeMetadata Type + { + get + { + return this._typeField; } - set { - this.typeField = value; + set + { + this._typeField = value; } } - + /// - public CmdletOutputMetadata CmdletOutputMetadata { - get { - return this.cmdletOutputMetadataField; + public CmdletOutputMetadata CmdletOutputMetadata + { + get + { + return this._cmdletOutputMetadataField; } - set { - this.cmdletOutputMetadataField = value; + 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.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; + [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + public InstanceMethodParameterMetadata[] Parameters + { + get + { + return this._parametersField; } - set { - this.parametersField = value; + 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; - + [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; + public CommonCmdletMetadata CmdletMetadata + { + get + { + return this._cmdletMetadataField; } - set { - this.cmdletMetadataField = value; + set + { + this._cmdletMetadataField = value; } } - + /// - public InstanceMethodMetadata Method { - get { - return this.methodField; + public InstanceMethodMetadata Method + { + get + { + return this._methodField; } - set { - this.methodField = value; + set + { + this._methodField = value; } } - + /// - public GetCmdletParameters GetCmdletParameters { - get { - return this.getCmdletParametersField; + public GetCmdletParameters GetCmdletParameters + { + get + { + return this._getCmdletParametersField; } - set { - this.getCmdletParametersField = value; + 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; - + [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; + public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata + { + get + { + return this._cmdletParameterMetadataField; } - set { - this.cmdletParameterMetadataField = value; + 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.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; + public bool AllowGlobbing + { + get + { + return this._allowGlobbingField; } - set { - this.allowGlobbingField = value; + set + { + this._allowGlobbingField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool AllowGlobbingSpecified { - get { - return this.allowGlobbingFieldSpecified; + public bool AllowGlobbingSpecified + { + get + { + return this._allowGlobbingFieldSpecified; } - set { - this.allowGlobbingFieldSpecified = value; + 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 { - + [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.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; + public string Name + { + get + { + return this._nameField; } - set { - this.nameField = value; + set + { + this._nameField = value; } } - + /// [System.Xml.Serialization.XmlTextAttribute()] - public string Value { - get { - return this.valueField; + public string Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + 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.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; + public EnumMetadataEnumValue[] Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + set + { + this._valueField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string EnumName { - get { - return this.enumNameField; + public string EnumName + { + get + { + return this._enumNameField; } - set { - this.enumNameField = value; + set + { + this._enumNameField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public string UnderlyingType { - get { - return this.underlyingTypeField; + public string UnderlyingType + { + get + { + return this._underlyingTypeField; } - set { - this.underlyingTypeField = value; + set + { + this._underlyingTypeField = value; } } - + /// [System.Xml.Serialization.XmlAttributeAttribute()] - public bool BitwiseFlags { - get { - return this.bitwiseFlagsField; + public bool BitwiseFlags + { + get + { + return this._bitwiseFlagsField; } - set { - this.bitwiseFlagsField = value; + set + { + this._bitwiseFlagsField = value; } } - + /// [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool BitwiseFlagsSpecified { - get { - return this.bitwiseFlagsFieldSpecified; + public bool BitwiseFlagsSpecified + { + get + { + return this._bitwiseFlagsFieldSpecified; } - set { - this.bitwiseFlagsFieldSpecified = value; + 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.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; + public string Name + { + get + { + return this._nameField; } - set { - this.nameField = value; + set + { + this._nameField = value; } } - + /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType="integer")] - public string Value { - get { - return this.valueField; + [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + public string Value + { + get + { + return this._valueField; } - set { - this.valueField = value; + 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 index 213a12e86..2a0c36e1d 100644 --- 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 @@ -2,7 +2,6 @@ // // This file has been generated // by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// based on the following input file: d:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\cmdlets-over-objects.xsd // // Generation timestamp: 10/21/2013 18:29:23 @@ -14,14 +13,16 @@ #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) { +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) { + if (o == null) + { WriteEmptyTag(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); return; } @@ -29,9 +30,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + public void Write51_ClassMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"ClassMetadata", @""); return; } @@ -39,9 +42,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write36_ClassMetadata(@"ClassMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o), true, false); } - public void Write52_ClassMetadataInstanceCmdlets(object o) { + public void Write52_ClassMetadataInstanceCmdlets(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"ClassMetadataInstanceCmdlets", @""); return; } @@ -49,9 +54,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write40_ClassMetadataInstanceCmdlets(@"ClassMetadataInstanceCmdlets", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o), true, false); } - public void Write53_GetCmdletParameters(object o) { + public void Write53_GetCmdletParameters(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"GetCmdletParameters", @""); return; } @@ -59,9 +66,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write19_GetCmdletParameters(@"GetCmdletParameters", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o), true, false); } - public void Write54_PropertyMetadata(object o) { + public void Write54_PropertyMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"PropertyMetadata", @""); return; } @@ -69,9 +78,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write15_PropertyMetadata(@"PropertyMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o), true, false); } - public void Write55_TypeMetadata(object o) { + public void Write55_TypeMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"TypeMetadata", @""); return; } @@ -79,9 +90,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write2_TypeMetadata(@"TypeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o), true, false); } - public void Write56_Association(object o) { + public void Write56_Association(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"Association", @""); return; } @@ -89,9 +102,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write17_Association(@"Association", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)o), true, false); } - public void Write57_AssociationAssociatedInstance(object o) { + public void Write57_AssociationAssociatedInstance(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"AssociationAssociatedInstance", @""); return; } @@ -99,9 +114,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write41_AssociationAssociatedInstance(@"AssociationAssociatedInstance", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o), true, false); } - public void Write58_CmdletParameterMetadata(object o) { + public void Write58_CmdletParameterMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadata", @""); return; } @@ -109,9 +126,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write10_CmdletParameterMetadata(@"CmdletParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o), true, false); } - public void Write59_Item(object o) { + public void Write59_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletParameter", @""); return; } @@ -119,9 +138,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write11_Item(@"CmdletParameterMetadataForGetCmdletParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o), true, false); } - public void Write60_Item(object o) { + public void Write60_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @""); return; } @@ -129,9 +150,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write12_Item(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o), true, false); } - public void Write61_Item(object o) { + public void Write61_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataValidateCount", @""); return; } @@ -139,9 +162,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write42_Item(@"CmdletParameterMetadataValidateCount", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o), true, false); } - public void Write62_Item(object o) { + public void Write62_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataValidateLength", @""); return; } @@ -149,9 +174,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write43_Item(@"CmdletParameterMetadataValidateLength", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o), true, false); } - public void Write63_Item(object o) { + public void Write63_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataValidateRange", @""); return; } @@ -159,9 +186,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write44_Item(@"CmdletParameterMetadataValidateRange", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o), true, false); } - public void Write64_ObsoleteAttributeMetadata(object o) { + public void Write64_ObsoleteAttributeMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"ObsoleteAttributeMetadata", @""); return; } @@ -169,9 +198,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write7_ObsoleteAttributeMetadata(@"ObsoleteAttributeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o), true, false); } - public void Write65_Item(object o) { + public void Write65_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataForInstanceMethodParameter", @""); return; } @@ -179,9 +210,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write9_Item(@"CmdletParameterMetadataForInstanceMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o), true, false); } - public void Write66_Item(object o) { + public void Write66_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletParameterMetadataForStaticMethodParameter", @""); return; } @@ -189,9 +222,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write8_Item(@"CmdletParameterMetadataForStaticMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o), true, false); } - public void Write67_QueryOption(object o) { + public void Write67_QueryOption(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"QueryOption", @""); return; } @@ -199,9 +234,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write18_QueryOption(@"QueryOption", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o), true, false); } - public void Write68_GetCmdletMetadata(object o) { + public void Write68_GetCmdletMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"GetCmdletMetadata", @""); return; } @@ -209,9 +246,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write22_GetCmdletMetadata(@"GetCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o), true, false); } - public void Write69_CommonCmdletMetadata(object o) { + public void Write69_CommonCmdletMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CommonCmdletMetadata", @""); return; } @@ -219,18 +258,22 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write21_CommonCmdletMetadata(@"CommonCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o), true, false); } - public void Write70_ConfirmImpact(object o) { + public void Write70_ConfirmImpact(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteEmptyTag(@"ConfirmImpact", @""); return; } WriteElementString(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o))); } - public void Write71_StaticCmdletMetadata(object o) { + public void Write71_StaticCmdletMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"StaticCmdletMetadata", @""); return; } @@ -238,9 +281,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write34_StaticCmdletMetadata(@"StaticCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o), true, false); } - public void Write72_Item(object o) { + public void Write72_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"StaticCmdletMetadataCmdletMetadata", @""); return; } @@ -248,9 +293,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write45_Item(@"StaticCmdletMetadataCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o), true, false); } - public void Write73_CommonMethodMetadata(object o) { + public void Write73_CommonMethodMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CommonMethodMetadata", @""); return; } @@ -258,9 +305,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write29_CommonMethodMetadata(@"CommonMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o), true, false); } - public void Write74_StaticMethodMetadata(object o) { + public void Write74_StaticMethodMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"StaticMethodMetadata", @""); return; } @@ -268,9 +317,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write28_StaticMethodMetadata(@"StaticMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o), true, false); } - public void Write75_CommonMethodParameterMetadata(object o) { + public void Write75_CommonMethodParameterMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CommonMethodParameterMetadata", @""); return; } @@ -278,9 +329,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write26_CommonMethodParameterMetadata(@"CommonMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o), true, false); } - public void Write76_StaticMethodParameterMetadata(object o) { + public void Write76_StaticMethodParameterMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"StaticMethodParameterMetadata", @""); return; } @@ -288,9 +341,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write27_StaticMethodParameterMetadata(@"StaticMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o), true, false); } - public void Write77_CmdletOutputMetadata(object o) { + public void Write77_CmdletOutputMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CmdletOutputMetadata", @""); return; } @@ -298,9 +353,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o), true, false); } - public void Write78_Item(object o) { + public void Write78_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"InstanceMethodParameterMetadata", @""); return; } @@ -308,9 +365,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write25_Item(@"InstanceMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o), true, false); } - public void Write79_Item(object o) { + public void Write79_Item(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"CommonMethodMetadataReturnValue", @""); return; } @@ -318,9 +377,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write46_Item(@"CommonMethodMetadataReturnValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o), true, false); } - public void Write80_InstanceMethodMetadata(object o) { + public void Write80_InstanceMethodMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"InstanceMethodMetadata", @""); return; } @@ -328,9 +389,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write30_InstanceMethodMetadata(@"InstanceMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o), true, false); } - public void Write81_InstanceCmdletMetadata(object o) { + public void Write81_InstanceCmdletMetadata(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"InstanceCmdletMetadata", @""); return; } @@ -338,9 +401,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write31_InstanceCmdletMetadata(@"InstanceCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o), true, false); } - public void Write82_PropertyQuery(object o) { + public void Write82_PropertyQuery(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"PropertyQuery", @""); return; } @@ -348,9 +413,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write14_PropertyQuery(@"PropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o), true, false); } - public void Write83_WildcardablePropertyQuery(object o) { + public void Write83_WildcardablePropertyQuery(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"WildcardablePropertyQuery", @""); return; } @@ -358,18 +425,22 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write13_WildcardablePropertyQuery(@"WildcardablePropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o), true, false); } - public void Write84_ItemsChoiceType(object o) { + public void Write84_ItemsChoiceType(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteEmptyTag(@"ItemsChoiceType", @""); return; } WriteElementString(@"ItemsChoiceType", @"", Write3_ItemsChoiceType(((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o))); } - public void Write85_ClassMetadataData(object o) { + public void Write85_ClassMetadataData(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"ClassMetadataData", @""); return; } @@ -377,9 +448,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write47_ClassMetadataData(@"ClassMetadataData", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o), true, false); } - public void Write86_EnumMetadataEnum(object o) { + public void Write86_EnumMetadataEnum(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"EnumMetadataEnum", @""); return; } @@ -387,9 +460,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write48_EnumMetadataEnum(@"EnumMetadataEnum", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o), true, false); } - public void Write87_EnumMetadataEnumValue(object o) { + public void Write87_EnumMetadataEnumValue(object o) + { WriteStartDocument(); - if (o == null) { + if (o == null) + { WriteNullTagLiteral(@"EnumMetadataEnumValue", @""); return; } @@ -397,16 +472,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Write49_EnumMetadataEnumValue(@"EnumMetadataEnumValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o), true, false); } - void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -417,16 +497,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -434,32 +519,41 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + 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++) { + 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) { + if (o.@BitwiseFlagsSpecified) + { } WriteEndElement(o); } - void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -470,31 +564,39 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write47_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) + { } - else { + 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){ + if ((object)(o.@Value) != null) + { WriteValue(((global::System.String)o.@Value)); } WriteEndElement(o); } - string Write3_ItemsChoiceType(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType v) { + private string Write3_ItemsChoiceType(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType v) + { string s = null; - switch (v) { + 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; @@ -504,53 +606,68 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return s; } - void Write13_WildcardablePropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) + { } - else { + 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) { + 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) { + if (o.@AllowGlobbingSpecified) + { } WriteEndElement(o); } - void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) + { } - else { + 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) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -560,17 +677,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"CmdletParameterSets", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -578,7 +699,8 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndAttribute(); } } - if (o.@ErrorOnNoMatchSpecified) { + 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); @@ -591,36 +713,47 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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.@IsMandatorySpecified) + { } - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + if (o.@ValueFromPipelineByPropertyNameSpecified) + { } - if (o.@ErrorOnNoMatchSpecified) { + if (o.@ErrorOnNoMatchSpecified) + { } WriteEndElement(o); } - void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -630,16 +763,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -650,16 +788,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -670,16 +813,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -690,169 +838,212 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write1_Object(string n, string ns, global::System.Object o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::System.Object)) { + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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)) { + 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[])) { + 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++) { + 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])); } } @@ -860,13 +1051,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])) { + 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++) { + 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); } } @@ -874,13 +1068,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association[])) { + 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++) { + 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); } } @@ -888,13 +1085,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])) { + 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++) { + 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); } } @@ -902,20 +1102,24 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) { + 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[])) { + 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++) { + 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); } } @@ -923,13 +1127,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])) { + 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++) { + 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); } } @@ -937,13 +1144,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])) { + 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++) { + 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); } } @@ -951,13 +1161,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])) { + 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++) { + 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); } } @@ -965,13 +1178,16 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])) { + 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++) { + 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); } } @@ -979,7 +1195,8 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndElement(); return; } - else { + else + { WriteTypedPrimitive(n, ns, o, true); return; } @@ -988,16 +1205,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1005,54 +1227,69 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + 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++) { + 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) { + if (o.@BitwiseFlagsSpecified) + { } WriteEndElement(o); } - void Write35_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) + { } - else { + 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){ + if ((object)(o.@Value) != null) + { WriteValue(((global::System.String)o.@Value)); } WriteEndElement(o); } - void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1061,8 +1298,10 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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++) { + 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); } } @@ -1070,16 +1309,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1090,9 +1334,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1101,16 +1347,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write27_StaticMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1124,16 +1375,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write23_CmdletOutputMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1144,29 +1400,37 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) + { } - else { + 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) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1176,10 +1440,12 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + 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); @@ -1192,34 +1458,44 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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.@IsMandatorySpecified) + { } - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + if (o.@ValueFromPipelineByPropertyNameSpecified) + { } WriteEndElement(o); } - void Write2_TypeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1230,16 +1506,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write24_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1250,16 +1531,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1269,9 +1555,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1279,20 +1567,24 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndAttribute(); } } - if (o.@ConfirmImpactSpecified) { + 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) { + if (o.@ConfirmImpactSpecified) + { } WriteEndElement(o); } - string Write20_ConfirmImpact(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact v) { + private string Write20_ConfirmImpact(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact v) + { string s = null; - switch (v) { + 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; @@ -1302,16 +1594,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return s; } - void Write25_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1325,29 +1622,37 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) + { } - else { + 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) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1357,7 +1662,8 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineByPropertyNameSpecified) { + 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); @@ -1370,32 +1676,41 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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.@IsMandatorySpecified) + { } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + if (o.@ValueFromPipelineByPropertyNameSpecified) + { } WriteEndElement(o); } - void Write18_QueryOption(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1407,33 +1722,42 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) { + 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); + 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 { + 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) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1443,17 +1767,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"CmdletParameterSets", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1471,34 +1799,44 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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.@IsMandatorySpecified) + { } - if (o.@ValueFromPipelineSpecified) { + if (o.@ValueFromPipelineSpecified) + { } - if (o.@ValueFromPipelineByPropertyNameSpecified) { + if (o.@ValueFromPipelineByPropertyNameSpecified) + { } WriteEndElement(o); } - void Write17_Association(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.Association o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1511,16 +1849,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write16_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1531,16 +1874,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write15_PropertyMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1550,31 +1898,40 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + 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++) { + 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 (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery && ((object)(ai) != null)) + { if (((object)ai) != null && !(ai is 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)) { + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery && ((object)(ai) != null)) + { if (((object)ai) != null && !(ai is 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)) { + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery && ((object)(ai) != null)) + { if (((object)ai) != null && !(ai is 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)) { + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery && ((object)(ai) != null)) + { if (((object)ai) != null && !(ai is 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){ + else if ((object)(ai) != null) + { throw CreateUnknownTypeException(ai); } } @@ -1584,20 +1941,26 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write14_PropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) { + 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); + 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 { + else + { throw CreateUnknownTypeException(o); } } @@ -1607,45 +1970,57 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write10_CmdletParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) { + 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); + 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); + 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); + 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); + 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 { + 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) { + 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) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1665,30 +2040,38 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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.@IsMandatorySpecified) + { } WriteEndElement(o); } - void Write19_GetCmdletParameters(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1697,9 +2080,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"QueryableProperties", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1707,9 +2092,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } { global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])((global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o.@QueryableAssociations); - if (a != null){ + if (a != null) + { WriteStartElement(@"QueryableAssociations", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1717,9 +2104,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } { global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o.@QueryOptions); - if (a != null){ + if (a != null) + { WriteStartElement(@"QueryOptions", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1728,16 +2117,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1747,9 +2141,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1757,31 +2153,39 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndAttribute(); } } - if (o.@ConfirmImpactSpecified) { + 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) { + if (o.@ConfirmImpactSpecified) + { } WriteEndElement(o); } - void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) { + 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); + 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 { + else + { throw CreateUnknownTypeException(o); } } @@ -1791,9 +2195,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) { + if (a != null) + { Writer.WriteStartAttribute(null, @"Aliases", @""); - for (int i = 0; i < a.Length; i++) { + for (int i = 0; i < a.Length; i++) + { global::System.String ai = (global::System.String)a[i]; if (i != 0) Writer.WriteString(" "); WriteValue(ai); @@ -1801,26 +2207,33 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Writer.WriteEndAttribute(); } } - if (o.@ConfirmImpactSpecified) { + 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) { + if (o.@ConfirmImpactSpecified) + { } WriteEndElement(o); } - void Write22_GetCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1831,16 +2244,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write30_InstanceMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1850,9 +2268,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1861,24 +2281,31 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write29_CommonMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) { + 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); + 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); + 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 { + else + { throw CreateUnknownTypeException(o); } } @@ -1889,24 +2316,31 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write26_CommonMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) { + 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); + 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); + 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 { + else + { throw CreateUnknownTypeException(o); } } @@ -1918,16 +2352,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write31_InstanceCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1939,16 +2378,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -1962,9 +2406,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"StaticCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1972,9 +2418,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } { global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o.@CmdletAdapterPrivateData); - if (a != null){ + if (a != null) + { WriteStartElement(@"CmdletAdapterPrivateData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -1983,16 +2431,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2002,8 +2455,10 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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++) { + 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); } } @@ -2011,16 +2466,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2030,8 +2490,10 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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++) { + 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); } } @@ -2039,16 +2501,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write41_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2059,16 +2526,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write42_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2079,16 +2551,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write43_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2099,16 +2576,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write44_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2119,16 +2601,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write46_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2139,16 +2626,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o, bool isNullable, bool needType) { - if ((object)o == null) { + 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) { + if (!needType) + { System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) { + if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) + { } - else { + else + { throw CreateUnknownTypeException(o); } } @@ -2157,9 +2649,11 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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){ + if (a != null) + { WriteStartElement(@"Enums", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) { + 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(); @@ -2168,692 +2662,891 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { WriteEndElement(o); } - protected override void InitCallbacks() { + protected override void InitCallbacks() + { } } -[System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializationReader1 : System.Xml.Serialization.XmlSerializationReader { - - public object Read50_PowerShellMetadata() { + [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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); } return (object)o; } - public object Read51_ClassMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadata"); } return (object)o; } - public object Read52_ClassMetadataInstanceCmdlets() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadataInstanceCmdlets"); } return (object)o; } - public object Read53_GetCmdletParameters() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":GetCmdletParameters"); } return (object)o; } - public object Read54_PropertyMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":PropertyMetadata"); } return (object)o; } - public object Read55_TypeMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":TypeMetadata"); } return (object)o; } - public object Read56_Association() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":Association"); } return (object)o; } - public object Read57_AssociationAssociatedInstance() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":AssociationAssociatedInstance"); } return (object)o; } - public object Read58_CmdletParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadata"); } return (object)o; } - public object Read59_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); } return (object)o; } - public object Read60_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); } return (object)o; } - public object Read61_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateCount"); } return (object)o; } - public object Read62_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateLength"); } return (object)o; } - public object Read63_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataValidateRange"); } return (object)o; } - public object Read64_ObsoleteAttributeMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ObsoleteAttributeMetadata"); } return (object)o; } - public object Read65_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); } return (object)o; } - public object Read66_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); } return (object)o; } - public object Read67_QueryOption() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":QueryOption"); } return (object)o; } - public object Read68_GetCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":GetCmdletMetadata"); } return (object)o; } - public object Read69_CommonCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonCmdletMetadata"); } return (object)o; } - public object Read70_ConfirmImpact() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ConfirmImpact"); } return (object)o; } - public object Read71_StaticCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticCmdletMetadata"); } return (object)o; } - public object Read72_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); } return (object)o; } - public object Read73_CommonMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodMetadata"); } return (object)o; } - public object Read74_StaticMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticMethodMetadata"); } return (object)o; } - public object Read75_CommonMethodParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodParameterMetadata"); } return (object)o; } - public object Read76_StaticMethodParameterMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":StaticMethodParameterMetadata"); } return (object)o; } - public object Read77_CmdletOutputMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CmdletOutputMetadata"); } return (object)o; } - public object Read78_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceMethodParameterMetadata"); } return (object)o; } - public object Read79_Item() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":CommonMethodMetadataReturnValue"); } return (object)o; } - public object Read80_InstanceMethodMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceMethodMetadata"); } return (object)o; } - public object Read81_InstanceCmdletMetadata() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":InstanceCmdletMetadata"); } return (object)o; } - public object Read82_PropertyQuery() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":PropertyQuery"); } return (object)o; } - public object Read83_WildcardablePropertyQuery() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":WildcardablePropertyQuery"); } return (object)o; } - public object Read84_ItemsChoiceType() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ItemsChoiceType"); } return (object)o; } - public object Read85_ClassMetadataData() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":ClassMetadataData"); } return (object)o; } - public object Read86_EnumMetadataEnum() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":EnumMetadataEnum"); } return (object)o; } - public object Read87_EnumMetadataEnumValue() { + 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)) { + 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 { + else + { throw CreateUnknownNodeException(); } } - else { + else + { UnknownNode(null, @":EnumMetadataEnumValue"); } return (object)o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read49_EnumMetadataEnumValue(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name, :Value"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -2861,11 +3554,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -2875,15 +3571,18 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read48_EnumMetadataEnum(bool isNullable, bool checkType) { + 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 (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; @@ -2891,26 +3590,32 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + 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; @@ -2919,16 +3624,21 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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); + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } } - else { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); } Reader.MoveToContent(); @@ -2939,35 +3649,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read37_EnumMetadataEnumValue(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name, :Value"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -2975,11 +3693,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -2989,31 +3710,38 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read47_ClassMetadataData(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Name"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3021,19 +3749,23 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { Reader.MoveToContent(); int whileIterations3 = 0; int readerCount3 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - 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) { + 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 { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -3043,8 +3775,10 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType Read3_ItemsChoiceType(string s) { - switch (s) { + 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; @@ -3053,32 +3787,39 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } } - global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery Read13_WildcardablePropertyQuery(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":AllowGlobbing"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3086,17 +3827,22 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } } - else { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); } Reader.MoveToContent(); @@ -3106,15 +3852,18 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter Read12_Item(bool isNullable, bool checkType) { + 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 (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; @@ -3126,55 +3875,68 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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]; + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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]; + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + 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); @@ -3184,83 +3946,105 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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)) { + 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()) { + 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)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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)) { + 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(); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations6, ref readerCount6); } - ReadEndElement(); + 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)) { + 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 { + 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 { + 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(); @@ -3272,31 +4056,38 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata Read7_ObsoleteAttributeMetadata(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Message"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3304,11 +4095,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -3318,35 +4112,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read6_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3354,11 +4156,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -3368,35 +4173,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read5_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3404,11 +4217,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -3418,35 +4234,43 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read4_Item(bool isNullable, bool checkType) { + 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 (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)) { + 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)) { + 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)) { + else if (!IsXmlnsAttribute(Reader.Name)) + { UnknownNode((object)o, @":Min, :Max"); } } Reader.MoveToElement(); - if (Reader.IsEmptyElement) { + if (Reader.IsEmptyElement) + { Reader.Skip(); return o; } @@ -3454,11 +4278,14 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { 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) { + while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) + { + if (Reader.NodeType == System.Xml.XmlNodeType.Element) + { UnknownNode((object)o, @""); } - else { + else + { UnknownNode((object)o, @""); } Reader.MoveToContent(); @@ -3468,403 +4295,490 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { return o; } - global::System.Object Read1_Object(bool isNullable, bool checkType) { + 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 (checkType) + { + if (isNull) + { if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } - if (xsiType == 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) + 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)) { + 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)) { + 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()) { + if (!ReadNull()) + { global::System.String[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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)) { + 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(); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations11, ref readerCount11); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations12, ref readerCount12); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.Association[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations13, ref readerCount13); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations14, ref readerCount14); } - ReadEndElement(); + 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)) { + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations15, ref readerCount15); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations16, ref readerCount16); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations17, ref readerCount17); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations18, ref readerCount18); } - ReadEndElement(); + 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)) { + 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()) { + if (!ReadNull()) + { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] z_0_0 = null; int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) { + if ((Reader.IsEmptyElement)) + { Reader.Skip(); } - else { + 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); + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } } - else { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); } Reader.MoveToContent(); CheckReaderCount(ref whileIterations19, ref readerCount19); } - ReadEndElement(); + ReadEndElement(); } a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); } @@ -3872,3886 +4786,4653 @@ namespace Microsoft.PowerShell.Cmdletization.Xml { } else return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); + } + if (isNull) return null; + global::System.Object o; + o = new global::System.Object(); + bool[] paramsRead = new bool[0]; + while (Reader.MoveToNextAttribute()) + { + if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o); } - if (isNull) return null; - global::System.Object o; - o = new global::System.Object(); - bool[] paramsRead = new bool[0]; - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations20, ref readerCount20); - } - ReadEndElement(); + } + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations20, ref readerCount20); + } + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@UnderlyingType = Reader.Value; + paramsRead[2] = true; } - 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; + 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; } - 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 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 { + 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; + 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; + } - 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)) { + 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; } - 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; + 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, @""); + } + 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, @""); + } + 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 (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":Name"); + 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); } - } - 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, @""); - } - 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, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations22, ref readerCount22); - } - ReadEndElement(); - return o; - } - - 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 { + 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; - } - - 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); + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); } - 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; + 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; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id87_CmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@CmdletParameterSet = Reader.Value; + paramsRead[3] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); } - 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - 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; - } - - 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; - } - - 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; + 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 (!paramsRead[1] && ((object) Reader.LocalName == (object)id95_ETSType && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@ETSType = Reader.Value; - paramsRead[1] = 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 if (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":PSType, :ETSType"); + 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.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + 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.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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations30, ref readerCount30); - } - ReadEndElement(); - return o; + CheckReaderCount(ref whileIterations24, ref readerCount24); } + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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); - } + else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@DefaultValue = Reader.Value; + paramsRead[2] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o, @":ParameterName, :DefaultValue"); } - 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - 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; + 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[2] && ((object) Reader.LocalName == (object)id97_Noun && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@Noun = Reader.Value; - paramsRead[2] = 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 (((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; + 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 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; - } - - 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)); - } - } - - 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 { + 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; - } - - 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); + { + 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"); } - 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; + CheckReaderCount(ref whileIterations26, ref readerCount26); } + ReadEndElement(); + return o; + } - 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)) { + 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; } - 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; + 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 (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":OptionName"); + 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"); } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + 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.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); + 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)) + { } - ReadEndElement(); + 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; } - - 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)) { + 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, @""); } - else if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id13_Item && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + else + { + UnknownNode((object)o, @""); + } + 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; } - 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"); + 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]; } } - 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; + else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@PSName = Reader.Value; + paramsRead[12] = true; } - 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); + 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); - ReadEndElement(); return o; } - - 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; + 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)id101_SourceRole && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@SourceRole = Reader.Value; + 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)id102_ResultRole && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@ResultRole = Reader.Value; + 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 (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":Association, :SourceRole, :ResultRole"); + 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"); } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + 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.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"); - } + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations39, ref readerCount39); } - ReadEndElement(); - return o; + else + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations39, ref readerCount39); } + ReadEndElement(); + return o; + } - 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)) { + 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); } - 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; } - } - 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 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 { + 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; + 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; + } - 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)) { + 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; } - 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); + 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); - ReadEndElement(); return o; } - - 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)) { + 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 if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id36_WildcardablePropertyQuery && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + 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); } - 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - 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)) { + 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 if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id12_Item && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + 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)) + 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)) + 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)) + 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; } - 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"); + 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]; } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; + else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@PSName = Reader.Value; + paramsRead[12] = true; } - 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); + 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); - ReadEndElement(); return o; } - - 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; + 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 (!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; - } - - 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; + 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)id97_Noun && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@Noun = Reader.Value; + 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 (((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[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)id23_ConfirmImpact && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = 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)id98_HelpUri && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@HelpUri = CollapseWhitespace(Reader.Value); + 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)id99_DefaultCmdletParameterSet && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@DefaultCmdletParameterSet = Reader.Value; + 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 (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); + 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"); } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; + 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.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); + 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)) + { } - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); + 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; } - - 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)) { + 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 if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id25_Item && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + 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; } - 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"); + 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]; } } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; + 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; } - 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 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 { + 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; - } - - 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); + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); } - 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; + CheckReaderCount(ref whileIterations50, ref readerCount50); } + o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); + ReadEndElement(); + return o; + } - 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)) { + 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); } - 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; + } + 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 if (!IsXmlnsAttribute(Reader.Name)) { - UnknownNode((object)o, @":MethodName"); + 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.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + 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.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); + 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)) + { } - ReadEndElement(); + 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; } - - 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)) { + 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 if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id33_InstanceMethodMetadata && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + 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)) + 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; } - 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"); - } + 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - 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)) { + 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 if (((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id29_StaticMethodParameterMetadata && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) + 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)) + 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; } - 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"); - } + else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@DefaultValue = Reader.Value; + paramsRead[2] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!IsXmlnsAttribute(Reader.Name)) + { + UnknownNode((object)o, @":ParameterName, :DefaultValue"); } - 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"); - } + } + 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 { + else + { UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations55, ref readerCount55); } - ReadEndElement(); - return o; + else + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations55, ref readerCount55); } + ReadEndElement(); + return o; + } - 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)) { + 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); } - 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; } - } - 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 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 { + 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"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations56, ref readerCount56); } - ReadEndElement(); - return o; + 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; + } - 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)) { + 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; } - 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"); - } + else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id113_ClassName && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@ClassName = Reader.Value; + paramsRead[6] = true; } - Reader.MoveToElement(); - if (Reader.IsEmptyElement) { - Reader.Skip(); - return o; + else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id114_ClassVersion && (object)Reader.NamespaceURI == (object)_id4_Item)) + { + o.@ClassVersion = Reader.Value; + paramsRead[7] = true; } - 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)) { + 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)) { - o.@Version = Reader.ReadElementString(); + Reader.Skip(); } - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id116_DefaultNoun && (object) Reader.NamespaceURI == (object)id2_Item)) { + else { - 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"); - } + 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 { + 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(); + else + { + UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); + } 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"); - } + 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 { + else + { UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations59, ref readerCount59); } - ReadEndElement(); + else + { + UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); + } + Reader.MoveToContent(); + CheckReaderCount(ref whileIterations59, ref readerCount59); } - o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); + ReadEndElement(); } - } - 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"); + o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); } } - else { + 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; + 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; + } - 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)) { + 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); } - 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; } - } - 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 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 { + 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"); } - 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; + 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; + } - 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)) { + 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); } - 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; } - } - 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 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 { + 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"); } - 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; + 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; + } - 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)) { + 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); } - 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; } - } - 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 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 { + 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; + 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; + } - 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)) { + 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; } - 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); + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + 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, @""); + } + else + { + UnknownNode((object)o, @""); + } + 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)id68_Max && (object) Reader.NamespaceURI == (object)id4_Item)) { - o.@Max = CollapseWhitespace(Reader.Value); + 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 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations63, ref readerCount63); - } - ReadEndElement(); - return o; - } - - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations64, ref readerCount64); - } - ReadEndElement(); - return o; - } - - 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, @""); - } - else { - UnknownNode((object)o, @""); - } - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations65, ref readerCount65); - } - ReadEndElement(); - return o; - } - - 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 { + 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; + 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; + } - 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)) { + 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); } - 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(); + } + Reader.MoveToElement(); + if (Reader.IsEmptyElement) + { + Reader.Skip(); return o; } - - protected override void InitCallbacks() { - } - - string id72_ArrayOfAssociation; - string id46_AllowGlobbing; - string id6_GetCmdletParameters; - string id25_Item; - string id62_ValidateRange; - string id118_StaticCmdlets; - string id58_ValidateNotNull; - string id17_ObsoleteAttributeMetadata; - string id49_PSName; - string id116_DefaultNoun; - string id38_ClassMetadataData; - string id114_ClassVersion; - string id66_Message; - string id65_Obsolete; - string id51_ValueFromPipeline; - string id108_MinValueQuery; - string id119_CmdletAdapterPrivateData; - string id21_GetCmdletMetadata; - string id120_GetCmdlet; - string id67_Min; - string id56_AllowEmptyString; - string id30_CmdletOutputMetadata; - string id106_RegularQuery; - string id74_Option; - string id75_Item; - string id23_ConfirmImpact; - string id117_InstanceCmdlets; - string id83_Enum; - string id40_EnumMetadataEnumValue; - string id111_QueryOptions; - string id34_InstanceCmdletMetadata; - string id60_ValidateCount; - string id45_BitwiseFlags; - string id81_Data; - string id31_Item; - string id1_PowerShellMetadata; - string id98_HelpUri; - string id91_DefaultValue; - string id4_Item; - string id32_Item; - string id43_EnumName; - string id122_Enums; - string id82_ArrayOfEnumMetadataEnum; - string id14_Item; - string id48_Aliases; - string id115_Version; - string id11_CmdletParameterMetadata; - string id70_ArrayOfPropertyMetadata; - string id9_Association; - string id102_ResultRole; - string id29_StaticMethodParameterMetadata; - string id97_Noun; - string id47_IsMandatory; - string id35_PropertyQuery; - string id54_ErrorOnNoMatch; - string id3_ClassMetadata; - string id77_Item; - string id2_Item; - string id22_CommonCmdletMetadata; - string id37_ItemsChoiceType; - string id36_WildcardablePropertyQuery; - string id113_ClassName; - string id64_AllowedValue; - string id52_Item; - string id55_AllowEmptyCollection; - string id13_Item; - string id76_Parameter; - string id19_Item; - string id105_MaxValueQuery; - string id101_SourceRole; - string id5_ClassMetadataInstanceCmdlets; - string id112_CmdletAdapter; - string id10_AssociationAssociatedInstance; - string id93_ErrorCode; - string id41_Name; - string id68_Max; - string id50_Position; - string id100_OptionName; - string id84_CmdletMetadata; - string id87_CmdletParameterSet; - string id104_PropertyName; - string id28_CommonMethodParameterMetadata; - string id107_ExcludeQuery; - string id92_Type; - string id33_InstanceMethodMetadata; - string id63_ValidateSet; - string id53_CmdletParameterSets; - string id15_Item; - string id109_QueryableProperties; - string id57_AllowNull; - string id80_ArrayOfClassMetadataData; - string id99_DefaultCmdletParameterSet; - string id20_QueryOption; - string id89_Parameters; - string id90_ParameterName; - string id61_ValidateLength; - string id78_ArrayOfStaticCmdletMetadata; - string id16_Item; - string id39_EnumMetadataEnum; - string id7_PropertyMetadata; - string id110_QueryableAssociations; - string id86_MethodName; - string id8_TypeMetadata; - string id71_Property; - string id27_StaticMethodMetadata; - string id94_PSType; - string id44_UnderlyingType; - string id103_AssociatedInstance; - string id79_Cmdlet; - string id18_Item; - string id85_Method; - string id95_ETSType; - string id26_CommonMethodMetadata; - string id88_ReturnValue; - string id69_ArrayOfString; - string id24_StaticCmdletMetadata; - string id59_ValidateNotNullOrEmpty; - string id96_Verb; - string id121_Class; - string id73_ArrayOfQueryOption; - string id12_Item; - 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(@""); - 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 System.Boolean 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ClassMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ClassMetadataInstanceCmdlets", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"GetCmdletParameters", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"PropertyMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"TypeMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"Association", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"AssociationAssociatedInstance", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletParameter", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateCount", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateLength", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateRange", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ObsoleteAttributeMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForInstanceMethodParameter", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForStaticMethodParameter", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"QueryOption", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"GetCmdletMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CommonCmdletMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ConfirmImpact", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"StaticCmdletMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"StaticCmdletMetadataCmdletMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CommonMethodMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"StaticMethodMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CommonMethodParameterMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"StaticMethodParameterMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CmdletOutputMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"InstanceMethodParameterMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"CommonMethodMetadataReturnValue", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"InstanceMethodMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"InstanceCmdletMetadata", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"PropertyQuery", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"WildcardablePropertyQuery", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ItemsChoiceType", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"ClassMetadataData", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"EnumMetadataEnum", @""); - } - - 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) { - return xmlReader.IsStartElement(@"EnumMetadataEnumValue", @""); - } - - 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(); } } - 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; + 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; } - return readMethods; - } - } - 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; + 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); + } } - return writeMethods; - } - } - 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; + else + { + UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); } - return typedSerializers; } + 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); } - public override System.Boolean 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; - } + 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(@""); + _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 System.Boolean 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ClassMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ClassMetadataInstanceCmdlets", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"GetCmdletParameters", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"PropertyMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"TypeMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"Association", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"AssociationAssociatedInstance", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletParameter", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateCount", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateLength", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateRange", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ObsoleteAttributeMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataForInstanceMethodParameter", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletParameterMetadataForStaticMethodParameter", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"QueryOption", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"GetCmdletMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CommonCmdletMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ConfirmImpact", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"StaticCmdletMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"StaticCmdletMetadataCmdletMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CommonMethodMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"StaticMethodMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CommonMethodParameterMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"StaticMethodParameterMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CmdletOutputMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"InstanceMethodParameterMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"CommonMethodMetadataReturnValue", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"InstanceMethodMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"InstanceCmdletMetadata", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"PropertyQuery", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"WildcardablePropertyQuery", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ItemsChoiceType", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"ClassMetadataData", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"EnumMetadataEnum", @""); + } + + 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 System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader) + { + return xmlReader.IsStartElement(@"EnumMetadataEnumValue", @""); + } + + 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 System.Boolean 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/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 9cb0f5d3a..af479aa15 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -74,7 +74,7 @@ namespace Microsoft.PowerShell.Cim } Collection result = new Collection(); - + if (cimInstance.CimInstanceProperties != null) { foreach (CimProperty property in cimInstance.CimInstanceProperties) @@ -110,11 +110,11 @@ namespace Microsoft.PowerShell.Cim } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; + CimInstance cimInstance = baseObject as CimInstance; if (null == cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, - CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, + CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, "baseObject", typeof(CimInstance).ToString()); throw new PSInvalidOperationException(msg); @@ -174,7 +174,7 @@ namespace Microsoft.PowerShell.Cim if (adaptedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) { - return ToStringCodeMethods.Type(typeof (string)); + return ToStringCodeMethods.Type(typeof(string)); } throw new ArgumentNullException("adaptedProperty"); @@ -200,7 +200,7 @@ namespace Microsoft.PowerShell.Cim if (adaptedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) { - CimInstance cimInstance = (CimInstance) adaptedProperty.Tag; + CimInstance cimInstance = (CimInstance)adaptedProperty.Tag; return cimInstance.GetCimSessionComputerName(); } @@ -221,9 +221,8 @@ namespace Microsoft.PowerShell.Cim typeNamesWithoutNamespace.Add(string.Format(CultureInfo.InvariantCulture, "Microsoft.Management.Infrastructure.CimInstance#{0}", className)); - } - + private List GetInheritanceChain(CimInstance cimInstance) { List inheritanceChain = new List(); @@ -264,9 +263,9 @@ namespace Microsoft.PowerShell.Cim if ((inheritanceChain == null) || (inheritanceChain.Count == 0)) { AddTypeNameHierarchy( - typeNamesWithNamespace, - typeNamesWithoutNamespace, - cimInstance.CimSystemProperties.Namespace, + typeNamesWithNamespace, + typeNamesWithoutNamespace, + cimInstance.CimSystemProperties.Namespace, cimInstance.CimSystemProperties.ClassName); } else @@ -274,9 +273,9 @@ namespace Microsoft.PowerShell.Cim foreach (CimClass cimClass in inheritanceChain) { AddTypeNameHierarchy( - typeNamesWithNamespace, - typeNamesWithoutNamespace, - cimClass.CimSystemProperties.Namespace, + typeNamesWithNamespace, + typeNamesWithoutNamespace, + cimClass.CimSystemProperties.Namespace, cimClass.CimSystemProperties.ClassName); cimClass.Dispose(); } @@ -370,10 +369,10 @@ namespace Microsoft.PowerShell.Cim switch (cimProperty.CimType) { case CimType.DateTime: - paramType = typeof (object); + paramType = typeof(object); break; case CimType.DateTimeArray: - paramType = typeof (object[]); + paramType = typeof(object[]); break; default: paramType = CimConverter.GetDotNetType(cimProperty.CimType); diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseCommand.cs index 93e227819..361566b3e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseCommand.cs @@ -12,23 +12,22 @@ using System.Management.Automation.Language; namespace Microsoft.PowerShell.Commands.Internal.Format { - /// /// facade class to provide context information to process /// exceptions /// internal sealed class TerminatingErrorContext { - internal TerminatingErrorContext (PSCmdlet command) + internal TerminatingErrorContext(PSCmdlet command) { if (command == null) - throw PSTraceSource.NewArgumentNullException ("command"); + throw PSTraceSource.NewArgumentNullException("command"); _command = command; } - internal void ThrowTerminatingError (ErrorRecord errorRecord) + internal void ThrowTerminatingError(ErrorRecord errorRecord) { - _command.ThrowTerminatingError (errorRecord); + _command.ThrowTerminatingError(errorRecord); } private PSCmdlet _command; @@ -48,11 +47,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// ExecutionContext used to create sub pipeline /// name of the command to run /// Type of the command to run - internal void Initialize (ExecutionContext execContext, string nameOfCommand, Type typeOfCommand) + internal void Initialize(ExecutionContext execContext, string nameOfCommand, Type typeOfCommand) { - context = execContext; - commandName = nameOfCommand; - commandType = typeOfCommand; + _context = execContext; + _commandName = nameOfCommand; + _commandType = typeOfCommand; } /// @@ -61,9 +60,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// name of the parameter /// value of the parameter - internal void AddNamedParameter (string parameterName, object parameterValue) + internal void AddNamedParameter(string parameterName, object parameterValue) { - commandParameterList.Add( + _commandParameterList.Add( CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, parameterName, null, PositionUtilities.EmptyExtent, parameterValue, @@ -76,51 +75,51 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to process /// Array of objects out of the success pipeline - internal Array Process (object o) + internal Array Process(object o) { - if (this.pp == null) + if (_pp == null) { // if this is the first call, we need to initialize the // pipeline underneath - DelayedInternalInitialize (); + DelayedInternalInitialize(); } - return this.pp.Step (o); + return _pp.Step(o); } /// /// shut down the pipeline /// /// Array of objects out of the success pipeline - internal Array ShutDown () + internal Array ShutDown() { - if (this.pp == null) + if (_pp == null) { // if Process() never got called, no sub pipeline // ever got created, hence we just return an empty array return new object[0]; } - PipelineProcessor ppTemp = this.pp; + PipelineProcessor ppTemp = _pp; - this.pp = null; + _pp = null; return ppTemp.SynchronousExecuteEnumerate(AutomationNull.Value); } - private void DelayedInternalInitialize () + private void DelayedInternalInitialize() { - this.pp = new PipelineProcessor (); + _pp = new PipelineProcessor(); - CmdletInfo cmdletInfo = new CmdletInfo(this.commandName, this.commandType, null, null, this.context); + CmdletInfo cmdletInfo = new CmdletInfo(_commandName, _commandType, null, null, _context); - CommandProcessor cp = new CommandProcessor (cmdletInfo, this.context); + CommandProcessor cp = new CommandProcessor(cmdletInfo, _context); - foreach (CommandParameterInternal par in this.commandParameterList) + foreach (CommandParameterInternal par in _commandParameterList) { cp.AddParameter(par); } - this.pp.Add (cp); + _pp.Add(cp); } /// @@ -128,20 +127,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// public void Dispose() { - if (this.pp == null) + if (_pp == null) return; - this.pp.Dispose (); - this.pp = null; + _pp.Dispose(); + _pp = null; } - private PipelineProcessor pp = null; + private PipelineProcessor _pp = null; - private string commandName = null; - private Type commandType; - private List commandParameterList = new List(); + private string _commandName = null; + private Type _commandType; + private List _commandParameterList = new List(); - private ExecutionContext context = null; + private ExecutionContext _context = null; } /// @@ -155,46 +154,46 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// This parameter specifies the current pipeline object /// - [Parameter (ValueFromPipeline = true)] + [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set { _inputObject = value; } get { return _inputObject; } } private PSObject _inputObject = AutomationNull.Value; - + #endregion /// /// hook up the calls from the implementation object /// and then call the implementation's Begin() /// - protected override void BeginProcessing () + protected override void BeginProcessing() { - Diagnostics.Assert (this.implementation != null, "this.implementation is null"); - this.implementation.OuterCmdletCall = new ImplementationCommandBase.OuterCmdletCallback (this.OuterCmdletCall); - this.implementation.InputObjectCall = new ImplementationCommandBase.InputObjectCallback (this.InputObjectCall); - this.implementation.WriteObjectCall = new ImplementationCommandBase.WriteObjectCallback (this.WriteObjectCall); - - this.implementation.CreateTerminatingErrorContext (); - - implementation.BeginProcessing (); + Diagnostics.Assert(this.implementation != null, "this.implementation is null"); + this.implementation.OuterCmdletCall = new ImplementationCommandBase.OuterCmdletCallback(this.OuterCmdletCall); + this.implementation.InputObjectCall = new ImplementationCommandBase.InputObjectCallback(this.InputObjectCall); + this.implementation.WriteObjectCall = new ImplementationCommandBase.WriteObjectCallback(this.WriteObjectCall); + + this.implementation.CreateTerminatingErrorContext(); + + implementation.BeginProcessing(); } /// /// call the implementation /// - protected override void ProcessRecord () + protected override void ProcessRecord() { - implementation.ProcessRecord (); + implementation.ProcessRecord(); } /// /// call the implementation /// - protected override void EndProcessing () + protected override void EndProcessing() { - implementation.EndProcessing (); + implementation.EndProcessing(); } /// @@ -209,7 +208,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// callback for the implementation to obtain a reference to the Cmdlet object /// /// Cmdlet reference - protected virtual PSCmdlet OuterCmdletCall () + protected virtual PSCmdlet OuterCmdletCall() { return this; } @@ -218,7 +217,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// callback for the implementation to get the current pipeline object /// /// current object from the pipeline - protected virtual PSObject InputObjectCall () + protected virtual PSObject InputObjectCall() { // just bind to the input object parameter return this.InputObject; @@ -228,7 +227,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// callback for the implementation to write objects /// /// object to be written - protected virtual void WriteObjectCall (object value) + protected virtual void WriteObjectCall(object value) { // just call Monad API this.WriteObject(value); @@ -247,7 +246,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// default implementation just delegates to internal helper /// /// This method calls GC.SuppressFinalize - public void Dispose () + public void Dispose() { Dispose(true); @@ -269,12 +268,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// Do-nothing implementation: derived classes will override as see fit /// - protected virtual void InternalDispose () + protected virtual void InternalDispose() { if (this.implementation == null) return; - this.implementation.Dispose (); + this.implementation.Dispose(); this.implementation = null; } #endregion @@ -289,21 +288,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// inner version of CommandBase.BeginProcessing() /// - internal virtual void BeginProcessing () + internal virtual void BeginProcessing() { } /// /// inner version of CommandBase.ProcessRecord() /// - internal virtual void ProcessRecord () + internal virtual void ProcessRecord() { } /// /// inner version of CommandBase.EndProcessing() /// - internal virtual void EndProcessing () + internal virtual void EndProcessing() { } @@ -317,22 +316,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// retrieve the current input pipeline object /// - internal virtual PSObject ReadObject () + internal virtual PSObject ReadObject() { // delegate to the front end object - System.Diagnostics.Debug.Assert (this.InputObjectCall != null, "this.InputObjectCall is null"); - return this.InputObjectCall (); + System.Diagnostics.Debug.Assert(this.InputObjectCall != null, "this.InputObjectCall is null"); + return this.InputObjectCall(); } /// /// write an object to the pipeline /// /// object to write to the pipeline - internal virtual void WriteObject (object o) + internal virtual void WriteObject(object o) { // delegate to the front end object - System.Diagnostics.Debug.Assert (this.WriteObjectCall != null, "this.WriteObjectCall is null"); - this.WriteObjectCall (o); + System.Diagnostics.Debug.Assert(this.WriteObjectCall != null, "this.WriteObjectCall is null"); + this.WriteObjectCall(o); } // callback methods to get to the outer Monad Cmdlet @@ -340,11 +339,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// get a hold of the Monad outer Cmdlet /// /// - internal virtual PSCmdlet OuterCmdlet () + internal virtual PSCmdlet OuterCmdlet() { // delegate to the front end object - System.Diagnostics.Debug.Assert (this.OuterCmdletCall != null, "this.OuterCmdletCall is null"); - return this.OuterCmdletCall (); + System.Diagnostics.Debug.Assert(this.OuterCmdletCall != null, "this.OuterCmdletCall is null"); + return this.OuterCmdletCall(); } protected TerminatingErrorContext TerminatingErrorContext @@ -357,7 +356,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal void CreateTerminatingErrorContext() { - _terminatingErrorContext = new TerminatingErrorContext (this.OuterCmdlet ()); + _terminatingErrorContext = new TerminatingErrorContext(this.OuterCmdlet()); } private TerminatingErrorContext _terminatingErrorContext; @@ -365,7 +364,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// delegate definition to get to the outer command-let /// - internal delegate PSCmdlet OuterCmdletCallback (); + internal delegate PSCmdlet OuterCmdletCallback(); /// /// callback to get to the outer command-let @@ -376,12 +375,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// delegate definition to get to the current pipeline input object /// - internal delegate PSObject InputObjectCallback (); + internal delegate PSObject InputObjectCallback(); /// /// delegate definition to write object /// - internal delegate void WriteObjectCallback (object o); + internal delegate void WriteObjectCallback(object o); /// /// callback to read object @@ -400,7 +399,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// default implementation just delegates to internal helper /// /// This method calls GC.SuppressFinalize - public void Dispose () + public void Dispose() { Dispose(true); @@ -418,7 +417,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// Do-nothing implementation: derived classes will override as see fit /// - protected virtual void InternalDispose () + protected virtual void InternalDispose() { } #endregion diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommand.cs index ea1801544..f1a00390a 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommand.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// constructor to set up the formatting context /// - internal InnerFormatShapeCommandBase () + internal InnerFormatShapeCommandBase() { contextManager.Push(FormattingContextState.none); } @@ -47,9 +47,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// constructor to glue to the CRO /// - internal InnerFormatShapeCommand (FormatShape shape) + internal InnerFormatShapeCommand(FormatShape shape) { - this.shape = shape; + _shape = shape; } internal static int FormatEnumerationLimit() @@ -76,16 +76,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return enumLimitVal is int ? (int)enumLimitVal : InitialSessionState.DefaultFormatEnumerationLimit; } - internal override void BeginProcessing () + internal override void BeginProcessing() { - base.BeginProcessing (); + base.BeginProcessing(); // Get the Format Enumeration Limit. - this.enumerationLimit = InnerFormatShapeCommand.FormatEnumerationLimit(); + _enumerationLimit = InnerFormatShapeCommand.FormatEnumerationLimit(); - this.expressionFactory = new MshExpressionFactory(); + _expressionFactory = new MshExpressionFactory(); - this.formatObjectDeserializer = new FormatObjectDeserializer (this.TerminatingErrorContext); + _formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext); } /// @@ -93,7 +93,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal override void ProcessRecord() { - this._typeInfoDataBase = this.OuterCmdlet().Context.FormatDBManager.GetTypeInfoDataBase(); + _typeInfoDataBase = this.OuterCmdlet().Context.FormatDBManager.GetTypeInfoDataBase(); PSObject so = this.ReadObject(); if (so == null || so == AutomationNull.Value) @@ -137,30 +137,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } break; } - } private EnumerableExpansion GetExpansionState(PSObject so) { // if the command line swtich has been specified, use this as an override - if (this.parameters != null && this.parameters.expansion.HasValue) + if (_parameters != null && _parameters.expansion.HasValue) { - return this.parameters.expansion.Value; + return _parameters.expansion.Value; } // check if we have an expansion entry in format.mshxml var typeNames = so.InternalTypeNames; - return DisplayDataQuery.GetEnumerableExpansionFromType ( - expressionFactory, this._typeInfoDataBase, typeNames); + return DisplayDataQuery.GetEnumerableExpansionFromType( + _expressionFactory, _typeInfoDataBase, typeNames); } - private void ProcessCoreOutOfBand (PSObject so, int count) + private void ProcessCoreOutOfBand(PSObject so, int count) { // emit some description header - SendCommentOutOfBand (FormatAndOut_format_xxx.IEnum_Header); + SendCommentOutOfBand(FormatAndOut_format_xxx.IEnum_Header); // emit the object as out of band - ProcessOutOfBand (so, isProcessingError: false); + ProcessOutOfBand(so, isProcessingError: false); string msg; // emit a comment to signal that the next N objects are from the IEnumerable @@ -182,15 +181,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } break; } - SendCommentOutOfBand (msg); + SendCommentOutOfBand(msg); } - private void SendCommentOutOfBand (string msg) + private void SendCommentOutOfBand(string msg) { - FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandObjectAsToString (PSObjectHelper.AsPSObject (msg)); + FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandObjectAsToString(PSObjectHelper.AsPSObject(msg)); if (fed != null) { - this.WriteObject (fed); + this.WriteObject(fed); } } @@ -198,11 +197,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// execute formatting on a single object /// /// object to process - private void ProcessObject (PSObject so) + private void ProcessObject(PSObject so) { // we do protect against reentrancy, assuming // no fancy multiplexing - if (this.formatObjectDeserializer.IsFormatInfoData (so)) + if (_formatObjectDeserializer.IsFormatInfoData(so)) { // we are already formatted... this.WriteObject(so); @@ -213,7 +212,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // bail now // this is the case of objects coming before the // context manager is properly set - if (ProcessOutOfBandObjectOutsideDocumentSequence (so)) + if (ProcessOutOfBandObjectOutsideDocumentSequence(so)) { return; } @@ -223,10 +222,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (ctx == FormattingContextState.none) { // initialize the view manager - this.viewManager.Initialize(this.TerminatingErrorContext, this.expressionFactory, this._typeInfoDataBase, so, this.shape, this.parameters); + _viewManager.Initialize(this.TerminatingErrorContext, _expressionFactory, _typeInfoDataBase, so, _shape, _parameters); // add the start message to output queue - WriteFormatStartData (so); + WriteFormatStartData(so); // enter the document context contextManager.Push(FormattingContextState.document); @@ -235,7 +234,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // if we are here, we are either in the document document, or in a group // since we have a view now, we check if objects should be treated as out of band - if (ProcessOutOfBandObjectInsideDocumentSequence (so)) + if (ProcessOutOfBandObjectInsideDocumentSequence(so)) { return; } @@ -271,41 +270,41 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - if (this.shape == FormatShape.Undefined || this.parameters == null) + if (_shape == FormatShape.Undefined || _parameters == null) { return true; } - return !this.parameters.forceFormattingAlsoOnOutOfBand; + return !_parameters.forceFormattingAlsoOnOutOfBand; } } - private bool ProcessOutOfBandObjectOutsideDocumentSequence (PSObject so) + private bool ProcessOutOfBandObjectOutsideDocumentSequence(PSObject so) { if (!ShouldProcessOutOfBand) { return false; } - if (so.InternalTypeNames.Count == 0) - { - return false; - } + if (so.InternalTypeNames.Count == 0) + { + return false; + } List errors; - var fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, this.expressionFactory, - this._typeInfoDataBase, so, enumerationLimit, false, out errors); + var fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, _expressionFactory, + _typeInfoDataBase, so, _enumerationLimit, false, out errors); WriteErrorRecords(errors); if (fed != null) { - this.WriteObject (fed); + this.WriteObject(fed); return true; } return false; } - private bool ProcessOutOfBandObjectInsideDocumentSequence (PSObject so) + private bool ProcessOutOfBandObjectInsideDocumentSequence(PSObject so) { if (!ShouldProcessOutOfBand) { @@ -313,19 +312,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } var typeNames = so.InternalTypeNames; - if (this.viewManager.ViewGenerator.IsObjectApplicable(typeNames)) + if (_viewManager.ViewGenerator.IsObjectApplicable(typeNames)) { return false; } - return ProcessOutOfBand (so, isProcessingError: false); + return ProcessOutOfBand(so, isProcessingError: false); } private bool ProcessOutOfBand(PSObject so, bool isProcessingError) { List errors; - FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, this.expressionFactory, - this._typeInfoDataBase, so, enumerationLimit, true, out errors); + FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, _expressionFactory, + _typeInfoDataBase, so, _enumerationLimit, true, out errors); if (!isProcessingError) WriteErrorRecords(errors); @@ -338,30 +337,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - protected void WriteInternalErrorMessage (string message) + protected void WriteInternalErrorMessage(string message) { - FormatEntryData fed = new FormatEntryData (); + FormatEntryData fed = new FormatEntryData(); fed.outOfBand = true; - ComplexViewEntry cve = new ComplexViewEntry (); - FormatEntry fe = new FormatEntry (); - cve.formatValueList.Add (fe); + ComplexViewEntry cve = new ComplexViewEntry(); + FormatEntry fe = new FormatEntry(); + cve.formatValueList.Add(fe); - fe.formatValueList.Add( new FormatNewLine()); + fe.formatValueList.Add(new FormatNewLine()); // get a field for the message - FormatTextField ftf = new FormatTextField (); + FormatTextField ftf = new FormatTextField(); ftf.text = message; - fe.formatValueList.Add (ftf); + fe.formatValueList.Add(ftf); + + fe.formatValueList.Add(new FormatNewLine()); - fe.formatValueList.Add( new FormatNewLine()); - fed.formatEntryInfo = cve; - this.WriteObject (fed); + this.WriteObject(fed); } - private void WriteErrorRecords (List errorRecordList) + private void WriteErrorRecords(List errorRecordList) { if (errorRecordList == null) return; @@ -374,19 +373,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (ErrorRecord errorRecord in errorRecordList) { // we are recursing on formatting errors: isProcessingError == true - ProcessOutOfBand (PSObjectHelper.AsPSObject (errorRecord), true); + ProcessOutOfBand(PSObjectHelper.AsPSObject(errorRecord), true); } } - internal override void EndProcessing () + internal override void EndProcessing() { // need to pop all the contexts, in case the transmission sequence // was interrupted while (true) { FormattingContextState ctx = contextManager.Peek(); - + if (ctx == FormattingContextState.none) { break; // we emerged and we are done @@ -402,14 +401,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this.WriteObject(endFormat); contextManager.Pop(); } - } // while } - internal void SetCommandLineParameters (FormattingCommandLineParameters commandLineParameters) + internal void SetCommandLineParameters(FormattingCommandLineParameters commandLineParameters) { Diagnostics.Assert(commandLineParameters != null, "the caller has to pass a valid instance"); - parameters = commandLineParameters; + _parameters = commandLineParameters; } /// @@ -425,14 +423,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object receoved from the input pipeline /// GroupTransition enumeration - private GroupTransition ComputeGroupTransition (PSObject so) + private GroupTransition ComputeGroupTransition(PSObject so) { // check if we have to start a group FormattingContextState ctx = contextManager.Peek(); if (ctx == FormattingContextState.document) { // prime the grouping algorithm - this.viewManager.ViewGenerator.UpdateGroupingKeyValue (so); + _viewManager.ViewGenerator.UpdateGroupingKeyValue(so); // need to start a group, but we are not in one return GroupTransition.enter; @@ -440,13 +438,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // check if we need to start another group and keep track // of the current value for the grouping property - return this.viewManager.ViewGenerator.UpdateGroupingKeyValue (so) ? GroupTransition.startNew : GroupTransition.none; + return _viewManager.ViewGenerator.UpdateGroupingKeyValue(so) ? GroupTransition.startNew : GroupTransition.none; } - private void WriteFormatStartData (PSObject so) + private void WriteFormatStartData(PSObject so) { - FormatStartData startFormat = this.viewManager.ViewGenerator.GenerateStartData (so); - this.WriteObject (startFormat); + FormatStartData startFormat = _viewManager.ViewGenerator.GenerateStartData(so); + this.WriteObject(startFormat); } @@ -455,17 +453,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// a FormatEntry object /// /// object to process - private void WritePayloadObject (PSObject so) + private void WritePayloadObject(PSObject so) { - Diagnostics.Assert (so != null, "object so cannot be null"); - FormatEntryData fed = this.viewManager.ViewGenerator.GeneratePayload (so, enumerationLimit); + Diagnostics.Assert(so != null, "object so cannot be null"); + FormatEntryData fed = _viewManager.ViewGenerator.GeneratePayload(so, _enumerationLimit); fed.SetStreamTypeFromPSObject(so); - this.WriteObject (fed); + this.WriteObject(fed); - List errors = this.viewManager.ViewGenerator.ErrorManager.DrainFailedResultList (); - WriteErrorRecords (errors); + List errors = _viewManager.ViewGenerator.ErrorManager.DrainFailedResultList(); + WriteErrorRecords(errors); } - + /// /// inject the start group information /// and push group context on stack @@ -474,7 +472,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// that is starting the group private void PushGroup(PSObject firstObjectInGroup) { - GroupStartData startGroup = this.viewManager.ViewGenerator.GenerateGroupStartData(firstObjectInGroup, enumerationLimit); + GroupStartData startGroup = _viewManager.ViewGenerator.GenerateGroupStartData(firstObjectInGroup, _enumerationLimit); this.WriteObject(startGroup); contextManager.Push(FormattingContextState.group); } @@ -485,7 +483,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private void PopGroup() { - GroupEndData endGroup = this.viewManager.ViewGenerator.GenerateGroupEndData (); + GroupEndData endGroup = _viewManager.ViewGenerator.GenerateGroupEndData(); this.WriteObject(endGroup); contextManager.Pop(); } @@ -493,30 +491,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// the formatting shape this formatter emits /// - private FormatShape shape; + private FormatShape _shape; #region expression factory /// - internal ScriptBlock CreateScriptBlock (string scriptText) + internal ScriptBlock CreateScriptBlock(string scriptText) { - var scriptBlock = this.OuterCmdlet ().InvokeCommand.NewScriptBlock (scriptText); + var scriptBlock = this.OuterCmdlet().InvokeCommand.NewScriptBlock(scriptText); scriptBlock.DebuggerStepThrough = true; return scriptBlock; } - private MshExpressionFactory expressionFactory; + private MshExpressionFactory _expressionFactory; #endregion - private FormatObjectDeserializer formatObjectDeserializer; + private FormatObjectDeserializer _formatObjectDeserializer; private TypeInfoDataBase _typeInfoDataBase = null; - private FormattingCommandLineParameters parameters = null; - private FormatViewManager viewManager = new FormatViewManager(); + private FormattingCommandLineParameters _parameters = null; + private FormatViewManager _viewManager = new FormatViewManager(); - private int enumerationLimit = InitialSessionState.DefaultFormatEnumerationLimit; + private int _enumerationLimit = InitialSessionState.DefaultFormatEnumerationLimit; } /// @@ -533,10 +531,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format [Parameter] public object GroupBy { - get { return groupByParameter; } - set { groupByParameter = value; } + get { return _groupByParameter; } + set { _groupByParameter = value; } } - private object groupByParameter = null; + private object _groupByParameter = null; /// @@ -546,10 +544,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format [Parameter] public string View { - get { return viewName; } - set { viewName = value; } + get { return _viewName; } + set { _viewName = value; } } - private string viewName = null; + private string _viewName = null; /// /// optional, non positional parameter @@ -593,43 +591,43 @@ namespace Microsoft.PowerShell.Commands.Internal.Format [Parameter] public SwitchParameter Force { - get { return forceFormattingAlsoOnOutOfBand; } - set { forceFormattingAlsoOnOutOfBand = value; } + get { return _forceFormattingAlsoOnOutOfBand; } + set { _forceFormattingAlsoOnOutOfBand = value; } } - private bool forceFormattingAlsoOnOutOfBand; + private bool _forceFormattingAlsoOnOutOfBand; /// /// optional, non positional parameter /// /// [Parameter] - [ValidateSet (EnumerableExpansionConversion.CoreOnlyString, + [ValidateSet(EnumerableExpansionConversion.CoreOnlyString, EnumerableExpansionConversion.EnumOnlyString, EnumerableExpansionConversion.BothString, IgnoreCase = true)] public string Expand { get { - return expansionString; + return _expansionString; } set { - expansionString = value; + _expansionString = value; } } - private string expansionString = null; + private string _expansionString = null; internal Nullable expansion = null; - internal Nullable ProcessExpandParameter () + internal Nullable ProcessExpandParameter() { Nullable retVal = null; - if (string.IsNullOrEmpty (this.expansionString)) + if (string.IsNullOrEmpty(_expansionString)) { return retVal; } EnumerableExpansion temp; - bool success = EnumerableExpansionConversion.Convert (this.expansionString, out temp); + bool success = EnumerableExpansionConversion.Convert(_expansionString, out temp); if (!success) { // this should never happen, since we use the [ValidateSet] attribute @@ -640,15 +638,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return retVal; } - internal MshParameter ProcessGroupByParameter () + internal MshParameter ProcessGroupByParameter() { - if (this.groupByParameter != null) + if (_groupByParameter != null) { - TerminatingErrorContext invocationContext = - new TerminatingErrorContext (this); - ParameterProcessor processor = new ParameterProcessor (new FormatGroupByParameterDefinition ()); - List groupParameterList = - processor.ProcessParameters (new object[] { this.groupByParameter }, + TerminatingErrorContext invocationContext = + new TerminatingErrorContext(this); + ParameterProcessor processor = new ParameterProcessor(new FormatGroupByParameterDefinition()); + List groupParameterList = + processor.ProcessParameters(new object[] { _groupByParameter }, invocationContext); if (groupParameterList.Count != 0) @@ -666,12 +664,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// protected override void BeginProcessing() { - InnerFormatShapeCommand innerFormatCommand = + InnerFormatShapeCommand innerFormatCommand = (InnerFormatShapeCommand)this.implementation; // read command line switches and pass them to the inner command FormattingCommandLineParameters parameters = GetCommandLineParameters(); - innerFormatCommand.SetCommandLineParameters (parameters); + innerFormatCommand.SetCommandLineParameters(parameters); // must call base class for further processing base.BeginProcessing(); @@ -688,18 +686,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - internal void ReportCannotSpecifyViewAndProperty () + internal void ReportCannotSpecifyViewAndProperty() { string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyViewAndPropertyError); - ErrorRecord errorRecord = new ErrorRecord ( - new InvalidDataException (), + ErrorRecord errorRecord = new ErrorRecord( + new InvalidDataException(), "FormatCannotSpecifyViewAndProperty", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); } } @@ -716,24 +714,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// The paramater is optional, since the defaults /// will be determined using property sets, etc. /// - [Parameter(Position=0)] + [Parameter(Position = 0)] public object[] Property { - get { return props; } - set { props = value; } + get { return _props; } + set { _props = value; } } - private object[] props; + private object[] _props; #endregion - internal override FormattingCommandLineParameters GetCommandLineParameters () + internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters (); + FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); + + GetCommandLineProperties(parameters, false); + parameters.groupByParameter = this.ProcessGroupByParameter(); - GetCommandLineProperties (parameters,false); - parameters.groupByParameter = this.ProcessGroupByParameter (); - parameters.forceFormattingAlsoOnOutOfBand = this.Force; if (this.showErrorsAsMessages.HasValue) parameters.showErrorsAsMessages = this.showErrorsAsMessages; @@ -745,28 +743,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return parameters; } - internal void GetCommandLineProperties (FormattingCommandLineParameters parameters, bool isTable) + internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable) { - if (this.props != null) + if (_props != null) { CommandParameterDefinition def; if (isTable) - def = new FormatTableParameterDefinition (); + def = new FormatTableParameterDefinition(); else - def = new FormatListParameterDefinition (); - ParameterProcessor processor = new ParameterProcessor (def); - TerminatingErrorContext invocationContext = new TerminatingErrorContext (this); + def = new FormatListParameterDefinition(); + ParameterProcessor processor = new ParameterProcessor(def); + TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); - parameters.mshParameterList = processor.ProcessParameters (this.props, invocationContext); + parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext); } - if (!string.IsNullOrEmpty (this.View)) + if (!string.IsNullOrEmpty(this.View)) { // we have a view command line switch if (parameters.mshParameterList.Count != 0) { - ReportCannotSpecifyViewAndProperty (); + ReportCannotSpecifyViewAndProperty(); } parameters.viewName = this.View; } @@ -787,15 +785,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format [Parameter] public SwitchParameter AutoSize { - get + get { - if (autosize.HasValue) - return autosize.Value; - return false; + if (_autosize.HasValue) + return _autosize.Value; + return false; } - set { autosize = value; } + set { _autosize = value; } } - private Nullable autosize = null; + private Nullable _autosize = null; /// /// optional, non positional parameter @@ -806,13 +804,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - if (hideHeaders.HasValue) - return hideHeaders.Value; + if (_hideHeaders.HasValue) + return _hideHeaders.Value; return false; } - set { hideHeaders = value; } + set { _hideHeaders = value; } } - private Nullable hideHeaders = null; + private Nullable _hideHeaders = null; /// /// optional, non positional parameter @@ -823,50 +821,49 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - if (multiLine.HasValue) - return multiLine.Value; + if (_multiLine.HasValue) + return _multiLine.Value; return false; } - set { multiLine = value; } + set { _multiLine = value; } } - private Nullable multiLine = null; + private Nullable _multiLine = null; #endregion - internal override FormattingCommandLineParameters GetCommandLineParameters () + internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters (); + FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); - GetCommandLineProperties (parameters, true); + GetCommandLineProperties(parameters, true); parameters.forceFormattingAlsoOnOutOfBand = this.Force; if (this.showErrorsAsMessages.HasValue) parameters.showErrorsAsMessages = this.showErrorsAsMessages; if (this.showErrorsInFormattedOutput.HasValue) parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput; - parameters.expansion = ProcessExpandParameter (); + parameters.expansion = ProcessExpandParameter(); - if (this.autosize.HasValue) - parameters.autosize = this.autosize.Value; + if (_autosize.HasValue) + parameters.autosize = _autosize.Value; - parameters.groupByParameter = this.ProcessGroupByParameter (); + parameters.groupByParameter = this.ProcessGroupByParameter(); - TableSpecificParameters tableParameters = new TableSpecificParameters (); + TableSpecificParameters tableParameters = new TableSpecificParameters(); parameters.shapeParameters = tableParameters; - if (this.hideHeaders.HasValue) + if (_hideHeaders.HasValue) { - tableParameters.hideHeaders = this.hideHeaders.Value; + tableParameters.hideHeaders = _hideHeaders.Value; } - if (this.multiLine.HasValue) + if (_multiLine.HasValue) { - tableParameters.multiLine = this.multiLine.Value; + tableParameters.multiLine = _multiLine.Value; } return parameters; } } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 06b1c9bd7..4a8864d0b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -11,7 +12,6 @@ using System.ComponentModel; namespace Microsoft.PowerShell.Commands.Internal.Format { - #region Formatting Command Line Parameters /// @@ -25,7 +25,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// MshParameter collection, as specified by metadata /// the list can be empty of no data is specified /// - internal List mshParameterList = new List (); + internal List mshParameterList = new List(); /// /// name of the group by property, it can be null @@ -111,23 +111,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// specialized class for the "expression" property /// - class ExpressionEntryDefinition : HashtableEntryDefinition + internal class ExpressionEntryDefinition : HashtableEntryDefinition { - internal ExpressionEntryDefinition () : this(false) + internal ExpressionEntryDefinition() : this(false) { } - internal ExpressionEntryDefinition (bool noGlobbing) : base(FormatParameterDefinitionKeys.ExpressionEntryKey, - new Type[] {typeof(string), typeof(ScriptBlock)}, true) + internal ExpressionEntryDefinition(bool noGlobbing) : base(FormatParameterDefinitionKeys.ExpressionEntryKey, + new Type[] { typeof(string), typeof(ScriptBlock) }, true) { - this._noGlobbing = noGlobbing; + _noGlobbing = noGlobbing; } - internal override Hashtable CreateHashtableFromSingleType (object val) + internal override Hashtable CreateHashtableFromSingleType(object val) { - Hashtable hash = new Hashtable (); + Hashtable hash = new Hashtable(); - hash.Add (FormatParameterDefinitionKeys.ExpressionEntryKey, val); + hash.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, val); return hash; } @@ -162,13 +162,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } #endif - internal override object Verify (object val, + internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { if (val == null) { - throw PSTraceSource.NewArgumentNullException ("val"); + throw PSTraceSource.NewArgumentNullException("val"); } // need to check the type: @@ -176,32 +176,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ScriptBlock sb = val as ScriptBlock; if (sb != null) { - MshExpression ex = new MshExpression (sb); + MshExpression ex = new MshExpression(sb); return ex; } string s = val as string; if (s != null) { - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) { - ProcessEmptyStringError (originalParameterWasHashTable, invocationContext); + ProcessEmptyStringError(originalParameterWasHashTable, invocationContext); } - MshExpression ex = new MshExpression (s); + MshExpression ex = new MshExpression(s); if (_noGlobbing) { if (ex.HasWildCardCharacters) - ProcessGlobbingCharactersError (originalParameterWasHashTable, s, invocationContext); + ProcessGlobbingCharactersError(originalParameterWasHashTable, s, invocationContext); } return ex; } - PSTraceSource.NewArgumentException ("val"); + PSTraceSource.NewArgumentException("val"); return null; } #region Error Processing - private void ProcessEmptyStringError (bool originalParameterWasHashTable, + private void ProcessEmptyStringError(bool originalParameterWasHashTable, TerminatingErrorContext invocationContext) { string msg; @@ -218,10 +218,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format errorID = "ExpressionEmptyString2"; } - ParameterProcessor.ThrowParameterBindingException (invocationContext, errorID, msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, errorID, msg); } - private void ProcessGlobbingCharactersError (bool originalParameterWasHashTable, string expression, TerminatingErrorContext invocationContext) + private void ProcessGlobbingCharactersError(bool originalParameterWasHashTable, string expression, TerminatingErrorContext invocationContext) { string msg; string errorID; @@ -238,7 +238,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format errorID = "ExpressionGlobbing2"; } - ParameterProcessor.ThrowParameterBindingException (invocationContext, errorID, msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, errorID, msg); } #endregion @@ -246,32 +246,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private bool _noGlobbing; } - class AligmentEntryDefinition : HashtableEntryDefinition + internal class AligmentEntryDefinition : HashtableEntryDefinition { - internal AligmentEntryDefinition () : base(FormatParameterDefinitionKeys.AligmentEntryKey, - new Type[] {typeof(string)}) + internal AligmentEntryDefinition() : base(FormatParameterDefinitionKeys.AligmentEntryKey, + new Type[] { typeof(string) }) { } - internal override object Verify (object val, + internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { if (!originalParameterWasHashTable) { // this should never happen - throw PSTraceSource.NewInvalidOperationException (); + throw PSTraceSource.NewInvalidOperationException(); } // it is a string, need to check for partial match in a case insensitive way // and normalize string s = val as string; - if (!string.IsNullOrEmpty (s)) + if (!string.IsNullOrEmpty(s)) { - for (int k = 0; k < legalValues.Length; k++) + for (int k = 0; k < s_legalValues.Length; k++) { - if (CommandParameterDefinition.FindPartialMatch (s, legalValues[k])) + if (CommandParameterDefinition.FindPartialMatch(s, s_legalValues[k])) { if (k == 0) return TextAlignment.Left; @@ -285,125 +285,123 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // nothing found, we have an illegal value - ProcessIllegalValue (s, invocationContext); + ProcessIllegalValue(s, invocationContext); return null; } #region Error Processing - private void ProcessIllegalValue (string s, TerminatingErrorContext invocationContext) + private void ProcessIllegalValue(string s, TerminatingErrorContext invocationContext) { string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalAlignmentValueError, s, this.KeyName, - ParameterProcessor.CatenateStringArray (legalValues) + ParameterProcessor.CatenateStringArray(s_legalValues) ); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "AlignmentIllegalValue", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "AlignmentIllegalValue", msg); } #endregion - private readonly static string[] legalValues = new string[] { LeftAlign, CenterAlign, RightAlign }; + private readonly static string[] s_legalValues = new string[] { LeftAlign, CenterAlign, RightAlign }; private const string LeftAlign = "left"; private const string CenterAlign = "center"; private const string RightAlign = "right"; } - class WidthEntryDefinition : HashtableEntryDefinition + internal class WidthEntryDefinition : HashtableEntryDefinition { - internal WidthEntryDefinition () : base(FormatParameterDefinitionKeys.WidthEntryKey, - new Type[] {typeof(int)}) + internal WidthEntryDefinition() : base(FormatParameterDefinitionKeys.WidthEntryKey, + new Type[] { typeof(int) }) { } - internal override object Verify (object val, + internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { if (!originalParameterWasHashTable) { // this should never happen - throw PSTraceSource.NewInvalidOperationException (); + throw PSTraceSource.NewInvalidOperationException(); } // it's an int, just check range, no need to change it - VerifyRange ((int)val, invocationContext); + VerifyRange((int)val, invocationContext); return null; } - private void VerifyRange (int width, TerminatingErrorContext invocationContext) + private void VerifyRange(int width, TerminatingErrorContext invocationContext) { if (width <= 0) { string msg = StringUtil.Format(FormatAndOut_MshParameter.OutOfRangeWidthValueError, - width, + width, this.KeyName ); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "WidthOutOfRange", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "WidthOutOfRange", msg); } } } - class LabelEntryDefinition : HashtableEntryDefinition + internal class LabelEntryDefinition : HashtableEntryDefinition { - internal LabelEntryDefinition () : base(FormatParameterDefinitionKeys.LabelEntryKey, new string[] {NameEntryDefinition.NameEntryKey} ,new Type[] {typeof(string)}, false) + internal LabelEntryDefinition() : base(FormatParameterDefinitionKeys.LabelEntryKey, new string[] { NameEntryDefinition.NameEntryKey }, new Type[] { typeof(string) }, false) { } } - class FormatStringDefinition : HashtableEntryDefinition + internal class FormatStringDefinition : HashtableEntryDefinition { - internal FormatStringDefinition () : base(FormatParameterDefinitionKeys.FormatStringEntryKey, - new Type[] {typeof(string)}) + internal FormatStringDefinition() : base(FormatParameterDefinitionKeys.FormatStringEntryKey, + new Type[] { typeof(string) }) { } - internal override object Verify (object val, + internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { if (!originalParameterWasHashTable) { // this should never happen - throw PSTraceSource.NewInvalidOperationException (); + throw PSTraceSource.NewInvalidOperationException(); } string s = val as string; - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) { string msg = StringUtil.Format(FormatAndOut_MshParameter.EmptyFormatStringValueError, this.KeyName ); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "FormatStringEmpty", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "FormatStringEmpty", msg); } // we expect a string and we build a field formatting directive - FieldFormattingDirective directive = new FieldFormattingDirective (); + FieldFormattingDirective directive = new FieldFormattingDirective(); directive.formatString = s; return directive; } - - } - class BooleanEntryDefinition : HashtableEntryDefinition + internal class BooleanEntryDefinition : HashtableEntryDefinition { - internal BooleanEntryDefinition (string entryKey) : base(entryKey, null) + internal BooleanEntryDefinition(string entryKey) : base(entryKey, null) { } - internal override object Verify (object val, + internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { if (!originalParameterWasHashTable) { // this should never happen - throw PSTraceSource.NewInvalidOperationException (); + throw PSTraceSource.NewInvalidOperationException(); } - return LanguagePrimitives.IsTrue (val); + return LanguagePrimitives.IsTrue(val); } } @@ -434,40 +432,40 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal class FormatGroupByParameterDefinition : CommandParameterDefinition { - protected override void SetEntries () + protected override void SetEntries() { - this.hashEntries.Add (new ExpressionEntryDefinition ()); - this.hashEntries.Add (new FormatStringDefinition ()); - this.hashEntries.Add (new LabelEntryDefinition ()); + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new FormatStringDefinition()); + this.hashEntries.Add(new LabelEntryDefinition()); } } internal class FormatParameterDefinitionBase : CommandParameterDefinition { - protected override void SetEntries () + protected override void SetEntries() { - this.hashEntries.Add (new ExpressionEntryDefinition ()); - this.hashEntries.Add (new FormatStringDefinition ()); + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new FormatStringDefinition()); } } internal class FormatTableParameterDefinition : FormatParameterDefinitionBase { - protected override void SetEntries () + protected override void SetEntries() { - base.SetEntries (); - this.hashEntries.Add (new WidthEntryDefinition ()); - this.hashEntries.Add (new AligmentEntryDefinition ()); - this.hashEntries.Add (new LabelEntryDefinition ()); + base.SetEntries(); + this.hashEntries.Add(new WidthEntryDefinition()); + this.hashEntries.Add(new AligmentEntryDefinition()); + this.hashEntries.Add(new LabelEntryDefinition()); } } internal class FormatListParameterDefinition : FormatParameterDefinitionBase { - protected override void SetEntries () + protected override void SetEntries() { - base.SetEntries (); - this.hashEntries.Add (new LabelEntryDefinition ()); + base.SetEntries(); + this.hashEntries.Add(new LabelEntryDefinition()); } } @@ -478,13 +476,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal class FormatObjectParameterDefinition : CommandParameterDefinition { - protected override void SetEntries () + protected override void SetEntries() { - this.hashEntries.Add (new ExpressionEntryDefinition ()); - this.hashEntries.Add (new HashtableEntryDefinition (FormatParameterDefinitionKeys.DepthEntryKey, new Type[] { typeof(int) })); + this.hashEntries.Add(new ExpressionEntryDefinition()); + this.hashEntries.Add(new HashtableEntryDefinition(FormatParameterDefinitionKeys.DepthEntryKey, new Type[] { typeof(int) })); } } #endregion - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseOutputtingCommand.cs index 3eec55ea0..eb5f6dbfa 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -17,26 +17,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// it manages the formatting protocol and it writes to a generic /// screen host /// - class OutCommandInner : ImplementationCommandBase + internal class OutCommandInner : ImplementationCommandBase { #region tracer - [TraceSource ("format_out_OutCommandInner", "OutCommandInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer ("format_out_OutCommandInner", "OutCommandInner"); + [TraceSource("format_out_OutCommandInner", "OutCommandInner")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner"); #endregion tracer internal override void BeginProcessing() { - base.BeginProcessing (); + base.BeginProcessing(); - this.formatObjectDeserializer = new FormatObjectDeserializer (this.TerminatingErrorContext); + _formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext); // hook up the event handlers for the context manager object - this.ctxManager.contextCreation = new FormatMessagesContextManager.FormatContextCreationCallback (this.CreateOutputContext); - this.ctxManager.fs = new FormatMessagesContextManager.FormatStartCallback (this.ProcessFormatStart); - this.ctxManager.fe = new FormatMessagesContextManager.FormatEndCallback (this.ProcessFormatEnd); - this.ctxManager.gs = new FormatMessagesContextManager.GroupStartCallback (this.ProcessGroupStart); - this.ctxManager.ge = new FormatMessagesContextManager.GroupEndCallback (this.ProcessGroupEnd); - this.ctxManager.payload = new FormatMessagesContextManager.PayloadCallback (this.ProcessPayload); + _ctxManager.contextCreation = new FormatMessagesContextManager.FormatContextCreationCallback(this.CreateOutputContext); + _ctxManager.fs = new FormatMessagesContextManager.FormatStartCallback(this.ProcessFormatStart); + _ctxManager.fe = new FormatMessagesContextManager.FormatEndCallback(this.ProcessFormatEnd); + _ctxManager.gs = new FormatMessagesContextManager.GroupStartCallback(this.ProcessGroupStart); + _ctxManager.ge = new FormatMessagesContextManager.GroupEndCallback(this.ProcessGroupEnd); + _ctxManager.payload = new FormatMessagesContextManager.PayloadCallback(this.ProcessPayload); } /// @@ -47,17 +47,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal override void ProcessRecord() { - PSObject so = this.ReadObject (); + PSObject so = this.ReadObject(); if (so == null || so == AutomationNull.Value) return; // try to process the object - if (ProcessObject (so)) + if (ProcessObject(so)) return; // send to the formatter for preprocessing - Array results = ApplyFormatting (so); + Array results = ApplyFormatting(so); if (results != null) { @@ -72,13 +72,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - internal override void EndProcessing () + internal override void EndProcessing() { - base.EndProcessing (); - if (this.command != null) + base.EndProcessing(); + if (_command != null) { // shut down the command processor, if we ever used it - Array results = this.command.ShutDown (); + Array results = _command.ShutDown(); if (results != null) { @@ -93,29 +93,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // we need to notify the interface implementor that // we are about to do the playback - LineOutput.DoPlayBackCall playBackCall = new LineOutput.DoPlayBackCall (this.DrainCache); + LineOutput.DoPlayBackCall playBackCall = new LineOutput.DoPlayBackCall(this.DrainCache); - this.LineOutput.ExecuteBufferPlayBack (playBackCall); + this.LineOutput.ExecuteBufferPlayBack(playBackCall); } else { // we drain the cache ourselves - DrainCache (); + DrainCache(); } } private void DrainCache() { - if (this.cache != null) + if (_cache != null) { // drain the cache, since we are shutting down - List unprocessedObjects = this.cache.Drain (); + List unprocessedObjects = _cache.Drain(); if (unprocessedObjects != null) { foreach (object obj in unprocessedObjects) { - ctxManager.Process (obj); + _ctxManager.Process(obj); } } } @@ -124,18 +124,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private bool ProcessObject(PSObject so) { - object o = this.formatObjectDeserializer.Deserialize (so); + object o = _formatObjectDeserializer.Deserialize(so); //Console.WriteLine("OutCommandInner.Execute() retrieved object {0}, of type {1}", o.ToString(), o.GetType()); if (NeedsPreprocessing(o)) { return false; } - + // instantiate the cache if not done yet - if (this.cache == null) + if (_cache == null) { - this.cache = new FormattedObjectsCache(this.LineOutput.RequiresBuffering); + _cache = new FormattedObjectsCache(this.LineOutput.RequiresBuffering); } // no need for formatting, just process the object @@ -148,7 +148,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (formatStart.autosizeInfo != null) { FormattedObjectsCache.ProcessCachedGroupNotification callBack = new FormattedObjectsCache.ProcessCachedGroupNotification(ProcessCachedGroup); - this.cache.EnableGroupCaching(callBack, formatStart.autosizeInfo.objectCount); + _cache.EnableGroupCaching(callBack, formatStart.autosizeInfo.objectCount); } else { @@ -159,28 +159,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format (headerInfo.tableColumnInfoList[0].width == 0)) { FormattedObjectsCache.ProcessCachedGroupNotification callBack = new FormattedObjectsCache.ProcessCachedGroupNotification(ProcessCachedGroup); - this.cache.EnableGroupCaching(callBack, TimeSpan.FromMilliseconds(300)); + _cache.EnableGroupCaching(callBack, TimeSpan.FromMilliseconds(300)); } } } //Console.WriteLine("OutCommandInner.Execute() calling ctxManager.Process({0})",o.ToString()); - List info = this.cache.Add((PacketInfoData)o); + List info = _cache.Add((PacketInfoData)o); if (info != null) { for (int k = 0; k < info.Count; k++) - ctxManager.Process(info[k]); + _ctxManager.Process(info[k]); } return true; } - + /// /// helper to return what shape we have to use to format the output /// private FormatShape ActiveFormattingShape { - get + get { // we assume that the format context // contains the information @@ -206,13 +206,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - protected override void InternalDispose () + protected override void InternalDispose() { - base.InternalDispose (); - if (this.command != null) + base.InternalDispose(); + if (_command != null) { - this.command.Dispose (); - this.command = null; + _command.Dispose(); + _command = null; } } @@ -220,36 +220,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// enum describing the state for the output finite state machine /// - private enum FormattingState - { + private enum FormattingState + { /// /// we are in the clear state: no formatting in process /// - Reset, - + Reset, + /// /// we received a Format Start message, but we are not inside a group /// - Formatting, - + Formatting, + /// /// we are inside a group because we received a Group Start /// - InsideGroup + InsideGroup } /// /// toggle to signal if we are in a formatting sequence /// - private FormattingState currentFormattingState = FormattingState.Reset; + private FormattingState _currentFormattingState = FormattingState.Reset; /// /// instance of a command wrapper to execute the /// default formatter when needed /// - private CommandWrapper command; - + private CommandWrapper _command; + /// /// enumeration to drive the preprocessing stage @@ -279,7 +279,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // when encountering FormatStartDate out of sequemce, // pretend that the previous formatting directives were properly closed - if (this.currentFormattingState == FormattingState.InsideGroup) + if (_currentFormattingState == FormattingState.InsideGroup) { this.EndProcessing(); this.BeginProcessing(); @@ -287,7 +287,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we got a Fs message, we enter a sequence ValidateCurrentFormattingState(FormattingState.Reset, o); - this.currentFormattingState = FormattingState.Formatting; + _currentFormattingState = FormattingState.Formatting; return false; } @@ -295,21 +295,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // we got a Fe message, we exit a sequence ValidateCurrentFormattingState(FormattingState.Formatting, o); - this.currentFormattingState = FormattingState.Reset; + _currentFormattingState = FormattingState.Reset; return false; } else if (o is GroupStartData) { ValidateCurrentFormattingState(FormattingState.Formatting, o); - this.currentFormattingState = FormattingState.InsideGroup; + _currentFormattingState = FormattingState.InsideGroup; return false; } else if (o is GroupEndData) { ValidateCurrentFormattingState(FormattingState.InsideGroup, o); - this.currentFormattingState = FormattingState.Formatting; + _currentFormattingState = FormattingState.Formatting; return false; } @@ -321,7 +321,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private void ValidateCurrentFormattingState(FormattingState expectedFormattingState, object obj) { // chec if we are in the expected formatting state - if (this.currentFormattingState != expectedFormattingState) + if (_currentFormattingState != expectedFormattingState) { // we are not in the expected state, some message is out of sequence, // need to abort the command @@ -351,13 +351,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format string msg = StringUtil.Format(FormatAndOut_out_xxx.OutLineOutput_OutOfSequencePacket, obj.GetType().FullName, violatingCommand); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(), "ConsoleLineOutputOutOfSequencePacket", ErrorCategory.InvalidData, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); + errorRecord.ErrorDetails = new ErrorDetails(msg); this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } } @@ -367,15 +367,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to be preprocessed /// array of objects returned by the preprocessing step - private Array ApplyFormatting (object o) + private Array ApplyFormatting(object o) { - if (this.command == null) + if (_command == null) { - this.command = new CommandWrapper (); - this.command.Initialize(this.OuterCmdlet().Context, "format-default", typeof(FormatDefaultCommand)); + _command = new CommandWrapper(); + _command.Initialize(this.OuterCmdlet().Context, "format-default", typeof(FormatDefaultCommand)); } - return this.command.Process (o); + return _command.Process(o); } /// @@ -407,35 +407,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { case FormatShape.Table: { - goc = new TableOutputContext (this, parentContext, gsd); + goc = new TableOutputContext(this, parentContext, gsd); break; } case FormatShape.List: { - goc = new ListOutputContext (this, parentContext, gsd); + goc = new ListOutputContext(this, parentContext, gsd); break; } case FormatShape.Wide: { - goc = new WideOutputContext (this, parentContext, gsd); + goc = new WideOutputContext(this, parentContext, gsd); break; } case FormatShape.Complex: { - goc = new ComplexOutputContext (this, parentContext, gsd); + goc = new ComplexOutputContext(this, parentContext, gsd); break; } default: { - Diagnostics.Assert (false, "Invalid shape. This should never happen"); + Diagnostics.Assert(false, "Invalid shape. This should never happen"); } break; } - goc.Initialize (); + goc.Initialize(); return goc; } @@ -449,7 +449,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private void ProcessFormatStart(FormatMessagesContextManager.OutputContext c) { // we just add an empty line to the display - this.LineOutput.WriteLine (""); + this.LineOutput.WriteLine(""); } /// @@ -461,7 +461,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { //Console.WriteLine("ProcessFormatEnd"); // we just add an empty line to the display - this.LineOutput.WriteLine (""); + this.LineOutput.WriteLine(""); } /// @@ -476,15 +476,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (goc.Data.groupingEntry != null) { - this.lo.WriteLine (""); + _lo.WriteLine(""); - ComplexWriter writer = new ComplexWriter (); - writer.Initialize (this.lo, this.lo.ColumnNumber); - writer.WriteObject (goc.Data.groupingEntry.formatValueList); + ComplexWriter writer = new ComplexWriter(); + writer.Initialize(_lo, _lo.ColumnNumber); + writer.WriteObject(goc.Data.groupingEntry.formatValueList); - this.LineOutput.WriteLine (""); + this.LineOutput.WriteLine(""); } - goc.GroupStart (); + goc.GroupStart(); } /// @@ -497,8 +497,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format //Console.WriteLine("ProcessGroupEnd"); GroupOutputContext goc = (GroupOutputContext)c; - goc.GroupEnd (); - this.LineOutput.WriteLine (""); + goc.GroupEnd(); + this.LineOutput.WriteLine(""); } /// @@ -511,17 +511,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we assume FormatEntryData as a standard wrapper if (fed == null) { - PSTraceSource.NewArgumentNullException ("fed"); + PSTraceSource.NewArgumentNullException("fed"); } if (fed.formatEntryInfo == null) { - PSTraceSource.NewArgumentNullException ("fed.formatEntryInfo"); + PSTraceSource.NewArgumentNullException("fed.formatEntryInfo"); } - WriteStreamType oldWSState = this.lo.WriteStream; + WriteStreamType oldWSState = _lo.WriteStream; try { - this.lo.WriteStream = fed.writeStream; + _lo.WriteStream = fed.writeStream; if (c == null) { @@ -536,11 +536,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } finally { - this.lo.WriteStream = oldWSState; + _lo.WriteStream = oldWSState; } } - private void ProcessOutOfBandPayload (FormatEntryData fed) + private void ProcessOutOfBandPayload(FormatEntryData fed) { // try if it is raw text RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry; @@ -550,13 +550,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { ComplexWriter complexWriter = new ComplexWriter(); - complexWriter.Initialize(this.lo, this.lo.ColumnNumber); + complexWriter.Initialize(_lo, _lo.ColumnNumber); complexWriter.WriteString(rte.text); } else { - this.lo.WriteLine(rte.text); - + _lo.WriteLine(rte.text); } return; @@ -566,10 +565,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; if (cve != null && cve.formatValueList != null) { - ComplexWriter complexWriter = new ComplexWriter (); + ComplexWriter complexWriter = new ComplexWriter(); - complexWriter.Initialize (this.lo, this.lo.ColumnNumber); - complexWriter.WriteObject (cve.formatValueList); + complexWriter.Initialize(_lo, _lo.ColumnNumber); + complexWriter.WriteObject(cve.formatValueList); return; } @@ -577,16 +576,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; if (lve != null && lve.listViewFieldList != null) { - ListWriter listWriter = new ListWriter (); + ListWriter listWriter = new ListWriter(); - this.lo.WriteLine (""); + _lo.WriteLine(""); - string[] properties = ListOutputContext.GetProperties (lve); - listWriter.Initialize (properties, this.lo.ColumnNumber, this.lo.DisplayCells); - string[] values = ListOutputContext.GetValues (lve); - listWriter.WriteProperties (values, this.lo); - - this.lo.WriteLine (""); + string[] properties = ListOutputContext.GetProperties(lve); + listWriter.Initialize(properties, _lo.ColumnNumber, _lo.DisplayCells); + string[] values = ListOutputContext.GetValues(lve); + listWriter.WriteProperties(values, _lo); + + _lo.WriteLine(""); return; } @@ -595,12 +594,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// the screen host associated with this outputter /// - private LineOutput lo = null; + private LineOutput _lo = null; internal LineOutput LineOutput { - set { this.lo = value; } - get { return this.lo; } + set { _lo = value; } + get { return _lo; } } private ShapeInfo ShapeInfoOnFormatContext @@ -615,7 +614,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return foc.Data.shapeInfo; } } - + /// /// retrieve the active FormatOutputContext on the stack @@ -625,7 +624,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - for (FormatMessagesContextManager.OutputContext oc = ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) + for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) { FormatOutputContext foc = oc as FormatOutputContext; @@ -641,9 +640,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// context manager instance to guide the message traversal /// - private FormatMessagesContextManager ctxManager = new FormatMessagesContextManager(); + private FormatMessagesContextManager _ctxManager = new FormatMessagesContextManager(); - private FormattedObjectsCache cache = null; + private FormattedObjectsCache _cache = null; /// /// handler for processing the caching notification and responsible for @@ -651,15 +650,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// /// - private void ProcessCachedGroup (FormatStartData formatStartData, List objects) + private void ProcessCachedGroup(FormatStartData formatStartData, List objects) { - this.formattingHint = null; + _formattingHint = null; TableHeaderInfo thi = formatStartData.shapeInfo as TableHeaderInfo; if (thi != null) { - ProcessCachedGroupOnTable (thi, objects); + ProcessCachedGroupOnTable(thi, objects); return; } @@ -667,12 +666,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (wvhi != null) { - ProcessCachedGroupOnWide (wvhi, objects); + ProcessCachedGroupOnWide(wvhi, objects); return; } } - private void ProcessCachedGroupOnTable (TableHeaderInfo thi, List objects) + private void ProcessCachedGroupOnTable(TableHeaderInfo thi, List objects) { if (thi.tableColumnInfoList.Count == 0) return; @@ -683,13 +682,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { string label = thi.tableColumnInfoList[k].label; - if (string.IsNullOrEmpty (label)) + if (string.IsNullOrEmpty(label)) label = thi.tableColumnInfoList[k].propertyName; if (string.IsNullOrEmpty(label)) widths[k] = 0; else - widths[k] = this.lo.DisplayCells.Length(label); + widths[k] = _lo.DisplayCells.Length(label); } int cellCount; // scratch variable @@ -705,7 +704,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (FormatPropertyField fpf in tre.formatPropertyFieldList) { - cellCount = this.lo.DisplayCells.Length(fpf.propertyValue); + cellCount = _lo.DisplayCells.Length(fpf.propertyValue); if (widths[kk] < cellCount) widths[kk] = cellCount; @@ -713,13 +712,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - TableFormattingHint hint = new TableFormattingHint (); + TableFormattingHint hint = new TableFormattingHint(); hint.columnWidths = widths; - this.formattingHint = hint; + _formattingHint = hint; } - private void ProcessCachedGroupOnWide (WideViewHeaderInfo wvhi, List objects) + private void ProcessCachedGroupOnWide(WideViewHeaderInfo wvhi, List objects) { if (wvhi.columns != 0) { @@ -740,24 +739,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format WideViewEntry wve = fed.formatEntryInfo as WideViewEntry; FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField; - if (!string.IsNullOrEmpty (fpf.propertyValue)) + if (!string.IsNullOrEmpty(fpf.propertyValue)) { - cellCount = this.lo.DisplayCells.Length(fpf.propertyValue); + cellCount = _lo.DisplayCells.Length(fpf.propertyValue); if (cellCount > maxLen) maxLen = cellCount; } } - WideFormattingHint hint = new WideFormattingHint (); + WideFormattingHint hint = new WideFormattingHint(); hint.maxWidth = maxLen; - this.formattingHint = hint; + _formattingHint = hint; } /// /// base class for all the formatting hints /// - private abstract class FormattingHint + private abstract class FormattingHint { } @@ -766,7 +765,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private sealed class TableFormattingHint : FormattingHint { - internal int [] columnWidths = null; + internal int[] columnWidths = null; } /// @@ -780,7 +779,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// variable holding the autosize hint (set by the caching code and reset by the hint consumer /// - private FormattingHint formattingHint = null; + private FormattingHint _formattingHint = null; /// /// helper for consuming the formatting hint @@ -788,12 +787,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private FormattingHint RetrieveFormattingHint() { - FormattingHint fh = this.formattingHint; - this.formattingHint = null; + FormattingHint fh = _formattingHint; + _formattingHint = null; return fh; } - private FormatObjectDeserializer formatObjectDeserializer; + private FormatObjectDeserializer _formatObjectDeserializer; /// @@ -806,21 +805,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// parent context in the stack /// format data to put in the context - internal FormatOutputContext (FormatMessagesContextManager.OutputContext parentContext, FormatStartData formatData) + internal FormatOutputContext(FormatMessagesContextManager.OutputContext parentContext, FormatStartData formatData) : base(parentContext) { - this.formatData = formatData; + _formatData = formatData; } /// /// retrieve the format data in the context /// - internal FormatStartData Data { get { return this.formatData; } } + internal FormatStartData Data { get { return _formatData; } } /// /// the active formatting message, as obtained from the stream /// - private FormatStartData formatData = null; + private FormatStartData _formatData = null; } /// @@ -832,60 +831,59 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// construct a context to push on the stack /// internal GroupOutputContext(OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(parentContext) { - this.cmd = cmd; - this.formatData = formatData; + _cmd = cmd; + _formatData = formatData; } /// /// called at creation time, overrides will initialize here, e.g. /// column widths, etc. /// - internal virtual void Initialize () { } + internal virtual void Initialize() { } /// /// called when a group of data is started, overrided will do /// things such as headers, etc... /// - internal virtual void GroupStart () { } + internal virtual void GroupStart() { } /// /// called when the end of a group is reached, overrides will do /// things such as group footers /// - internal virtual void GroupEnd () { } + internal virtual void GroupEnd() { } /// /// called when there is an entry to process, overrides will do /// things such as writing a row in a table /// /// FormatEntryData to process - internal virtual void ProcessPayload (FormatEntryData fed) { } + internal virtual void ProcessPayload(FormatEntryData fed) { } /// /// retrieve the format data in the context /// - internal GroupStartData Data { get { return this.formatData; } } + internal GroupStartData Data { get { return _formatData; } } protected OutCommandInner InnerCommand { - get { return this.cmd; } + get { return _cmd; } } /// /// OutCommandInner reference, for accessing context data /// - private OutCommandInner cmd; + private OutCommandInner _cmd; /// /// the active formatting message, as obtained from the stream /// - private GroupStartData formatData = null; - + private GroupStartData _formatData = null; } private class TableOutputContextBase : GroupOutputContext @@ -897,8 +895,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// parent context in the stack /// format data to put in the context internal TableOutputContextBase(OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(cmd, parentContext, formatData) { } @@ -906,14 +904,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// Get the table writer for this context /// - protected TableWriter Writer { get { return this.tableWriter; } } + protected TableWriter Writer { get { return _tableWriter; } } /// /// helper class to properly write a table using text output /// - private TableWriter tableWriter = new TableWriter(); - - + private TableWriter _tableWriter = new TableWriter(); } private sealed class TableOutputContext : TableOutputContextBase @@ -924,9 +920,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// reference to the OutCommandInner instance who owns this instance /// parent context in the stack /// format data to put in the context - internal TableOutputContext (OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + internal TableOutputContext(OutCommandInner cmd, + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(cmd, parentContext, formatData) { } @@ -934,9 +930,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// initialize column widths /// - internal override void Initialize () + internal override void Initialize() { - TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint () as TableFormattingHint; + TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint() as TableFormattingHint; int[] columnWidthsHint = null; if (tableHint != null) @@ -944,14 +940,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format columnWidthsHint = tableHint.columnWidths; } - int columsOnTheScreen = this.InnerCommand.lo.ColumnNumber; + int columsOnTheScreen = this.InnerCommand._lo.ColumnNumber; int columns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count; if (columns == 0) { return; } - + // create arrays for widths and alignment int[] columnWidths = new int[columns]; int[] alignment = new int[columns]; @@ -963,13 +959,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format alignment[k] = tci.alignment; k++; } - this.Writer.Initialize (0, columsOnTheScreen, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader); + this.Writer.Initialize(0, columsOnTheScreen, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader); } /// /// write the headers /// - internal override void GroupStart () + internal override void GroupStart() { int columns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count; @@ -984,14 +980,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { properties[k++] = (tci.label != null) ? tci.label : tci.propertyName; } - this.Writer.GenerateHeader(properties ,this.InnerCommand.lo); + this.Writer.GenerateHeader(properties, this.InnerCommand._lo); } /// /// write a row into the table /// /// FormatEntryData to process - internal override void ProcessPayload (FormatEntryData fed) + internal override void ProcessPayload(FormatEntryData fed) { int headerColumns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count; @@ -1007,7 +1003,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format int[] alignment = new int[headerColumns]; int fieldCount = tre.formatPropertyFieldList.Count; - + for (int k = 0; k < headerColumns; k++) { if (k < fieldCount) @@ -1021,8 +1017,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format alignment[k] = TextAlignment.Left; // hard coded default } } - this.Writer.GenerateRow (values, this.InnerCommand.lo, tre.multiLine, alignment, InnerCommand.lo.DisplayCells); - } + this.Writer.GenerateRow(values, this.InnerCommand._lo, tre.multiLine, alignment, InnerCommand._lo.DisplayCells); + } private TableHeaderInfo CurrentTableHeaderInfo { @@ -1031,7 +1027,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return (TableHeaderInfo)this.InnerCommand.ShapeInfoOnFormatContext; } } - } private sealed class ListOutputContext : GroupOutputContext @@ -1042,9 +1037,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// reference to the OutCommandInner instance who owns this instance /// parent context in the stack /// format data to put in the context - internal ListOutputContext (OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + internal ListOutputContext(OutCommandInner cmd, + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(cmd, parentContext, formatData) { } @@ -1052,42 +1047,42 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// initialize column widths /// - internal override void Initialize () + internal override void Initialize() { } - private void InternalInitialize (ListViewEntry lve) + private void InternalInitialize(ListViewEntry lve) { - this.properties = GetProperties (lve); - this.listWriter.Initialize (this.properties, this.InnerCommand.lo.ColumnNumber, InnerCommand.lo.DisplayCells); + _properties = GetProperties(lve); + _listWriter.Initialize(_properties, this.InnerCommand._lo.ColumnNumber, InnerCommand._lo.DisplayCells); } - internal static string[] GetProperties (ListViewEntry lve) + internal static string[] GetProperties(ListViewEntry lve) { - StringCollection props = new StringCollection (); + StringCollection props = new StringCollection(); foreach (ListViewField lvf in lve.listViewFieldList) { - props.Add ((lvf.label != null) ? lvf.label : lvf.propertyName); + props.Add((lvf.label != null) ? lvf.label : lvf.propertyName); } if (props.Count == 0) return null; string[] retVal = new string[props.Count]; - props.CopyTo (retVal, 0); + props.CopyTo(retVal, 0); return retVal; } - internal static string[] GetValues (ListViewEntry lve) + internal static string[] GetValues(ListViewEntry lve) { - StringCollection vals = new StringCollection (); + StringCollection vals = new StringCollection(); foreach (ListViewField lvf in lve.listViewFieldList) { - vals.Add (lvf.formatPropertyField.propertyValue); + vals.Add(lvf.formatPropertyField.propertyValue); } if (vals.Count == 0) return null; string[] retVal = new string[vals.Count]; - vals.CopyTo (retVal, 0); + vals.CopyTo(retVal, 0); return retVal; } @@ -1095,33 +1090,33 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// write the headers /// - internal override void GroupStart () + internal override void GroupStart() { - this.InnerCommand.lo.WriteLine(""); + this.InnerCommand._lo.WriteLine(""); } /// /// write a row into the list /// /// FormatEntryData to process - internal override void ProcessPayload (FormatEntryData fed) + internal override void ProcessPayload(FormatEntryData fed) { ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; - InternalInitialize (lve); - string[] values = GetValues (lve); - this.listWriter.WriteProperties(values, this.InnerCommand.lo); - this.InnerCommand.lo.WriteLine(""); + InternalInitialize(lve); + string[] values = GetValues(lve); + _listWriter.WriteProperties(values, this.InnerCommand._lo); + this.InnerCommand._lo.WriteLine(""); } /// /// property list currently active /// - private string[] properties = null; + private string[] _properties = null; /// /// writer to do the actual formatting /// - private ListWriter listWriter = new ListWriter(); + private ListWriter _listWriter = new ListWriter(); } private sealed class WideOutputContext : TableOutputContextBase @@ -1132,30 +1127,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// reference to the OutCommandInner instance who owns this instance /// parent context in the stack /// format data to put in the context - internal WideOutputContext (OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + internal WideOutputContext(OutCommandInner cmd, + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(cmd, parentContext, formatData) { } - private StringValuesBuffer buffer = null; + private StringValuesBuffer _buffer = null; /// /// initialize column widths /// - internal override void Initialize () + internal override void Initialize() { // set the hard wider default, to be used if no other info is available int itemsPerRow = 2; // get the header info and the wiew hint - WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint () as WideFormattingHint; + WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint() as WideFormattingHint; // give a preference to the hint, if there if (hint != null && hint.maxWidth > 0) { - itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, this.InnerCommand.lo.ColumnNumber); + itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, this.InnerCommand._lo.ColumnNumber); } else if (this.CurrentWideHeaderInfo.columns > 0) { @@ -1163,7 +1158,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // create a buffer object to hold partial rows - buffer = new StringValuesBuffer(itemsPerRow); + _buffer = new StringValuesBuffer(itemsPerRow); // initialize the writer int[] columnWidths = new int[itemsPerRow]; @@ -1175,22 +1170,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format alignment[k] = TextAlignment.Left; } - this.Writer.Initialize (0, this.InnerCommand.lo.ColumnNumber, columnWidths, alignment, false); + this.Writer.Initialize(0, this.InnerCommand._lo.ColumnNumber, columnWidths, alignment, false); } /// /// write the headers /// - internal override void GroupStart () + internal override void GroupStart() { - this.InnerCommand.lo.WriteLine(""); + this.InnerCommand._lo.WriteLine(""); } /// /// called when the end of a group is reached, flush the /// write buffer /// - internal override void GroupEnd () + internal override void GroupEnd() { WriteStringBuffer(); } @@ -1199,14 +1194,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// write a row into the table /// /// FormatEntryData to process - internal override void ProcessPayload (FormatEntryData fed) + internal override void ProcessPayload(FormatEntryData fed) { WideViewEntry wve = fed.formatEntryInfo as WideViewEntry; FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField; - buffer.Add (fpf.propertyValue); - if (buffer.IsFull) + _buffer.Add(fpf.propertyValue); + if (_buffer.IsFull) { - WriteStringBuffer (); + WriteStringBuffer(); } } @@ -1220,21 +1215,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private void WriteStringBuffer() { - if (buffer.IsEmpty) + if (_buffer.IsEmpty) { return; } - - string[] values = new string[buffer.Lenght]; - for (int k=0; k< values.Length; k++) + + string[] values = new string[_buffer.Lenght]; + for (int k = 0; k < values.Length; k++) { - if (k < buffer.CurrentCount) - values[k] = buffer[k]; + if (k < _buffer.CurrentCount) + values[k] = _buffer[k]; else values[k] = ""; } - this.Writer.GenerateRow(values, this.InnerCommand.lo, false, null, InnerCommand.lo.DisplayCells); - buffer.Reset(); + this.Writer.GenerateRow(values, this.InnerCommand._lo, false, null, InnerCommand._lo.DisplayCells); + _buffer.Reset(); } @@ -1248,27 +1243,27 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// construct the buffer /// /// number of entries to cache - internal StringValuesBuffer (int size) + internal StringValuesBuffer(int size) { - arr = new string[size]; + _arr = new string[size]; Reset(); } /// /// get the size of the buffer /// - internal int Lenght { get { return arr.Length; } } + internal int Lenght { get { return _arr.Length; } } /// /// get the current number of entries in the buffer /// - internal int CurrentCount { get { return lastEmptySpot; } } + internal int CurrentCount { get { return _lastEmptySpot; } } /// /// check if the buffer is full /// internal bool IsFull { - get { return lastEmptySpot == arr.Length; } + get { return _lastEmptySpot == _arr.Length; } } /// @@ -1276,35 +1271,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal bool IsEmpty { - get { return lastEmptySpot == 0; } + get { return _lastEmptySpot == 0; } } /// /// indexer to access the k-th item in the buffer /// - internal string this[int k] { get { return arr[k]; } } + internal string this[int k] { get { return _arr[k]; } } /// /// add an item to the buffer /// /// string to add - internal void Add (string s) + internal void Add(string s) { - arr[lastEmptySpot++] = s; + _arr[_lastEmptySpot++] = s; } /// /// reset the buffer /// - internal void Reset () + internal void Reset() { - lastEmptySpot = 0; - for(int k=0; kreference to the OutCommandInner instance who owns this instance /// parent context in the stack /// format data to put in the context - internal ComplexOutputContext (OutCommandInner cmd, - FormatMessagesContextManager.OutputContext parentContext, - GroupStartData formatData) + internal ComplexOutputContext(OutCommandInner cmd, + FormatMessagesContextManager.OutputContext parentContext, + GroupStartData formatData) : base(cmd, parentContext, formatData) { } - internal override void Initialize () + internal override void Initialize() { - this.writer.Initialize (this.InnerCommand.lo, - this.InnerCommand.lo.ColumnNumber); + _writer.Initialize(this.InnerCommand._lo, + this.InnerCommand._lo.ColumnNumber); } @@ -1334,19 +1329,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// write a row into the list /// /// FormatEntryData to process - internal override void ProcessPayload (FormatEntryData fed) + internal override void ProcessPayload(FormatEntryData fed) { ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve == null || cve.formatValueList == null) + if (cve == null || cve.formatValueList == null) return; - this.writer.WriteObject (cve.formatValueList); + _writer.WriteObject(cve.formatValueList); } - ComplexWriter writer = new ComplexWriter(); - + private ComplexWriter _writer = new ComplexWriter(); } - - } - + } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ColumnWidthManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ColumnWidthManager.cs index 2f7352dde..fd23f79f4 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ColumnWidthManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ColumnWidthManager.cs @@ -18,11 +18,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// overall width of the table in characters /// minimum usable column width /// number of separator characters - internal ColumnWidthManager (int tableWidth, int minimumColumnWidth, int separatorWidth) + internal ColumnWidthManager(int tableWidth, int minimumColumnWidth, int separatorWidth) { - this.tableWidth = tableWidth; - this.minimumColumnWidth = minimumColumnWidth; - this.separatorWidth = separatorWidth; + _tableWidth = tableWidth; + _minimumColumnWidth = minimumColumnWidth; + _separatorWidth = separatorWidth; } /// @@ -32,16 +32,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// with column elimination, starting from the right most column /// /// array of column widths to appropriately size - internal void CalculateColumnWidths (int[] columnWidths) + internal void CalculateColumnWidths(int[] columnWidths) { - if (AssignColumnWidths (columnWidths)) + if (AssignColumnWidths(columnWidths)) { // we do not have any trimming to do, we are done return; } // total width exceeds screen width, go on with trimming - TrimToFit (columnWidths); + TrimToFit(columnWidths); } /// @@ -50,7 +50,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// columns to process /// true if there was a fit, false if there is need for trimming - private bool AssignColumnWidths (int[] columnWidths) + private bool AssignColumnWidths(int[] columnWidths) { // run a quick check to see if all the columns have a specified width, // if so, we are done @@ -71,8 +71,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (allSpecified) { // compute the total table width (columns and separators) - maxInitialWidthSum += this.separatorWidth * (columnWidths.Length - 1); - if (maxInitialWidthSum <= this.tableWidth) + maxInitialWidthSum += _separatorWidth * (columnWidths.Length - 1); + if (maxInitialWidthSum <= _tableWidth) { // we fit with all the columns specified return true; @@ -89,12 +89,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { fixedColumn[k] = columnWidths[k] > 0; if (columnWidths[k] == 0) - columnWidths[k] = this.minimumColumnWidth; + columnWidths[k] = _minimumColumnWidth; } // see if we fit - int currentTableWidth = CurrentTableWidth (columnWidths); - int availableWidth = this.tableWidth - currentTableWidth; + int currentTableWidth = CurrentTableWidth(columnWidths); + int availableWidth = _tableWidth - currentTableWidth; if (availableWidth < 0) { @@ -106,9 +106,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we just fit return true; } - + // we still have room and we want to add more width - + while (availableWidth > 0) { for (int k = 0; k < columnWidths.Length; k++) @@ -130,19 +130,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// trim columns if the total column width is too much for the screen. /// /// column widths to trim - private void TrimToFit (int[] columnWidths) + private void TrimToFit(int[] columnWidths) { while (true) { - int currentTableWidth = CurrentTableWidth (columnWidths); - int widthInExcess = currentTableWidth - this.tableWidth; + int currentTableWidth = CurrentTableWidth(columnWidths); + int widthInExcess = currentTableWidth - _tableWidth; if (widthInExcess <= 0) { return; // we are done, because we fit } // we need to remove or shrink the last visible column - int lastVisibleColumn = GetLastVisibleColumn (columnWidths); + int lastVisibleColumn = GetLastVisibleColumn(columnWidths); if (lastVisibleColumn < 0) return; // nothing left to hide, because all the columns are hidden @@ -150,7 +150,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // try to trim the last column to fit int newLastVisibleColumnWidth = columnWidths[lastVisibleColumn] - widthInExcess; - if (newLastVisibleColumnWidth < this.minimumColumnWidth) + if (newLastVisibleColumnWidth < _minimumColumnWidth) { // cannot fit it in, just hide columnWidths[lastVisibleColumn] = -1; @@ -162,7 +162,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format columnWidths[lastVisibleColumn] = newLastVisibleColumnWidth; } } - } /// @@ -170,7 +169,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// column widths array /// - private int CurrentTableWidth (int[] columnWidths) + private int CurrentTableWidth(int[] columnWidths) { int sum = 0; int visibleColumns = 0; @@ -184,7 +183,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - return sum + this.separatorWidth * (visibleColumns-1); + return sum + _separatorWidth * (visibleColumns - 1); } /// @@ -192,7 +191,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// column widths array /// index of the last visible column, -1 if none - private static int GetLastVisibleColumn (int[] columnWidths) + private static int GetLastVisibleColumn(int[] columnWidths) { for (int k = 0; k < columnWidths.Length; k++) { @@ -203,8 +202,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return columnWidths.Length - 1; } - private int tableWidth; - private int minimumColumnWidth; - private int separatorWidth; + private int _tableWidth; + private int _minimumColumnWidth; + private int _separatorWidth; } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ComplexWriter.cs index 2ded87054..d6d7ccf7e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ComplexWriter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -20,10 +21,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// LineOutput interfaces to write to /// number of columns used to write out - internal void Initialize (LineOutput lineOutput, int numberOfTextColumns) + internal void Initialize(LineOutput lineOutput, int numberOfTextColumns) { - lo = lineOutput; - textColumns = numberOfTextColumns; + _lo = lineOutput; + _textColumns = numberOfTextColumns; } /// @@ -32,7 +33,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal void WriteString(string s) { - this.indentationManager.Clear(); + _indentationManager.Clear(); AddToBuffer(s); @@ -46,16 +47,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal void WriteObject(List formatValueList) { // we always start with no identation - this.indentationManager.Clear (); + _indentationManager.Clear(); foreach (FormatEntry fe in formatValueList) { // operate on each directive inside the list, // carrying the identation from invocation to invocation - GenerateFormatEntryDisplay (fe, 0); + GenerateFormatEntryDisplay(fe, 0); } // make sure that, if we have pending text in the buffer it gets flushed - WriteToScreen (); + WriteToScreen(); } /// @@ -63,7 +64,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// entry to process /// current depth of recursion - private void GenerateFormatEntryDisplay (FormatEntry fe, int currentDepth) + private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) { foreach (object obj in fe.formatValueList) { @@ -72,39 +73,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (currentDepth < maxRecursionDepth) { - if (feChild.frameInfo != null) { // if we have frame information, we need to push it on the // indentation stack - using (this.indentationManager.StackFrame (feChild.frameInfo)) + using (_indentationManager.StackFrame(feChild.frameInfo)) { - GenerateFormatEntryDisplay (feChild, currentDepth + 1); + GenerateFormatEntryDisplay(feChild, currentDepth + 1); } } else { // no need here of activating an indentation stack frame - GenerateFormatEntryDisplay (feChild, currentDepth + 1); + GenerateFormatEntryDisplay(feChild, currentDepth + 1); } } continue; } if (obj is FormatNewLine) { - this.WriteToScreen (); + this.WriteToScreen(); continue; } FormatTextField ftf = obj as FormatTextField; if (ftf != null) { - this.AddToBuffer (ftf.text); + this.AddToBuffer(ftf.text); continue; } FormatPropertyField fpf = obj as FormatPropertyField; if (fpf != null) { - this.AddToBuffer (fpf.propertyValue); + this.AddToBuffer(fpf.propertyValue); } } } @@ -113,29 +113,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// add a string to the current buffer, waiting for a FlushBuffer() /// /// string to add to buffer - private void AddToBuffer (string s) + private void AddToBuffer(string s) { - this.stringBuffer.Append (s); + _stringBuffer.Append(s); } /// /// write to the output interface /// - private void WriteToScreen () + private void WriteToScreen() { - int leftIndentation = this.indentationManager.LeftIndentation; - int rightIndentation = this.indentationManager.RightIndentation; - int firstLineIndentation = this.indentationManager.FirstLineIndentation; + int leftIndentation = _indentationManager.LeftIndentation; + int rightIndentation = _indentationManager.RightIndentation; + int firstLineIndentation = _indentationManager.FirstLineIndentation; // VALIDITY CHECKS: // check the useful ("active") witdth - int usefulWidth = this.textColumns - rightIndentation - leftIndentation; + int usefulWidth = _textColumns - rightIndentation - leftIndentation; if (usefulWidth <= 0) { // fatal error, there is nothing to write to the device // just clear the buffer and return - this.stringBuffer = new StringBuilder (); + _stringBuffer = new StringBuilder(); } // check indentation or hanging is not larger than the active width @@ -148,7 +148,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // compute the first line indentation or hanging - int firstLineWidth = this.textColumns - rightIndentation - leftIndentation; + int firstLineWidth = _textColumns - rightIndentation - leftIndentation; int followingLinesWidth = firstLineWidth; if (firstLineIndentation >= 0) @@ -165,7 +165,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format //error checking on invalid values // generate the lines using the computed widths - StringCollection sc = StringManipulationHelper.GenerateLines (lo.DisplayCells, this.stringBuffer.ToString (), + StringCollection sc = StringManipulationHelper.GenerateLines(_lo.DisplayCells, _stringBuffer.ToString(), firstLineWidth, followingLinesWidth); // compute padding @@ -189,36 +189,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (firstLine) { firstLine = false; - lo.WriteLine (StringManipulationHelper.PadLeft (s, firstLinePadding)); + _lo.WriteLine(StringManipulationHelper.PadLeft(s, firstLinePadding)); } else { - lo.WriteLine (StringManipulationHelper.PadLeft (s, followingLinesPadding)); + _lo.WriteLine(StringManipulationHelper.PadLeft(s, followingLinesPadding)); } } - this.stringBuffer = new StringBuilder (); + _stringBuffer = new StringBuilder(); } - + /// /// helper object to manage the frame-based indentation and margins /// - private IndentationManager indentationManager = new IndentationManager (); + private IndentationManager _indentationManager = new IndentationManager(); /// /// buffer to accumulate partially constructed text /// - private StringBuilder stringBuffer = new StringBuilder (); + private StringBuilder _stringBuffer = new StringBuilder(); /// /// interface to write to /// - private LineOutput lo; + private LineOutput _lo; /// /// nomber of columns for the output device /// - private int textColumns; + private int _textColumns; private const int maxRecursionDepth = 50; } @@ -228,37 +228,37 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { private sealed class IndentationStackFrame : IDisposable { - internal IndentationStackFrame (IndentationManager mgr) + internal IndentationStackFrame(IndentationManager mgr) { _mgr = mgr; } - public void Dispose () + public void Dispose() { - if (this._mgr != null) + if (_mgr != null) { - this._mgr.RemoveStackFrame (); + _mgr.RemoveStackFrame(); } } private IndentationManager _mgr; } - internal void Clear () + internal void Clear() { - _frameInfoStack.Clear (); + _frameInfoStack.Clear(); } - internal IDisposable StackFrame (FrameInfo frameInfo) + internal IDisposable StackFrame(FrameInfo frameInfo) { - IndentationStackFrame frame = new IndentationStackFrame (this); - _frameInfoStack.Push (frameInfo); + IndentationStackFrame frame = new IndentationStackFrame(this); + _frameInfoStack.Push(frameInfo); return frame; } - private void RemoveStackFrame () + private void RemoveStackFrame() { - _frameInfoStack.Pop (); + _frameInfoStack.Pop(); } internal int RightIndentation @@ -283,32 +283,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (_frameInfoStack.Count == 0) return 0; - return _frameInfoStack.Peek ().firstLine; + return _frameInfoStack.Peek().firstLine; } } - private int ComputeRightIndentation () + private int ComputeRightIndentation() { int val = 0; - foreach (FrameInfo fi in this._frameInfoStack) + foreach (FrameInfo fi in _frameInfoStack) { val += fi.rightIndentation; } return val; } - private int ComputeLeftIndentation () + private int ComputeLeftIndentation() { int val = 0; - foreach (FrameInfo fi in this._frameInfoStack) + foreach (FrameInfo fi in _frameInfoStack) { val += fi.leftIndentation; } return val; } - private Stack _frameInfoStack = new Stack (); + private Stack _frameInfoStack = new Stack(); } /// @@ -325,19 +325,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class StringManipulationHelper { - private static readonly char SoftHyphen = '\u00AD'; - private static readonly char HardHyphen = '\u2011'; - private static readonly char NonBreakingSpace = '\u00A0'; - private static Collection CultureCollection = new Collection(); + private static readonly char s_softHyphen = '\u00AD'; + private static readonly char s_hardHyphen = '\u2011'; + private static readonly char s_nonBreakingSpace = '\u00A0'; + private static Collection s_cultureCollection = new Collection(); static StringManipulationHelper() { - CultureCollection.Add("en"); // English - CultureCollection.Add("fr"); // French - CultureCollection.Add("de"); // German - CultureCollection.Add("it"); // Italian - CultureCollection.Add("pt"); // Portuguese - CultureCollection.Add("es"); // Spanish + s_cultureCollection.Add("en"); // English + s_cultureCollection.Add("fr"); // French + s_cultureCollection.Add("de"); // German + s_cultureCollection.Add("it"); // Italian + s_cultureCollection.Add("pt"); // Portuguese + s_cultureCollection.Add("es"); // Spanish } /// @@ -355,7 +355,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int i = 0; i < s.Length; i++) { // Soft hyphen = \u00AD - Should break, and add a hyphen if needed. If not needed for a break, hyphen should be absent - if (s[i] == ' ' || s[i] == '\t' || s[i] == SoftHyphen) + if (s[i] == ' ' || s[i] == '\t' || s[i] == s_softHyphen) { result.Word = sb.ToString(); sb.Clear(); @@ -365,7 +365,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // Non-breaking space = \u00A0 - ideally shouldn't wrap // Hard hyphen = \u2011 - Should not break - else if (s[i] == HardHyphen || s[i] == NonBreakingSpace) + else if (s[i] == s_hardHyphen || s[i] == s_nonBreakingSpace) { result.Word = sb.ToString(); sb.Clear(); @@ -387,7 +387,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal static StringCollection GenerateLines(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen) { - if (CultureCollection.Contains(CultureInfo.CurrentCulture.TwoLetterISOLanguageName)) + if (s_cultureCollection.Contains(CultureInfo.CurrentCulture.TwoLetterISOLanguageName)) { return GenerateLinesWithWordWrap(displayCells, val, firstLineLen, followingLinesLen); } @@ -399,17 +399,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen) { - StringCollection retVal = new StringCollection (); + StringCollection retVal = new StringCollection(); - if (string.IsNullOrEmpty (val)) + if (string.IsNullOrEmpty(val)) { // if null or empty, just add and we are done - retVal.Add (val); + retVal.Add(val); return retVal; } // break string on newlines and process each line separately - string[] lines = SplitLines (val); + string[] lines = SplitLines(val); for (int k = 0; k < lines.Length; k++) { @@ -480,20 +480,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private sealed class SplitLinesAccumulator { - internal SplitLinesAccumulator (StringCollection retVal, int firstLineLen, int followingLinesLen) + internal SplitLinesAccumulator(StringCollection retVal, int firstLineLen, int followingLinesLen) { _retVal = retVal; _firstLineLen = firstLineLen; _followingLinesLen = followingLinesLen; } - internal void AddLine (string s) + internal void AddLine(string s) { if (!_addedFirstLine) { _addedFirstLine = true; } - _retVal.Add (s); + _retVal.Add(s); } internal int ActiveLen @@ -510,29 +510,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private bool _addedFirstLine; private int _firstLineLen; private int _followingLinesLen; - } private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen) { - StringCollection retVal = new StringCollection (); + StringCollection retVal = new StringCollection(); - if (string.IsNullOrEmpty (val)) + if (string.IsNullOrEmpty(val)) { // if null or empty, just add and we are done - retVal.Add (val); + retVal.Add(val); return retVal; } // break string on newlines and process each line separately - string[] lines = SplitLines (val); + string[] lines = SplitLines(val); for (int k = 0; k < lines.Length; k++) { if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen) { // we do not need to split further, just add - retVal.Add (lines[k]); + retVal.Add(lines[k]); continue; } @@ -546,9 +545,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format string wordToAdd = word.Word; // Handle soft hyphen - if (word.Delim == SoftHyphen.ToString()) + if (word.Delim == s_softHyphen.ToString()) { - int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(SoftHyphen.ToString()); + int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen.ToString()); // Add hyphen only if necessary if (wordWidthWithHyphen == spacesLeft) @@ -658,20 +657,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// string to split /// string array with the values - internal static string[] SplitLines (string s) + internal static string[] SplitLines(string s) { - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) return new string[1] { s }; - StringBuilder sb = new StringBuilder (); + StringBuilder sb = new StringBuilder(); foreach (char c in s) { if (c != '\r') - sb.Append (c); + sb.Append(c); } - return sb.ToString ().Split (newLineChar); + return sb.ToString().Split(s_newLineChar); } #if false @@ -701,26 +700,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return sb.ToString (); } #endif - internal static string TruncateAtNewLine (string s) + internal static string TruncateAtNewLine(string s) { - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) return s; - int lineBreak = s.IndexOfAny (lineBreakChars); + int lineBreak = s.IndexOfAny(s_lineBreakChars); if (lineBreak < 0) return s; - return s.Substring (0, lineBreak) + PSObjectHelper.ellipses; + return s.Substring(0, lineBreak) + PSObjectHelper.ellipses; } - internal static string PadLeft (string val, int count) + internal static string PadLeft(string val, int count) { - return new string (' ', count) + val; + return new string(' ', count) + val; } - static readonly private char[] newLineChar = new char[] { '\n' }; - static readonly private char[] lineBreakChars = new char[] { '\n', '\r' }; + static readonly private char[] s_newLineChar = new char[] { '\n' }; + static readonly private char[] s_lineBreakChars = new char[] { '\n', '\r' }; } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Certificate_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Certificate_format_ps1xml.cs index 48c8011be..f5d62ae16 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Certificate_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Certificate_format_ps1xml.cs @@ -63,11 +63,11 @@ namespace System.Management.Automation.Runspaces { yield return new FormatViewDefinition("ThumbprintList", ListControl.Create() - .StartEntry(entrySelectedByType: new[] {"Microsoft.PowerShell.Commands.X509StoreLocation"}) + .StartEntry(entrySelectedByType: new[] { "Microsoft.PowerShell.Commands.X509StoreLocation" }) .AddItemProperty(@"Location") .AddItemProperty(@"StoreNames") .EndEntry() - .StartEntry(entrySelectedByType: new[] {"System.Security.Cryptography.X509Certificates.X509Store"}) + .StartEntry(entrySelectedByType: new[] { "System.Security.Cryptography.X509Certificates.X509Store" }) .AddItemProperty(@"Name") .EndEntry() .StartEntry() @@ -92,10 +92,10 @@ namespace System.Management.Automation.Runspaces .StartEntry() .AddItemProperty(@"PSPathPath") .EndEntry() - .StartEntry(entrySelectedByType: new[] {"Microsoft.PowerShell.Commands.X509StoreLocation"}) + .StartEntry(entrySelectedByType: new[] { "Microsoft.PowerShell.Commands.X509StoreLocation" }) .AddItemProperty(@"PSPathPath") .EndEntry() - .StartEntry(entrySelectedByType: new[] {"System.Security.Cryptography.X509Certificates.X509Store"}) + .StartEntry(entrySelectedByType: new[] { "System.Security.Cryptography.X509Certificates.X509Store" }) .AddItemProperty(@"PSPath") .EndEntry() .EndList()); diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/FileSystem_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/FileSystem_format_ps1xml.cs index fd29c45da..ca65a3357 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/FileSystem_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/FileSystem_format_ps1xml.cs @@ -64,7 +64,7 @@ namespace System.Management.Automation.Runspaces yield return new FormatViewDefinition("children", ListControl.Create() .GroupByProperty("PSParentPath", customControl: sharedControls[0]) - .StartEntry(entrySelectedByType: new[] {"System.IO.FileInfo"}) + .StartEntry(entrySelectedByType: new[] { "System.IO.FileInfo" }) .AddItemProperty(@"Name") .AddItemProperty(@"Length") .AddItemProperty(@"CreationTime") @@ -90,7 +90,7 @@ namespace System.Management.Automation.Runspaces WideControl.Create() .GroupByProperty("PSParentPath", customControl: sharedControls[0]) .AddPropertyEntry("Name") - .AddPropertyEntry("Name", format: "[{0}]", entrySelectedByType: new[] {"System.IO.DirectoryInfo"}) + .AddPropertyEntry("Name", format: "[{0}]", entrySelectedByType: new[] { "System.IO.DirectoryInfo" }) .EndWideControl()); } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs index 33f68dc34..70aa64910 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/HelpV3_format_ps1xml.cs @@ -41,7 +41,7 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlShortDescriptionControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlParaTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() @@ -51,25 +51,25 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlDescriptionControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlParaTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlOrderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlOrderedListTextItem" }) .StartFrame(firstLineHanging: 4) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlUnorderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlUnorderedListTextItem" }) .StartFrame(firstLineHanging: 2) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlDefinitionTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlDefinitionTextItem" }) .AddPropertyExpressionBinding(@"Term") .AddNewline() .StartFrame(leftIndent: 4) @@ -83,7 +83,7 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlFieldCustomControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlPSClassHelpInfo#field"}) + .StartEntry(entrySelectedByType: new[] { "MamlPSClassHelpInfo#field" }) .AddScriptBlockExpressionBinding(@"""["" + $_.fieldData.type.name + ""] $"" + $_.fieldData.name") .AddNewline() .AddScriptBlockExpressionBinding(@"$_.introduction.text") @@ -96,7 +96,7 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlMethodCustomControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlPSClassHelpInfo#method"}) + .StartEntry(entrySelectedByType: new[] { "MamlPSClassHelpInfo#method" }) .StartFrame() .AddNewline() .AddScriptBlockExpressionBinding(@"function GetParam diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs index 75c297c7e..530425a2e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/Help_format_ps1xml.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlShortDescriptionControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlParaTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() @@ -29,25 +29,25 @@ namespace System.Management.Automation.Runspaces .EndControl(); var MamlDescriptionControl = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlParaTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlOrderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlOrderedListTextItem" }) .StartFrame(firstLineHanging: 4) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlUnorderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlUnorderedListTextItem" }) .StartFrame(firstLineHanging: 2) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlDefinitionTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlDefinitionTextItem" }) .AddPropertyExpressionBinding(@"Term") .AddNewline() .StartFrame(leftIndent: 4) @@ -86,21 +86,21 @@ else { '-{0}{1} ' }) -f $_.Name, $parameterValue") .EndControl(); var MamlTextItem = CustomControl.Create() - .StartEntry(entrySelectedByType: new[] {"MamlParaTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlOrderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlOrderedListTextItem" }) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlUnorderedListTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlUnorderedListTextItem" }) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlDefinitionTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlDefinitionTextItem" }) .AddPropertyExpressionBinding(@"Term") .AddNewline() .StartFrame(leftIndent: 4) @@ -108,7 +108,7 @@ else { '-{0}{1} ' }) -f $_.Name, $parameterValue") .EndFrame() .AddNewline() .EndEntry() - .StartEntry(entrySelectedByType: new[] {"MamlPreformattedTextItem"}) + .StartEntry(entrySelectedByType: new[] { "MamlPreformattedTextItem" }) .AddPropertyExpressionBinding(@"Text") .EndEntry() .StartEntry() diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 997f9a956..84c2d371a 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -1113,7 +1113,7 @@ namespace System.Management.Automation.Runspaces yield return new FormatViewDefinition("Breakpoint", ListControl.Create() - .StartEntry(entrySelectedByType: new[] {"System.Management.Automation.LineBreakpoint"}) + .StartEntry(entrySelectedByType: new[] { "System.Management.Automation.LineBreakpoint" }) .AddItemProperty(@"ID") .AddItemProperty(@"Script") .AddItemProperty(@"Line") @@ -1122,7 +1122,7 @@ namespace System.Management.Automation.Runspaces .AddItemProperty(@"HitCount") .AddItemProperty(@"Action") .EndEntry() - .StartEntry(entrySelectedByType: new[] {"System.Management.Automation.VariableBreakpoint"}) + .StartEntry(entrySelectedByType: new[] { "System.Management.Automation.VariableBreakpoint" }) .AddItemProperty(@"ID") .AddItemProperty(@"Variable") .AddItemProperty(@"AccessMode") @@ -1130,7 +1130,7 @@ namespace System.Management.Automation.Runspaces .AddItemProperty(@"HitCount") .AddItemProperty(@"Action") .EndEntry() - .StartEntry(entrySelectedByType: new[] {"System.Management.Automation.CommandBreakpoint"}) + .StartEntry(entrySelectedByType: new[] { "System.Management.Automation.CommandBreakpoint" }) .AddItemProperty(@"ID") .AddItemProperty(@"Command") .AddItemProperty(@"Enabled") diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 9109d5237..cc354588a 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -32,7 +32,7 @@ namespace System.Management.Automation.Runspaces [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public class FormatTableLoadException : RuntimeException { - private Collection errors; + private Collection _errors; #region Constructors @@ -82,7 +82,7 @@ namespace System.Management.Automation.Runspaces internal FormatTableLoadException(ConcurrentBag loadErrors) : base(StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatTableLoadErrors)) { - errors = new Collection(loadErrors.ToArray()); + _errors = new Collection(loadErrors.ToArray()); SetDefaultErrorRecord(); } @@ -102,11 +102,11 @@ namespace System.Management.Automation.Runspaces int errorCount = info.GetInt32("ErrorCount"); if (errorCount > 0) { - errors = new Collection(); + _errors = new Collection(); for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - errors.Add(info.GetString(key)); + _errors.Add(info.GetString(key)); } } } @@ -128,15 +128,15 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue - if (null != errors) + if (null != _errors) { - int errorCount = errors.Count; + int errorCount = _errors.Count; info.AddValue("ErrorCount", errorCount); for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - info.AddValue(key, errors[index]); + info.AddValue(key, _errors[index]); } } } @@ -157,12 +157,12 @@ namespace System.Management.Automation.Runspaces { get { - return errors; + return _errors; } } } - /// + /// /// A class that keeps the information from format.ps1xml files in a cache table /// [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] @@ -170,7 +170,7 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private TypeInfoDataBaseManager formatDBMgr; + private TypeInfoDataBaseManager _formatDBMgr; #endregion @@ -181,7 +181,7 @@ namespace System.Management.Automation.Runspaces /// internal FormatTable() { - formatDBMgr = new TypeInfoDataBaseManager(); + _formatDBMgr = new TypeInfoDataBaseManager(); } /// @@ -217,7 +217,7 @@ namespace System.Management.Automation.Runspaces { if (formatData == null) throw PSTraceSource.NewArgumentNullException("formatData"); - formatDBMgr.AddFormatData(formatData, false); + _formatDBMgr.AddFormatData(formatData, false); } /// @@ -236,7 +236,7 @@ namespace System.Management.Automation.Runspaces { if (formatData == null) throw PSTraceSource.NewArgumentNullException("formatData"); - formatDBMgr.AddFormatData(formatData, true); + _formatDBMgr.AddFormatData(formatData, true); } /// @@ -265,7 +265,7 @@ namespace System.Management.Automation.Runspaces throw PSTraceSource.NewArgumentNullException("formatFiles"); } - formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host); + _formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host); } #endregion @@ -274,7 +274,7 @@ namespace System.Management.Automation.Runspaces internal TypeInfoDataBaseManager FormatDBManager { - get { return formatDBMgr; } + get { return _formatDBMgr; } } @@ -289,7 +289,7 @@ namespace System.Management.Automation.Runspaces /// internal void Add(string formatFile, bool shouldPrepend) { - formatDBMgr.Add(formatFile, shouldPrepend); + _formatDBMgr.Add(formatFile, shouldPrepend); } /// @@ -299,7 +299,7 @@ namespace System.Management.Automation.Runspaces /// internal void Remove(string formatFile) { - formatDBMgr.Remove(formatFile); + _formatDBMgr.Remove(formatFile); } #endregion diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 0fc500bd8..2262091d6 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -49,9 +49,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// entry logged by the loader and made available to external consumers /// - internal class XmlLoaderLoggerEntry + internal class XmlLoaderLoggerEntry { - internal enum EntryType {Error, Trace}; + internal enum EntryType { Error, Trace }; /// /// type of information being logged @@ -79,7 +79,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal bool failToLoadFile = false; } - + /// /// logger object used by the loader (class XmlLoaderBase) to write log entries. /// It logs to a memory buffer and (optionally) to a text file @@ -89,34 +89,34 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region tracer //PSS/end-user tracer [TraceSource("FormatFileLoading", "Loading format files")] - private static PSTraceSource formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false); + private static PSTraceSource s_formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false); #endregion tracer /// /// log an entry /// /// entry to log - internal void LogEntry (XmlLoaderLoggerEntry entry) + internal void LogEntry(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) - this.hasErrors = true; + _hasErrors = true; - if (this.saveInMemory) - this.entries.Add (entry); + if (_saveInMemory) + _entries.Add(entry); - if ((formatFileLoadingtracer.Options | PSTraceSourceOptions.WriteLine) != 0) - WriteToTracer (entry); + if ((s_formatFileLoadingtracer.Options | PSTraceSourceOptions.WriteLine) != 0) + WriteToTracer(entry); } private void WriteToTracer(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { - formatFileLoadingtracer.WriteLine("ERROR:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); + s_formatFileLoadingtracer.WriteLine("ERROR:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); } else if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Trace) { - formatFileLoadingtracer.WriteLine("TRACE:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); + s_formatFileLoadingtracer.WriteLine("TRACE:\r\n FilePath: {0}\r\n XPath: {1}\r\n Message = {2}", entry.filePath, entry.xPath, entry.message); } } @@ -124,7 +124,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// IDisposable implementation /// /// This method calls GC.SuppressFinalize - public void Dispose () + public void Dispose() { Dispose(true); @@ -135,7 +135,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (disposing) { - } } @@ -143,7 +142,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return this.entries; + return _entries; } } @@ -151,24 +150,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return this.hasErrors; + return _hasErrors; } } /// /// if true, log entries to memory /// - private bool saveInMemory = true; + private bool _saveInMemory = true; - /// + /// /// list of entries logged if saveInMemory is true /// - private List entries = new List (); + private List _entries = new List(); /// /// true if we ever logged an error /// - private bool hasErrors = false; + private bool _hasErrors = false; } @@ -180,7 +179,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { #region tracer [TraceSource("XmlLoaderBase", "XmlLoaderBase")] - private static PSTraceSource tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase"); + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase"); #endregion tracer /// @@ -188,9 +187,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private sealed class XmlLoaderStackFrame : IDisposable { - internal XmlLoaderStackFrame (XmlLoaderBase loader, XmlNode n, int index) + internal XmlLoaderStackFrame(XmlLoaderBase loader, XmlNode n, int index) { - this.loader = loader; + _loader = loader; this.node = n; this.index = index; } @@ -198,19 +197,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// IDisposable implementation /// - public void Dispose () + public void Dispose() { - if (this.loader != null) + if (_loader != null) { - this.loader.RemoveStackFrame (); - this.loader = null; + _loader.RemoveStackFrame(); + _loader = null; } } /// /// back pointer to the loader, used to pop a stack frame /// - private XmlLoaderBase loader; + private XmlLoaderBase _loader; /// /// node the stack frame refers to @@ -228,7 +227,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// IDisposable implementation /// /// This method calls GC.SuppressFinalize - public void Dispose () + public void Dispose() { Dispose(true); @@ -239,10 +238,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (disposing) { - if (this.logger != null) + if (_logger != null) { - this.logger.Dispose(); - this.logger = null; + _logger.Dispose(); + _logger = null; } } } @@ -255,7 +254,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return this.logger.LogEntries; + return _logger.LogEntries; } } @@ -267,7 +266,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return this.logger.HasErrors; + return _logger.HasErrors; } } @@ -277,9 +276,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// node to push on the stack /// object to dispose when exiting the frame - protected IDisposable StackFrame (XmlNode n) + protected IDisposable StackFrame(XmlNode n) { - return StackFrame (n, -1); + return StackFrame(n, -1); } /// @@ -289,13 +288,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// node to push on the stack /// index of the node of the same name in a collection /// object to dispose when exiting the frame - protected IDisposable StackFrame (XmlNode n, int index) + protected IDisposable StackFrame(XmlNode n, int index) { - XmlLoaderStackFrame sf = new XmlLoaderStackFrame (this, n, index); + XmlLoaderStackFrame sf = new XmlLoaderStackFrame(this, n, index); - executionStack.Push (sf); - if (logStackActivity) - WriteStackLocation ("Enter"); + _executionStack.Push(sf); + if (_logStackActivity) + WriteStackLocation("Enter"); return sf; } @@ -303,32 +302,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// called by the Dispose code of the XmlLoaderStackFrame object /// to pop a frame off the stack /// - private void RemoveStackFrame () + private void RemoveStackFrame() { - if (logStackActivity) - WriteStackLocation ("Exit"); - executionStack.Pop (); + if (_logStackActivity) + WriteStackLocation("Exit"); + _executionStack.Pop(); } - protected void ProcessUnknownNode (XmlNode n) + protected void ProcessUnknownNode(XmlNode n) { if (IsFilteredOutNode(n)) return; - ReportIllegalXmlNode (n); + ReportIllegalXmlNode(n); } - protected void ProcessUnknownAttribute (XmlAttribute a) + protected void ProcessUnknownAttribute(XmlAttribute a) { - ReportIllegalXmlAttribute (a); + ReportIllegalXmlAttribute(a); } - protected static bool IsFilteredOutNode (XmlNode n) + protected static bool IsFilteredOutNode(XmlNode n) { return (n is XmlComment || n is XmlWhitespace); } - protected bool VerifyNodeHasNoChildren (XmlNode n) + protected bool VerifyNodeHasNoChildren(XmlNode n) { if (n.ChildNodes.Count == 0) return true; @@ -343,20 +342,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - internal string GetMandatoryInnerText (XmlNode n) + internal string GetMandatoryInnerText(XmlNode n) { - if (String.IsNullOrEmpty (n.InnerText)) + if (String.IsNullOrEmpty(n.InnerText)) { - this.ReportEmptyNode (n); + this.ReportEmptyNode(n); return null; } return n.InnerText; } - internal string GetMandatoryAttributeValue (XmlAttribute a) + internal string GetMandatoryAttributeValue(XmlAttribute a) { - if (String.IsNullOrEmpty (a.Value)) + if (String.IsNullOrEmpty(a.Value)) { this.ReportEmptyAttribute(a); return null; @@ -374,15 +373,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// string to compare the node name to /// if true, accept the presence of attributes on the node /// true if there is a match - private bool MatchNodeNameHelper (XmlNode n, string s, bool allowAttributes) + private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) { bool match = false; - if (String.Equals (n.Name, s, StringComparison.Ordinal)) + if (String.Equals(n.Name, s, StringComparison.Ordinal)) { // we have a case sensitive match match = true; } - else if (String.Equals (n.Name, s, StringComparison.OrdinalIgnoreCase)) + else if (String.Equals(n.Name, s, StringComparison.OrdinalIgnoreCase)) { // try a case insensitive match // we differ only in case: flag this as an ERROR for the time being @@ -407,24 +406,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return match; } - internal bool MatchNodeNameWithAttributes (XmlNode n, string s) + internal bool MatchNodeNameWithAttributes(XmlNode n, string s) { - return MatchNodeNameHelper (n, s, true); + return MatchNodeNameHelper(n, s, true); } - internal bool MatchNodeName (XmlNode n, string s) + internal bool MatchNodeName(XmlNode n, string s) { - return MatchNodeNameHelper (n, s, false); + return MatchNodeNameHelper(n, s, false); } - internal bool MatchAttributeName (XmlAttribute a, string s) + internal bool MatchAttributeName(XmlAttribute a, string s) { - if (String.Equals (a.Name, s, StringComparison.Ordinal)) + if (String.Equals(a.Name, s, StringComparison.Ordinal)) { // we have a case sensitive match return true; } - else if (String.Equals (a.Name, s, StringComparison.OrdinalIgnoreCase)) + else if (String.Equals(a.Name, s, StringComparison.OrdinalIgnoreCase)) { // try a case insensitive match // we differ only in case: flag this as an ERROR for the time being @@ -437,37 +436,37 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - internal void ProcessDuplicateNode (XmlNode n) + internal void ProcessDuplicateNode(XmlNode n) { //Error at XPath {0} in file {1}: Duplicated node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.DuplicatedNode, ComputeCurrentXPath(), FilePath), XmlLoaderLoggerEntry.EntryType.Error); } - internal void ProcessDuplicateAlternateNode (string node1, string node2) + internal void ProcessDuplicateAlternateNode(string node1, string node2) { //Error at XPath {0} in file {1}: {2} and {3} are mutually exclusive. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, node1, node2), XmlLoaderLoggerEntry.EntryType.Error); } - internal void ProcessDuplicateAlternateNode (XmlNode n, string node1, string node2) + internal void ProcessDuplicateAlternateNode(XmlNode n, string node1, string node2) { //Error at XPath {0} in file {1}: {2}, {3} and {4} are mutually exclusive. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.ThreeMutuallyExclusiveNode, ComputeCurrentXPath(), FilePath, n.Name, node1, node2), XmlLoaderLoggerEntry.EntryType.Error); } - private void ReportIllegalXmlNode (XmlNode n) + private void ReportIllegalXmlNode(XmlNode n) { //UnknownNode=Error at XPath {0} in file {1}: {2} is an unknown node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error); } - private void ReportIllegalXmlAttribute (XmlAttribute a) + private void ReportIllegalXmlAttribute(XmlAttribute a) { //Error at XPath {0} in file {1}: {2} is an unknown attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.UnknownAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error); } - protected void ReportMissingAttribute (string name) + protected void ReportMissingAttribute(string name) { //Error at XPath {0} in file {1}: {2} is a missing attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingAttribute, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error); @@ -479,20 +478,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, name), XmlLoaderLoggerEntry.EntryType.Error); } - protected void ReportMissingNodes (string[] names) + protected void ReportMissingNodes(string[] names) { //Error at XPath {0} in file {1}: Missing Node from {2}. string namesString = string.Join(", ", names); ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNodeFromList, ComputeCurrentXPath(), FilePath, namesString), XmlLoaderLoggerEntry.EntryType.Error); } - protected void ReportEmptyNode (XmlNode n) + protected void ReportEmptyNode(XmlNode n) { //Error at XPath {0} in file {1}: {2} is an empty node. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyNode, ComputeCurrentXPath(), FilePath, n.Name), XmlLoaderLoggerEntry.EntryType.Error); } - protected void ReportEmptyAttribute (XmlAttribute a) + protected void ReportEmptyAttribute(XmlAttribute a) { //EmptyAttribute=Error at XPath {0} in file {1}: {2} is an empty attribute. ReportLogEntryHelper(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyAttribute, ComputeCurrentXPath(), FilePath, a.Name), XmlLoaderLoggerEntry.EntryType.Error); @@ -504,20 +503,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// trace message, non-localized string is OK. /// - protected void ReportTrace (string message) + protected void ReportTrace(string message) { - ReportLogEntryHelper (message, XmlLoaderLoggerEntry.EntryType.Trace); + ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Trace); } - protected void ReportError (string message) + protected void ReportError(string message) { - ReportLogEntryHelper (message, XmlLoaderLoggerEntry.EntryType.Error); + ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Error); } - private void ReportLogEntryHelper (string message, XmlLoaderLoggerEntry.EntryType entryType, bool failToLoadFile = false) + private void ReportLogEntryHelper(string message, XmlLoaderLoggerEntry.EntryType entryType, bool failToLoadFile = false) { - string currentPath = ComputeCurrentXPath (); - XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry (); + string currentPath = ComputeCurrentXPath(); + XmlLoaderLoggerEntry entry = new XmlLoaderLoggerEntry(); entry.entryType = entryType; entry.filePath = this.FilePath; @@ -530,31 +529,31 @@ namespace Microsoft.PowerShell.Commands.Internal.Format entry.failToLoadFile = true; } - this.logger.LogEntry (entry); + _logger.LogEntry(entry); if (entryType == XmlLoaderLoggerEntry.EntryType.Error) { - this.currentErrorCount++; - if (this.currentErrorCount >= this.maxNumberOfErrors) + _currentErrorCount++; + if (_currentErrorCount >= _maxNumberOfErrors) { // we have to log a last error and then bail - if (this.maxNumberOfErrors > 1) + if (_maxNumberOfErrors > 1) { - XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry (); + XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry(); lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error; lastEntry.filePath = this.FilePath; lastEntry.xPath = currentPath; lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrors, FilePath); - this.logger.LogEntry (lastEntry); - this.currentErrorCount++; + _logger.LogEntry(lastEntry); + _currentErrorCount++; } // NOTE: this exception is an internal one, and it is caught // internally by the calling code. - TooManyErrorsException e = new TooManyErrorsException (); + TooManyErrorsException e = new TooManyErrorsException(); - e.errorCount = this.currentErrorCount; + e.errorCount = _currentErrorCount; throw e; } } @@ -571,40 +570,40 @@ namespace Microsoft.PowerShell.Commands.Internal.Format entry.entryType = XmlLoaderLoggerEntry.EntryType.Error; entry.message = message; - this.logger.LogEntry(entry); + _logger.LogEntry(entry); - this.currentErrorCount++; - if (this.currentErrorCount >= this.maxNumberOfErrors) + _currentErrorCount++; + if (_currentErrorCount >= _maxNumberOfErrors) { // we have to log a last error and then bail - if (this.maxNumberOfErrors > 1) + if (_maxNumberOfErrors > 1) { XmlLoaderLoggerEntry lastEntry = new XmlLoaderLoggerEntry(); lastEntry.entryType = XmlLoaderLoggerEntry.EntryType.Error; lastEntry.message = StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyErrorsInFormattingData, typeName); - this.logger.LogEntry(lastEntry); - this.currentErrorCount++; + _logger.LogEntry(lastEntry); + _currentErrorCount++; } // NOTE: this exception is an internal one, and it is caught // internally by the calling code. TooManyErrorsException e = new TooManyErrorsException(); - e.errorCount = this.currentErrorCount; + e.errorCount = _currentErrorCount; throw e; } } - private void WriteStackLocation (string label) + private void WriteStackLocation(string label) { - ReportTrace (label); + ReportTrace(label); } - protected string ComputeCurrentXPath () + protected string ComputeCurrentXPath() { StringBuilder path = new StringBuilder(); - foreach (XmlLoaderStackFrame sf in this.executionStack) + foreach (XmlLoaderStackFrame sf in _executionStack) { path.Insert(0, "/"); if (sf.index != -1) @@ -620,8 +619,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return path.Length > 0 ? path.ToString() : null; } -#region helpers for loading XML documents - + #region helpers for loading XML documents + protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted) { // get file contents @@ -642,9 +641,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } catch (PSSecurityException reason) { - string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException, - string.Empty /* TODO/FIXME snapin */, - FilePath, + string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException, + string.Empty /* TODO/FIXME snapin */, + FilePath, reason.Message); ReportLogEntryHelper(errorMessage, XmlLoaderLoggerEntry.EntryType.Error, failToLoadFile: true); return null; @@ -655,7 +654,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format try { XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( - fileContents, + fileContents, true, /* preserve whitespace, comments, etc. */ null); /* default maxCharacters */ this.ReportTrace("XmlDocument loaded OK"); @@ -674,7 +673,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } -#endregion + #endregion /// /// file system path for the file we are loading from @@ -684,36 +683,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return loadingInfo.filePath; + return _loadingInfo.filePath; } } - protected void SetDatabaseLoadingInfo (XmlFileLoadInfo info) + protected void SetDatabaseLoadingInfo(XmlFileLoadInfo info) { - loadingInfo.fileDirectory = info.fileDirectory; - loadingInfo.filePath = info.filePath; + _loadingInfo.fileDirectory = info.fileDirectory; + _loadingInfo.filePath = info.filePath; } protected void SetLoadingInfoIsFullyTrusted(bool isFullyTrusted) { - loadingInfo.isFullyTrusted = isFullyTrusted; + _loadingInfo.isFullyTrusted = isFullyTrusted; } protected void SetLoadingInfoIsProductCode(bool isProductCode) { - loadingInfo.isProductCode = isProductCode; + _loadingInfo.isProductCode = isProductCode; } - private DatabaseLoadingInfo loadingInfo = new DatabaseLoadingInfo (); + private DatabaseLoadingInfo _loadingInfo = new DatabaseLoadingInfo(); protected DatabaseLoadingInfo LoadingInfo { get { - DatabaseLoadingInfo info = new DatabaseLoadingInfo (); - info.filePath = loadingInfo.filePath; - info.fileDirectory = loadingInfo.fileDirectory; - info.isFullyTrusted = loadingInfo.isFullyTrusted; - info.isProductCode = loadingInfo.isProductCode; + DatabaseLoadingInfo info = new DatabaseLoadingInfo(); + info.filePath = _loadingInfo.filePath; + info.fileDirectory = _loadingInfo.fileDirectory; + info.isFullyTrusted = _loadingInfo.isFullyTrusted; + info.isProductCode = _loadingInfo.isProductCode; return info; } } @@ -725,18 +724,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal bool VerifyStringResources { - get { return this.verifyStringResources; } + get { return _verifyStringResources; } } - private bool verifyStringResources = true; + private bool _verifyStringResources = true; - private int maxNumberOfErrors = 30; + private int _maxNumberOfErrors = 30; - private int currentErrorCount = 0; + private int _currentErrorCount = 0; - private bool logStackActivity = false; + private bool _logStackActivity = false; - private Stack executionStack = new Stack(); + private Stack _executionStack = new Stack(); - XmlLoaderLogger logger = new XmlLoaderLogger (); + private XmlLoaderLogger _logger = new XmlLoaderLogger(); } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/commands.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/commands.cs index 9242a73e3..677a0ef21 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/commands.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/commands.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.IO; using System.Xml; diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index feee5ba90..96edc4b3b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -36,16 +36,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed partial class TypeInfoDataBase { // define the sections corresponding the XML file - internal DefaultSettingsSection defaultSettingsSection = new DefaultSettingsSection (); - internal TypeGroupsSection typeGroupSection = new TypeGroupsSection (); - internal ViewDefinitionsSection viewDefinitionsSection = new ViewDefinitionsSection (); - internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder (); + internal DefaultSettingsSection defaultSettingsSection = new DefaultSettingsSection(); + internal TypeGroupsSection typeGroupSection = new TypeGroupsSection(); + internal ViewDefinitionsSection viewDefinitionsSection = new ViewDefinitionsSection(); + internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder(); /// /// cache for resource strings in format.ps1xml /// - internal DisplayResourceManagerCache displayResourceManagerCache = new DisplayResourceManagerCache (); + internal DisplayResourceManagerCache displayResourceManagerCache = new DisplayResourceManagerCache(); } internal sealed class DatabaseLoadingInfo @@ -109,13 +109,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (!_multilineTables.HasValue) { - this._multilineTables = value; + _multilineTables = value; } } get { if (_multilineTables.HasValue) - return this._multilineTables.Value; + return _multilineTables.Value; return false; } } @@ -123,8 +123,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); - internal ShapeSelectionDirectives shapeSelectionDirectives = new ShapeSelectionDirectives (); - internal List enumerableExpansionDirectiveList = new List (); + internal ShapeSelectionDirectives shapeSelectionDirectives = new ShapeSelectionDirectives(); + internal List enumerableExpansionDirectiveList = new List(); } internal sealed class FormatErrorPolicy @@ -138,13 +138,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (!_showErrorsAsMessages.HasValue) { - this._showErrorsAsMessages = value; + _showErrorsAsMessages = value; } } get { if (_showErrorsAsMessages.HasValue) - return this._showErrorsAsMessages.Value; + return _showErrorsAsMessages.Value; return false; } } @@ -160,13 +160,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (!_showErrorsInFormattedOutput.HasValue) { - this._showErrorsInFormattedOutput = value; + _showErrorsInFormattedOutput = value; } } get { if (_showErrorsInFormattedOutput.HasValue) - return this._showErrorsInFormattedOutput.Value; + return _showErrorsInFormattedOutput.Value; return false; } } @@ -194,19 +194,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (!_propertyCountForTable.HasValue) { - this._propertyCountForTable = value; + _propertyCountForTable = value; } } get { if (_propertyCountForTable.HasValue) - return this._propertyCountForTable.Value; + return _propertyCountForTable.Value; return 4; } } private int? _propertyCountForTable; - internal List formatShapeSelectionOnTypeList = new List (); + internal List formatShapeSelectionOnTypeList = new List(); } internal enum FormatShape { Table, List, Wide, Complex, Undefined } @@ -234,13 +234,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class TypeGroupsSection { - internal List typeGroupDefinitionList = new List (); + internal List typeGroupDefinitionList = new List(); } internal sealed class TypeGroupDefinition { internal string name; - internal List typeReferenceList = new List (); + internal List typeReferenceList = new List(); } internal abstract class TypeOrGroupReference @@ -287,7 +287,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// item associated with this frame definition /// - internal ComplexControlItemDefinition itemDefinition = new ComplexControlItemDefinition (); + internal ComplexControlItemDefinition itemDefinition = new ComplexControlItemDefinition(); /// /// frame info assocated with this frame definition @@ -319,7 +319,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal int firstLine = 0; } - + internal sealed class ExpressionToken { internal ExpressionToken() { } @@ -341,7 +341,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal ExpressionToken conditionToken = null; - internal ExpressionToken expression = new ExpressionToken (); + internal ExpressionToken expression = new ExpressionToken(); internal bool enumerateCollection = false; } @@ -365,7 +365,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #endregion Elementary Tokens - + #region Control Definitions: common data /// @@ -457,18 +457,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region View Definitions: common data internal sealed class ViewDefinitionsSection { - internal List viewDefinitionList = new List (); + internal List viewDefinitionList = new List(); } internal sealed partial class AppliesTo { //it can contain either a type or type group reference - internal List referenceList = new List (); + internal List referenceList = new List(); } internal sealed class GroupBy { - internal StartGroup startGroup = new StartGroup (); + internal StartGroup startGroup = new StartGroup(); // NOTE: extension point for describing: // * end group statistics // * end group footer @@ -505,7 +505,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// list of control definitions /// - internal List controlDefinitionList = new List (); + internal List controlDefinitionList = new List(); } /// @@ -533,7 +533,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// container for optional local formatting directives /// - internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder (); + internal FormatControlDefinitionHolder formatControlDefinitionHolder = new FormatControlDefinitionHolder(); /// /// main control for the view (e.g. reference to a control or a control body @@ -577,11 +577,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal string baseName = null; internal string resourceId = null; } - + #endregion - - - } namespace System.Management.Automation @@ -706,7 +703,7 @@ namespace System.Management.Automation /// You can group by same property value, or result of evaluating a script block. /// public PSControlGroupBy GroupBy { get; set; } - + /// /// When the "shape" of formatting has been determined by previous objects, /// sometimes you want objects of different types to continue using that shape diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs index 92a1e5749..e68de768e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; namespace Microsoft.PowerShell.Commands.Internal.Format { - #region Type Info Database internal sealed partial class TypeInfoDataBase @@ -16,7 +15,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } #endregion -#region View Definitions: common data + #region View Definitions: common data internal sealed partial class AppliesTo { #if false @@ -28,15 +27,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this.referenceList.Add (tgr); } #endif - internal void AddAppliesToType (string typeName) + internal void AddAppliesToType(string typeName) { - TypeReference tr = new TypeReference (); + TypeReference tr = new TypeReference(); tr.name = typeName; - this.referenceList.Add (tr); + this.referenceList.Add(tr); } } -#endregion - + #endregion } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index d67276b03..4b6a4f94b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -11,7 +11,6 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { - #region Complex View Definitions /// @@ -28,7 +27,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// optional list of list entry definition overrides. It can be empty if there are no overrides /// - internal List optionalEntryList = new List (); + internal List optionalEntryList = new List(); } internal sealed class ComplexControlEntryDefinition @@ -42,7 +41,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// item associated with this entry definition /// - internal ComplexControlItemDefinition itemDefinition = new ComplexControlItemDefinition (); + internal ComplexControlItemDefinition itemDefinition = new ComplexControlItemDefinition(); } internal sealed class ComplexControlItemDefinition @@ -50,12 +49,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// list of tokens the item can contain /// - internal List formatTokenList = new List (); + internal List formatTokenList = new List(); } - #endregion - } namespace System.Management.Automation @@ -98,7 +95,7 @@ namespace System.Management.Automation /// public static CustomControlBuilder Create(bool outOfBand = false) { - var customControl = new CustomControl {OutOfBand = outOfBand}; + var customControl = new CustomControl { OutOfBand = outOfBand }; return new CustomControlBuilder(customControl); } @@ -152,7 +149,7 @@ namespace System.Management.Automation /// public EntrySelectedBy SelectedBy { get; set; } - + /// public List CustomItems { get; set; } @@ -194,8 +191,8 @@ namespace System.Management.Automation { var frame = new CustomItemFrame { - RightIndent = (uint) frameToken.frameInfoDefinition.rightIndentation, - LeftIndent = (uint) frameToken.frameInfoDefinition.leftIndentation + RightIndent = (uint)frameToken.frameInfoDefinition.rightIndentation, + LeftIndent = (uint)frameToken.frameInfoDefinition.leftIndentation }; var firstLine = frameToken.frameInfoDefinition.firstLine; if (firstLine > 0) @@ -204,8 +201,7 @@ namespace System.Management.Automation } else if (firstLine < 0) { - frame.FirstLineHanging = (uint) -firstLine; - + frame.FirstLineHanging = (uint)-firstLine; } foreach (var frameItemToken in frameToken.itemDefinition.formatTokenList) { @@ -217,7 +213,7 @@ namespace System.Management.Automation var cpt = token as CompoundPropertyToken; if (cpt != null) { - var cie = new CustomItemExpression {EnumerateCollection = cpt.enumerateCollection}; + var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; if (cpt.conditionToken != null) { @@ -347,7 +343,7 @@ namespace System.Management.Automation /// public CustomEntryBuilder AddText(string text) { - _entryStack.Peek().Add(new CustomItemText {Text = text}); + _entryStack.Peek().Add(new CustomItemText { Text = text }); return this; } @@ -413,7 +409,7 @@ namespace System.Management.Automation EnumerateCollection = enumerateCollection, CustomControl = customControl }); - + return this; } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index ec96d08ec..9d612673f 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -12,7 +12,6 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { - #region List View Definitions /// @@ -29,7 +28,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// optional list of list entry definition overrides. It can be empty if there are no overrides /// - internal List optionalEntryList = new List (); + internal List optionalEntryList = new List(); internal override ControlBase Copy() { @@ -64,7 +63,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// mandatory list of list view items. /// It cannot be empty /// - internal List itemDefinitionList = new List (); + internal List itemDefinitionList = new List(); /// /// Returns a Shallow Copy of the current object. @@ -107,7 +106,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// * PropertyToken /// * NOTHING (provide an empty cell) /// - internal List formatTokenList = new List (); + internal List formatTokenList = new List(); } #endregion @@ -126,7 +125,7 @@ namespace System.Management.Automation /// public static ListControlBuilder Create(bool outOfBand = false) { - var list = new ListControl {OutOfBand = false}; + var list = new ListControl { OutOfBand = false }; return new ListControlBuilder(list); } @@ -160,7 +159,7 @@ namespace System.Management.Automation internal ListControl(ListControlBody listcontrolbody, ViewDefinition viewDefinition) : this() { - this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); + this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); this.OutOfBand = viewDefinition.outOfBand; Entries.Add(new ListControlEntry(listcontrolbody.defaultEntryDefinition)); @@ -212,13 +211,13 @@ namespace System.Management.Automation get { if (EntrySelectedBy == null) - EntrySelectedBy = new EntrySelectedBy {TypeNames = new List()}; + EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } } /// List of typenames and/or a script block which select this entry. - public EntrySelectedBy EntrySelectedBy { get; internal set; } + public EntrySelectedBy EntrySelectedBy { get; internal set; } /// Initiate an instance of ListControlEntry public ListControlEntry() @@ -259,7 +258,7 @@ namespace System.Management.Automation if (selectedBy == null) throw PSTraceSource.NewArgumentNullException("selectedBy"); - EntrySelectedBy = new EntrySelectedBy {TypeNames = new List(selectedBy)}; + EntrySelectedBy = new EntrySelectedBy { TypeNames = new List(selectedBy) }; foreach (ListControlEntryItem item in listItems) { this.Items.Add(item); @@ -268,7 +267,7 @@ namespace System.Management.Automation internal bool SafeForExport() { - foreach(var item in Items) + foreach (var item in Items) { if (!item.SafeForExport()) return false; @@ -279,7 +278,7 @@ namespace System.Management.Automation internal bool CompatibleWithOldPowerShell() { - foreach(var item in Items) + foreach (var item in Items) { if (!item.CompatibleWithOldPowerShell()) return false; diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs index 0002d65d6..65290f596 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs @@ -16,7 +16,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class FieldControlBody : ControlBody { - internal FieldFormattingDirective fieldFormattingDirective = new FieldFormattingDirective (); + internal FieldFormattingDirective fieldFormattingDirective = new FieldFormattingDirective(); } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index f2561a4fe..eb5326968 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -11,9 +11,8 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { - #region Table View Definitions - + /// /// alignment values /// NOTE: we do not use an enum because this will have to be @@ -35,7 +34,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// optional, if not present, use data off the default table row definition /// - internal TableHeaderDefinition header = new TableHeaderDefinition (); + internal TableHeaderDefinition header = new TableHeaderDefinition(); /// /// default row definition @@ -84,8 +83,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// mandatory list of column header definitions /// - internal List columnHeaderDefinitionList = - new List (); + internal List columnHeaderDefinitionList = + new List(); /// /// Returns a Shallow Copy of the current object. @@ -93,7 +92,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal TableHeaderDefinition Copy() { - TableHeaderDefinition result = new TableHeaderDefinition {hideHeader = this.hideHeader}; + TableHeaderDefinition result = new TableHeaderDefinition { hideHeader = this.hideHeader }; foreach (TableColumnHeaderDefinition tchd in this.columnHeaderDefinitionList) { result.columnHeaderDefinitionList.Add(tchd); @@ -124,7 +123,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal int width = 0; // undefined } - + /// /// definition of the data to be displayed in a table row /// @@ -146,7 +145,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// mandatory list of column items. /// It cannot be empty /// - internal List rowItemDefinitionList = new List (); + internal List rowItemDefinitionList = new List(); /// /// Returns a Shallow Copy of the current object. @@ -185,11 +184,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// * PropertyToken /// * NOTHING (provide an empty cell) /// - internal List formatTokenList = new List (); + internal List formatTokenList = new List(); } #endregion - } namespace System.Management.Automation @@ -214,7 +212,7 @@ namespace System.Management.Automation /// Create a default TableControl public static TableControlBuilder Create(bool outOfBand = false, bool autoSize = false, bool hideTableHeaders = false) { - var table = new TableControl {OutOfBand = outOfBand, AutoSize = autoSize, HideTableHeaders = hideTableHeaders}; + var table = new TableControl { OutOfBand = outOfBand, AutoSize = autoSize, HideTableHeaders = hideTableHeaders }; return new TableControlBuilder(table); } @@ -265,7 +263,7 @@ namespace System.Management.Automation internal TableControl(TableControlBody tcb, ViewDefinition viewDefinition) : this() { this.OutOfBand = viewDefinition.outOfBand; - this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); + this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); this.AutoSize = tcb.autosize.HasValue && tcb.autosize.Value; this.HideTableHeaders = tcb.header.hideHeader; @@ -294,7 +292,7 @@ namespace System.Management.Automation /// public TableControl(TableControlRow tableControlRow) : this() { - if(tableControlRow == null) + if (tableControlRow == null) throw PSTraceSource.NewArgumentNullException("tableControlRows"); this.Rows.Add(tableControlRow); @@ -584,11 +582,11 @@ namespace System.Management.Automation _table.Headers.Add(new TableControlColumnHeader(label, width, alignment)); return this; } - + /// Add a header public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerable entrySelectedByType = null, IEnumerable entrySelectedByCondition = null) { - var row = new TableControlRow {Wrap = wrap}; + var row = new TableControlRow { Wrap = wrap }; if (entrySelectedByType != null || entrySelectedByCondition != null) { row.SelectedBy = new EntrySelectedBy(); @@ -611,5 +609,4 @@ namespace System.Management.Automation return _table; } } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index fc9d481f0..660271fbc 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -12,7 +12,7 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands.Internal.Format { #region Wide View Definitions - + /// /// in line definition of a wide control /// @@ -32,7 +32,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// optional list of list entry definition overrides. It can be empty if there are no overrides /// - internal List optionalEntryList = new List (); + internal List optionalEntryList = new List(); } /// @@ -53,10 +53,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// * PropertyToken /// * NOTHING (provide an empty cell) /// - internal List formatTokenList = new List (); + internal List formatTokenList = new List(); } - #endregion + #endregion } namespace System.Management.Automation @@ -78,7 +78,7 @@ namespace System.Management.Automation /// Create a default WideControl public static WideControlBuilder Create(bool outOfBand = false, bool autoSize = false, uint columns = 0) { - var control = new WideControl {OutOfBand = false, AutoSize = autoSize, Columns = columns}; + var control = new WideControl { OutOfBand = false, AutoSize = autoSize, Columns = columns }; return new WideControlBuilder(control); } @@ -188,13 +188,13 @@ namespace System.Management.Automation get { if (EntrySelectedBy == null) - EntrySelectedBy = new EntrySelectedBy {TypeNames = new List()}; + EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } } /// List of typenames and/or a script block which select this entry. - public EntrySelectedBy EntrySelectedBy { get; internal set; } + public EntrySelectedBy EntrySelectedBy { get; internal set; } /// Format string to apply public string FormatString { get; internal set; } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 3c7295a6f..0df683aac 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Reflection; @@ -14,47 +15,47 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal enum LoadingResult { NoError, AssemblyNotFound, ResourceNotFound, StringNotFound } internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath }; - internal string GetTextTokenString (TextToken tt) + internal string GetTextTokenString(TextToken tt) { if (tt.resource != null) { - string resString = this.GetString (tt.resource); + string resString = this.GetString(tt.resource); if (resString != null) return resString; } return tt.text; } - internal void VerifyResource (StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) + internal void VerifyResource(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) { - GetStringHelper (resourceReference, out result, out bindingStatus); + GetStringHelper(resourceReference, out result, out bindingStatus); } - private string GetString (StringResourceReference resourceReference) + private string GetString(StringResourceReference resourceReference) { LoadingResult result; AssemblyBindingStatus bindingStatus; - return GetStringHelper (resourceReference, out result, out bindingStatus); + return GetStringHelper(resourceReference, out result, out bindingStatus); } - private string GetStringHelper (StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) + private string GetStringHelper(StringResourceReference resourceReference, out LoadingResult result, out AssemblyBindingStatus bindingStatus) { result = LoadingResult.AssemblyNotFound; bindingStatus = AssemblyBindingStatus.NotFound; AssemblyLoadResult loadResult = null; // try first to see if we have an assembly reference in the cache - if (_resourceReferenceToAssemblyCache.Contains (resourceReference)) + if (_resourceReferenceToAssemblyCache.Contains(resourceReference)) { loadResult = _resourceReferenceToAssemblyCache[resourceReference] as AssemblyLoadResult; bindingStatus = loadResult.status; } else { - loadResult = new AssemblyLoadResult (); + loadResult = new AssemblyLoadResult(); // we do not have an assembly, we try to load it bool foundInGac; - loadResult.a = LoadAssemblyFromResourceReference (resourceReference, out foundInGac); + loadResult.a = LoadAssemblyFromResourceReference(resourceReference, out foundInGac); if (loadResult.a == null) { loadResult.status = AssemblyBindingStatus.NotFound; @@ -65,7 +66,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // add to the cache even if null - _resourceReferenceToAssemblyCache.Add (resourceReference, loadResult); + _resourceReferenceToAssemblyCache.Add(resourceReference, loadResult); } bindingStatus = loadResult.status; @@ -76,12 +77,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format result = LoadingResult.AssemblyNotFound; return null; } - + // load now the resource from the resource manager cache try { - string val = ResourceManagerCache.GetResourceString (loadResult.a, resourceReference.baseName, resourceReference.resourceId); + string val = ResourceManagerCache.GetResourceString(loadResult.a, resourceReference.baseName, resourceReference.resourceId); if (val == null) { result = LoadingResult.StringNotFound; @@ -217,8 +218,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } private AssemblyNameResolver _assemblyNameResolver = new AssemblyNameResolver(); - private Hashtable _resourceReferenceToAssemblyCache = new Hashtable (); + private Hashtable _resourceReferenceToAssemblyCache = new Hashtable(); } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index ff9be138a..bbb57af17 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -32,12 +32,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// instance of the object holding the format.ps1xml in memory database /// - private TypeInfoDataBase dataBase; + private TypeInfoDataBase _dataBase; internal TypeInfoDataBase Database { get { - return dataBase; + return _dataBase; } } @@ -48,7 +48,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal object updateDatabaseLock = new object(); // this is used to throw errors when updating a shared TypeTable. internal bool isShared; - private List formatFileList; + private List _formatFileList; /// /// If set to true, disables any updates to format table. This includes disabling @@ -56,11 +56,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// All the disabling happens silently ie., the user will not get any exception. /// By default, this is set to False. /// - private bool disableFormatTableUpdates; + private bool _disableFormatTableUpdates; internal bool DisableFormatTableUpdates { - get { return disableFormatTableUpdates; } - set { disableFormatTableUpdates = value; } + get { return _disableFormatTableUpdates; } + set { _disableFormatTableUpdates = value; } } @@ -71,7 +71,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal TypeInfoDataBaseManager() { isShared = false; - formatFileList = new List(); + _formatFileList = new List(); } /// @@ -94,12 +94,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// detailed error messages. /// internal TypeInfoDataBaseManager( - IEnumerable formatFiles, - bool isShared, - AuthorizationManager authorizationManager, + IEnumerable formatFiles, + bool isShared, + AuthorizationManager authorizationManager, PSHost host) { - formatFileList = new List(); + _formatFileList = new List(); Collection filesToLoad = new Collection(); ConcurrentBag errors = new ConcurrentBag(); @@ -113,12 +113,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); fileToLoad.Errors = errors; filesToLoad.Add(fileToLoad); - formatFileList.Add(formatFile); + _formatFileList.Add(formatFile); } MshExpressionFactory expressionFactory = new MshExpressionFactory(); List logEntries = null; - + // load the files LoadFromFile(filesToLoad, expressionFactory, true, authorizationManager, host, false, out logEntries); this.isShared = isShared; @@ -134,7 +134,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal TypeInfoDataBase GetTypeInfoDataBase() { - return dataBase; + return _dataBase; } /// @@ -153,15 +153,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format throw PSTraceSource.NewArgumentException("formatFile", FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); } - lock (formatFileList) + lock (_formatFileList) { if (shouldPrepend) { - formatFileList.Insert(0, formatFile); + _formatFileList.Insert(0, formatFile); } else { - formatFileList.Add(formatFile); + _formatFileList.Add(formatFile); } } } @@ -173,9 +173,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal void Remove(string formatFile) { - lock (formatFileList) + lock (_formatFileList) { - formatFileList.Remove(formatFile); + _formatFileList.Remove(formatFile); } } @@ -193,33 +193,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal void AddFormatData(IEnumerable formatData, bool shouldPrepend) { Diagnostics.Assert(isShared, "this method should only be called from FormatTable to update a shared database"); - + Collection filesToLoad = new Collection(); ConcurrentBag errors = new ConcurrentBag(); - if(shouldPrepend) - { - foreach(ExtendedTypeDefinition typeDefinition in formatData) - { - PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition); - entryToLoad.Errors = errors; - filesToLoad.Add(entryToLoad); - } - // check if the passed in formatData is empty - if(filesToLoad.Count == 0) - { - return; - } - } - lock (formatFileList) - { - foreach (string formatFile in formatFileList) - { - PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); - fileToLoad.Errors = errors; - filesToLoad.Add(fileToLoad); - } - } - if(!shouldPrepend) + if (shouldPrepend) { foreach (ExtendedTypeDefinition typeDefinition in formatData) { @@ -228,7 +205,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format filesToLoad.Add(entryToLoad); } // check if the passed in formatData is empty - if(filesToLoad.Count == formatFileList.Count) + if (filesToLoad.Count == 0) + { + return; + } + } + lock (_formatFileList) + { + foreach (string formatFile in _formatFileList) + { + PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); + fileToLoad.Errors = errors; + filesToLoad.Add(fileToLoad); + } + } + if (!shouldPrepend) + { + foreach (ExtendedTypeDefinition typeDefinition in formatData) + { + PSSnapInTypeAndFormatErrors entryToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, typeDefinition); + entryToLoad.Errors = errors; + filesToLoad.Add(entryToLoad); + } + // check if the passed in formatData is empty + if (filesToLoad.Count == _formatFileList.Count) { return; } @@ -271,9 +271,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } Collection filesToLoad = new Collection(); - lock (formatFileList) + lock (_formatFileList) { - foreach (string formatFile in formatFileList) + foreach (string formatFile in _formatFileList) { PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); filesToLoad.Add(fileToLoad); @@ -363,7 +363,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format lock (databaseLock) { if (acceptLoadingErrors || success) - this.dataBase = newDataBase; + _dataBase = newDataBase; } } finally @@ -372,18 +372,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // data base to an empty instance lock (databaseLock) { - if (this.dataBase == null) + if (_dataBase == null) { TypeInfoDataBase tempDataBase = new TypeInfoDataBase(); AddPreLoadInstrinsics(tempDataBase); AddPostLoadInstrinsics(tempDataBase); - this.dataBase = tempDataBase; + _dataBase = tempDataBase; } } } return success; } - + /// /// it loads a database from file(s). /// @@ -403,8 +403,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// true if no error occurred /// a database instance loaded from file(s) private static TypeInfoDataBase LoadFromFileHelper( - Collection files, - MshExpressionFactory expressionFactory, + Collection files, + MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, bool preValidated, @@ -414,12 +414,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format success = true; // Holds the aggregated log entries for all files... logEntries = new List(); - + // fresh instance of the database TypeInfoDataBase db = new TypeInfoDataBase(); // prepopulate the database with any necessary overriding data - AddPreLoadInstrinsics (db); + AddPreLoadInstrinsics(db); var etwEnabled = RunspaceEventSource.Log.IsEnabled(); @@ -439,7 +439,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success)) { // Loads formatting data from formatting data XML file - XmlFileLoadInfo info = + XmlFileLoadInfo info = new XmlFileLoadInfo(Path.GetPathRoot(file.FullPath), file.FullPath, file.Errors, file.PSSnapinName); using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader()) { @@ -465,7 +465,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // add any sensible defaults to the database - AddPostLoadInstrinsics (db); + AddPostLoadInstrinsics(db); return db; } @@ -498,7 +498,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } private delegate IEnumerable TypeGenerator(); - private static Dictionary> _builtinGenerators; + private static Dictionary> s_builtinGenerators; private static Tuple GetBuiltin(bool isForHelp, TypeGenerator generator) { @@ -512,7 +512,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format List logEntries, ref bool success) { - if (_builtinGenerators == null) + if (s_builtinGenerators == null) { var builtInGenerators = new Dictionary>(StringComparer.OrdinalIgnoreCase); @@ -530,11 +530,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format builtInGenerators.Add(Path.Combine(psHome, "Registry.format.ps1xml"), GetBuiltin(false, Registry_Format_Ps1Xml.GetFormatData)); builtInGenerators.Add(Path.Combine(psHome, "WSMan.Format.ps1xml"), GetBuiltin(false, WSMan_Format_Ps1Xml.GetFormatData)); - Interlocked.CompareExchange(ref _builtinGenerators, builtInGenerators, null); + Interlocked.CompareExchange(ref s_builtinGenerators, builtInGenerators, null); } Tuple generator; - if (!_builtinGenerators.TryGetValue(file.FullPath, out generator)) + if (!s_builtinGenerators.TryGetValue(file.FullPath, out generator)) return false; ProcessBuiltinFormatViewDefinitions(generator.Item2(), db, expressionFactory, file, logEntries, generator.Item1, ref success); @@ -560,7 +560,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// helper to to add any pre-load intrinsics to the db /// /// db being iniitalized - private static void AddPreLoadInstrinsics (TypeInfoDataBase db) + private static void AddPreLoadInstrinsics(TypeInfoDataBase db) { // NOTE: nothing to add for the time being. Add here if needed. } @@ -569,17 +569,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// helper to to add any post-load intrinsics to the db /// /// db being iniitalized - private static void AddPostLoadInstrinsics (TypeInfoDataBase db) + private static void AddPostLoadInstrinsics(TypeInfoDataBase db) { // add entry for the output of update-formatdata // we want to be able to display this as a list, unless overridden // by an entry loaded from file - FormatShapeSelectionOnType sel = new FormatShapeSelectionOnType (); - sel.appliesTo = new AppliesTo (); + FormatShapeSelectionOnType sel = new FormatShapeSelectionOnType(); + sel.appliesTo = new AppliesTo(); sel.appliesTo.AddAppliesToType("Microsoft.PowerShell.Commands.FormatDataLoadingInfo"); sel.formatShape = FormatShape.List; - db.defaultSettingsSection.shapeSelectionDirectives.formatShapeSelectionOnTypeList.Add (sel); + db.defaultSettingsSection.shapeSelectionDirectives.formatShapeSelectionOnTypeList.Add(sel); } } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 165080689..d851b958b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -12,13 +12,12 @@ using System.Management.Automation; namespace Microsoft.PowerShell.Commands.Internal.Format { - internal static class DisplayCondition { - internal static bool Evaluate (PSObject obj, MshExpression ex, out MshExpressionResult expressionResult) + internal static bool Evaluate(PSObject obj, MshExpression ex, out MshExpressionResult expressionResult) { expressionResult = null; - List res = ex.GetValues (obj); + List res = ex.GetValues(obj); if (res.Count == 0) return false; if (res[0].Exception != null) @@ -26,7 +25,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format expressionResult = res[0]; return false; } - return LanguagePrimitives.IsTrue (res[0].Result); + return LanguagePrimitives.IsTrue(res[0].Result); } } @@ -38,12 +37,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class TypeMatchItem { - internal TypeMatchItem (object obj, AppliesTo a) + internal TypeMatchItem(object obj, AppliesTo a) { _item = obj; _appliesTo = a; } - internal TypeMatchItem (object obj, AppliesTo a, PSObject currentObject) + internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject) { _item = obj; _appliesTo = a; @@ -68,30 +67,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region tracer [TraceSource("TypeMatch", "F&O TypeMatch")] - private static readonly PSTraceSource classTracer = + private static readonly PSTraceSource s_classTracer = PSTraceSource.GetTracer("TypeMatch", "F&O TypeMatch"); - private static PSTraceSource activeTracer = null; + private static PSTraceSource s_activeTracer = null; private static PSTraceSource ActiveTracer { get { - return activeTracer ?? classTracer; + return s_activeTracer ?? s_classTracer; } } internal static void SetTracer(PSTraceSource t) { - activeTracer = t; + s_activeTracer = t; } internal static void ResetTracer() { - activeTracer = classTracer; + s_activeTracer = s_classTracer; } #endregion tracer - internal TypeMatch (MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) + internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) { _expressionFactory = expressionFactory; _db = db; @@ -99,7 +98,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format _useInheritance = true; } - internal TypeMatch (MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames, bool useInheritance) + internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames, bool useInheritance) { _expressionFactory = expressionFactory; _db = db; @@ -107,9 +106,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format _useInheritance = useInheritance; } - internal bool PerfectMatch (TypeMatchItem item) + internal bool PerfectMatch(TypeMatchItem item) { - int match = ComputeBestMatch (item.AppliesTo, item.CurrentObject); + int match = ComputeBestMatch(item.AppliesTo, item.CurrentObject); if (match == BestMatchIndexUndefined) return false; @@ -124,7 +123,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal object BestMatch { - get + get { if (_bestMatchItem == null) return null; @@ -132,7 +131,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private int ComputeBestMatch (AppliesTo appliesTo, PSObject currentObject) + private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) { int best = BestMatchIndexUndefined; foreach (TypeOrGroupReference r in appliesTo.referenceList) @@ -140,7 +139,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format MshExpression ex = null; if (r.conditionToken != null) { - ex = _expressionFactory.CreateFromExpressionToken (r.conditionToken); + ex = _expressionFactory.CreateFromExpressionToken(r.conditionToken); } int currentMatch = BestMatchIndexUndefined; @@ -149,7 +148,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (tr != null) { // we have a type - currentMatch = MatchTypeIndex (tr.name, currentObject, ex); + currentMatch = MatchTypeIndex(tr.name, currentObject, ex); } else { @@ -157,12 +156,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format TypeGroupReference tgr = r as TypeGroupReference; // find the type group definition the reference points to - TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition (_db, tgr.name); + TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition(_db, tgr.name); if (tgd != null) { // we found the group, see if the group has the type - currentMatch = ComputeBestMatchInGroup (tgd, currentObject, ex); + currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex); } } if (currentMatch == BestMatchIndexPerfect) @@ -177,13 +176,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return best; } - private int ComputeBestMatchInGroup (TypeGroupDefinition tgd, PSObject currentObject, MshExpression ex) + private int ComputeBestMatchInGroup(TypeGroupDefinition tgd, PSObject currentObject, MshExpression ex) { int best = BestMatchIndexUndefined; int k = 0; foreach (TypeReference tr in tgd.typeReferenceList) { - int currentMatch = MatchTypeIndex (tr.name, currentObject, ex); + int currentMatch = MatchTypeIndex(tr.name, currentObject, ex); if (currentMatch == BestMatchIndexPerfect) return currentMatch; @@ -196,36 +195,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return best; } - private int MatchTypeIndex (string typeName, PSObject currentObject, MshExpression ex) + private int MatchTypeIndex(string typeName, PSObject currentObject, MshExpression ex) { if (string.IsNullOrEmpty(typeName)) return BestMatchIndexUndefined; int k = 0; - foreach (string name in _typeNameHierarchy) + foreach (string name in _typeNameHierarchy) + { + if (string.Equals(name, typeName, StringComparison.OrdinalIgnoreCase) + && MatchCondition(currentObject, ex)) { - if (string.Equals(name, typeName, StringComparison.OrdinalIgnoreCase) - && MatchCondition(currentObject, ex)) - { - return k; - } - if (k == 0 && !_useInheritance) - break; - k++; + return k; } + if (k == 0 && !_useInheritance) + break; + k++; + } return BestMatchIndexUndefined; } - private bool MatchCondition (PSObject currentObject, MshExpression ex) + private bool MatchCondition(PSObject currentObject, MshExpression ex) { if (ex == null) return true; MshExpressionResult expressionResult; - bool retVal = DisplayCondition.Evaluate (currentObject, ex, out expressionResult); + bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { - _failedResultsList.Add (expressionResult); + _failedResultsList.Add(expressionResult); } return retVal; } @@ -234,9 +233,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private MshExpressionFactory _expressionFactory; private TypeInfoDataBase _db; private Collection _typeNameHierarchy; - bool _useInheritance; + private bool _useInheritance; - private List _failedResultsList = new List (); + private List _failedResultsList = new List(); private int _bestMatchIndex = BestMatchIndexUndefined; private TypeMatchItem _bestMatchItem; @@ -250,35 +249,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region tracer [TraceSource("DisplayDataQuery", "DisplayDataQuery")] - private static readonly PSTraceSource classTracer = + private static readonly PSTraceSource s_classTracer = PSTraceSource.GetTracer("DisplayDataQuery", "DisplayDataQuery"); - private static PSTraceSource activeTracer = null; + private static PSTraceSource s_activeTracer = null; private static PSTraceSource ActiveTracer { get { - return activeTracer ?? classTracer; + return s_activeTracer ?? s_classTracer; } } internal static void SetTracer(PSTraceSource t) { - activeTracer = t; + s_activeTracer = t; } internal static void ResetTracer() { - activeTracer = classTracer; + s_activeTracer = s_classTracer; } #endregion tracer - internal static EnumerableExpansion GetEnumerableExpansionFromType (MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) + internal static EnumerableExpansion GetEnumerableExpansionFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) { - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (EnumerableExpansionDirective expansionDirective in db.defaultSettingsSection.enumerableExpansionDirectiveList) { - if (match.PerfectMatch (new TypeMatchItem (expansionDirective, expansionDirective.appliesTo))) + if (match.PerfectMatch(new TypeMatchItem(expansionDirective, expansionDirective.appliesTo))) { return expansionDirective.enumerableExpansion; } @@ -301,14 +300,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - internal static FormatShape GetShapeFromType (MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) + internal static FormatShape GetShapeFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) { ShapeSelectionDirectives shapeDirectives = db.defaultSettingsSection.shapeSelectionDirectives; - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (FormatShapeSelectionOnType shapeSelOnType in shapeDirectives.formatShapeSelectionOnTypeList) { - if (match.PerfectMatch (new TypeMatchItem (shapeSelOnType, shapeSelOnType.appliesTo))) + if (match.PerfectMatch(new TypeMatchItem(shapeSelOnType, shapeSelOnType.appliesTo))) { return shapeSelOnType.formatShape; } @@ -331,7 +330,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - internal static FormatShape GetShapeFromPropertyCount (TypeInfoDataBase db, int propertyCount) + internal static FormatShape GetShapeFromPropertyCount(TypeInfoDataBase db, int propertyCount) { if (propertyCount <= db.defaultSettingsSection.shapeSelectionDirectives.PropertyCountForTable) return FormatShape.Table; @@ -340,7 +339,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } - internal static ViewDefinition GetViewByShapeAndType (MshExpressionFactory expressionFactory, TypeInfoDataBase db, + internal static ViewDefinition GetViewByShapeAndType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, FormatShape shape, Collection typeNames, string viewName) { if (shape == FormatShape.Undefined) @@ -373,16 +372,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return GetView(expressionFactory, db, t, typeNames, viewName); } - internal static ViewDefinition GetOutOfBandView (MshExpressionFactory expressionFactory, + internal static ViewDefinition GetOutOfBandView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) { - - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { - if (!IsOutOfBandView (vd)) + if (!IsOutOfBandView(vd)) continue; - if (match.PerfectMatch (new TypeMatchItem (vd, vd.appliesTo))) + if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo))) { return vd; } @@ -405,9 +403,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return result; } - private static ViewDefinition GetView (MshExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection typeNames, string viewName) + private static ViewDefinition GetView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection typeNames, string viewName) { - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { if (vd == null || mainControlType != vd.mainControl.GetType()) @@ -433,7 +431,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // first make sure we match on name: // if not, we do not try a match at all - if (viewName != null && !string.Equals (vd.name, viewName, StringComparison.OrdinalIgnoreCase)) + if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase)) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", @@ -512,9 +510,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return bestMatchedVD; } - private static ViewDefinition GetDefaultView (MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) + private static ViewDefinition GetDefaultView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection typeNames) { - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { @@ -568,7 +566,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } - private static bool IsOutOfBandView (ViewDefinition vd) + private static bool IsOutOfBandView(ViewDefinition vd) { return (vd.mainControl is ComplexControlBody || vd.mainControl is ListControlBody) && vd.outOfBand; } @@ -580,9 +578,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// database to use /// object to lookup /// - internal static AppliesTo GetAllApplicableTypes (TypeInfoDataBase db, AppliesTo appliesTo) + internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo appliesTo) { - Hashtable allTypes = new Hashtable (StringComparer.OrdinalIgnoreCase); + Hashtable allTypes = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (TypeOrGroupReference r in appliesTo.referenceList) { @@ -590,8 +588,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format TypeReference tr = r as TypeReference; if (tr != null) { - if (!allTypes.ContainsKey (tr.name)) - allTypes.Add (tr.name, null); + if (!allTypes.ContainsKey(tr.name)) + allTypes.Add(tr.name, null); } else { @@ -602,7 +600,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format continue; // find the type group definition the rererence points to - TypeGroupDefinition tgd = FindGroupDefinition (db, tgr.name); + TypeGroupDefinition tgd = FindGroupDefinition(db, tgr.name); if (tgd == null) continue; @@ -610,23 +608,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we found the group, go over it foreach (TypeReference x in tgd.typeReferenceList) { - if (!allTypes.ContainsKey (x.name)) - allTypes.Add (x.name, null); + if (!allTypes.ContainsKey(x.name)) + allTypes.Add(x.name, null); } } } - AppliesTo retVal = new AppliesTo (); + AppliesTo retVal = new AppliesTo(); foreach (DictionaryEntry x in allTypes) { - retVal.AddAppliesToType (x.Key as string); + retVal.AddAppliesToType(x.Key as string); } return retVal; } - internal static TypeGroupDefinition FindGroupDefinition (TypeInfoDataBase db, string groupName) + internal static TypeGroupDefinition FindGroupDefinition(TypeInfoDataBase db, string groupName) { foreach (TypeGroupDefinition tgd in db.typeGroupSection.typeGroupDefinitionList) { @@ -637,20 +635,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - internal static ControlBody ResolveControlReference (TypeInfoDataBase db, List viewControlDefinitionList, + internal static ControlBody ResolveControlReference(TypeInfoDataBase db, List viewControlDefinitionList, ControlReference controlReference) { // first tri to resolve the reference at the view level - ControlBody controlBody = ResolveControlReferenceInList (controlReference, + ControlBody controlBody = ResolveControlReferenceInList(controlReference, viewControlDefinitionList); if (controlBody != null) return controlBody; // fall back to the global definitions - return ResolveControlReferenceInList (controlReference, db.formatControlDefinitionHolder.controlDefinitionList); + return ResolveControlReferenceInList(controlReference, db.formatControlDefinitionHolder.controlDefinitionList); } - private static ControlBody ResolveControlReferenceInList (ControlReference controlReference, + private static ControlBody ResolveControlReferenceInList(ControlReference controlReference, List controlDefinitionList) { foreach (ControlDefinition x in controlDefinitionList) diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 9ea28ab27..b43f275aa 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -19,7 +19,6 @@ using System.Threading; namespace Microsoft.PowerShell.Commands.Internal.Format { - internal sealed class XmlFileLoadInfo { internal XmlFileLoadInfo() { } @@ -46,8 +45,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private const string resBaseName = "TypeInfoDataBaseLoaderStrings"; #region tracer - [TraceSource ("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader")] - private static PSTraceSource tracer = PSTraceSource.GetTracer ("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader"); + [TraceSource("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader")] + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader"); #endregion tracer /// @@ -61,7 +60,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal const string SelectionSetsNode = "SelectionSets"; internal const string ViewDefinitionsNode = "ViewDefinitions"; internal const string ControlsNode = "Controls"; - + // default settings entries internal const string MultilineTablesNode = "WrapTables"; internal const string PropertyCountForTableNode = "PropertyCountForTable"; @@ -152,7 +151,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal const string AssemblyNameAttribute = "AssemblyName"; internal const string BaseNameAttribute = "BaseName"; internal const string ResourceIdAttribute = "ResourceId"; - } /// @@ -170,7 +168,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // Flag that determines whether validation should be suppressed while // processing pre-validated type / formatting information. - private bool suppressValidation = false; + private bool _suppressValidation = false; /// @@ -191,24 +189,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// true if successful internal bool LoadXmlFile( - XmlFileLoadInfo info, - TypeInfoDataBase db, + XmlFileLoadInfo info, + TypeInfoDataBase db, MshExpressionFactory expressionFactory, AuthorizationManager authorizationManager, PSHost host, bool preValidated) { if (info == null) - throw PSTraceSource.NewArgumentNullException ("info"); + throw PSTraceSource.NewArgumentNullException("info"); if (info.filePath == null) - throw PSTraceSource.NewArgumentNullException ("info.filePath"); + throw PSTraceSource.NewArgumentNullException("info.filePath"); if (db == null) - throw PSTraceSource.NewArgumentNullException ("db"); + throw PSTraceSource.NewArgumentNullException("db"); if (expressionFactory == null) - throw PSTraceSource.NewArgumentNullException ("expressionFactory"); + throw PSTraceSource.NewArgumentNullException("expressionFactory"); if (SecuritySupport.IsProductBinary(info.filePath)) { @@ -219,7 +217,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this.expressionFactory = expressionFactory; this.SetDatabaseLoadingInfo(info); - this.ReportTrace ("loading file started"); + this.ReportTrace("loading file started"); // load file into XML document XmlDocument newDocument = null; @@ -241,10 +239,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // load the XML document into a copy of the // in memory database - bool previousSuppressValidation = this.suppressValidation; + bool previousSuppressValidation = _suppressValidation; try { - this.suppressValidation = preValidated; + _suppressValidation = preValidated; try { @@ -268,10 +266,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } finally { - this.suppressValidation = previousSuppressValidation; + _suppressValidation = previousSuppressValidation; } - this.ReportTrace ("file loaded with no errors"); + this.ReportTrace("file loaded with no errors"); return true; } @@ -285,8 +283,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// true when the view is for help output /// internal bool LoadFormattingData( - ExtendedTypeDefinition typeDefinition, - TypeInfoDataBase db, + ExtendedTypeDefinition typeDefinition, + TypeInfoDataBase db, MshExpressionFactory expressionFactory, bool isBuiltInFormatData, bool isForHelp) @@ -336,13 +334,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// XML document to load from, cannot be null /// instance of the databaseto load into - private void LoadData (XmlDocument doc, TypeInfoDataBase db) + private void LoadData(XmlDocument doc, TypeInfoDataBase db) { if (doc == null) - throw PSTraceSource.NewArgumentNullException ("doc"); + throw PSTraceSource.NewArgumentNullException("doc"); if (db == null) - throw PSTraceSource.NewArgumentNullException ("db"); + throw PSTraceSource.NewArgumentNullException("db"); // create a new instance of the database to be loaded XmlElement documentElement = doc.DocumentElement; @@ -352,59 +350,59 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool viewDefinitionsFound = false; bool controlDefinitionsFound = false; - if (MatchNodeName (documentElement, XmlTags.ConfigurationNode)) + if (MatchNodeName(documentElement, XmlTags.ConfigurationNode)) { // load the various sections - using (this.StackFrame (documentElement)) + using (this.StackFrame(documentElement)) { foreach (XmlNode n in documentElement.ChildNodes) { - if (MatchNodeName (n, XmlTags.DefaultSettingsNode)) + if (MatchNodeName(n, XmlTags.DefaultSettingsNode)) { if (defaultSettingsNodeFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } defaultSettingsNodeFound = true; - LoadDefaultSettings (db, n); + LoadDefaultSettings(db, n); } - else if (MatchNodeName (n, XmlTags.SelectionSetsNode)) + else if (MatchNodeName(n, XmlTags.SelectionSetsNode)) { if (typeGroupsFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } typeGroupsFound = true; - LoadTypeGroups (db, n); + LoadTypeGroups(db, n); } - else if (MatchNodeName (n, XmlTags.ViewDefinitionsNode)) + else if (MatchNodeName(n, XmlTags.ViewDefinitionsNode)) { if (viewDefinitionsFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } viewDefinitionsFound = true; - LoadViewDefinitions (db, n); + LoadViewDefinitions(db, n); } - else if (MatchNodeName (n, XmlTags.ControlsNode)) + else if (MatchNodeName(n, XmlTags.ControlsNode)) { if (controlDefinitionsFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } controlDefinitionsFound = true; - LoadControlDefinitions (n, db.formatControlDefinitionHolder.controlDefinitionList); + LoadControlDefinitions(n, db.formatControlDefinitionHolder.controlDefinitionList); } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } // foreach } // using } else { - ProcessUnknownNode (documentElement); + ProcessUnknownNode(documentElement); } } @@ -462,7 +460,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format AppliesTo appliesTo = new AppliesTo(); foreach (var typename in typeNames) { - TypeReference tr = new TypeReference {name = typename}; + TypeReference tr = new TypeReference { name = typename }; appliesTo.referenceList.Add(tr); } @@ -473,28 +471,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format var firstTypeName = typeNames[0]; PSControl control = formatView.Control; - if(control is TableControl) + if (control is TableControl) { var tableControl = control as TableControl; view.mainControl = LoadTableControlFromObjectModel(tableControl, viewIndex, firstTypeName); } - else if(control is ListControl) + else if (control is ListControl) { var listControl = control as ListControl; view.mainControl = LoadListControlFromObjectModel(listControl, viewIndex, firstTypeName); } - else if(control is WideControl) + else if (control is WideControl) { var wideControl = control as WideControl; view.mainControl = LoadWideControlFromObjectModel(wideControl, viewIndex, firstTypeName); } else { - view.mainControl = LoadCustomControlFromObjectModel((CustomControl) control, viewIndex, firstTypeName); + view.mainControl = LoadCustomControlFromObjectModel((CustomControl)control, viewIndex, firstTypeName); } // Check if the PSControl is successfully loaded - if(view.mainControl == null) + if (view.mainControl == null) { return null; } @@ -512,7 +510,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format }; if (control.GroupBy.Label != null) { - view.groupBy.startGroup.labelTextToken = new TextToken {text = control.GroupBy.Label}; + view.groupBy.startGroup.labelTextToken = new TextToken { text = control.GroupBy.Label }; } if (control.GroupBy.CustomControl != null) { @@ -534,7 +532,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private ControlBase LoadTableControlFromObjectModel(TableControl table, int viewIndex, string typeName) { - TableControlBody tableBody = new TableControlBody {autosize = table.AutoSize}; + TableControlBody tableBody = new TableControlBody { autosize = table.AutoSize }; LoadHeadersSectionFromObjectModel(tableBody, table.Headers); @@ -550,7 +548,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format LoadRowEntriesSectionFromObjectModel(tableBody, table.Rows, viewIndex, typeName); // When error occurs while loading rowEntry, the tableBody.defaultDefinition would be null - if(tableBody.defaultDefinition == null) + if (tableBody.defaultDefinition == null) { return null; } @@ -594,7 +592,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // Label --- Lable cardinality 0..1 // Width --- Width cardinality 0..1 // Alignment --- Alignment cardinality 0..1 - if(!String.IsNullOrEmpty(header.Label)) + if (!String.IsNullOrEmpty(header.Label)) { TextToken tt = new TextToken(); tt.text = header.Label; @@ -618,7 +616,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { foreach (TableControlRow row in rowEntries) { - TableRowDefinition trd = new TableRowDefinition {multiLine = row.Wrap}; + TableRowDefinition trd = new TableRowDefinition { multiLine = row.Wrap }; // Contains: // Columns --- TableColumnItems cardinality: 0..1 @@ -646,7 +644,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // rowEntries must not be empty - if(tableBody.defaultDefinition == null) + if (tableBody.defaultDefinition == null) { this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntryInFormattingData, typeName, viewIndex, XmlTags.TableRowEntryNode), typeName); @@ -663,17 +661,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private void LoadColumnEntriesFromObjectModel(TableRowDefinition trd, List columns, int viewIndex, string typeName) { - foreach(TableControlColumn column in columns) + foreach (TableControlColumn column in columns) { TableRowItemDefinition rid = new TableRowItemDefinition(); // Contain: // DisplayEntry --- Expression cardinality: 0..1 // Alignment --- Alignment cardinality: 0..1 - if(column.DisplayEntry != null) + if (column.DisplayEntry != null) { ExpressionToken expression = LoadExpressionFromObjectModel(column.DisplayEntry, viewIndex, typeName); - if(expression == null) + if (expression == null) { trd.rowItemDefinitionList = null; return; @@ -701,12 +699,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private ExpressionToken LoadExpressionFromObjectModel(DisplayEntry displayEntry, int viewIndex, string typeName) { ExpressionToken token = new ExpressionToken(); - if(displayEntry.ValueType == DisplayEntryValueType.Property) + if (displayEntry.ValueType == DisplayEntryValueType.Property) { token.expressionValue = displayEntry.Value; return token; } - else if(displayEntry.ValueType == DisplayEntryValueType.ScriptBlock) + else if (displayEntry.ValueType == DisplayEntryValueType.ScriptBlock) { token.isScriptBlock = true; token.expressionValue = displayEntry.Value; @@ -753,7 +751,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (String.IsNullOrEmpty(type)) return null; - TypeReference tr = new TypeReference {name = type}; + TypeReference tr = new TypeReference { name = type }; appliesTo.referenceList.Add(tr); } } @@ -784,7 +782,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // load the list entries section LoadListControlEntriesFromObjectModel(listBody, list.Entries, viewIndex, typeName); - if(listBody.defaultEntryDefinition == null) + if (listBody.defaultEntryDefinition == null) { return null; // fatal error } @@ -798,7 +796,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (ListControlEntry listEntry in entries) { ListControlEntryDefinition lved = LoadListControlEntryDefinitionFromObjectModel(listEntry, viewIndex, typeName); - if(lved == null) + if (lved == null) { this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailedInFormattingData, typeName, viewIndex, XmlTags.ListEntryNode), typeName); @@ -827,7 +825,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } // list entries is empty - if(listBody.defaultEntryDefinition == null) + if (listBody.defaultEntryDefinition == null) { // Error: there must be at least one default this.ReportErrorForLoadingFromObjectModel( @@ -849,20 +847,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // Contains: // SelectedBy --- EntrySelectedBy(TypeName) cardinality 0..1 // Items --- ListItems cardinality 1 - if(listEntry.EntrySelectedBy != null) + if (listEntry.EntrySelectedBy != null) { lved.appliesTo = LoadAppliesToSectionFromObjectModel(listEntry.EntrySelectedBy.TypeNames, listEntry.EntrySelectedBy.SelectionCondition); } LoadListControlItemDefinitionsFromObjectModel(lved, listEntry.Items, viewIndex, typeName); - if(lved.itemDefinitionList == null) + if (lved.itemDefinitionList == null) { return null; } return lved; } - + /// /// Load ListItems into ListControlItemDefinition /// @@ -879,10 +877,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // Contains: // DisplayEntry --- Expression cardinality 0..1 // Label --- Label cardinality 0..1 - if(listItem.DisplayEntry != null) + if (listItem.DisplayEntry != null) { ExpressionToken expression = LoadExpressionFromObjectModel(listItem.DisplayEntry, viewIndex, typeName); - if(expression == null) + if (expression == null) { lved.itemDefinitionList = null; return; // fatal @@ -938,7 +936,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format wideBody.autosize = true; LoadWideControlEntriesFromObjectModel(wideBody, wide.Entries, viewIndex, typeName); - if(wideBody.defaultEntryDefinition == null) + if (wideBody.defaultEntryDefinition == null) { // if we have no default entry definition, it means there was a failure return null; @@ -958,7 +956,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (WideControlEntryItem wideItem in wideEntries) { WideControlEntryDefinition wved = LoadWideControlEntryFromObjectModel(wideItem, viewIndex, typeName); - if(wved == null) + if (wved == null) { this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidFormattingData, typeName, viewIndex, XmlTags.WideEntryNode), typeName); @@ -987,7 +985,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format wideBody.optionalEntryList.Add(wved); } } - if(wideBody.defaultEntryDefinition == null) + if (wideBody.defaultEntryDefinition == null) { this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntryInFormattingData, typeName, viewIndex, XmlTags.WideEntryNode), typeName); @@ -1081,13 +1079,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format var text = item as CustomItemText; if (text != null) { - return new TextToken {text = text.Text}; + return new TextToken { text = text.Text }; } var expr = item as CustomItemExpression; if (expr != null) { - var cpt = new CompoundPropertyToken {enumerateCollection = expr.EnumerateCollection}; + var cpt = new CompoundPropertyToken { enumerateCollection = expr.EnumerateCollection }; if (expr.ItemSelectionCondition != null) { @@ -1108,7 +1106,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } - var frame = (CustomItemFrame) item; + var frame = (CustomItemFrame)item; var frameToken = new FrameToken { frameInfoDefinition = @@ -1132,7 +1130,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Default Settings Loading - private void LoadDefaultSettings (TypeInfoDataBase db, XmlNode defaultSettingsNode) + private void LoadDefaultSettings(TypeInfoDataBase db, XmlNode defaultSettingsNode) { // all these nodes are of [0..1] cardinality bool propertyCountForTableFound = false; @@ -1143,7 +1141,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool tempVal; - using (this.StackFrame (defaultSettingsNode)) + using (this.StackFrame(defaultSettingsNode)) { foreach (XmlNode n in defaultSettingsNode.ChildNodes) { @@ -1151,32 +1149,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (showErrorsAsMessagesFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } showErrorsAsMessagesFound = true; - if (ReadBooleanNode (n, out tempVal)) + if (ReadBooleanNode(n, out tempVal)) db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages = tempVal; } - else if (MatchNodeName (n, XmlTags.ShowErrorsInFormattedOutputNode)) + else if (MatchNodeName(n, XmlTags.ShowErrorsInFormattedOutputNode)) { if (showErrorsInFormattedOutputFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } showErrorsInFormattedOutputFound = true; - if (ReadBooleanNode (n, out tempVal)) + if (ReadBooleanNode(n, out tempVal)) db.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput = tempVal; } - else if (MatchNodeName (n, XmlTags.PropertyCountForTableNode)) + else if (MatchNodeName(n, XmlTags.PropertyCountForTableNode)) { if (propertyCountForTableFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } propertyCountForTableFound = true; int val; - if (ReadPositiveIntegerValue (n, out val)) + if (ReadPositiveIntegerValue(n, out val)) { db.defaultSettingsSection.shapeSelectionDirectives.PropertyCountForTable = val; } @@ -1186,15 +1184,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNodeValue, ComputeCurrentXPath(), FilePath, XmlTags.PropertyCountForTableNode)); } } - else if (MatchNodeName (n, XmlTags.MultilineTablesNode)) + else if (MatchNodeName(n, XmlTags.MultilineTablesNode)) { if (multilineTablesFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } multilineTablesFound = true; - if (ReadBooleanNode (n, out tempVal)) + if (ReadBooleanNode(n, out tempVal)) { db.defaultSettingsSection.MultilineTables = tempVal; } @@ -1204,81 +1202,80 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNodeValue, ComputeCurrentXPath(), FilePath, XmlTags.MultilineTablesNode)); } } - else if (MatchNodeName (n, XmlTags.EnumerableExpansionsNode)) + else if (MatchNodeName(n, XmlTags.EnumerableExpansionsNode)) { if (enumerableExpansionsFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); } enumerableExpansionsFound = true; db.defaultSettingsSection.enumerableExpansionDirectiveList = - LoadEnumerableExpansionDirectiveList (n); + LoadEnumerableExpansionDirectiveList(n); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } } } - private List LoadEnumerableExpansionDirectiveList (XmlNode expansionListNode) + private List LoadEnumerableExpansionDirectiveList(XmlNode expansionListNode) { - List retVal = - new List (); - using (this.StackFrame (expansionListNode)) + List retVal = + new List(); + using (this.StackFrame(expansionListNode)) { - int k = 0; foreach (XmlNode n in expansionListNode.ChildNodes) { if (MatchNodeName(n, XmlTags.EnumerableExpansionNode)) { - EnumerableExpansionDirective eed = LoadEnumerableExpansionDirective (n, k++); + EnumerableExpansionDirective eed = LoadEnumerableExpansionDirective(n, k++); if (eed == null) { //Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.EnumerableExpansionNode)); return null; // fatal error } - retVal.Add (eed); + retVal.Add(eed); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } } return retVal; } - private EnumerableExpansionDirective LoadEnumerableExpansionDirective (XmlNode directive, int index) + private EnumerableExpansionDirective LoadEnumerableExpansionDirective(XmlNode directive, int index) { - using (this.StackFrame (directive, index)) + using (this.StackFrame(directive, index)) { - EnumerableExpansionDirective eed = new EnumerableExpansionDirective (); + EnumerableExpansionDirective eed = new EnumerableExpansionDirective(); bool appliesToNodeFound = false; // cardinality 1 bool expandNodeFound = false; // cardinality 1 foreach (XmlNode n in directive.ChildNodes) { - if (MatchNodeName (n, XmlTags.EntrySelectedByNode)) + if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } appliesToNodeFound = true; - eed.appliesTo = LoadAppliesToSection (n, true); + eed.appliesTo = LoadAppliesToSection(n, true); } - else if (MatchNodeName (n, XmlTags.ExpandNode)) + else if (MatchNodeName(n, XmlTags.ExpandNode)) { if (expandNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } @@ -1288,7 +1285,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { return null; //fatal } - bool success = EnumerableExpansionConversion.Convert (s, out eed.enumerableExpansion); + bool success = EnumerableExpansionConversion.Convert(s, out eed.enumerableExpansion); if (!success) { //Error at XPath {0} in file {1}: Invalid {2} value. @@ -1298,7 +1295,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } return eed; @@ -1310,124 +1307,124 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Type Groups Loading - private void LoadTypeGroups (TypeInfoDataBase db, XmlNode typeGroupsNode) + private void LoadTypeGroups(TypeInfoDataBase db, XmlNode typeGroupsNode) { - using (this.StackFrame (typeGroupsNode)) + using (this.StackFrame(typeGroupsNode)) { int typeGroupCount = 0; foreach (XmlNode n in typeGroupsNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.SelectionSetNode)) + if (MatchNodeName(n, XmlTags.SelectionSetNode)) { - LoadTypeGroup (db, n, typeGroupCount++); + LoadTypeGroup(db, n, typeGroupCount++); } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } // for each } //using } - private void LoadTypeGroup (TypeInfoDataBase db, XmlNode typeGroupNode, int index) + private void LoadTypeGroup(TypeInfoDataBase db, XmlNode typeGroupNode, int index) { - using (this.StackFrame (typeGroupNode, index)) + using (this.StackFrame(typeGroupNode, index)) { // create data structure - TypeGroupDefinition typeGroupDefinition = new TypeGroupDefinition (); + TypeGroupDefinition typeGroupDefinition = new TypeGroupDefinition(); bool nameNodeFound = false; foreach (XmlNode n in typeGroupNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.NameNode)) + if (MatchNodeName(n, XmlTags.NameNode)) { if (nameNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); continue; } nameNodeFound = true; - typeGroupDefinition.name = GetMandatoryInnerText (n); + typeGroupDefinition.name = GetMandatoryInnerText(n); } - else if (MatchNodeName (n, XmlTags.TypesNode)) + else if (MatchNodeName(n, XmlTags.TypesNode)) { - LoadTypeGroupTypeRefs (n, typeGroupDefinition); + LoadTypeGroupTypeRefs(n, typeGroupDefinition); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (!nameNodeFound) { - this.ReportMissingNode (XmlTags.NameNode); + this.ReportMissingNode(XmlTags.NameNode); } // finally add to the list - db.typeGroupSection.typeGroupDefinitionList.Add (typeGroupDefinition); + db.typeGroupSection.typeGroupDefinitionList.Add(typeGroupDefinition); } // using } - private void LoadTypeGroupTypeRefs (XmlNode typesNode, TypeGroupDefinition typeGroupDefinition) + private void LoadTypeGroupTypeRefs(XmlNode typesNode, TypeGroupDefinition typeGroupDefinition) { - using (this.StackFrame (typesNode)) + using (this.StackFrame(typesNode)) { int typeRefCount = 0; foreach (XmlNode n in typesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.TypeNameNode)) + if (MatchNodeName(n, XmlTags.TypeNameNode)) { - using (this.StackFrame (n, typeRefCount++)) + using (this.StackFrame(n, typeRefCount++)) { - TypeReference tr = new TypeReference (); + TypeReference tr = new TypeReference(); - tr.name = GetMandatoryInnerText (n); - typeGroupDefinition.typeReferenceList.Add (tr); + tr.name = GetMandatoryInnerText(n); + typeGroupDefinition.typeReferenceList.Add(tr); } // using } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } } } - #endregion + #endregion -#region AppliesTo Loading + #region AppliesTo Loading - private AppliesTo LoadAppliesToSection (XmlNode appliesToNode, bool allowSelectionCondition) + private AppliesTo LoadAppliesToSection(XmlNode appliesToNode, bool allowSelectionCondition) { - using (this.StackFrame (appliesToNode)) + using (this.StackFrame(appliesToNode)) { - AppliesTo appliesTo = new AppliesTo (); + AppliesTo appliesTo = new AppliesTo(); // expect: type ref, group ref, or nothing foreach (XmlNode n in appliesToNode.ChildNodes) { - using (this.StackFrame (n)) + using (this.StackFrame(n)) { - if (MatchNodeName (n, XmlTags.SelectionSetNameNode)) + if (MatchNodeName(n, XmlTags.SelectionSetNameNode)) { - TypeGroupReference tgr = LoadTypeGroupReference (n); + TypeGroupReference tgr = LoadTypeGroupReference(n); if (tgr != null) { - appliesTo.referenceList.Add (tgr); + appliesTo.referenceList.Add(tgr); } else { return null; } } - else if (MatchNodeName (n, XmlTags.TypeNameNode)) + else if (MatchNodeName(n, XmlTags.TypeNameNode)) { - TypeReference tr = LoadTypeReference (n); + TypeReference tr = LoadTypeReference(n); if (tr != null) { appliesTo.referenceList.Add(tr); @@ -1437,12 +1434,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } } - else if (allowSelectionCondition && MatchNodeName (n, XmlTags.SelectionConditionNode)) + else if (allowSelectionCondition && MatchNodeName(n, XmlTags.SelectionConditionNode)) { - TypeOrGroupReference tgr = LoadSelectionConditionNode (n); + TypeOrGroupReference tgr = LoadSelectionConditionNode(n); if (tgr != null) { - appliesTo.referenceList.Add (tgr); + appliesTo.referenceList.Add(tgr); } else { @@ -1451,7 +1448,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } // using } @@ -1468,35 +1465,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private TypeReference LoadTypeReference (XmlNode n) + private TypeReference LoadTypeReference(XmlNode n) { - string val = GetMandatoryInnerText (n); + string val = GetMandatoryInnerText(n); if (val != null) { - TypeReference tr = new TypeReference (); + TypeReference tr = new TypeReference(); tr.name = val; return tr; } return null; } - private TypeGroupReference LoadTypeGroupReference (XmlNode n) + private TypeGroupReference LoadTypeGroupReference(XmlNode n) { - string val = GetMandatoryInnerText (n); + string val = GetMandatoryInnerText(n); if (val != null) { - TypeGroupReference tgr = new TypeGroupReference (); + TypeGroupReference tgr = new TypeGroupReference(); tgr.name = val; return tgr; } return null; } - private TypeOrGroupReference LoadSelectionConditionNode (XmlNode selectionConditionNode) + private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditionNode) { - using (this.StackFrame (selectionConditionNode)) + using (this.StackFrame(selectionConditionNode)) { TypeOrGroupReference retVal = null; @@ -1506,19 +1503,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool typeFound = false; // cardinality 0..1 bool typeGroupFound = false; // cardinality 0..1 - ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch (this); + ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this); foreach (XmlNode n in selectionConditionNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.SelectionSetNameNode)) + if (MatchNodeName(n, XmlTags.SelectionSetNameNode)) { if (typeGroupFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); return null; } typeGroupFound = true; - TypeGroupReference tgr = LoadTypeGroupReference (n); + TypeGroupReference tgr = LoadTypeGroupReference(n); if (tgr != null) { retVal = tgr; @@ -1528,15 +1525,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } } - else if (MatchNodeName (n, XmlTags.TypeNameNode)) + else if (MatchNodeName(n, XmlTags.TypeNameNode)) { if (typeFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode); return null; } typeFound = true; - TypeReference tr = LoadTypeReference (n); + TypeReference tr = LoadTypeReference(n); if (tr != null) { retVal = tr; @@ -1550,16 +1547,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (expressionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } expressionNodeFound = true; - if (!expressionMatch.ProcessNode (n)) + if (!expressionMatch.ProcessNode(n)) return null; // fatal error } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -1574,14 +1571,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (retVal == null) { // missing mandatory node - this.ReportMissingNodes (new string[] { XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode }); + this.ReportMissingNodes(new string[] { XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode }); return null; } if (expressionNodeFound) { // mandatory node - retVal.conditionToken = expressionMatch.GenerateExpressionToken (); + retVal.conditionToken = expressionMatch.GenerateExpressionToken(); if (retVal.conditionToken == null) { return null; // fatal error @@ -1594,16 +1591,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } } -#endregion + #endregion -#region GroupBy Loading + #region GroupBy Loading - private GroupBy LoadGroupBySection (XmlNode groupByNode) + private GroupBy LoadGroupBySection(XmlNode groupByNode) { - using (this.StackFrame (groupByNode)) + using (this.StackFrame(groupByNode)) { - ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch (this); - ComplexControlMatch controlMatch = new ComplexControlMatch (this); + ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this); + ComplexControlMatch controlMatch = new ComplexControlMatch(this); bool expressionNodeFound = false; // cardinality 0..1 @@ -1611,38 +1608,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool controlFound = false; // cardinality 0..1 bool labelFound = false; // cardinality 0..1 - GroupBy groupBy = new GroupBy (); + GroupBy groupBy = new GroupBy(); TextToken labelTextToken = null; foreach (XmlNode n in groupByNode) { - if (expressionMatch.MatchNode (n)) + if (expressionMatch.MatchNode(n)) { if (expressionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } expressionNodeFound = true; - if (!expressionMatch.ProcessNode (n)) + if (!expressionMatch.ProcessNode(n)) return null; // fatal error } - else if (controlMatch.MatchNode (n)) + else if (controlMatch.MatchNode(n)) { if (controlFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } controlFound = true; - if (!controlMatch.ProcessNode (n)) + if (!controlMatch.ProcessNode(n)) return null; // fatal error } - else if (MatchNodeNameWithAttributes (n, XmlTags.LabelNode)) + else if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode)) { if (labelFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } labelFound = true; @@ -1652,11 +1649,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { return null; // fatal error } - } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -1688,7 +1684,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (expressionNodeFound) { // we add only if we encountered one, since it's not mandatory - ExpressionToken expression = expressionMatch.GenerateExpressionToken (); + ExpressionToken expression = expressionMatch.GenerateExpressionToken(); if (expression == null) { return null; // fatal error @@ -1706,19 +1702,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } - private TextToken LoadLabel (XmlNode textNode) + private TextToken LoadLabel(XmlNode textNode) { - using (this.StackFrame (textNode)) + using (this.StackFrame(textNode)) { - return LoadTextToken (textNode); + return LoadTextToken(textNode); } } - private TextToken LoadTextToken (XmlNode n) + private TextToken LoadTextToken(XmlNode n) { - TextToken tt = new TextToken (); + TextToken tt = new TextToken(); - if (!LoadStringResourceReference (n, out tt.resource)) + if (!LoadStringResourceReference(n, out tt.resource)) { return null; } @@ -1730,7 +1726,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // inner text is mandatory - tt.text = this.GetMandatoryInnerText (n); + tt.text = this.GetMandatoryInnerText(n); if (tt.text == null) return null; @@ -1757,15 +1753,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // need to find mandatory attributes - resource = LoadResourceAttributes (e.Attributes); + resource = LoadResourceAttributes(e.Attributes); // we committed to having resources, if not obtained, it's an error return resource != null; } - private StringResourceReference LoadResourceAttributes (XmlAttributeCollection attributes) + private StringResourceReference LoadResourceAttributes(XmlAttributeCollection attributes) { - StringResourceReference resource = new StringResourceReference (); + StringResourceReference resource = new StringResourceReference(); foreach (XmlAttribute a in attributes) { if (MatchAttributeName(a, XmlTags.AssemblyNameAttribute)) @@ -1774,21 +1770,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (resource.assemblyName == null) return null; } - else if (MatchAttributeName (a, XmlTags.BaseNameAttribute)) + else if (MatchAttributeName(a, XmlTags.BaseNameAttribute)) { - resource.baseName = GetMandatoryAttributeValue (a); + resource.baseName = GetMandatoryAttributeValue(a); if (resource.baseName == null) return null; } - else if (MatchAttributeName (a, XmlTags.ResourceIdAttribute)) + else if (MatchAttributeName(a, XmlTags.ResourceIdAttribute)) { - resource.resourceId = GetMandatoryAttributeValue (a); + resource.resourceId = GetMandatoryAttributeValue(a); if (resource.resourceId == null) return null; } else { - ProcessUnknownAttribute (a); + ProcessUnknownAttribute(a); return null; } } @@ -1796,17 +1792,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // make sure we got all the attributes, since allof them are mandatory if (resource.assemblyName == null) { - ReportMissingAttribute (XmlTags.AssemblyNameAttribute); + ReportMissingAttribute(XmlTags.AssemblyNameAttribute); return null; } if (resource.baseName == null) { - ReportMissingAttribute (XmlTags.BaseNameAttribute); + ReportMissingAttribute(XmlTags.BaseNameAttribute); return null; } if (resource.resourceId == null) { - ReportMissingAttribute (XmlTags.ResourceIdAttribute); + ReportMissingAttribute(XmlTags.ResourceIdAttribute); return null; } @@ -1819,20 +1815,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { DisplayResourceManagerCache.LoadingResult result; DisplayResourceManagerCache.AssemblyBindingStatus bindingStatus; - this.displayResourceManagerCache.VerifyResource (resource, out result, out bindingStatus); + this.displayResourceManagerCache.VerifyResource(resource, out result, out bindingStatus); if (result != DisplayResourceManagerCache.LoadingResult.NoError) { - ReportStringResourceFailure (resource, result, bindingStatus); + ReportStringResourceFailure(resource, result, bindingStatus); return null; } - } return resource; } - private void ReportStringResourceFailure (StringResourceReference resource, - DisplayResourceManagerCache.LoadingResult result, + private void ReportStringResourceFailure(StringResourceReference resource, + DisplayResourceManagerCache.LoadingResult result, DisplayResourceManagerCache.AssemblyBindingStatus bindingStatus) { string assemblyDisplayName; @@ -1840,7 +1835,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { case DisplayResourceManagerCache.AssemblyBindingStatus.FoundInPath: { - assemblyDisplayName = + assemblyDisplayName = System.IO.Path.Combine(resource.loadingInfo.fileDirectory, resource.assemblyName); } break; @@ -1880,10 +1875,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } break; } - this.ReportError (msg); + this.ReportError(msg); } -#endregion + #endregion #region Expression Loading /// @@ -1892,11 +1887,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// script block string to verify /// true if parsed correctly, false if failed - internal bool VerifyScriptBlock (string scriptBlockText) + internal bool VerifyScriptBlock(string scriptBlockText) { try { - this.expressionFactory.VerifyScriptBlockText (scriptBlockText); + this.expressionFactory.VerifyScriptBlockText(scriptBlockText); } catch (ParseException e) { @@ -1917,30 +1912,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private sealed class ExpressionNodeMatch { - internal ExpressionNodeMatch (TypeInfoDataBaseLoader loader) + internal ExpressionNodeMatch(TypeInfoDataBaseLoader loader) { _loader = loader; } - internal bool MatchNode (XmlNode n) + internal bool MatchNode(XmlNode n) { - return _loader.MatchNodeName (n, XmlTags.PropertyNameNode) || _loader.MatchNodeName (n, XmlTags.ScriptBlockNode); + return _loader.MatchNodeName(n, XmlTags.PropertyNameNode) || _loader.MatchNodeName(n, XmlTags.ScriptBlockNode); } - internal bool ProcessNode (XmlNode n) + internal bool ProcessNode(XmlNode n) { - if (_loader.MatchNodeName (n, XmlTags.PropertyNameNode)) + if (_loader.MatchNodeName(n, XmlTags.PropertyNameNode)) { if (_token != null) { if (_token.isScriptBlock) - _loader.ProcessDuplicateAlternateNode (n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); + _loader.ProcessDuplicateAlternateNode(n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); else - _loader.ProcessDuplicateNode (n); + _loader.ProcessDuplicateNode(n); return false; // fatal error } - _token = new ExpressionToken (); - _token.expressionValue = _loader.GetMandatoryInnerText (n); + _token = new ExpressionToken(); + _token.expressionValue = _loader.GetMandatoryInnerText(n); if (_token.expressionValue == null) { //Error at XPath {0} in file {1}: Missing property. @@ -1950,20 +1945,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } return true; } - else if (_loader.MatchNodeName (n, XmlTags.ScriptBlockNode)) + else if (_loader.MatchNodeName(n, XmlTags.ScriptBlockNode)) { if (_token != null) { if (!_token.isScriptBlock) - _loader.ProcessDuplicateAlternateNode (n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); + _loader.ProcessDuplicateAlternateNode(n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); else - _loader.ProcessDuplicateNode (n); + _loader.ProcessDuplicateNode(n); return false; // fatal error } - _token = new ExpressionToken (); + _token = new ExpressionToken(); _token.isScriptBlock = true; - _token.expressionValue = _loader.GetMandatoryInnerText (n); + _token.expressionValue = _loader.GetMandatoryInnerText(n); if (_token.expressionValue == null) { //Error at XPath {0} in file {1}: Missing script block text. @@ -1972,7 +1967,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; // fatal error } - if((! _loader.suppressValidation) && (!_loader.VerifyScriptBlock (_token.expressionValue))) + if ((!_loader._suppressValidation) && (!_loader.VerifyScriptBlock(_token.expressionValue))) { _fatalError = true; return false; // fatal error @@ -1980,11 +1975,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return true; } // this should never happen if the API is used correctly - PSTraceSource.NewInvalidOperationException (); + PSTraceSource.NewInvalidOperationException(); return false; } - internal ExpressionToken GenerateExpressionToken () + internal ExpressionToken GenerateExpressionToken() { if (_fatalError) { @@ -1996,7 +1991,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // we do not have a token: we never got one // the user should have specified either a property or a script block - _loader.ReportMissingNodes (new string[] { XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode }); + _loader.ReportMissingNodes(new string[] { XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode }); return null; } return _token; @@ -2005,7 +2000,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private TypeInfoDataBaseLoader _loader; private ExpressionToken _token; private bool _fatalError = false; - } /// @@ -2014,19 +2008,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private sealed class ViewEntryNodeMatch { - internal ViewEntryNodeMatch (TypeInfoDataBaseLoader loader) + internal ViewEntryNodeMatch(TypeInfoDataBaseLoader loader) { _loader = loader; } - internal bool ProcessExpressionDirectives (XmlNode containerNode, List unprocessedNodes) + internal bool ProcessExpressionDirectives(XmlNode containerNode, List unprocessedNodes) { if (containerNode == null) - throw PSTraceSource.NewArgumentNullException ("containerNode"); + throw PSTraceSource.NewArgumentNullException("containerNode"); string formatString = null; TextToken textToken = null; - ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch (_loader); + ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(_loader); bool formatStringNodeFound = false; // cardinality 0..1 bool expressionNodeFound = false; // cardinality 0..1 @@ -2034,27 +2028,27 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in containerNode.ChildNodes) { - if (expressionMatch.MatchNode (n)) + if (expressionMatch.MatchNode(n)) { if (expressionNodeFound) { - _loader.ProcessDuplicateNode (n); + _loader.ProcessDuplicateNode(n); return false; // fatal error } expressionNodeFound = true; - if (!expressionMatch.ProcessNode (n)) + if (!expressionMatch.ProcessNode(n)) return false; // fatal error } - else if (_loader.MatchNodeName (n, XmlTags.FormatStringNode)) + else if (_loader.MatchNodeName(n, XmlTags.FormatStringNode)) { if (formatStringNodeFound) { - _loader.ProcessDuplicateNode (n); + _loader.ProcessDuplicateNode(n); return false; // fatal error } formatStringNodeFound = true; - formatString = _loader.GetMandatoryInnerText (n); + formatString = _loader.GetMandatoryInnerText(n); if (formatString == null) { //Error at XPath {0} in file {1}: Missing a format string. @@ -2062,15 +2056,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; // fatal error } } - else if (_loader.MatchNodeNameWithAttributes (n, XmlTags.TextNode)) + else if (_loader.MatchNodeNameWithAttributes(n, XmlTags.TextNode)) { if (textNodeFound) { - _loader.ProcessDuplicateNode (n); + _loader.ProcessDuplicateNode(n); return false; // fatal error } textNodeFound = true; - textToken = _loader.LoadText (n); + textToken = _loader.LoadText(n); if (textToken == null) { //Error at XPath {0} in file {1}: Invalid {2}. @@ -2081,7 +2075,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format else { // for further processing by calling context - unprocessedNodes.Add (n); + unprocessedNodes.Add(n); } } // foreach @@ -2096,18 +2090,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; // fatal error } - ExpressionToken expression = expressionMatch.GenerateExpressionToken (); + ExpressionToken expression = expressionMatch.GenerateExpressionToken(); if (expression == null) { return false; // fatal error } // set the output data - if (!string.IsNullOrEmpty (formatString)) + if (!string.IsNullOrEmpty(formatString)) { - this._formatString = formatString; + _formatString = formatString; } - this._expression = expression; + _expression = expression; } else { @@ -2123,16 +2117,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we might have a text node if (textNodeFound) { - this._textToken = textToken; + _textToken = textToken; } } return true; } - internal string FormatString { get { return this._formatString; } } - internal TextToken TextToken { get { return this._textToken; } } - internal ExpressionToken Expression { get { return this._expression; } } + internal string FormatString { get { return _formatString; } } + internal TextToken TextToken { get { return _textToken; } } + internal ExpressionToken Expression { get { return _expression; } } private string _formatString; private TextToken _textToken; @@ -2147,40 +2141,40 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private sealed class ComplexControlMatch { - internal ComplexControlMatch (TypeInfoDataBaseLoader loader) + internal ComplexControlMatch(TypeInfoDataBaseLoader loader) { _loader = loader; } - internal bool MatchNode (XmlNode n) + internal bool MatchNode(XmlNode n) { - return _loader.MatchNodeName (n, XmlTags.ComplexControlNode) || - _loader.MatchNodeName (n, XmlTags.ComplexControlNameNode); + return _loader.MatchNodeName(n, XmlTags.ComplexControlNode) || + _loader.MatchNodeName(n, XmlTags.ComplexControlNameNode); } - internal bool ProcessNode (XmlNode n) + internal bool ProcessNode(XmlNode n) { - if (_loader.MatchNodeName (n, XmlTags.ComplexControlNode)) + if (_loader.MatchNodeName(n, XmlTags.ComplexControlNode)) { // load an embedded complex control - _control = _loader.LoadComplexControl (n); + _control = _loader.LoadComplexControl(n); return true; } - else if (_loader.MatchNodeName (n, XmlTags.ComplexControlNameNode)) + else if (_loader.MatchNodeName(n, XmlTags.ComplexControlNameNode)) { - string name = _loader.GetMandatoryInnerText (n); + string name = _loader.GetMandatoryInnerText(n); if (name == null) { return false; } - ControlReference controlRef = new ControlReference (); + ControlReference controlRef = new ControlReference(); controlRef.name = name; controlRef.controlType = typeof(ComplexControlBody); _control = controlRef; return true; } // this should never happen if the API is used correctly - PSTraceSource.NewInvalidOperationException (); + PSTraceSource.NewInvalidOperationException(); return false; } @@ -2196,5 +2190,5 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #endregion } } - + diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs index d2999fe7a..715e90219 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs @@ -19,28 +19,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { - private ComplexControlBody LoadComplexControl (XmlNode controlNode) + private ComplexControlBody LoadComplexControl(XmlNode controlNode) { - using (this.StackFrame (controlNode)) + using (this.StackFrame(controlNode)) { - ComplexControlBody complexBody = new ComplexControlBody (); + ComplexControlBody complexBody = new ComplexControlBody(); bool entriesFound = false; foreach (XmlNode n in controlNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ComplexEntriesNode)) + if (MatchNodeName(n, XmlTags.ComplexEntriesNode)) { if (entriesFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); continue; } entriesFound = true; // now read the columns section - LoadComplexControlEntries (n, complexBody); + LoadComplexControlEntries(n, complexBody); if (complexBody.defaultEntry == null) { return null; // fatal error @@ -48,30 +48,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (!entriesFound) { - this.ReportMissingNode (XmlTags.ComplexEntriesNode); + this.ReportMissingNode(XmlTags.ComplexEntriesNode); return null; // fatal error } return complexBody; } } - private void LoadComplexControlEntries (XmlNode complexControlEntriesNode, ComplexControlBody complexBody) + private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, ComplexControlBody complexBody) { - using (this.StackFrame (complexControlEntriesNode)) + using (this.StackFrame(complexControlEntriesNode)) { int entryIndex = 0; foreach (XmlNode n in complexControlEntriesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ComplexEntryNode)) + if (MatchNodeName(n, XmlTags.ComplexEntryNode)) { - ComplexControlEntryDefinition cced = LoadComplexControlEntryDefinition (n, entryIndex++); + ComplexControlEntryDefinition cced = LoadComplexControlEntryDefinition(n, entryIndex++); if (cced == null) { //Error at XPath {0} in file {1}: {2} failed to load. @@ -96,12 +96,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - complexBody.optionalEntryList.Add (cced); + complexBody.optionalEntryList.Add(cced); } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (complexBody.defaultEntry == null) @@ -112,43 +112,43 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private ComplexControlEntryDefinition LoadComplexControlEntryDefinition (XmlNode complexControlEntryNode, int index) + private ComplexControlEntryDefinition LoadComplexControlEntryDefinition(XmlNode complexControlEntryNode, int index) { - using (this.StackFrame (complexControlEntryNode, index)) + using (this.StackFrame(complexControlEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool bodyNodeFound = false; // cardinality 1 - ComplexControlEntryDefinition cced = new ComplexControlEntryDefinition (); + ComplexControlEntryDefinition cced = new ComplexControlEntryDefinition(); foreach (XmlNode n in complexControlEntryNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.EntrySelectedByNode)) + if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } appliesToNodeFound = true; // optional section - cced.appliesTo = LoadAppliesToSection (n, true); + cced.appliesTo = LoadAppliesToSection(n, true); } - else if (MatchNodeName (n, XmlTags.ComplexItemNode)) + else if (MatchNodeName(n, XmlTags.ComplexItemNode)) { if (bodyNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } bodyNodeFound = true; - cced.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions (n); + cced.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -163,11 +163,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - List LoadComplexControlTokenListDefinitions (XmlNode bodyNode) + private List LoadComplexControlTokenListDefinitions(XmlNode bodyNode) { - using (this.StackFrame (bodyNode)) + using (this.StackFrame(bodyNode)) { - List formatTokenList = new List (); + List formatTokenList = new List(); int compoundPropertyIndex = 0; int newLineIndex = 0; @@ -176,9 +176,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in bodyNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ExpressionBindingNode)) + if (MatchNodeName(n, XmlTags.ExpressionBindingNode)) { - CompoundPropertyToken cpt = LoadCompoundProperty (n, compoundPropertyIndex++); + CompoundPropertyToken cpt = LoadCompoundProperty(n, compoundPropertyIndex++); if (cpt == null) { @@ -187,11 +187,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - formatTokenList.Add (cpt); + formatTokenList.Add(cpt); } - else if (MatchNodeName (n, XmlTags.NewLineNode)) + else if (MatchNodeName(n, XmlTags.NewLineNode)) { - NewLineToken nlt = LoadNewLine (n, newLineIndex++); + NewLineToken nlt = LoadNewLine(n, newLineIndex++); if (nlt == null) { @@ -200,11 +200,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - formatTokenList.Add (nlt); + formatTokenList.Add(nlt); } - else if (MatchNodeNameWithAttributes (n, XmlTags.TextNode)) + else if (MatchNodeNameWithAttributes(n, XmlTags.TextNode)) { - TextToken tt = LoadText (n, textIndex++); + TextToken tt = LoadText(n, textIndex++); if (tt == null) { @@ -213,11 +213,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - formatTokenList.Add (tt); + formatTokenList.Add(tt); } - else if (MatchNodeName (n, XmlTags.FrameNode)) + else if (MatchNodeName(n, XmlTags.FrameNode)) { - FrameToken frame = LoadFrameDefinition (n, frameIndex++); + FrameToken frame = LoadFrameDefinition(n, frameIndex++); if (frame == null) { @@ -226,11 +226,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; } - formatTokenList.Add (frame); + formatTokenList.Add(frame); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -243,12 +243,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return formatTokenList; } - } - private bool LoadPropertyBaseHelper (XmlNode propertyBaseNode, PropertyTokenBase ptb, List unprocessedNodes) + private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase ptb, List unprocessedNodes) { - ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch (this); + ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this); bool expressionNodeFound = false; // cardinality 0..1 bool collectionNodeFound = false; // cardinality 0..1 @@ -262,34 +261,34 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (expressionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; // fatal error } expressionNodeFound = true; - if (!expressionMatch.ProcessNode (n)) + if (!expressionMatch.ProcessNode(n)) return false; // fatal error } - else if (MatchNodeName (n, XmlTags.EnumerateCollectionNode)) + else if (MatchNodeName(n, XmlTags.EnumerateCollectionNode)) { if (collectionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } collectionNodeFound = true; - if (!ReadBooleanNode (n, out ptb.enumerateCollection)) + if (!ReadBooleanNode(n, out ptb.enumerateCollection)) return false; } - else if (MatchNodeName (n, XmlTags.ItemSelectionConditionNode)) + else if (MatchNodeName(n, XmlTags.ItemSelectionConditionNode)) { if (itemSelectionConditionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } itemSelectionConditionNodeFound = true; - condition = LoadItemSelectionCondition (n); + condition = LoadItemSelectionCondition(n); if (condition == null) { return false; @@ -298,7 +297,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format else { if (!IsFilteredOutNode(n)) - unprocessedNodes.Add (n); + unprocessedNodes.Add(n); } } // foreach @@ -306,7 +305,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (expressionNodeFound) { // we add only if we encountered one, since it's not mandatory - ExpressionToken expression = expressionMatch.GenerateExpressionToken (); + ExpressionToken expression = expressionMatch.GenerateExpressionToken(); if (expression == null) { return false; // fatal error @@ -343,13 +342,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } #endif - private CompoundPropertyToken LoadCompoundProperty (XmlNode compoundPropertyNode, int index) + private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, int index) { - using (this.StackFrame (compoundPropertyNode, index)) + using (this.StackFrame(compoundPropertyNode, index)) { - CompoundPropertyToken cpt = new CompoundPropertyToken (); - List unprocessedNodes = new List (); - bool success = LoadPropertyBaseHelper (compoundPropertyNode, cpt, unprocessedNodes); + CompoundPropertyToken cpt = new CompoundPropertyToken(); + List unprocessedNodes = new List(); + bool success = LoadPropertyBaseHelper(compoundPropertyNode, cpt, unprocessedNodes); if (!success) { @@ -362,32 +361,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool complexControlFound = false; // cardinality 0..1 bool fieldControlFound = false; // cardinality 0..1 - ComplexControlMatch controlMatch = new ComplexControlMatch (this); + ComplexControlMatch controlMatch = new ComplexControlMatch(this); FieldControlBody fieldControlBody = null; foreach (XmlNode n in unprocessedNodes) { - if (controlMatch.MatchNode (n)) + if (controlMatch.MatchNode(n)) { if (complexControlFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; } complexControlFound = true; - if (!controlMatch.ProcessNode (n)) + if (!controlMatch.ProcessNode(n)) return null; // fatal error } else if (MatchNodeName(n, XmlTags.FieldControlNode)) { if (fieldControlFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; // fatal error } fieldControlFound = true; - fieldControlBody = new FieldControlBody (); - fieldControlBody.fieldFormattingDirective.formatString = GetMandatoryInnerText (n); + fieldControlBody = new FieldControlBody(); + fieldControlBody.fieldFormattingDirective.formatString = GetMandatoryInnerText(n); if (fieldControlBody.fieldFormattingDirective.formatString == null) { return null; // fatal error @@ -395,13 +394,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } if (fieldControlFound && complexControlFound) { - this.ProcessDuplicateAlternateNode (XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); + this.ProcessDuplicateAlternateNode(XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode); return null; // fatal error } @@ -425,47 +424,47 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private NewLineToken LoadNewLine (XmlNode newLineNode, int index) + private NewLineToken LoadNewLine(XmlNode newLineNode, int index) { - using (this.StackFrame (newLineNode, index)) + using (this.StackFrame(newLineNode, index)) { if (!VerifyNodeHasNoChildren(newLineNode)) { return null; } - NewLineToken nlt = new NewLineToken (); + NewLineToken nlt = new NewLineToken(); return nlt; } } - private TextToken LoadText (XmlNode textNode, int index) + private TextToken LoadText(XmlNode textNode, int index) { - using (this.StackFrame (textNode, index)) + using (this.StackFrame(textNode, index)) { - return LoadTextToken (textNode); + return LoadTextToken(textNode); } } - internal TextToken LoadText (XmlNode textNode) + internal TextToken LoadText(XmlNode textNode) { - using (this.StackFrame (textNode)) + using (this.StackFrame(textNode)) { - return LoadTextToken (textNode); + return LoadTextToken(textNode); } } - private int LoadIntegerValue (XmlNode node, out bool success) + private int LoadIntegerValue(XmlNode node, out bool success) { - using (this.StackFrame (node)) + using (this.StackFrame(node)) { success = false; int retVal = 0; - if (!VerifyNodeHasNoChildren (node)) + if (!VerifyNodeHasNoChildren(node)) { return retVal; } - string val = this.GetMandatoryInnerText (node); + string val = this.GetMandatoryInnerText(node); if (val == null) { @@ -474,7 +473,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return retVal; } - if (!int.TryParse (val, out retVal)) + if (!int.TryParse(val, out retVal)) { //Error at XPath {0} in file {1}: An integer is expected. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectInteger, ComputeCurrentXPath(), FilePath)); @@ -486,12 +485,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private int LoadPositiveOrZeroIntegerValue (XmlNode node, out bool success) + private int LoadPositiveOrZeroIntegerValue(XmlNode node, out bool success) { int val = LoadIntegerValue(node, out success); if (!success) return val; - using(this.StackFrame(node)) + using (this.StackFrame(node)) { if (val < 0) { @@ -503,9 +502,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private FrameToken LoadFrameDefinition (XmlNode frameNode, int index) + private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) { - using (this.StackFrame (frameNode, index)) + using (this.StackFrame(frameNode, index)) { bool itemNodeFound = false; // cardinality 1 bool leftIndentFound = false; // cardinality 0..1 @@ -517,36 +516,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format bool success; // scratch variable - FrameToken frame = new FrameToken (); + FrameToken frame = new FrameToken(); foreach (XmlNode n in frameNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.LeftIndentNode)) + if (MatchNodeName(n, XmlTags.LeftIndentNode)) { if (leftIndentFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } leftIndentFound = true; // optional section - frame.frameInfoDefinition.leftIndentation = LoadPositiveOrZeroIntegerValue (n, out success); + frame.frameInfoDefinition.leftIndentation = LoadPositiveOrZeroIntegerValue(n, out success); if (!success) return null; } - else if (MatchNodeName (n, XmlTags.RightIndentNode)) + else if (MatchNodeName(n, XmlTags.RightIndentNode)) { if (rightIndentFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } rightIndentFound = true; // optional section - frame.frameInfoDefinition.rightIndentation = LoadPositiveOrZeroIntegerValue (n, out success); + frame.frameInfoDefinition.rightIndentation = LoadPositiveOrZeroIntegerValue(n, out success); if (!success) return null; } @@ -554,51 +553,49 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (firstLineIndentFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; } firstLineIndentFound = true; - frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue (n, out success); + frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success); if (!success) return null; - } else if (MatchNodeName(n, XmlTags.FirstLineHangingNode)) { if (firstLineHangingFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; } firstLineHangingFound = true; - frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue (n, out success); + frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success); if (!success) return null; // hanging is codified as negative frame.frameInfoDefinition.firstLine = -frame.frameInfoDefinition.firstLine; - } - else if (MatchNodeName (n, XmlTags.ComplexItemNode)) + else if (MatchNodeName(n, XmlTags.ComplexItemNode)) { if (itemNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } itemNodeFound = true; - frame.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions (n); + frame.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (firstLineHangingFound && firstLineIndentFound) { - this.ProcessDuplicateAlternateNode (XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); + this.ProcessDuplicateAlternateNode(XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode); return null; // fatal error } if (frame.itemDefinition.formatTokenList == null) @@ -611,7 +608,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private bool ReadBooleanNode (XmlNode collectionElement, out bool val) + private bool ReadBooleanNode(XmlNode collectionElement, out bool val) { val = false; @@ -621,18 +618,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } string s = collectionElement.InnerText; - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) { val = true; return true; } - if (string.Equals (s, XMLStringValues.False, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(s, XMLStringValues.False, StringComparison.OrdinalIgnoreCase)) { val = false; return true; } - else if (string.Equals (s, XMLStringValues.True, StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(s, XMLStringValues.True, StringComparison.OrdinalIgnoreCase)) { val = true; return true; @@ -642,6 +639,5 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs index 7dff3fcd3..108154553 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs @@ -18,28 +18,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { - private ListControlBody LoadListControl (XmlNode controlNode) + private ListControlBody LoadListControl(XmlNode controlNode) { - using (this.StackFrame (controlNode)) + using (this.StackFrame(controlNode)) { - ListControlBody listBody = new ListControlBody (); + ListControlBody listBody = new ListControlBody(); bool listViewEntriesFound = false; foreach (XmlNode n in controlNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ListEntriesNode)) + if (MatchNodeName(n, XmlTags.ListEntriesNode)) { if (listViewEntriesFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); continue; } listViewEntriesFound = true; // now read the columns section - LoadListControlEntries (n, listBody); + LoadListControlEntries(n, listBody); if (listBody.defaultEntryDefinition == null) { return null; // fatal error @@ -47,30 +47,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (!listViewEntriesFound) { - this.ReportMissingNode (XmlTags.ListEntriesNode); + this.ReportMissingNode(XmlTags.ListEntriesNode); return null; // fatal error } return listBody; } } - private void LoadListControlEntries (XmlNode listViewEntriesNode, ListControlBody listBody) + private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody listBody) { - using (this.StackFrame (listViewEntriesNode)) + using (this.StackFrame(listViewEntriesNode)) { int entryIndex = 0; foreach (XmlNode n in listViewEntriesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ListEntryNode)) + if (MatchNodeName(n, XmlTags.ListEntryNode)) { - ListControlEntryDefinition lved = LoadListControlEntryDefinition (n, entryIndex++); + ListControlEntryDefinition lved = LoadListControlEntryDefinition(n, entryIndex++); if (lved == null) { //Error at XPath {0} in file {1}: {2} failed to load. @@ -95,12 +95,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - listBody.optionalEntryList.Add (lved); + listBody.optionalEntryList.Add(lved); } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (listBody.optionalEntryList == null) @@ -111,44 +111,44 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private ListControlEntryDefinition LoadListControlEntryDefinition (XmlNode listViewEntryNode, int index) + private ListControlEntryDefinition LoadListControlEntryDefinition(XmlNode listViewEntryNode, int index) { - using(this.StackFrame(listViewEntryNode, index)) + using (this.StackFrame(listViewEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool bodyNodeFound = false; // cardinality 1 - ListControlEntryDefinition lved = new ListControlEntryDefinition (); + ListControlEntryDefinition lved = new ListControlEntryDefinition(); foreach (XmlNode n in listViewEntryNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.EntrySelectedByNode)) + if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } appliesToNodeFound = true; - + // optional section - lved.appliesTo = LoadAppliesToSection (n, true); + lved.appliesTo = LoadAppliesToSection(n, true); } - else if (MatchNodeName (n, XmlTags.ListItemsNode)) + else if (MatchNodeName(n, XmlTags.ListItemsNode)) { if (bodyNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } bodyNodeFound = true; - LoadListControlItemDefinitions (lved, n); + LoadListControlItemDefinitions(lved, n); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -163,15 +163,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private void LoadListControlItemDefinitions (ListControlEntryDefinition lved, XmlNode bodyNode) + private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, XmlNode bodyNode) { - using (this.StackFrame (bodyNode)) + using (this.StackFrame(bodyNode)) { int index = 0; foreach (XmlNode n in bodyNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ListItemNode)) + if (MatchNodeName(n, XmlTags.ListItemNode)) { index++; ListControlItemDefinition lvid = LoadListControlItemDefinition(n); @@ -182,11 +182,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format lved.itemDefinitionList = null; return; //fatal } - lved.itemDefinitionList.Add (lvid); + lved.itemDefinitionList.Add(lvid); } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -202,7 +202,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } private ListControlItemDefinition LoadListControlItemDefinition(XmlNode propertyEntryNode) { - using (this.StackFrame (propertyEntryNode)) + using (this.StackFrame(propertyEntryNode)) { // process Mshexpression, format string and text token ViewEntryNodeMatch match = new ViewEntryNodeMatch(this); @@ -220,29 +220,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in unprocessedNodes) { - if (MatchNodeName (n, XmlTags.ItemSelectionConditionNode)) + if (MatchNodeName(n, XmlTags.ItemSelectionConditionNode)) { if (itemSelectionConditionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } itemSelectionConditionNodeFound = true; - condition = LoadItemSelectionCondition (n); + condition = LoadItemSelectionCondition(n); if (condition == null) { return null; // fatal error } } - else if (MatchNodeNameWithAttributes (n, XmlTags.LabelNode)) + else if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode)) { if (labelNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } labelNodeFound = true; - labelToken = LoadLabel (n); + labelToken = LoadLabel(n); if (labelToken == null) { return null; // fatal error @@ -250,12 +250,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } // finally build the item to return - ListControlItemDefinition lvid = new ListControlItemDefinition (); + ListControlItemDefinition lvid = new ListControlItemDefinition(); // add the label lvid.label = labelToken; @@ -266,46 +266,46 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // add either the text token or the MshExpression with optional format string if (match.TextToken != null) { - lvid.formatTokenList.Add (match.TextToken); + lvid.formatTokenList.Add(match.TextToken); } else { - FieldPropertyToken fpt = new FieldPropertyToken (); + FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; fpt.fieldFormattingDirective.formatString = match.FormatString; - lvid.formatTokenList.Add (fpt); + lvid.formatTokenList.Add(fpt); } return lvid; } } - private ExpressionToken LoadItemSelectionCondition (XmlNode itemNode) + private ExpressionToken LoadItemSelectionCondition(XmlNode itemNode) { - using (this.StackFrame (itemNode)) + using (this.StackFrame(itemNode)) { bool expressionNodeFound = false; // cardinality 1 - ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch (this); + ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this); foreach (XmlNode n in itemNode.ChildNodes) { - if (expressionMatch.MatchNode (n)) + if (expressionMatch.MatchNode(n)) { if (expressionNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } expressionNodeFound = true; - if (!expressionMatch.ProcessNode (n)) + if (!expressionMatch.ProcessNode(n)) return null; } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } - return expressionMatch.GenerateExpressionToken (); + return expressionMatch.GenerateExpressionToken(); } } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index 7454b42e1..a71efe65e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -19,11 +19,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { - private ControlBase LoadTableControl (XmlNode controlNode) + private ControlBase LoadTableControl(XmlNode controlNode) { - using (this.StackFrame (controlNode)) + using (this.StackFrame(controlNode)) { - TableControlBody tableBody = new TableControlBody (); + TableControlBody tableBody = new TableControlBody(); bool headersNodeFound = false; // cardinality 0..1 bool rowEntriesNodeFound = false; // cardinality 1 bool hideHeadersNodeFound = false; // cardinality 0..1 @@ -31,11 +31,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in controlNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.HideTableHeadersNode)) + if (MatchNodeName(n, XmlTags.HideTableHeadersNode)) { if (hideHeadersNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } @@ -45,11 +45,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; //fatal error } } - else if (MatchNodeName (n, XmlTags.AutoSizeNode)) + else if (MatchNodeName(n, XmlTags.AutoSizeNode)) { if (autosizeNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } autosizeNodeFound = true; @@ -60,36 +60,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } tableBody.autosize = tempVal; } - else if (MatchNodeName (n, XmlTags.TableHeadersNode)) + else if (MatchNodeName(n, XmlTags.TableHeadersNode)) { if (headersNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } headersNodeFound = true; // now read the columns header section - LoadHeadersSection (tableBody, n); + LoadHeadersSection(tableBody, n); if (tableBody.header.columnHeaderDefinitionList == null) { // if we have an empty list, it means there was a failure return null; // fatal error } } - else if (MatchNodeName (n, XmlTags.TableRowEntriesNode)) + else if (MatchNodeName(n, XmlTags.TableRowEntriesNode)) { if (rowEntriesNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } rowEntriesNodeFound = true; // now read the columns section - LoadRowEntriesSection (tableBody, n); + LoadRowEntriesSection(tableBody, n); if (tableBody.defaultDefinition == null) { return null; // fatal error @@ -97,13 +97,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (!rowEntriesNodeFound) { - this.ReportMissingNode (XmlTags.TableRowEntriesNode); + this.ReportMissingNode(XmlTags.TableRowEntriesNode); return null; // fatal error } @@ -148,19 +148,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private void LoadHeadersSection (TableControlBody tableBody, XmlNode headersNode) + private void LoadHeadersSection(TableControlBody tableBody, XmlNode headersNode) { - using (this.StackFrame (headersNode)) + using (this.StackFrame(headersNode)) { int columnIndex = 0; foreach (XmlNode n in headersNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.TableColumnHeaderNode)) + if (MatchNodeName(n, XmlTags.TableColumnHeaderNode)) { - TableColumnHeaderDefinition chd = LoadColumnHeaderDefinition (n, columnIndex++); + TableColumnHeaderDefinition chd = LoadColumnHeaderDefinition(n, columnIndex++); if (chd != null) - tableBody.header.columnHeaderDefinitionList.Add (chd); + tableBody.header.columnHeaderDefinitionList.Add(chd); else { //Error at XPath {0} in file {1}: Column header definition is invalid; all headers are discarded. @@ -171,18 +171,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } // NOTICE: the list can be empty if no entries were found } } - private TableColumnHeaderDefinition LoadColumnHeaderDefinition (XmlNode columnHeaderNode, int index) + private TableColumnHeaderDefinition LoadColumnHeaderDefinition(XmlNode columnHeaderNode, int index) { - using (this.StackFrame (columnHeaderNode, index)) + using (this.StackFrame(columnHeaderNode, index)) { - TableColumnHeaderDefinition chd = new TableColumnHeaderDefinition (); + TableColumnHeaderDefinition chd = new TableColumnHeaderDefinition(); bool labelNodeFound = false; // cardinality 0..1 bool widthNodeFound = false; // cardinality 0..1 @@ -190,32 +190,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in columnHeaderNode.ChildNodes) { - if (MatchNodeNameWithAttributes (n, XmlTags.LabelNode)) + if (MatchNodeNameWithAttributes(n, XmlTags.LabelNode)) { if (labelNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } labelNodeFound = true; - chd.label = LoadLabel (n); + chd.label = LoadLabel(n); if (chd.label == null) { return null; // fatal error } } - else if (MatchNodeName (n, XmlTags.WidthNode)) + else if (MatchNodeName(n, XmlTags.WidthNode)) { if (widthNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } widthNodeFound = true; int wVal; - if (ReadPositiveIntegerValue (n, out wVal)) + if (ReadPositiveIntegerValue(n, out wVal)) { chd.width = wVal; } @@ -226,23 +226,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; //fatal error } } - else if (MatchNodeName (n, XmlTags.AlignmentNode)) + else if (MatchNodeName(n, XmlTags.AlignmentNode)) { if (alignmentNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } alignmentNodeFound = true; - if (!LoadAlignmentValue (n, out chd.alignment)) + if (!LoadAlignmentValue(n, out chd.alignment)) { return null; // fatal error } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } // foreach return chd; @@ -252,7 +252,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private bool ReadPositiveIntegerValue(XmlNode n, out int val) { val = -1; - string text = GetMandatoryInnerText (n); + string text = GetMandatoryInnerText(n); if (text == null) return false; bool isInteger = int.TryParse(text, out val); @@ -265,24 +265,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return true; } - private bool LoadAlignmentValue (XmlNode n, out int alignmentValue) + private bool LoadAlignmentValue(XmlNode n, out int alignmentValue) { alignmentValue = TextAlignment.Undefined; - string alignmentString = GetMandatoryInnerText (n); + string alignmentString = GetMandatoryInnerText(n); if (alignmentString == null) { return false; // fatal error } - if (string.Equals (n.InnerText, XMLStringValues.AligmentLeft, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(n.InnerText, XMLStringValues.AligmentLeft, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Left; } - else if (string.Equals (n.InnerText, XMLStringValues.AligmentRight, StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(n.InnerText, XMLStringValues.AligmentRight, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Right; } - else if (string.Equals (n.InnerText, XMLStringValues.AligmentCenter, StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(n.InnerText, XMLStringValues.AligmentCenter, StringComparison.OrdinalIgnoreCase)) { alignmentValue = TextAlignment.Center; } @@ -295,16 +295,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return true; } - private void LoadRowEntriesSection (TableControlBody tableBody, XmlNode rowEntriesNode) + private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntriesNode) { - using (this.StackFrame (rowEntriesNode)) + using (this.StackFrame(rowEntriesNode)) { int rowEntryIndex = 0; foreach (XmlNode n in rowEntriesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.TableRowEntryNode)) + if (MatchNodeName(n, XmlTags.TableRowEntryNode)) { - TableRowDefinition trd = LoadRowEntryDefinition (n, rowEntryIndex++); + TableRowDefinition trd = LoadRowEntryDefinition(n, rowEntryIndex++); if (trd == null) { //Error at XPath {0} in file {1}: {2} failed to load. @@ -330,12 +330,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - tableBody.optionalDefinitionList.Add (trd); + tableBody.optionalDefinitionList.Add(trd); } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (tableBody.defaultDefinition == null) @@ -346,78 +346,78 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private TableRowDefinition LoadRowEntryDefinition (XmlNode rowEntryNode, int index) + private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int index) { - using(this.StackFrame(rowEntryNode, index)) + using (this.StackFrame(rowEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool columnEntriesNodeFound = false; // cardinality 1 bool multiLineFound = false; // cardinality 0..1 - TableRowDefinition trd = new TableRowDefinition (); + TableRowDefinition trd = new TableRowDefinition(); foreach (XmlNode n in rowEntryNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.EntrySelectedByNode)) + if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } appliesToNodeFound = true; // optional section - trd.appliesTo = LoadAppliesToSection (n, true); + trd.appliesTo = LoadAppliesToSection(n, true); } - else if (MatchNodeName (n, XmlTags.TableColumnItemsNode)) + else if (MatchNodeName(n, XmlTags.TableColumnItemsNode)) { if (columnEntriesNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } - LoadColumnEntries (n, trd); + LoadColumnEntries(n, trd); if (trd.rowItemDefinitionList == null) { return null; // fatal error } } - else if (MatchNodeName (n, XmlTags.MultiLineNode)) + else if (MatchNodeName(n, XmlTags.MultiLineNode)) { if (multiLineFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } multiLineFound = true; - if (!this.ReadBooleanNode (n, out trd.multiLine)) + if (!this.ReadBooleanNode(n, out trd.multiLine)) { return null; //fatal error } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } return trd; } } - private void LoadColumnEntries (XmlNode columnEntriesNode, TableRowDefinition trd) + private void LoadColumnEntries(XmlNode columnEntriesNode, TableRowDefinition trd) { - using (this.StackFrame (columnEntriesNode)) + using (this.StackFrame(columnEntriesNode)) { int columnEntryIndex = 0; foreach (XmlNode n in columnEntriesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.TableColumnItemNode)) + if (MatchNodeName(n, XmlTags.TableColumnItemNode)) { - TableRowItemDefinition rid = LoadColumnEntry (n, columnEntryIndex++); + TableRowItemDefinition rid = LoadColumnEntry(n, columnEntryIndex++); if (rid != null) { - trd.rowItemDefinitionList.Add (rid); + trd.rowItemDefinitionList.Add(rid); } else { @@ -429,48 +429,47 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } } } - private TableRowItemDefinition LoadColumnEntry (XmlNode columnEntryNode, int index) + private TableRowItemDefinition LoadColumnEntry(XmlNode columnEntryNode, int index) { - using (this.StackFrame (columnEntryNode, index)) + using (this.StackFrame(columnEntryNode, index)) { - // process Mshexpression, format string and text token - ViewEntryNodeMatch match = new ViewEntryNodeMatch (this); - List unprocessedNodes = new List (); - if (!match.ProcessExpressionDirectives (columnEntryNode, unprocessedNodes)) + ViewEntryNodeMatch match = new ViewEntryNodeMatch(this); + List unprocessedNodes = new List(); + if (!match.ProcessExpressionDirectives(columnEntryNode, unprocessedNodes)) { return null; // fatal error } - TableRowItemDefinition rid = new TableRowItemDefinition (); + TableRowItemDefinition rid = new TableRowItemDefinition(); // process the remaining nodes bool alignmentNodeFound = false; // cardinality 0..1 foreach (XmlNode n in unprocessedNodes) { - if (MatchNodeName (n, XmlTags.AlignmentNode)) + if (MatchNodeName(n, XmlTags.AlignmentNode)) { if (alignmentNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; // fatal error } alignmentNodeFound = true; - if (!LoadAlignmentValue (n, out rid.alignment)) + if (!LoadAlignmentValue(n, out rid.alignment)) { return null; // fatal error } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } @@ -478,14 +477,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // add either the text token or the MshExpression with optional format string if (match.TextToken != null) { - rid.formatTokenList.Add (match.TextToken); + rid.formatTokenList.Add(match.TextToken); } else if (match.Expression != null) { - FieldPropertyToken fpt = new FieldPropertyToken (); + FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; fpt.fieldFormattingDirective.formatString = match.FormatString; - rid.formatTokenList.Add (fpt); + rid.formatTokenList.Add(fpt); } return rid; diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index 9726d2165..95199b2d9 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -20,45 +20,44 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { - - private void LoadViewDefinitions (TypeInfoDataBase db, XmlNode viewDefinitionsNode) + private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNode) { - using (this.StackFrame (viewDefinitionsNode)) + using (this.StackFrame(viewDefinitionsNode)) { int index = 0; foreach (XmlNode n in viewDefinitionsNode.ChildNodes) { if (MatchNodeName(n, XmlTags.ViewNode)) { - ViewDefinition view = LoadView (n, index++); + ViewDefinition view = LoadView(n, index++); if (view != null) { ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from file {2}", ControlBase.GetControlShapeName(view.mainControl), - view.name, view.loadingInfo.filePath )); + view.name, view.loadingInfo.filePath)); // we are fine, add the view to the list - db.viewDefinitionsSection.viewDefinitionList.Add (view); + db.viewDefinitionsSection.viewDefinitionList.Add(view); } } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } } } - - - private ViewDefinition LoadView (XmlNode viewNode, int index) + + + private ViewDefinition LoadView(XmlNode viewNode, int index) { - using (this.StackFrame (viewNode, index)) + using (this.StackFrame(viewNode, index)) { // load the common data - ViewDefinition view = new ViewDefinition (); - List unprocessedNodes = new List (); - bool success = LoadCommonViewData (viewNode, view, unprocessedNodes); + ViewDefinition view = new ViewDefinition(); + List unprocessedNodes = new List(); + bool success = LoadCommonViewData(viewNode, view, unprocessedNodes); if (!success) { @@ -71,7 +70,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // only one control can exist, and it can be // of the various types: Table, List, etc. - string[] controlNodeTags = new string[] + string[] controlNodeTags = new string[] { XmlTags.TableControlNode, XmlTags.ListControlNode, @@ -79,65 +78,65 @@ namespace Microsoft.PowerShell.Commands.Internal.Format XmlTags.ComplexControlNode }; - List secondPassUnprocessedNodes = new List (); + List secondPassUnprocessedNodes = new List(); bool mainControlFound = false; // cardinality 1 foreach (XmlNode n in unprocessedNodes) { - if (MatchNodeName (n, XmlTags.TableControlNode)) + if (MatchNodeName(n, XmlTags.TableControlNode)) { if (mainControlFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); return null; } mainControlFound = true; - view.mainControl = LoadTableControl (n); + view.mainControl = LoadTableControl(n); } - else if (MatchNodeName (n, XmlTags.ListControlNode)) + else if (MatchNodeName(n, XmlTags.ListControlNode)) { if (mainControlFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); return null; } mainControlFound = true; - view.mainControl = LoadListControl (n); + view.mainControl = LoadListControl(n); } - else if (MatchNodeName (n, XmlTags.WideControlNode)) + else if (MatchNodeName(n, XmlTags.WideControlNode)) { if (mainControlFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); return null; } mainControlFound = true; - view.mainControl = LoadWideControl (n); + view.mainControl = LoadWideControl(n); } - else if (MatchNodeName (n, XmlTags.ComplexControlNode)) + else if (MatchNodeName(n, XmlTags.ComplexControlNode)) { if (mainControlFound) { - ProcessDuplicateNode (n); + ProcessDuplicateNode(n); return null; } mainControlFound = true; - view.mainControl = LoadComplexControl (n); + view.mainControl = LoadComplexControl(n); } else { - secondPassUnprocessedNodes.Add (n); + secondPassUnprocessedNodes.Add(n); } } // foreach if (view.mainControl == null) { - this.ReportMissingNodes (controlNodeTags); + this.ReportMissingNodes(controlNodeTags); return null; // fatal } - if (!LoadMainControlDependentData (secondPassUnprocessedNodes, view)) + if (!LoadMainControlDependentData(secondPassUnprocessedNodes, view)) { return null; // fatal } @@ -154,23 +153,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private bool LoadMainControlDependentData (List unprocessedNodes, ViewDefinition view) + private bool LoadMainControlDependentData(List unprocessedNodes, ViewDefinition view) { foreach (XmlNode n in unprocessedNodes) { bool outOfBandNodeFound = false; // cardinality 0..1 bool controlDefinitionsFound = false; // cardinality 0..1 - if (MatchNodeName (n, XmlTags.OutOfBandNode)) + if (MatchNodeName(n, XmlTags.OutOfBandNode)) { if (outOfBandNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } outOfBandNodeFound = true; - if (!this.ReadBooleanNode (n, out view.outOfBand)) + if (!this.ReadBooleanNode(n, out view.outOfBand)) { return false; } @@ -181,36 +180,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } } - else if (MatchNodeName (n, XmlTags.ControlsNode)) + else if (MatchNodeName(n, XmlTags.ControlsNode)) { if (controlDefinitionsFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } controlDefinitionsFound = true; - LoadControlDefinitions (n, view.formatControlDefinitionHolder.controlDefinitionList); + LoadControlDefinitions(n, view.formatControlDefinitionHolder.controlDefinitionList); } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } return true; } - private bool LoadCommonViewData (XmlNode viewNode, ViewDefinition view, List unprocessedNodes) + private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, List unprocessedNodes) { if (viewNode == null) - throw PSTraceSource.NewArgumentNullException ("viewNode"); + throw PSTraceSource.NewArgumentNullException("viewNode"); if (view == null) - throw PSTraceSource.NewArgumentNullException ("view"); + throw PSTraceSource.NewArgumentNullException("view"); // set loading information view.loadingInfo = this.LoadingInfo; - view.loadingInfo.xPath = this.ComputeCurrentXPath (); + view.loadingInfo.xPath = this.ComputeCurrentXPath(); // start the loading process bool nameNodeFound = false; // cardinality 1 @@ -219,48 +218,48 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in viewNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.NameNode)) + if (MatchNodeName(n, XmlTags.NameNode)) { if (nameNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } nameNodeFound = true; - view.name = GetMandatoryInnerText (n); + view.name = GetMandatoryInnerText(n); if (view.name == null) { return false; } } - else if (MatchNodeName (n, XmlTags.ViewSelectedByNode)) + else if (MatchNodeName(n, XmlTags.ViewSelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } appliesToNodeFound = true; // if null, we invalidate the view - view.appliesTo = LoadAppliesToSection (n, false); + view.appliesTo = LoadAppliesToSection(n, false); if (view.appliesTo == null) { return false; } } - else if (MatchNodeName (n, XmlTags.GroupByNode)) + else if (MatchNodeName(n, XmlTags.GroupByNode)) { if (groupByFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return false; } groupByFound = true; - view.groupBy = LoadGroupBySection (n); + view.groupBy = LoadGroupBySection(n); if (view.groupBy == null) { return false; @@ -269,69 +268,69 @@ namespace Microsoft.PowerShell.Commands.Internal.Format else { // save for further processing - unprocessedNodes.Add (n); + unprocessedNodes.Add(n); } } // for if (!nameNodeFound) { - this.ReportMissingNode (XmlTags.NameNode); + this.ReportMissingNode(XmlTags.NameNode); return false; } if (!appliesToNodeFound) { - this.ReportMissingNode (XmlTags.ViewSelectedByNode); + this.ReportMissingNode(XmlTags.ViewSelectedByNode); return false; } return true; } - private void LoadControlDefinitions (XmlNode definitionsNode, List controlDefinitionList) + private void LoadControlDefinitions(XmlNode definitionsNode, List controlDefinitionList) { - using (this.StackFrame (definitionsNode)) + using (this.StackFrame(definitionsNode)) { int controlDefinitionIndex = 0; foreach (XmlNode n in definitionsNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.ControlNode)) + if (MatchNodeName(n, XmlTags.ControlNode)) { - ControlDefinition def = LoadControlDefinition (n, controlDefinitionIndex++); + ControlDefinition def = LoadControlDefinition(n, controlDefinitionIndex++); if (def != null) { - controlDefinitionList.Add (def); + controlDefinitionList.Add(def); } } else { - ProcessUnknownNode (n); + ProcessUnknownNode(n); } } } } - private ControlDefinition LoadControlDefinition (XmlNode controlDefinitionNode, int index) + private ControlDefinition LoadControlDefinition(XmlNode controlDefinitionNode, int index) { - using(this.StackFrame(controlDefinitionNode, index)) + using (this.StackFrame(controlDefinitionNode, index)) { bool nameNodeFound = false; // cardinality 1 bool controlNodeFound = false; // cardinality 1 ControlDefinition def = new ControlDefinition(); - + foreach (XmlNode n in controlDefinitionNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.NameNode)) + if (MatchNodeName(n, XmlTags.NameNode)) { if (nameNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); continue; } nameNodeFound = true; - def.name = GetMandatoryInnerText (n); + def.name = GetMandatoryInnerText(n); if (def.name == null) { //Error at XPath {0} in file {1}: Control cannot have a null Name. @@ -339,17 +338,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; //fatal error } } - else if (MatchNodeName (n, XmlTags.ComplexControlNode)) + else if (MatchNodeName(n, XmlTags.ComplexControlNode)) { // NOTE: for the time being we allow only complex control definitions to be loaded if (controlNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } controlNodeFound = true; - def.controlBody = LoadComplexControl (n); + def.controlBody = LoadComplexControl(n); if (def.controlBody == null) { return null; //fatal error @@ -357,27 +356,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (def.name == null) { - this.ReportMissingNode (XmlTags.NameNode); + this.ReportMissingNode(XmlTags.NameNode); return null; //fatal } if (def.controlBody == null) { - this.ReportMissingNode (XmlTags.ComplexControlNode); + this.ReportMissingNode(XmlTags.ComplexControlNode); return null; //fatal } return def; } } - } - - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs index ef92764e7..68cb64f12 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs @@ -17,11 +17,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase { - private WideControlBody LoadWideControl (XmlNode controlNode) + private WideControlBody LoadWideControl(XmlNode controlNode) { - using (this.StackFrame (controlNode)) + using (this.StackFrame(controlNode)) { - WideControlBody wideBody = new WideControlBody (); + WideControlBody wideBody = new WideControlBody(); bool wideViewEntriesFound = false; @@ -31,47 +31,47 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in controlNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.AutoSizeNode)) + if (MatchNodeName(n, XmlTags.AutoSizeNode)) { if (autosizeNodeFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } autosizeNodeFound = true; bool tempVal; - if (!this.ReadBooleanNode (n, out tempVal)) + if (!this.ReadBooleanNode(n, out tempVal)) { return null; // fatal error } wideBody.autosize = tempVal; } - else if (MatchNodeName (n, XmlTags.ColumnNumberNode)) + else if (MatchNodeName(n, XmlTags.ColumnNumberNode)) { if (columnsNodeFound) { - this.ProcessDuplicateAlternateNode (n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); + this.ProcessDuplicateAlternateNode(n, XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } columnsNodeFound = true; - - if (!ReadPositiveIntegerValue (n, out wideBody.columns)) + + if (!ReadPositiveIntegerValue(n, out wideBody.columns)) { return null; // fatal error } } - else if (MatchNodeName (n, XmlTags.WideEntriesNode)) + else if (MatchNodeName(n, XmlTags.WideEntriesNode)) { if (wideViewEntriesFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); continue; } wideViewEntriesFound = true; // now read the entries section - LoadWideControlEntries (n, wideBody); + LoadWideControlEntries(n, wideBody); if (wideBody.defaultEntryDefinition == null) { // if we have an default entry, it means there was a failure @@ -80,35 +80,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (autosizeNodeFound && columnsNodeFound) { - this.ProcessDuplicateAlternateNode (XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); + this.ProcessDuplicateAlternateNode(XmlTags.AutoSizeNode, XmlTags.ColumnNumberNode); return null; // fatal error } if (!wideViewEntriesFound) { - this.ReportMissingNode (XmlTags.WideEntriesNode); + this.ReportMissingNode(XmlTags.WideEntriesNode); return null; // fatal error } return wideBody; } } - private void LoadWideControlEntries (XmlNode wideControlEntriesNode, WideControlBody wideBody) + private void LoadWideControlEntries(XmlNode wideControlEntriesNode, WideControlBody wideBody) { - using (this.StackFrame (wideControlEntriesNode)) + using (this.StackFrame(wideControlEntriesNode)) { int entryIndex = 0; foreach (XmlNode n in wideControlEntriesNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.WideEntryNode)) + if (MatchNodeName(n, XmlTags.WideEntryNode)) { - WideControlEntryDefinition wved = LoadWideControlEntry (n, entryIndex++); + WideControlEntryDefinition wved = LoadWideControlEntry(n, entryIndex++); if (wved == null) { //Error at XPath {0} in file {1}: Invalid {2}. @@ -132,12 +132,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - wideBody.optionalEntryList.Add (wved); + wideBody.optionalEntryList.Add(wved); } } else { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } } if (wideBody.defaultEntryDefinition == null) @@ -148,27 +148,27 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private WideControlEntryDefinition LoadWideControlEntry (XmlNode wideControlEntryNode, int index) + private WideControlEntryDefinition LoadWideControlEntry(XmlNode wideControlEntryNode, int index) { - using (this.StackFrame (wideControlEntryNode, index)) + using (this.StackFrame(wideControlEntryNode, index)) { bool appliesToNodeFound = false; // cardinality 0..1 bool propertyEntryNodeFound = false; // cardinality 1 - WideControlEntryDefinition wved = new WideControlEntryDefinition (); + WideControlEntryDefinition wved = new WideControlEntryDefinition(); foreach (XmlNode n in wideControlEntryNode.ChildNodes) { - if (MatchNodeName (n, XmlTags.EntrySelectedByNode)) + if (MatchNodeName(n, XmlTags.EntrySelectedByNode)) { if (appliesToNodeFound) { - this.ProcessDuplicateNode (n); + this.ProcessDuplicateNode(n); return null; //fatal } appliesToNodeFound = true; - wved.appliesTo = LoadAppliesToSection (n, true); + wved.appliesTo = LoadAppliesToSection(n, true); } else if (MatchNodeName(n, XmlTags.WideItemNode)) { @@ -203,14 +203,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private List LoadPropertyEntry (XmlNode propertyEntryNode) + private List LoadPropertyEntry(XmlNode propertyEntryNode) { - using (this.StackFrame (propertyEntryNode)) + using (this.StackFrame(propertyEntryNode)) { // process Mshexpression, format string and text token - ViewEntryNodeMatch match = new ViewEntryNodeMatch (this); - List unprocessedNodes = new List (); - if (!match.ProcessExpressionDirectives (propertyEntryNode, unprocessedNodes)) + ViewEntryNodeMatch match = new ViewEntryNodeMatch(this); + List unprocessedNodes = new List(); + if (!match.ProcessExpressionDirectives(propertyEntryNode, unprocessedNodes)) { return null; // fatal error } @@ -219,23 +219,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (XmlNode n in unprocessedNodes) { - this.ProcessUnknownNode (n); + this.ProcessUnknownNode(n); } // finally build the item to return - List formatTokenList = new List (); + List formatTokenList = new List(); // add either the text token or the MshExpression with optional format string if (match.TextToken != null) { - formatTokenList.Add (match.TextToken); + formatTokenList.Add(match.TextToken); } else { - FieldPropertyToken fpt = new FieldPropertyToken (); + FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; fpt.fieldFormattingDirective.formatString = match.FormatString; - formatTokenList.Add (fpt); + formatTokenList.Add(fpt); } return formatTokenList; } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatGroupManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatGroupManager.cs index eb781ca73..c4a5bd3e7 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatGroupManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatGroupManager.cs @@ -21,24 +21,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// name of the grouping porperty /// dispaly name of the property - internal void Initialize (MshExpression groupingExpression, string displayLabel) + internal void Initialize(MshExpression groupingExpression, string displayLabel) { - groupingKeyExpression = groupingExpression; - label = displayLabel; + _groupingKeyExpression = groupingExpression; + _label = displayLabel; } internal object CurrentGroupingKeyPropertyValue { - get { return this.currentGroupingKeyPropertyValue; } + get { return _currentGroupingKeyPropertyValue; } } internal string GroupingKeyDisplayName { - get + get { - if (this.label != null) - return this.label; - return this.groupingKeyDisplayName; + if (_label != null) + return _label; + return _groupingKeyDisplayName; } } @@ -47,29 +47,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to use to compute the property value /// true if there was an update - internal bool UpdateGroupingKeyValue (PSObject so) + internal bool UpdateGroupingKeyValue(PSObject so) { - if (this.groupingKeyExpression == null) + if (_groupingKeyExpression == null) return false; - List results = this.groupingKeyExpression.GetValues (so); + List results = _groupingKeyExpression.GetValues(so); // if we have more that one match, we have to select the first one if (results.Count > 0 && results[0].Exception == null) { // no exception got thrown, so we can update object newValue = results[0].Result; - object oldValue = this.currentGroupingKeyPropertyValue; + object oldValue = _currentGroupingKeyPropertyValue; - this.currentGroupingKeyPropertyValue = newValue; + _currentGroupingKeyPropertyValue = newValue; // now do the comparison - bool update = !(IsEqual(this.currentGroupingKeyPropertyValue, oldValue) || - IsEqual(oldValue, this.currentGroupingKeyPropertyValue)); + bool update = !(IsEqual(_currentGroupingKeyPropertyValue, oldValue) || + IsEqual(oldValue, _currentGroupingKeyPropertyValue)); - if (update && this.label == null) + if (update && _label == null) { - this.groupingKeyDisplayName = results[0].ResolvedExpression.ToString(); + _groupingKeyDisplayName = results[0].ResolvedExpression.ToString(); } return update; } @@ -108,23 +108,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// value of the display label passed in. /// - private string label = null; + private string _label = null; /// /// value of the current active grouping key /// - private string groupingKeyDisplayName = null; + private string _groupingKeyDisplayName = null; /// /// name of the current grouping key /// - private MshExpression groupingKeyExpression = null; + private MshExpression _groupingKeyExpression = null; /// /// the current value of the grouping key /// - private object currentGroupingKeyPropertyValue = AutomationNull.Value; + private object _currentGroupingKeyPropertyValue = AutomationNull.Value; } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatMsgCtxManager.cs index 69aa9fbf6..31bb41b6d 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; namespace Microsoft.PowerShell.Commands.Internal.Format { - /// /// INTERNAL IMPLEMENTATION CLASS /// @@ -20,12 +19,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal class FormatMessagesContextManager { // callbacks declarations - internal delegate OutputContext FormatContextCreationCallback (OutputContext parentContext, FormatInfoData formatData); - internal delegate void FormatStartCallback (OutputContext c); - internal delegate void FormatEndCallback (FormatEndData fe, OutputContext c); - internal delegate void GroupStartCallback (OutputContext c); - internal delegate void GroupEndCallback (GroupEndData fe, OutputContext c); - internal delegate void PayloadCallback (FormatEntryData formatEntryData, OutputContext c); + internal delegate OutputContext FormatContextCreationCallback(OutputContext parentContext, FormatInfoData formatData); + internal delegate void FormatStartCallback(OutputContext c); + internal delegate void FormatEndCallback(FormatEndData fe, OutputContext c); + internal delegate void GroupStartCallback(OutputContext c); + internal delegate void GroupEndCallback(GroupEndData fe, OutputContext c); + internal delegate void PayloadCallback(FormatEntryData formatEntryData, OutputContext c); // callback instances internal FormatContextCreationCallback contextCreation = null; @@ -48,20 +47,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// parent context in the stack, it can be null internal OutputContext(OutputContext parentContextInStack) { - parentContext = parentContextInStack; + _parentContext = parentContextInStack; } /// /// accessor for the parent context field /// - internal OutputContext ParentContext { get { return this.parentContext; } } + internal OutputContext ParentContext { get { return _parentContext; } } /// /// the outer context: the context object pushed onto the /// stack before the current one. For the first object pushed onto /// the stack it will be null /// - private OutputContext parentContext; + private OutputContext _parentContext; } /// @@ -69,17 +68,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// calls back on the specified event delegates /// /// object to process - internal void Process (object o) + internal void Process(object o) { PacketInfoData formatData = o as PacketInfoData; FormatEntryData fed = formatData as FormatEntryData; if (fed != null) { OutputContext ctx = null; - + if (!fed.outOfBand) { - ctx = this.stack.Peek (); + ctx = _stack.Peek(); } // notify for Payload this.payload(fed, ctx); @@ -92,8 +91,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we assume for the moment that they are in the correct sequence if (formatDataIsFormatStartData || formatDataIsGroupStartData) { - OutputContext oc = this.contextCreation(this.ActiveOutputContext, formatData); - this.stack.Push(oc); + OutputContext oc = this.contextCreation(this.ActiveOutputContext, formatData); + _stack.Push(oc); // now we have the context properly set: need to notify the // underlying algorithm to do the start document or group stuff @@ -115,7 +114,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format FormatEndData fEndd = formatData as FormatEndData; if (ged != null || fEndd != null) { - OutputContext oc = this.stack.Peek(); + OutputContext oc = _stack.Peek(); if (fEndd != null) { // notify for Fe, passing the Fe info, before a Pop() @@ -126,7 +125,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // notify for Fe, passing the Fe info, before a Pop() this.ge(ged, oc); } - this.stack.Pop(); + _stack.Pop(); } } } @@ -137,14 +136,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// access the active context (top of the stack). It can be null. /// internal OutputContext ActiveOutputContext - { - get { return (this.stack.Count > 0)?this.stack.Peek() : null; } + { + get { return (_stack.Count > 0) ? _stack.Peek() : null; } } /// /// internal stack to manage context /// - private Stack stack = new Stack(); + private Stack _stack = new Stack(); } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator.cs index 402d0a68a..0b845f6af 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator.cs @@ -2,6 +2,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -17,16 +18,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal abstract class ViewGenerator { - - internal virtual void Initialize (TerminatingErrorContext terminatingErrorContext, + internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { - Diagnostics.Assert (mshExpressionFactory != null, "mshExpressionFactory cannot be null"); - Diagnostics.Assert (db != null, "db cannot be null"); - Diagnostics.Assert (view != null, "view cannot be null"); + Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null"); + Diagnostics.Assert(db != null, "db cannot be null"); + Diagnostics.Assert(view != null, "view cannot be null"); errorContext = terminatingErrorContext; expressionFactory = mshExpressionFactory; @@ -34,14 +34,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format dataBaseInfo.db = db; dataBaseInfo.view = view; - dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes (db, view.appliesTo); + dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes(db, view.appliesTo); InitializeHelper(); } internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, - PSObject so, + PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters formatParameters) { @@ -90,26 +90,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format formatErrorPolicy.ShowErrorsInFormattedOutput = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; } - this.errorManager = new FormatErrorManager(formatErrorPolicy); + _errorManager = new FormatErrorManager(formatErrorPolicy); } - private void InitializeGroupBy () + private void InitializeGroupBy() { // first check if there is an override from the command line if (parameters != null && parameters.groupByParameter != null) { // get the epxpression to use - MshExpression groupingKeyExpression = parameters.groupByParameter.GetEntry (FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; + MshExpression groupingKeyExpression = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; // set the label string label = null; - object labelKey = parameters.groupByParameter.GetEntry (FormatParameterDefinitionKeys.LabelEntryKey); + object labelKey = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (labelKey != AutomationNull.Value) { label = labelKey as string; } - this.groupingManager = new GroupingInfoManager (); - this.groupingManager.Initialize (groupingKeyExpression, label); + _groupingManager = new GroupingInfoManager(); + _groupingManager.Initialize(groupingKeyExpression, label); return; } @@ -126,19 +126,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return; } - MshExpression ex = this.expressionFactory.CreateFromExpressionToken (gb.startGroup.expression, this.dataBaseInfo.view.loadingInfo); + MshExpression ex = this.expressionFactory.CreateFromExpressionToken(gb.startGroup.expression, this.dataBaseInfo.view.loadingInfo); - this.groupingManager = new GroupingInfoManager (); - this.groupingManager.Initialize (ex, null); + _groupingManager = new GroupingInfoManager(); + _groupingManager.Initialize(ex, null); } } - private void InitializeAutoSize () + private void InitializeAutoSize() { // check the autosize flag first if (parameters != null && parameters.autosize.HasValue) { - this.autosize = parameters.autosize.Value; + _autosize = parameters.autosize.Value; return; } // check if we have a view with autosize checked @@ -147,36 +147,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; if (controlBody != null && controlBody.autosize.HasValue) { - this.autosize = controlBody.autosize.Value; + _autosize = controlBody.autosize.Value; } } } - internal virtual FormatStartData GenerateStartData (PSObject so) + internal virtual FormatStartData GenerateStartData(PSObject so) { - FormatStartData startFormat = new FormatStartData (); + FormatStartData startFormat = new FormatStartData(); - if (this.autosize) + if (_autosize) { - startFormat.autosizeInfo = new AutosizeInfo (); + startFormat.autosizeInfo = new AutosizeInfo(); } return startFormat; } - abstract internal FormatEntryData GeneratePayload (PSObject so, int enumerationLimit); + abstract internal FormatEntryData GeneratePayload(PSObject so, int enumerationLimit); - internal GroupStartData GenerateGroupStartData (PSObject firstObjectInGroup, int enumerationLimit) + internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int enumerationLimit) { - GroupStartData startGroup = new GroupStartData (); - if (this.groupingManager == null) + GroupStartData startGroup = new GroupStartData(); + if (_groupingManager == null) return startGroup; - object currentGroupingValue = this.groupingManager.CurrentGroupingKeyPropertyValue; + object currentGroupingValue = _groupingManager.CurrentGroupingKeyPropertyValue; if (currentGroupingValue == AutomationNull.Value) return startGroup; - PSObject so = PSObjectHelper.AsPSObject (currentGroupingValue); + PSObject so = PSObjectHelper.AsPSObject(currentGroupingValue); // we need to determine how to display the group header ControlBase control = null; @@ -192,7 +192,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - startGroup.groupingEntry = new GroupingEntry (); + startGroup.groupingEntry = new GroupingEntry(); if (control == null) { @@ -200,56 +200,56 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // snippet of complex display using a label StringFormatError formatErrorObject = null; - if (this.errorManager.DisplayFormatErrorString) + if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings formatErrorObject = new StringFormatError(); } - string currentGroupingValueDisplay = PSObjectHelper.SmartToString (so, this.expressionFactory, enumerationLimit, formatErrorObject); + string currentGroupingValueDisplay = PSObjectHelper.SmartToString(so, this.expressionFactory, enumerationLimit, formatErrorObject); if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present - this.errorManager.LogStringFormatError(formatErrorObject); - if (this.errorManager.DisplayFormatErrorString) + _errorManager.LogStringFormatError(formatErrorObject); + if (_errorManager.DisplayFormatErrorString) { - currentGroupingValueDisplay = this.errorManager.FormatErrorString; + currentGroupingValueDisplay = _errorManager.FormatErrorString; } } - FormatEntry fe = new FormatEntry (); - startGroup.groupingEntry.formatValueList.Add (fe); + FormatEntry fe = new FormatEntry(); + startGroup.groupingEntry.formatValueList.Add(fe); - FormatTextField ftf = new FormatTextField (); + FormatTextField ftf = new FormatTextField(); // determine what the label should be. If we have a label from the // database, let's use it, else fall back to the string provided // by the grouping manager string label; if (labelTextToken != null) - label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString (labelTextToken); + label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(labelTextToken); else - label = this.groupingManager.GroupingKeyDisplayName; + label = _groupingManager.GroupingKeyDisplayName; ftf.text = StringUtil.Format(FormatAndOut_format_xxx.GroupStartDataIndentedAutoGeneratedLabel, label); - fe.formatValueList.Add (ftf); + fe.formatValueList.Add(ftf); - FormatPropertyField fpf = new FormatPropertyField (); + FormatPropertyField fpf = new FormatPropertyField(); fpf.propertyValue = currentGroupingValueDisplay; - fe.formatValueList.Add (fpf); + fe.formatValueList.Add(fpf); } else { // NOTE: we set a max depth to protect ourselves from infinite loops const int maxTreeDepth = 50; ComplexControlGenerator controlGenerator = - new ComplexControlGenerator (this.dataBaseInfo.db, + new ComplexControlGenerator(this.dataBaseInfo.db, this.dataBaseInfo.view.loadingInfo, this.expressionFactory, this.dataBaseInfo.view.formatControlDefinitionHolder.controlDefinitionList, @@ -257,9 +257,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format enumerationLimit, this.errorContext); - controlGenerator.GenerateFormatEntries (maxTreeDepth, + controlGenerator.GenerateFormatEntries(maxTreeDepth, control, firstObjectInGroup, startGroup.groupingEntry.formatValueList); - } return startGroup; } @@ -269,20 +268,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to use for the update /// true if the value of the key changed - internal bool UpdateGroupingKeyValue (PSObject so) + internal bool UpdateGroupingKeyValue(PSObject so) { - if (this.groupingManager == null) + if (_groupingManager == null) return false; - return this.groupingManager.UpdateGroupingKeyValue (so); + return _groupingManager.UpdateGroupingKeyValue(so); } - internal GroupEndData GenerateGroupEndData () + internal GroupEndData GenerateGroupEndData() { - return new GroupEndData (); + return new GroupEndData(); } - internal bool IsObjectApplicable (Collection typeNames) + internal bool IsObjectApplicable(Collection typeNames) { if (dataBaseInfo.view == null) return true; @@ -290,8 +289,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (typeNames.Count == 0) return false; - TypeMatch match = new TypeMatch (expressionFactory, dataBaseInfo.db, typeNames); - if (match.PerfectMatch (new TypeMatchItem (this, dataBaseInfo.applicableTypes))) + TypeMatch match = new TypeMatch(expressionFactory, dataBaseInfo.db, typeNames); + if (match.PerfectMatch(new TypeMatchItem(this, dataBaseInfo.applicableTypes))) { return true; } @@ -313,13 +312,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } - private GroupingInfoManager groupingManager = null; + private GroupingInfoManager _groupingManager = null; protected bool AutoSize { - get { return this.autosize; } + get { return _autosize; } } - private bool autosize = false; + private bool _autosize = false; protected class DataBaseInfo { @@ -339,25 +338,25 @@ namespace Microsoft.PowerShell.Commands.Internal.Format protected List activeAssociationList = null; protected FormattingCommandLineParameters inputParameters = null; - protected string GetExpressionDisplayValue (PSObject so, int enumerationLimit, MshExpression ex, + protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, MshExpression ex, FieldFormattingDirective directive) { MshExpressionResult resolvedExpression; - return GetExpressionDisplayValue (so, enumerationLimit, ex, directive, out resolvedExpression); + return GetExpressionDisplayValue(so, enumerationLimit, ex, directive, out resolvedExpression); } - protected string GetExpressionDisplayValue (PSObject so, int enumerationLimit, MshExpression ex, + protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, MshExpression ex, FieldFormattingDirective directive, out MshExpressionResult expressionResult) { StringFormatError formatErrorObject = null; - if (this.errorManager.DisplayFormatErrorString) + if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings - formatErrorObject = new StringFormatError (); + formatErrorObject = new StringFormatError(); } - string retVal = PSObjectHelper.GetExpressionDisplayValue (so, enumerationLimit, ex, + string retVal = PSObjectHelper.GetExpressionDisplayValue(so, enumerationLimit, ex, directive, formatErrorObject, expressionFactory, out expressionResult); if (expressionResult != null) @@ -365,38 +364,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we obtained a result, check if there is an error if (expressionResult.Exception != null) { - this.errorManager.LogMshExpressionFailedResult (expressionResult, so); - if (this.errorManager.DisplayErrorStrings) + _errorManager.LogMshExpressionFailedResult(expressionResult, so); + if (_errorManager.DisplayErrorStrings) { - retVal = this.errorManager.ErrorString; + retVal = _errorManager.ErrorString; } } else if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present - this.errorManager.LogStringFormatError (formatErrorObject); - if (this.errorManager.DisplayErrorStrings) + _errorManager.LogStringFormatError(formatErrorObject); + if (_errorManager.DisplayErrorStrings) { - retVal = this.errorManager.FormatErrorString; + retVal = _errorManager.FormatErrorString; } } } return retVal; } - protected bool EvaluateDisplayCondition (PSObject so, ExpressionToken conditionToken) + protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { if (conditionToken == null) return true; - MshExpression ex = this.expressionFactory.CreateFromExpressionToken (conditionToken, this.dataBaseInfo.view.loadingInfo); + MshExpression ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, this.dataBaseInfo.view.loadingInfo); MshExpressionResult expressionResult; - bool retVal = DisplayCondition.Evaluate (so, ex, out expressionResult); + bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { - this.errorManager.LogMshExpressionFailedResult (expressionResult, so); + _errorManager.LogMshExpressionFailedResult(expressionResult, so); } return retVal; } @@ -404,24 +403,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal FormatErrorManager ErrorManager { - get { return this.errorManager; } + get { return _errorManager; } } - private FormatErrorManager errorManager; + private FormatErrorManager _errorManager; #region helpers - protected FormatPropertyField GenerateFormatPropertyField (List formatTokenList, PSObject so, int enumerationLimit) + protected FormatPropertyField GenerateFormatPropertyField(List formatTokenList, PSObject so, int enumerationLimit) { MshExpressionResult result; - return GenerateFormatPropertyField (formatTokenList, so, enumerationLimit, out result); + return GenerateFormatPropertyField(formatTokenList, so, enumerationLimit, out result); } - protected FormatPropertyField GenerateFormatPropertyField (List formatTokenList, PSObject so, int enumerationLimit, out MshExpressionResult result) + protected FormatPropertyField GenerateFormatPropertyField(List formatTokenList, PSObject so, int enumerationLimit, out MshExpressionResult result) { result = null; - FormatPropertyField fpf = new FormatPropertyField (); + FormatPropertyField fpf = new FormatPropertyField(); if (formatTokenList.Count != 0) { FormatToken token = formatTokenList[0]; @@ -429,13 +428,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (fpt != null) { MshExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); - fpf.propertyValue = this.GetExpressionDisplayValue (so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); + fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); } else { TextToken tt = token as TextToken; if (tt != null) - fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString (tt); + fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else @@ -446,7 +445,5 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } #endregion - } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Complex.cs index fec400806..788c09c0b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -13,46 +14,45 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class ComplexViewGenerator : ViewGenerator { - - internal override void Initialize (TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, + internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { - base.Initialize (errorContext, expressionFactory, so, db, parameters); + base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; } - internal override FormatStartData GenerateStartData (PSObject so) + internal override FormatStartData GenerateStartData(PSObject so) { - FormatStartData startFormat = base.GenerateStartData (so); - startFormat.shapeInfo = new ComplexViewHeaderInfo (); + FormatStartData startFormat = base.GenerateStartData(so); + startFormat.shapeInfo = new ComplexViewHeaderInfo(); return startFormat; } - internal override FormatEntryData GeneratePayload (PSObject so, int enumerationLimit) + internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit) { - FormatEntryData fed = new FormatEntryData (); + FormatEntryData fed = new FormatEntryData(); if (this.dataBaseInfo.view != null) - fed.formatEntryInfo = GenerateComplexViewEntryFromDataBaseInfo (so, enumerationLimit); + fed.formatEntryInfo = GenerateComplexViewEntryFromDataBaseInfo(so, enumerationLimit); else - fed.formatEntryInfo = GenerateComplexViewEntryFromProperties (so, enumerationLimit); + fed.formatEntryInfo = GenerateComplexViewEntryFromProperties(so, enumerationLimit); return fed; } - private ComplexViewEntry GenerateComplexViewEntryFromProperties (PSObject so, int enumerationLimit) + private ComplexViewEntry GenerateComplexViewEntryFromProperties(PSObject so, int enumerationLimit) { - ComplexViewObjectBrowser browser = new ComplexViewObjectBrowser (this.ErrorManager, this.expressionFactory, enumerationLimit); - return browser.GenerateView (so, this.inputParameters); + ComplexViewObjectBrowser browser = new ComplexViewObjectBrowser(this.ErrorManager, this.expressionFactory, enumerationLimit); + return browser.GenerateView(so, this.inputParameters); } - private ComplexViewEntry GenerateComplexViewEntryFromDataBaseInfo (PSObject so, int enumerationLimit) + private ComplexViewEntry GenerateComplexViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit) { // execute on the format directive - ComplexViewEntry cve = new ComplexViewEntry (); + ComplexViewEntry cve = new ComplexViewEntry(); // NOTE: we set a max depth to protect ourselves from infinite loops const int maxTreeDepth = 50; - ComplexControlGenerator controlGenerator = + ComplexControlGenerator controlGenerator = new ComplexControlGenerator(this.dataBaseInfo.db, this.dataBaseInfo.view.loadingInfo, this.expressionFactory, @@ -61,11 +61,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format enumerationLimit, this.errorContext); - controlGenerator.GenerateFormatEntries (maxTreeDepth, + controlGenerator.GenerateFormatEntries(maxTreeDepth, this.dataBaseInfo.view.mainControl, so, cve.formatValueList); return cve; } - } /// @@ -74,7 +73,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class ComplexControlGenerator { - internal ComplexControlGenerator (TypeInfoDataBase dataBase, + internal ComplexControlGenerator(TypeInfoDataBase dataBase, DatabaseLoadingInfo loadingInfo, MshExpressionFactory expressionFactory, List controlDefinitionList, @@ -82,16 +81,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format int enumerationLimit, TerminatingErrorContext errorContext) { - this.db = dataBase; - this.loadingInfo = loadingInfo; - this.expressionFactory = expressionFactory; - this.controlDefinitionList = controlDefinitionList; - this.errorManager = resultErrorManager; - this.enumerationLimit = enumerationLimit; - this.errorContext = errorContext; + _db = dataBase; + _loadingInfo = loadingInfo; + _expressionFactory = expressionFactory; + _controlDefinitionList = controlDefinitionList; + _errorManager = resultErrorManager; + _enumerationLimit = enumerationLimit; + _errorContext = errorContext; } - internal void GenerateFormatEntries (int maxTreeDepth, ControlBase control, + internal void GenerateFormatEntries(int maxTreeDepth, ControlBase control, PSObject so, List formatValueList) { if (control == null) @@ -99,11 +98,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format throw PSTraceSource.NewArgumentNullException("control"); } - ExecuteFormatControl (new TraversalInfo (0, maxTreeDepth), control, + ExecuteFormatControl(new TraversalInfo(0, maxTreeDepth), control, so, formatValueList); } - private bool ExecuteFormatControl (TraversalInfo level, ControlBase control, + private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, PSObject so, List formatValueList) { // we are looking for a complex control to execute @@ -114,9 +113,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference - complexBody = DisplayDataQuery.ResolveControlReference ( - this.db, - this.controlDefinitionList, + complexBody = DisplayDataQuery.ResolveControlReference( + _db, + _controlDefinitionList, controlReference) as ComplexControlBody; } else @@ -129,31 +128,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (complexBody != null) { // we have an inline control, just execute it - ExecuteFormatControlBody (level, so, complexBody, formatValueList); + ExecuteFormatControlBody(level, so, complexBody, formatValueList); return true; } return false; } - private void ExecuteFormatControlBody (TraversalInfo level, + private void ExecuteFormatControlBody(TraversalInfo level, PSObject so, ComplexControlBody complexBody, List formatValueList) { ComplexControlEntryDefinition activeControlEntryDefinition = - GetActiveComplexControlEntryDefinition (complexBody, so); + GetActiveComplexControlEntryDefinition(complexBody, so); - ExecuteFormatTokenList (level, + ExecuteFormatTokenList(level, so, activeControlEntryDefinition.itemDefinition.formatTokenList, formatValueList); - } - private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition (ComplexControlBody complexBody, PSObject so) + private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(ComplexControlBody complexBody, PSObject so) { // see if we have an override that matches var typeNames = so.InternalTypeNames; - TypeMatch match = new TypeMatch (expressionFactory, db, typeNames); + TypeMatch match = new TypeMatch(_expressionFactory, _db, typeNames); foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList) { - if (match.PerfectMatch (new TypeMatchItem (x, x.appliesTo))) + if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { return x; } @@ -167,7 +165,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { - match = new TypeMatch(expressionFactory, db, typesWithoutPrefix); + match = new TypeMatch(_expressionFactory, _db, typesWithoutPrefix); foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) @@ -186,12 +184,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private void ExecuteFormatTokenList (TraversalInfo level, + private void ExecuteFormatTokenList(TraversalInfo level, PSObject so, List formatTokenList, List formatValueList) { if (so == null) { - throw PSTraceSource.NewArgumentNullException ("so"); + throw PSTraceSource.NewArgumentNullException("so"); } // guard against infinite loop @@ -200,9 +198,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return; } - FormatEntry fe = new FormatEntry (); + FormatEntry fe = new FormatEntry(); - formatValueList.Add (fe); + formatValueList.Add(fe); #region foreach loop foreach (FormatToken t in formatTokenList) { @@ -210,7 +208,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (tt != null) { FormatTextField ftf = new FormatTextField(); - ftf.text = this.db.displayResourceManagerCache.GetTextTokenString(tt); + ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); fe.formatValueList.Add(ftf); continue; } @@ -244,7 +242,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } #region CompoundPropertyToken CompoundPropertyToken cpt = t as CompoundPropertyToken; - if (cpt != null) + if (cpt != null) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { @@ -263,14 +261,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - MshExpression ex = this.expressionFactory.CreateFromExpressionToken(cpt.expression, this.loadingInfo); + MshExpression ex = _expressionFactory.CreateFromExpressionToken(cpt.expression, _loadingInfo); List resultList = ex.GetValues(so); if (resultList.Count > 0) { val = resultList[0].Result; if (resultList[0].Exception != null) { - this.errorManager.LogMshExpressionFailedResult(resultList[0], so); + _errorManager.LogMshExpressionFailedResult(resultList[0], so); } } } @@ -291,7 +289,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (cpt.control != null) { fieldFormattingDirective = ((FieldControlBody)cpt.control).fieldFormattingDirective; - if (fieldFormattingDirective != null && this.errorManager.DisplayFormatErrorString) + if (fieldFormattingDirective != null && _errorManager.DisplayFormatErrorString) { formatErrorObject = new StringFormatError(); } @@ -310,7 +308,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } fpf = new FormatPropertyField(); - fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, enumerationLimit, formatErrorObject, expressionFactory); + fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } } @@ -318,13 +316,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { fpf = new FormatPropertyField(); - fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, enumerationLimit, formatErrorObject, expressionFactory); + fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } if (formatErrorObject != null && formatErrorObject.exception != null) { - this.errorManager.LogStringFormatError(formatErrorObject); - fpf.propertyValue = this.errorManager.FormatErrorString; + _errorManager.LogStringFormatError(formatErrorObject); + fpf.propertyValue = _errorManager.FormatErrorString; } } else @@ -361,34 +359,34 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #endregion foreach loop } - private bool EvaluateDisplayCondition (PSObject so, ExpressionToken conditionToken) + private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { if (conditionToken == null) return true; - MshExpression ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, loadingInfo); + MshExpression ex = _expressionFactory.CreateFromExpressionToken(conditionToken, _loadingInfo); MshExpressionResult expressionResult; - bool retVal = DisplayCondition.Evaluate (so, ex, out expressionResult); + bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { - this.errorManager.LogMshExpressionFailedResult (expressionResult, so); + _errorManager.LogMshExpressionFailedResult(expressionResult, so); } return retVal; } - private TypeInfoDataBase db; - private DatabaseLoadingInfo loadingInfo; - private MshExpressionFactory expressionFactory; - private List controlDefinitionList; - private FormatErrorManager errorManager; - private TerminatingErrorContext errorContext; - private int enumerationLimit; + private TypeInfoDataBase _db; + private DatabaseLoadingInfo _loadingInfo; + private MshExpressionFactory _expressionFactory; + private List _controlDefinitionList; + private FormatErrorManager _errorManager; + private TerminatingErrorContext _errorContext; + private int _enumerationLimit; } internal class TraversalInfo { - internal TraversalInfo (int level, int maxDepth) + internal TraversalInfo(int level, int maxDepth) { _level = level; _maxDepth = maxDepth; @@ -401,7 +399,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - return new TraversalInfo (this._level + 1, this._maxDepth); + return new TraversalInfo(_level + 1, _maxDepth); } } @@ -416,9 +414,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal ComplexViewObjectBrowser(FormatErrorManager resultErrorManager, MshExpressionFactory mshExpressionFactory, int enumerationLimit) { - this.errorManager = resultErrorManager; - this.expressionFactory = mshExpressionFactory; - this.enumerationLimit = enumerationLimit; + _errorManager = resultErrorManager; + _expressionFactory = mshExpressionFactory; + _enumerationLimit = enumerationLimit; } /// @@ -428,26 +426,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// object to process /// parameters from the command line /// complex view entry to send to the output command - internal ComplexViewEntry GenerateView (PSObject so, FormattingCommandLineParameters inputParameters) + internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParameters inputParameters) { - this.complexSpecificParameters = (ComplexSpecificParameters)inputParameters.shapeParameters; + _complexSpecificParameters = (ComplexSpecificParameters)inputParameters.shapeParameters; - int maxDepth = this.complexSpecificParameters.maxDepth; - TraversalInfo level = new TraversalInfo (0, maxDepth); + int maxDepth = _complexSpecificParameters.maxDepth; + TraversalInfo level = new TraversalInfo(0, maxDepth); List mshParameterList = null; if (inputParameters != null) mshParameterList = inputParameters.mshParameterList; // create a top level entry as root of the tree - ComplexViewEntry cve = new ComplexViewEntry (); + ComplexViewEntry cve = new ComplexViewEntry(); var typeNames = so.InternalTypeNames; - if (TreatAsScalarType (typeNames)) + if (TreatAsScalarType(typeNames)) { - FormatEntry fe = new FormatEntry (); + FormatEntry fe = new FormatEntry(); - cve.formatValueList.Add (fe); - DisplayRawObject (so, fe.formatValueList); + cve.formatValueList.Add(fe); + DisplayRawObject(so, fe.formatValueList); } else { @@ -457,49 +455,49 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (e != null) { // let's start the traversal with an enumeration - FormatEntry fe = new FormatEntry (); + FormatEntry fe = new FormatEntry(); - cve.formatValueList.Add (fe); - DisplayEnumeration (e, level, fe.formatValueList); + cve.formatValueList.Add(fe); + DisplayEnumeration(e, level, fe.formatValueList); } else { // let's start the traversal with a traversal on properties - DisplayObject (so, level, mshParameterList, cve.formatValueList); + DisplayObject(so, level, mshParameterList, cve.formatValueList); } } return cve; } - private void DisplayRawObject (PSObject so, List formatValueList) + private void DisplayRawObject(PSObject so, List formatValueList) { - FormatPropertyField fpf = new FormatPropertyField (); + FormatPropertyField fpf = new FormatPropertyField(); StringFormatError formatErrorObject = null; - if (this.errorManager.DisplayFormatErrorString) + if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings formatErrorObject = new StringFormatError(); } - fpf.propertyValue = PSObjectHelper.SmartToString (so, this.expressionFactory, enumerationLimit, formatErrorObject); + fpf.propertyValue = PSObjectHelper.SmartToString(so, _expressionFactory, _enumerationLimit, formatErrorObject); if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present - this.errorManager.LogStringFormatError(formatErrorObject); - if (this.errorManager.DisplayFormatErrorString) + _errorManager.LogStringFormatError(formatErrorObject); + if (_errorManager.DisplayFormatErrorString) { - fpf.propertyValue = this.errorManager.FormatErrorString; + fpf.propertyValue = _errorManager.FormatErrorString; } } - formatValueList.Add (fpf); - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(fpf); + formatValueList.Add(new FormatNewLine()); } /// @@ -509,51 +507,51 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// current level in the traversal /// list of parameters from the command line /// list of format tokens to add to - private void DisplayObject (PSObject so, TraversalInfo currentLevel, List parameterList, + private void DisplayObject(PSObject so, TraversalInfo currentLevel, List parameterList, List formatValueList) { // resolve the names of the properties List activeAssociationList = - AssociationManager.SetupActiveProperties (parameterList, so, this.expressionFactory); + AssociationManager.SetupActiveProperties(parameterList, so, _expressionFactory); // create a format entry - FormatEntry fe = new FormatEntry (); - formatValueList.Add (fe); + FormatEntry fe = new FormatEntry(); + formatValueList.Add(fe); // add the display name of the object - string objectDisplayName = GetObjectDisplayName (so); + string objectDisplayName = GetObjectDisplayName(so); if (objectDisplayName != null) objectDisplayName = "class " + objectDisplayName; - AddPrologue (fe.formatValueList, "{", objectDisplayName); - ProcessActiveAssociationList (so, currentLevel, activeAssociationList, AddIndentationLevel (fe.formatValueList)); - AddEpilogue (fe.formatValueList, "}"); + AddPrologue(fe.formatValueList, "{", objectDisplayName); + ProcessActiveAssociationList(so, currentLevel, activeAssociationList, AddIndentationLevel(fe.formatValueList)); + AddEpilogue(fe.formatValueList, "}"); } - private void ProcessActiveAssociationList (PSObject so, + private void ProcessActiveAssociationList(PSObject so, TraversalInfo currentLevel, List activeAssociationList, List formatValueList) { foreach (MshResolvedExpressionParameterAssociation a in activeAssociationList) { - FormatTextField ftf = new FormatTextField (); + FormatTextField ftf = new FormatTextField(); - ftf.text = a.ResolvedExpression.ToString () + " = "; - formatValueList.Add (ftf); + ftf.text = a.ResolvedExpression.ToString() + " = "; + formatValueList.Add(ftf); // compute the value of the entry - List resList = a.ResolvedExpression.GetValues (so); + List resList = a.ResolvedExpression.GetValues(so); object val = null; if (resList.Count >= 1) { MshExpressionResult result = resList[0]; if (result.Exception != null) { - this.errorManager.LogMshExpressionFailedResult (result, so); - if (this.errorManager.DisplayErrorStrings) + _errorManager.LogMshExpressionFailedResult(result, so); + if (_errorManager.DisplayErrorStrings) { - val = this.errorManager.ErrorString; + val = _errorManager.ErrorString; } else { @@ -571,11 +569,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format TraversalInfo level = currentLevel; if (a.OriginatingParameter != null) { - object maxDepthKey = a.OriginatingParameter.GetEntry (FormatParameterDefinitionKeys.DepthEntryKey); + object maxDepthKey = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.DepthEntryKey); if (maxDepthKey != AutomationNull.Value) { int parameterMaxDept = (int)maxDepthKey; - level = new TraversalInfo (currentLevel.Level, parameterMaxDept); + level = new TraversalInfo(currentLevel.Level, parameterMaxDept); } } @@ -585,21 +583,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (e != null) { - formatValueList.Add (new FormatNewLine ()); - DisplayEnumeration (e, level.NextLevel, AddIndentationLevel (formatValueList)); - + formatValueList.Add(new FormatNewLine()); + DisplayEnumeration(e, level.NextLevel, AddIndentationLevel(formatValueList)); } - else if (val == null || TreatAsLeafNode (val, level)) + else if (val == null || TreatAsLeafNode(val, level)) { - DisplayLeaf (val, formatValueList); + DisplayLeaf(val, formatValueList); } else { - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(new FormatNewLine()); // we need to go one more level down - DisplayObject (PSObject.AsPSObject (val), level.NextLevel, null, - AddIndentationLevel (formatValueList)); + DisplayObject(PSObject.AsPSObject(val), level.NextLevel, null, + AddIndentationLevel(formatValueList)); } } // for each } @@ -610,16 +607,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// enumeration to display /// current level in the traversal /// list of format tokens to add to - private void DisplayEnumeration (IEnumerable e, TraversalInfo level, List formatValueList) + private void DisplayEnumeration(IEnumerable e, TraversalInfo level, List formatValueList) { - AddPrologue (formatValueList, "[", null); - DisplayEnumerationInner (e, level, AddIndentationLevel (formatValueList)); - AddEpilogue (formatValueList, "]"); + AddPrologue(formatValueList, "[", null); + DisplayEnumerationInner(e, level, AddIndentationLevel(formatValueList)); + AddEpilogue(formatValueList, "]"); - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(new FormatNewLine()); } - private void DisplayEnumerationInner (IEnumerable e, TraversalInfo level, List formatValueList) + private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List formatValueList) { int enumCount = 0; foreach (object x in e) @@ -628,32 +625,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { throw new PipelineStoppedException(); } - if (enumerationLimit >= 0) + if (_enumerationLimit >= 0) { - if (enumerationLimit == enumCount) + if (_enumerationLimit == enumCount) { DisplayLeaf(PSObjectHelper.ellipses, formatValueList); break; } enumCount++; } - if (TreatAsLeafNode (x, level)) + if (TreatAsLeafNode(x, level)) { - DisplayLeaf (x, formatValueList); + DisplayLeaf(x, formatValueList); } else { - // check if the top level object is an enumeration + // check if the top level object is an enumeration IEnumerable e1 = PSObjectHelper.GetEnumerable(x); if (e1 != null) { - formatValueList.Add (new FormatNewLine ()); - DisplayEnumeration (e1, level.NextLevel, AddIndentationLevel (formatValueList)); + formatValueList.Add(new FormatNewLine()); + DisplayEnumeration(e1, level.NextLevel, AddIndentationLevel(formatValueList)); } else { - DisplayObject (PSObjectHelper.AsPSObject (x), level.NextLevel, null, formatValueList); + DisplayObject(PSObjectHelper.AsPSObject(x), level.NextLevel, null, formatValueList); } } } @@ -664,13 +661,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to display /// list of format tokens to add to - private void DisplayLeaf (object val, List formatValueList) + private void DisplayLeaf(object val, List formatValueList) { - FormatPropertyField fpf = new FormatPropertyField (); + FormatPropertyField fpf = new FormatPropertyField(); - fpf.propertyValue = PSObjectHelper.FormatField(null, PSObjectHelper.AsPSObject(val), enumerationLimit, null, expressionFactory); - formatValueList.Add (fpf); - formatValueList.Add (new FormatNewLine ()); + fpf.propertyValue = PSObjectHelper.FormatField(null, PSObjectHelper.AsPSObject(val), _enumerationLimit, null, _expressionFactory); + formatValueList.Add(fpf); + formatValueList.Add(new FormatNewLine()); } /// @@ -679,7 +676,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// object to verify /// current level of recursion /// - private static bool TreatAsLeafNode (object val, TraversalInfo level) + private static bool TreatAsLeafNode(object val, TraversalInfo level) { if (level.Level >= level.MaxDepth || val == null) return true; @@ -692,14 +689,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// name of the type to check /// true if it has to be treated as a scalar - private static bool TreatAsScalarType (Collection typeNames) + private static bool TreatAsScalarType(Collection typeNames) { - return DefaultScalarTypes.IsTypeInList (typeNames); + return DefaultScalarTypes.IsTypeInList(typeNames); } - private string GetObjectDisplayName (PSObject so) + private string GetObjectDisplayName(PSObject so) { - if (this.complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.none) + if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.none) return null; var typeNames = so.InternalTypeNames; @@ -708,7 +705,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return "PSObject"; } - if (this.complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName) + if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName) { // get the last token in the full name string[] arr = typeNames[0].Split(Utils.Separators.Dot); @@ -719,60 +716,59 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return typeNames[0]; } - private static void AddPrologue (List formatValueList, string openTag, string label) + private static void AddPrologue(List formatValueList, string openTag, string label) { if (label != null) { - FormatTextField ftfLabel = new FormatTextField (); + FormatTextField ftfLabel = new FormatTextField(); ftfLabel.text = label; - formatValueList.Add (ftfLabel); - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(ftfLabel); + formatValueList.Add(new FormatNewLine()); } - FormatTextField ftf = new FormatTextField (); + FormatTextField ftf = new FormatTextField(); ftf.text = openTag; - formatValueList.Add (ftf); + formatValueList.Add(ftf); - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(new FormatNewLine()); } - private static void AddEpilogue (List formatValueList, string closeTag) + private static void AddEpilogue(List formatValueList, string closeTag) { - FormatTextField ftf = new FormatTextField (); + FormatTextField ftf = new FormatTextField(); ftf.text = closeTag; - formatValueList.Add (ftf); + formatValueList.Add(ftf); - formatValueList.Add (new FormatNewLine ()); + formatValueList.Add(new FormatNewLine()); } - private List AddIndentationLevel (List formatValueList) + private List AddIndentationLevel(List formatValueList) { - FormatEntry feFrame = new FormatEntry (); - feFrame.frameInfo = new FrameInfo (); + FormatEntry feFrame = new FormatEntry(); + feFrame.frameInfo = new FrameInfo(); // add the frame info feFrame.frameInfo.firstLine = 0; - feFrame.frameInfo.leftIndentation = indentationStep; + feFrame.frameInfo.leftIndentation = _indentationStep; feFrame.frameInfo.rightIndentation = 0; - formatValueList.Add (feFrame); + formatValueList.Add(feFrame); return feFrame.formatValueList; } - private ComplexSpecificParameters complexSpecificParameters; + private ComplexSpecificParameters _complexSpecificParameters; /// /// identation added to each level in the recursion /// - private int indentationStep = 2; + private int _indentationStep = 2; - private FormatErrorManager errorManager; + private FormatErrorManager _errorManager; - private MshExpressionFactory expressionFactory; + private MshExpressionFactory _expressionFactory; - private int enumerationLimit; + private int _enumerationLimit; } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_List.cs index 84aaa1e91..07fc6f731 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -13,14 +14,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class ListViewGenerator : ViewGenerator { // tableBody to use for this instance of the ViewGenerator; - private ListControlBody listBody; + private ListControlBody _listBody; internal override void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view)) { - listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; + _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } } @@ -30,7 +31,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format base.Initialize(errorContext, expressionFactory, so, db, parameters); if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view)) { - listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; + _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } this.inputParameters = parameters; @@ -52,7 +53,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) { - listBody = (ListControlBody)this.dataBaseInfo.view.mainControl.Copy(); + _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl.Copy(); // build up the definition for computer name. ListControlItemDefinition cnListItemDefinition = new ListControlItemDefinition(); cnListItemDefinition.label = new TextToken(); @@ -62,7 +63,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format cnListItemDefinition.formatTokenList.Add(fpt); - listBody.defaultEntryDefinition.itemDefinitionList.Add(cnListItemDefinition); + _listBody.defaultEntryDefinition.itemDefinitionList.Add(cnListItemDefinition); } } @@ -89,7 +90,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format ListViewEntry lve = new ListViewEntry(); ListControlEntryDefinition activeListControlEntryDefinition = - GetActiveListControlEntryDefinition(listBody, so); + GetActiveListControlEntryDefinition(_listBody, so); foreach (ListControlItemDefinition listItem in activeListControlEntryDefinition.itemDefinitionList) { diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Table.cs index a5dc329ed..019c73a96 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -13,14 +14,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class TableViewGenerator : ViewGenerator { // tableBody to use for this instance of the ViewGenerator; - private TableControlBody tableBody; + private TableControlBody _tableBody; internal override void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view)) { - tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; + _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } } @@ -32,7 +33,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if ((null != this.dataBaseInfo) && (null != this.dataBaseInfo.view)) { - tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; + _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } List rawMshParameterList = null; @@ -93,21 +94,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // dont change the original format definition in the database..just make a copy and work // with the copy - tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl.Copy(); + _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl.Copy(); TableRowItemDefinition cnRowDefinition = new TableRowItemDefinition(); PropertyTokenBase propToken = new FieldPropertyToken(); propToken.expression = new ExpressionToken(RemotingConstants.ComputerNameNoteProperty, false); cnRowDefinition.formatTokenList.Add(propToken); - tableBody.defaultDefinition.rowItemDefinitionList.Add(cnRowDefinition); + _tableBody.defaultDefinition.rowItemDefinitionList.Add(cnRowDefinition); // add header only if there are other header definitions - if (tableBody.header.columnHeaderDefinitionList.Count > 0) + if (_tableBody.header.columnHeaderDefinitionList.Count > 0) { TableColumnHeaderDefinition cnHeaderDefinition = new TableColumnHeaderDefinition(); cnHeaderDefinition.label = new TextToken(); cnHeaderDefinition.label.text = RemotingConstants.ComputerNameNoteProperty; - tableBody.header.columnHeaderDefinitionList.Add(cnHeaderDefinition); + _tableBody.header.columnHeaderDefinitionList.Add(cnHeaderDefinition); } } } @@ -155,7 +156,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format TableHeaderInfo thi = new TableHeaderInfo(); bool dummy; - List activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, so, out dummy); + List activeRowItemDefinitionList = GetActiveTableRowDefinition(_tableBody, so, out dummy); thi.hideHeader = this.HideHeaders; int col = 0; @@ -163,8 +164,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { TableColumnInfo ci = new TableColumnInfo(); TableColumnHeaderDefinition colHeader = null; - if (tableBody.header.columnHeaderDefinitionList.Count > 0) - colHeader = tableBody.header.columnHeaderDefinitionList[col]; + if (_tableBody.header.columnHeaderDefinitionList.Count > 0) + colHeader = _tableBody.header.columnHeaderDefinitionList[col]; if (colHeader != null) { @@ -289,7 +290,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // if we have a view, get the value out of it if (this.dataBaseInfo.view != null) { - return tableBody.header.hideHeader; + return _tableBody.header.hideHeader; } return false; } @@ -434,7 +435,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { TableRowEntry tre = new TableRowEntry(); - List activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, so, out tre.multiLine); + List activeRowItemDefinitionList = GetActiveTableRowDefinition(_tableBody, so, out tre.multiLine); foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { FormatPropertyField fpf = GenerateFormatPropertyField(rowItem.formatTokenList, so, enumerationLimit); @@ -465,8 +466,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } return tre; } - } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Wide.cs index 0c5b79811..0c77afb99 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -11,18 +12,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal sealed class WideViewGenerator : ViewGenerator { - internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, + internal override void Initialize(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { - base.Initialize (errorContext, expressionFactory, so, db, parameters); + base.Initialize(errorContext, expressionFactory, so, db, parameters); this.inputParameters = parameters; } - internal override FormatStartData GenerateStartData (PSObject so) + internal override FormatStartData GenerateStartData(PSObject so) { - FormatStartData startFormat = base.GenerateStartData (so); + FormatStartData startFormat = base.GenerateStartData(so); - WideViewHeaderInfo wideViewHeaderInfo = new WideViewHeaderInfo (); + WideViewHeaderInfo wideViewHeaderInfo = new WideViewHeaderInfo(); startFormat.shapeInfo = wideViewHeaderInfo; @@ -62,14 +63,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - internal override FormatEntryData GeneratePayload (PSObject so, int enumerationLimit) + internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLimit) { - FormatEntryData fed = new FormatEntryData (); + FormatEntryData fed = new FormatEntryData(); if (this.dataBaseInfo.view != null) - fed.formatEntryInfo = GenerateWideViewEntryFromDataBaseInfo (so, enumerationLimit); + fed.formatEntryInfo = GenerateWideViewEntryFromDataBaseInfo(so, enumerationLimit); else - fed.formatEntryInfo = GenerateWideViewEntryFromProperties (so, enumerationLimit); + fed.formatEntryInfo = GenerateWideViewEntryFromProperties(so, enumerationLimit); return fed; } @@ -79,24 +80,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format WideControlBody wideBody = (WideControlBody)this.dataBaseInfo.view.mainControl; WideControlEntryDefinition activeWideControlEntryDefinition = - GetActiveWideControlEntryDefinition (wideBody, so); + GetActiveWideControlEntryDefinition(wideBody, so); - WideViewEntry wve = new WideViewEntry (); - wve.formatPropertyField = GenerateFormatPropertyField (activeWideControlEntryDefinition.formatTokenList, so, enumerationLimit); + WideViewEntry wve = new WideViewEntry(); + wve.formatPropertyField = GenerateFormatPropertyField(activeWideControlEntryDefinition.formatTokenList, so, enumerationLimit); //wve.aligment = activeWideViewEntryDefinition.alignment; - + return wve; } - private WideControlEntryDefinition GetActiveWideControlEntryDefinition (WideControlBody wideBody, PSObject so) + private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideControlBody wideBody, PSObject so) { // see if we have an override that matches var typeNames = so.InternalTypeNames; - TypeMatch match = new TypeMatch (expressionFactory, this.dataBaseInfo.db, typeNames); + TypeMatch match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typeNames); foreach (WideControlEntryDefinition x in wideBody.optionalEntryList) { - if (match.PerfectMatch (new TypeMatchItem (x, x.appliesTo))) + if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { return x; } @@ -129,16 +130,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - private WideViewEntry GenerateWideViewEntryFromProperties (PSObject so, int enumerationLimit) + private WideViewEntry GenerateWideViewEntryFromProperties(PSObject so, int enumerationLimit) { // compute active properties every time if (this.activeAssociationList == null) { - SetUpActiveProperty (so); + SetUpActiveProperty(so); } - WideViewEntry wve = new WideViewEntry (); - FormatPropertyField fpf = new FormatPropertyField (); + WideViewEntry wve = new WideViewEntry(); + FormatPropertyField fpf = new FormatPropertyField(); wve.formatPropertyField = fpf; if (this.activeAssociationList.Count > 0) @@ -148,17 +149,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format FieldFormattingDirective directive = null; if (a.OriginatingParameter != null) { - directive = a.OriginatingParameter.GetEntry (FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; + directive = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } - fpf.propertyValue = this.GetExpressionDisplayValue (so, enumerationLimit, a.ResolvedExpression, directive); + fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, a.ResolvedExpression, directive); } this.activeAssociationList = null; return wve; } - private void SetUpActiveProperty (PSObject so) + private void SetUpActiveProperty(PSObject so) { List rawMshParameterList = null; @@ -168,22 +169,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // check if we received properties from the command line if (rawMshParameterList != null && rawMshParameterList.Count > 0) { - this.activeAssociationList = AssociationManager.ExpandParameters (rawMshParameterList, so); + this.activeAssociationList = AssociationManager.ExpandParameters(rawMshParameterList, so); return; } // we did not get any properties: //try to get the display property of the object - MshExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression (so, this.expressionFactory); + MshExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression(so, this.expressionFactory); if (displayNameExpression != null) { - this.activeAssociationList = new List (); - this.activeAssociationList.Add (new MshResolvedExpressionParameterAssociation (null, displayNameExpression)); + this.activeAssociationList = new List(); + this.activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, displayNameExpression)); return; } // try to get the default property set (we will use the first property) - this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet (so, this.expressionFactory); + this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); if (this.activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set @@ -192,7 +193,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we failed to get anything from the default property set // just get all the properties - this.activeAssociationList = AssociationManager.ExpandAll (so); + this.activeAssociationList = AssociationManager.ExpandAll(so); } } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewManager.cs index 8e3b1c8b0..c655fdb91 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatViewManager.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -10,16 +11,15 @@ using System.Text; namespace Microsoft.PowerShell.Commands.Internal.Format { - internal static class DefaultScalarTypes { - internal static bool IsTypeInList (Collection typeNames) + internal static bool IsTypeInList(Collection typeNames) { // NOTE: we do not use inheritance here, since we deal with // value types or with types where inheritance is not a factor for the selection - string typeName = PSObjectHelper.PSObjectIsOfExactType (typeNames); + string typeName = PSObjectHelper.PSObjectIsOfExactType(typeNames); - if (string.IsNullOrEmpty (typeName)) + if (string.IsNullOrEmpty(typeName)) return false; string originalTypeName = Deserializer.MaskDeserializationPrefix(typeName); @@ -33,31 +33,31 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (PSObjectHelper.PSObjectIsEnum(typeNames)) return true; - return defaultScalarTypesHash.Contains(originalTypeName); + return s_defaultScalarTypesHash.Contains(originalTypeName); } - static DefaultScalarTypes () + static DefaultScalarTypes() { - defaultScalarTypesHash.Add("System.String"); - defaultScalarTypesHash.Add("System.SByte"); - defaultScalarTypesHash.Add("System.Byte"); - defaultScalarTypesHash.Add("System.Int16"); - defaultScalarTypesHash.Add("System.UInt16"); - defaultScalarTypesHash.Add("System.Int32"); - defaultScalarTypesHash.Add("System.UInt32"); - defaultScalarTypesHash.Add("System.Int64"); - defaultScalarTypesHash.Add("System.UInt64"); - defaultScalarTypesHash.Add("System.Char"); - defaultScalarTypesHash.Add("System.Single"); - defaultScalarTypesHash.Add("System.Double"); - defaultScalarTypesHash.Add("System.Boolean"); - defaultScalarTypesHash.Add("System.Decimal"); - defaultScalarTypesHash.Add("System.IntPtr"); - defaultScalarTypesHash.Add("System.Security.SecureString"); - defaultScalarTypesHash.Add("System.Numerics.BigInteger"); + s_defaultScalarTypesHash.Add("System.String"); + s_defaultScalarTypesHash.Add("System.SByte"); + s_defaultScalarTypesHash.Add("System.Byte"); + s_defaultScalarTypesHash.Add("System.Int16"); + s_defaultScalarTypesHash.Add("System.UInt16"); + s_defaultScalarTypesHash.Add("System.Int32"); + s_defaultScalarTypesHash.Add("System.UInt32"); + s_defaultScalarTypesHash.Add("System.Int64"); + s_defaultScalarTypesHash.Add("System.UInt64"); + s_defaultScalarTypesHash.Add("System.Char"); + s_defaultScalarTypesHash.Add("System.Single"); + s_defaultScalarTypesHash.Add("System.Double"); + s_defaultScalarTypesHash.Add("System.Boolean"); + s_defaultScalarTypesHash.Add("System.Decimal"); + s_defaultScalarTypesHash.Add("System.IntPtr"); + s_defaultScalarTypesHash.Add("System.Security.SecureString"); + s_defaultScalarTypesHash.Add("System.Numerics.BigInteger"); } - private readonly static HashSet defaultScalarTypesHash = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly static HashSet s_defaultScalarTypesHash = new HashSet(StringComparer.OrdinalIgnoreCase); } /// @@ -68,7 +68,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { #region tracer [TraceSource("FormatViewBinding", "Format view binding")] - private static PSTraceSource formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false); + private static PSTraceSource s_formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false); #endregion tracer @@ -102,13 +102,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format const string viewNotFound = "No applicable view has been found"; try { - DisplayDataQuery.SetTracer(formatViewBindingTracer); + DisplayDataQuery.SetTracer(s_formatViewBindingTracer); // shape not specified: we need to select one var typeNames = so.InternalTypeNames; if (shape == FormatShape.Undefined) { - using (formatViewBindingTracer.TraceScope(findViewType, PSObjectTypeName(so))) + using (s_formatViewBindingTracer.TraceScope(findViewType, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } @@ -116,22 +116,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // we got a matching view from the database // use this and we are done - this.viewGenerator = SelectViewGeneratorFromViewDefinition( + _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); - formatViewBindingTracer.WriteLine(viewFound); - PrepareViewForRemoteObjects(ViewGenerator, so); + s_formatViewBindingTracer.WriteLine(viewFound); + PrepareViewForRemoteObjects(ViewGenerator, so); return; } - formatViewBindingTracer.WriteLine(viewNotFound); + s_formatViewBindingTracer.WriteLine(viewNotFound); // we did not get any default view (and shape), we need to force one // we just select properties out of the object itself, since they were not // specified on the command line - this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null); + _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null); PrepareViewForRemoteObjects(ViewGenerator, so); return; @@ -140,61 +140,60 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we have a predefined shape: did the user specify properties on the command line? if (parameters != null && parameters.mshParameterList.Count > 0) { - this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); + _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); return; } // predefined shape: did the user specify the name of a view? if (parameters != null && !string.IsNullOrEmpty(parameters.viewName)) { - using (formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName, + using (s_formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName); } if (view != null) { - this.viewGenerator = SelectViewGeneratorFromViewDefinition( + _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); - formatViewBindingTracer.WriteLine(viewFound); + s_formatViewBindingTracer.WriteLine(viewFound); return; } - formatViewBindingTracer.WriteLine(viewNotFound); + s_formatViewBindingTracer.WriteLine(viewNotFound); // illegal input, we have to terminate ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape); } // predefined shape: do we have a default view in format.ps1xml? - using (formatViewBindingTracer.TraceScope(findViewShapeType, shape, PSObjectTypeName(so))) + using (s_formatViewBindingTracer.TraceScope(findViewShapeType, shape, PSObjectTypeName(so))) { view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } if (view != null) { - this.viewGenerator = SelectViewGeneratorFromViewDefinition( + _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, expressionFactory, db, view, parameters); - formatViewBindingTracer.WriteLine(viewFound); + s_formatViewBindingTracer.WriteLine(viewFound); PrepareViewForRemoteObjects(ViewGenerator, so); return; } - formatViewBindingTracer.WriteLine(viewNotFound); + s_formatViewBindingTracer.WriteLine(viewNotFound); // we just select properties out of the object itself - this.viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); - PrepareViewForRemoteObjects(ViewGenerator, so); + _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); + PrepareViewForRemoteObjects(ViewGenerator, so); } finally { DisplayDataQuery.ResetTracer(); - } } @@ -356,27 +355,27 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { get { - Diagnostics.Assert (this.viewGenerator != null, "this.viewGenerator cannot be null"); - return this.viewGenerator; + Diagnostics.Assert(_viewGenerator != null, "this.viewGenerator cannot be null"); + return _viewGenerator; } } - private static ViewGenerator SelectViewGeneratorFromViewDefinition ( + private static ViewGenerator SelectViewGeneratorFromViewDefinition( TerminatingErrorContext errorContext, - MshExpressionFactory expressionFactory, - TypeInfoDataBase db, + MshExpressionFactory expressionFactory, + TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters parameters) { ViewGenerator viewGenerator = null; if (view.mainControl is TableControlBody) { - viewGenerator = new TableViewGenerator (); + viewGenerator = new TableViewGenerator(); } else if (view.mainControl is ListControlBody) { - viewGenerator = new ListViewGenerator (); + viewGenerator = new ListViewGenerator(); } else if (view.mainControl is WideControlBody) { @@ -384,27 +383,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else if (view.mainControl is ComplexControlBody) { - viewGenerator = new ComplexViewGenerator (); + viewGenerator = new ComplexViewGenerator(); } - Diagnostics.Assert (viewGenerator != null, "viewGenerator != null"); - viewGenerator.Initialize (errorContext, expressionFactory, db, view, parameters); - return viewGenerator; + Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); + viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters); + return viewGenerator; } - private static ViewGenerator SelectViewGeneratorFromProperties (FormatShape shape, PSObject so, - TerminatingErrorContext errorContext, + private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so, + TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { - // use some heuristics to determine the shape if none is specified if (shape == FormatShape.Undefined && parameters == null) { // check first if we have a known shape for a type var typeNames = so.InternalTypeNames; - shape = DisplayDataQuery.GetShapeFromType (expressionFactory, db, typeNames); + shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames); if (shape == FormatShape.Undefined) { @@ -422,39 +420,39 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // decide what shape we want for the given number of properties - shape = DisplayDataQuery.GetShapeFromPropertyCount (db, expressionList.Count); + shape = DisplayDataQuery.GetShapeFromPropertyCount(db, expressionList.Count); } } ViewGenerator viewGenerator = null; if (shape == FormatShape.Table) { - viewGenerator = new TableViewGenerator (); + viewGenerator = new TableViewGenerator(); } else if (shape == FormatShape.List) { - viewGenerator = new ListViewGenerator (); + viewGenerator = new ListViewGenerator(); } else if (shape == FormatShape.Wide) { - viewGenerator = new WideViewGenerator (); + viewGenerator = new WideViewGenerator(); } else if (shape == FormatShape.Complex) { - viewGenerator = new ComplexViewGenerator (); + viewGenerator = new ComplexViewGenerator(); } Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); - viewGenerator.Initialize (errorContext, expressionFactory, so, db, parameters); + viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters); return viewGenerator; } - + /// /// the view generator that produced data for a selected shape /// - private ViewGenerator viewGenerator = null; + private ViewGenerator _viewGenerator = null; } /// @@ -466,12 +464,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal static bool IsPropertyLessObject(PSObject so) { List allProperties = AssociationManager.ExpandAll(so); - + if (allProperties.Count == 0) { return true; } - if(allProperties.Count == 3) + if (allProperties.Count == 3) { foreach (MshResolvedExpressionParameterAssociation property in allProperties) { @@ -520,13 +518,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, + internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, MshExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List errors) { errors = null; var typeNames = so.InternalTypeNames; - ViewDefinition view = DisplayDataQuery.GetOutOfBandView (expressionFactory, db, typeNames); + ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames); ViewGenerator outOfBandViewGenerator; if (view != null) @@ -534,13 +532,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // process an out of band view retrieved from the display database if (view.mainControl is ComplexControlBody) { - outOfBandViewGenerator = new ComplexViewGenerator (); + outOfBandViewGenerator = new ComplexViewGenerator(); } else { - outOfBandViewGenerator = new ListViewGenerator (); + outOfBandViewGenerator = new ListViewGenerator(); } - outOfBandViewGenerator.Initialize (errorContext, expressionFactory, db, view, null); + outOfBandViewGenerator.Initialize(errorContext, expressionFactory, db, view, null); } else { @@ -548,7 +546,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format IsPropertyLessObject(so)) { // we force a ToString() on well known types - return GenerateOutOfBandObjectAsToString (so); + return GenerateOutOfBandObjectAsToString(so); } if (!useToStringFallback) @@ -557,32 +555,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // we must check we have enough properties for a list view - if (new MshExpression ("*").ResolveNames (so).Count <= 0) + if (new MshExpression("*").ResolveNames(so).Count <= 0) { return null; } // we do not have a view, we default to list view // process an out of band view as a default - outOfBandViewGenerator = new ListViewGenerator (); - outOfBandViewGenerator.Initialize (errorContext, expressionFactory, so, db, null); + outOfBandViewGenerator = new ListViewGenerator(); + outOfBandViewGenerator.Initialize(errorContext, expressionFactory, so, db, null); } - - FormatEntryData fed = outOfBandViewGenerator.GeneratePayload (so, enumerationLimit); + + FormatEntryData fed = outOfBandViewGenerator.GeneratePayload(so, enumerationLimit); fed.outOfBand = true; fed.SetStreamTypeFromPSObject(so); - errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList (); + errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList(); return fed; } - internal static FormatEntryData GenerateOutOfBandObjectAsToString (PSObject so) + internal static FormatEntryData GenerateOutOfBandObjectAsToString(PSObject so) { - FormatEntryData fed = new FormatEntryData (); + FormatEntryData fed = new FormatEntryData(); fed.outOfBand = true; - RawTextFormatEntry rawTextEntry = new RawTextFormatEntry (); + RawTextFormatEntry rawTextEntry = new RawTextFormatEntry(); rawTextEntry.text = so.ToString(); fed.formatEntryInfo = rawTextEntry; @@ -601,9 +599,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class FormatErrorManager { - internal FormatErrorManager (FormatErrorPolicy formatErrorPolicy) + internal FormatErrorManager(FormatErrorPolicy formatErrorPolicy) { - this.formatErrorPolicy = formatErrorPolicy; + _formatErrorPolicy = formatErrorPolicy; } /// @@ -611,49 +609,49 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// MshExpressionResult containing the failed evaluation data /// object used to evaluate the MshExpression - internal void LogMshExpressionFailedResult (MshExpressionResult result, object sourceObject) + internal void LogMshExpressionFailedResult(MshExpressionResult result, object sourceObject) { - if (!this.formatErrorPolicy.ShowErrorsAsMessages) + if (!_formatErrorPolicy.ShowErrorsAsMessages) return; - MshExpressionError error = new MshExpressionError (); + MshExpressionError error = new MshExpressionError(); error.result = result; error.sourceObject = sourceObject; - this.formattingErrorList.Add (error); + _formattingErrorList.Add(error); } /// /// log a failed formatting operation /// /// string format error object - internal void LogStringFormatError (StringFormatError error) + internal void LogStringFormatError(StringFormatError error) { - if (!this.formatErrorPolicy.ShowErrorsAsMessages) + if (!_formatErrorPolicy.ShowErrorsAsMessages) return; - this.formattingErrorList.Add (error); + _formattingErrorList.Add(error); } internal bool DisplayErrorStrings { - get { return this.formatErrorPolicy.ShowErrorsInFormattedOutput; } + get { return _formatErrorPolicy.ShowErrorsInFormattedOutput; } } internal bool DisplayFormatErrorString { - get + get { // NOTE: we key off the same flag - return this.DisplayErrorStrings; + return this.DisplayErrorStrings; } } internal string ErrorString { - get { return this.formatErrorPolicy.errorStringInFormattedOutput; } + get { return _formatErrorPolicy.errorStringInFormattedOutput; } } internal string FormatErrorString { - get { return this.formatErrorPolicy.formatErrorStringInFormattedOutput; } + get { return _formatErrorPolicy.formatErrorStringInFormattedOutput; } } /// @@ -662,19 +660,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// errors /// /// list of ErrorRecord objects - internal List DrainFailedResultList () + internal List DrainFailedResultList() { - if (!this.formatErrorPolicy.ShowErrorsAsMessages) + if (!_formatErrorPolicy.ShowErrorsAsMessages) return null; - List retVal = new List (); - foreach (FormattingError error in this.formattingErrorList) + List retVal = new List(); + foreach (FormattingError error in _formattingErrorList) { - ErrorRecord errorRecord = GenerateErrorRecord (error); + ErrorRecord errorRecord = GenerateErrorRecord(error); if (errorRecord != null) - retVal.Add (errorRecord); + retVal.Add(errorRecord); } - this.formattingErrorList.Clear (); + _formattingErrorList.Clear(); return retVal; } @@ -683,28 +681,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// internal error object /// corresponding ErrorRecord instance - private static ErrorRecord GenerateErrorRecord (FormattingError error) + private static ErrorRecord GenerateErrorRecord(FormattingError error) { ErrorRecord errorRecord = null; string msg = null; MshExpressionError mshExpressionError = error as MshExpressionError; if (mshExpressionError != null) { - errorRecord = new ErrorRecord ( + errorRecord = new ErrorRecord( mshExpressionError.result.Exception, "mshExpressionError", ErrorCategory.InvalidArgument, mshExpressionError.sourceObject); msg = StringUtil.Format(FormatAndOut_format_xxx.MshExpressionError, - mshExpressionError.result.ResolvedExpression.ToString ()); - errorRecord.ErrorDetails = new ErrorDetails (msg); + mshExpressionError.result.ResolvedExpression.ToString()); + errorRecord.ErrorDetails = new ErrorDetails(msg); } StringFormatError formattingError = error as StringFormatError; if (formattingError != null) { - errorRecord = new ErrorRecord ( + errorRecord = new ErrorRecord( formattingError.exception, "formattingError", ErrorCategory.InvalidArgument, @@ -712,22 +710,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format msg = StringUtil.Format(FormatAndOut_format_xxx.FormattingError, formattingError.formatString); - errorRecord.ErrorDetails = new ErrorDetails (msg); + errorRecord.ErrorDetails = new ErrorDetails(msg); } return errorRecord; } - FormatErrorPolicy formatErrorPolicy; + private FormatErrorPolicy _formatErrorPolicy; /// /// current list of failed MsExpression evaluations /// - private List formattingErrorList = new List (); + private List _formattingErrorList = new List(); } - - - - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatXMLWriter.cs index c25fd0f00..117024cfd 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormatXMLWriter.cs @@ -16,8 +16,8 @@ namespace Microsoft.PowerShell.Commands /// internal class FormatXmlWriter { - private XmlWriter writer; - private bool exportScriptBlock; + private XmlWriter _writer; + private bool _exportScriptBlock; private FormatXmlWriter() { } @@ -31,7 +31,7 @@ namespace Microsoft.PowerShell.Commands /// true - to export scriptblocks /// true - do not overwrite the file /// true - bypass wildcard expansion on the file name - internal static void WriteToPs1Xml(PSCmdlet cmdlet, List typeDefinitions, + internal static void WriteToPs1Xml(PSCmdlet cmdlet, List typeDefinitions, string filepath, bool force, bool noclobber, bool writeScriptBlock, bool isLiteralPath) { StreamWriter streamWriter; @@ -46,8 +46,8 @@ namespace Microsoft.PowerShell.Commands { var writer = new FormatXmlWriter { - writer = xmlWriter, - exportScriptBlock = writeScriptBlock + _writer = xmlWriter, + _exportScriptBlock = writeScriptBlock }; writer.WriteToXml(typeDefinitions); } @@ -61,7 +61,7 @@ namespace Microsoft.PowerShell.Commands internal static void WriteToXml(XmlWriter writer, IEnumerable typeDefinitions, bool writeScriptBlock) { - var formatXmlWriter = new FormatXmlWriter {exportScriptBlock = writeScriptBlock, writer = writer}; + var formatXmlWriter = new FormatXmlWriter { _exportScriptBlock = writeScriptBlock, _writer = writer }; formatXmlWriter.WriteToXml(typeDefinitions); } @@ -89,173 +89,173 @@ namespace Microsoft.PowerShell.Commands } } - writer.WriteStartElement("Configuration"); + _writer.WriteStartElement("Configuration"); - writer.WriteStartElement("ViewDefinitions"); - foreach(var pair in formatdefs) + _writer.WriteStartElement("ViewDefinitions"); + foreach (var pair in formatdefs) { Guid id = pair.Key; FormatViewDefinition formatdef = pair.Value; - writer.WriteStartElement("View"); - writer.WriteElementString("Name", formatdef.Name); - writer.WriteStartElement("ViewSelectedBy"); + _writer.WriteStartElement("View"); + _writer.WriteElementString("Name", formatdef.Name); + _writer.WriteStartElement("ViewSelectedBy"); foreach (ExtendedTypeDefinition definition in views[id]) { - writer.WriteElementString("TypeName", definition.TypeName); + _writer.WriteElementString("TypeName", definition.TypeName); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); var groupBy = formatdef.Control.GroupBy; if (groupBy != null) { - writer.WriteStartElement("GroupBy"); + _writer.WriteStartElement("GroupBy"); WriteDisplayEntry(groupBy.Expression); if (!string.IsNullOrEmpty(groupBy.Label)) { - writer.WriteElementString("Label", groupBy.Label); + _writer.WriteElementString("Label", groupBy.Label); } if (groupBy.CustomControl != null) { WriteCustomControl(groupBy.CustomControl); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } if (formatdef.Control.OutOfBand) { - writer.WriteElementString("OutOfBand", ""); + _writer.WriteElementString("OutOfBand", ""); } formatdef.Control.WriteToXml(this); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } internal void WriteTableControl(TableControl tableControl) { - writer.WriteStartElement("TableControl"); + _writer.WriteStartElement("TableControl"); if (tableControl.AutoSize) { - writer.WriteElementString("AutoSize", ""); + _writer.WriteElementString("AutoSize", ""); } if (tableControl.HideTableHeaders) { - writer.WriteElementString("HideTableHeaders", ""); + _writer.WriteElementString("HideTableHeaders", ""); } - writer.WriteStartElement("TableHeaders"); + _writer.WriteStartElement("TableHeaders"); foreach (TableControlColumnHeader columnheader in tableControl.Headers) { - writer.WriteStartElement("TableColumnHeader"); + _writer.WriteStartElement("TableColumnHeader"); if (!string.IsNullOrEmpty(columnheader.Label)) { - writer.WriteElementString("Label", columnheader.Label); + _writer.WriteElementString("Label", columnheader.Label); } if (columnheader.Width > 0) { - writer.WriteElementString("Width", columnheader.Width.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("Width", columnheader.Width.ToString(CultureInfo.InvariantCulture)); } if (columnheader.Alignment != Alignment.Undefined) { - writer.WriteElementString("Alignment", columnheader.Alignment.ToString()); + _writer.WriteElementString("Alignment", columnheader.Alignment.ToString()); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); - writer.WriteStartElement("TableRowEntries"); + _writer.WriteStartElement("TableRowEntries"); foreach (TableControlRow row in tableControl.Rows) { - writer.WriteStartElement("TableRowEntry"); + _writer.WriteStartElement("TableRowEntry"); if (row.Wrap) { - writer.WriteStartElement("Wrap"); - writer.WriteEndElement(/**/); + _writer.WriteStartElement("Wrap"); + _writer.WriteEndElement(/**/); } if (row.SelectedBy != null) { WriteEntrySelectedBy(row.SelectedBy); } - writer.WriteStartElement("TableColumnItems"); + _writer.WriteStartElement("TableColumnItems"); foreach (TableControlColumn coldefn in row.Columns) { - writer.WriteStartElement("TableColumnItem"); + _writer.WriteStartElement("TableColumnItem"); if (coldefn.Alignment != Alignment.Undefined) { - writer.WriteElementString("Alignment", coldefn.Alignment.ToString()); + _writer.WriteElementString("Alignment", coldefn.Alignment.ToString()); } if (!string.IsNullOrEmpty(coldefn.FormatString)) { - writer.WriteElementString("FormatString", coldefn.FormatString); + _writer.WriteElementString("FormatString", coldefn.FormatString); } WriteDisplayEntry(coldefn.DisplayEntry); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } internal void WriteListControl(ListControl listControl) { - writer.WriteStartElement("ListControl"); - writer.WriteStartElement("ListEntries"); + _writer.WriteStartElement("ListControl"); + _writer.WriteStartElement("ListEntries"); // write the list entry's one by one foreach (ListControlEntry entry in listControl.Entries) { - writer.WriteStartElement("ListEntry"); + _writer.WriteStartElement("ListEntry"); // write entry selected by if available WriteEntrySelectedBy(entry.EntrySelectedBy); if (entry.Items.Count > 0) { - writer.WriteStartElement("ListItems"); + _writer.WriteStartElement("ListItems"); // write the list items foreach (ListControlEntryItem item in entry.Items) { - writer.WriteStartElement("ListItem"); + _writer.WriteStartElement("ListItem"); if (!string.IsNullOrEmpty(item.Label)) { - writer.WriteElementString("Label", item.Label); + _writer.WriteElementString("Label", item.Label); } if (!string.IsNullOrEmpty(item.FormatString)) { - writer.WriteElementString("FormatString", item.FormatString); + _writer.WriteElementString("FormatString", item.FormatString); } if (item.ItemSelectionCondition != null) { - writer.WriteStartElement("ItemSelectionCondition"); + _writer.WriteStartElement("ItemSelectionCondition"); WriteDisplayEntry(item.ItemSelectionCondition); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } // write the entry WriteDisplayEntry(item.DisplayEntry); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } private void WriteEntrySelectedBy(EntrySelectedBy entrySelectedBy) @@ -264,97 +264,97 @@ namespace Microsoft.PowerShell.Commands ((entrySelectedBy.TypeNames != null && entrySelectedBy.TypeNames.Count > 0) || (entrySelectedBy.SelectionCondition != null && entrySelectedBy.SelectionCondition.Count > 0))) { - writer.WriteStartElement("EntrySelectedBy"); + _writer.WriteStartElement("EntrySelectedBy"); if (entrySelectedBy.TypeNames != null) { foreach (string typename in entrySelectedBy.TypeNames) { - writer.WriteElementString("TypeName", typename); + _writer.WriteElementString("TypeName", typename); } } if (entrySelectedBy.SelectionCondition != null) { foreach (var condition in entrySelectedBy.SelectionCondition) { - writer.WriteStartElement("SelectionCondition"); + _writer.WriteStartElement("SelectionCondition"); WriteDisplayEntry(condition); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } } internal void WriteWideControl(WideControl wideControl) { - writer.WriteStartElement("WideControl"); + _writer.WriteStartElement("WideControl"); if (wideControl.Columns > 0) { - writer.WriteElementString("ColumnNumber", wideControl.Columns.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("ColumnNumber", wideControl.Columns.ToString(CultureInfo.InvariantCulture)); } if (wideControl.AutoSize) { - writer.WriteElementString("AutoSize", ""); + _writer.WriteElementString("AutoSize", ""); } - writer.WriteStartElement("WideEntries"); + _writer.WriteStartElement("WideEntries"); foreach (WideControlEntryItem entry in wideControl.Entries) { - writer.WriteStartElement("WideEntry"); + _writer.WriteStartElement("WideEntry"); WriteEntrySelectedBy(entry.EntrySelectedBy); - writer.WriteStartElement("WideItem"); + _writer.WriteStartElement("WideItem"); WriteDisplayEntry(entry.DisplayEntry); if (!string.IsNullOrEmpty(entry.FormatString)) { - writer.WriteElementString("FormatString", entry.FormatString); + _writer.WriteElementString("FormatString", entry.FormatString); } - writer.WriteEndElement(/**/); - - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); - - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + + _writer.WriteEndElement(/**/); } internal void WriteDisplayEntry(DisplayEntry displayEntry) { if (displayEntry.ValueType == DisplayEntryValueType.Property) { - writer.WriteElementString("PropertyName", displayEntry.Value); + _writer.WriteElementString("PropertyName", displayEntry.Value); } else if (displayEntry.ValueType == DisplayEntryValueType.ScriptBlock) { - writer.WriteStartElement("ScriptBlock"); - writer.WriteValue(exportScriptBlock ? displayEntry.Value : ";"); - writer.WriteEndElement(/**/); + _writer.WriteStartElement("ScriptBlock"); + _writer.WriteValue(_exportScriptBlock ? displayEntry.Value : ";"); + _writer.WriteEndElement(/**/); } } internal void WriteCustomControl(CustomControl customControl) { - writer.WriteStartElement("CustomControl"); + _writer.WriteStartElement("CustomControl"); - writer.WriteStartElement("CustomEntries"); + _writer.WriteStartElement("CustomEntries"); foreach (var entry in customControl.Entries) { - writer.WriteStartElement("CustomEntry"); + _writer.WriteStartElement("CustomEntry"); WriteEntrySelectedBy(entry.SelectedBy); - writer.WriteStartElement("CustomItem"); + _writer.WriteStartElement("CustomItem"); foreach (var item in entry.CustomItems) { WriteCustomItem(item); } - writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } - writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } internal void WriteCustomItem(CustomItemBase item) @@ -364,7 +364,7 @@ namespace Microsoft.PowerShell.Commands { for (int i = 0; i < newline.Count; i++) { - writer.WriteElementString("NewLine", ""); + _writer.WriteElementString("NewLine", ""); } return; } @@ -372,24 +372,24 @@ namespace Microsoft.PowerShell.Commands var text = item as CustomItemText; if (text != null) { - writer.WriteElementString("Text", text.Text); + _writer.WriteElementString("Text", text.Text); return; } var expr = item as CustomItemExpression; if (expr != null) { - writer.WriteStartElement("ExpressionBinding"); + _writer.WriteStartElement("ExpressionBinding"); if (expr.EnumerateCollection) { - writer.WriteElementString("EnumerateCollection", ""); + _writer.WriteElementString("EnumerateCollection", ""); } if (expr.ItemSelectionCondition != null) { - writer.WriteStartElement("ItemSelectionCondition"); + _writer.WriteStartElement("ItemSelectionCondition"); WriteDisplayEntry(expr.ItemSelectionCondition); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } if (expr.Expression != null) @@ -402,28 +402,28 @@ namespace Microsoft.PowerShell.Commands WriteCustomControl(expr.CustomControl); } - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); return; } - var frame = (CustomItemFrame) item; - writer.WriteStartElement("Frame"); + var frame = (CustomItemFrame)item; + _writer.WriteStartElement("Frame"); if (frame.LeftIndent != 0) - writer.WriteElementString("LeftIndent", frame.LeftIndent.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("LeftIndent", frame.LeftIndent.ToString(CultureInfo.InvariantCulture)); if (frame.RightIndent != 0) - writer.WriteElementString("RightIndent", frame.RightIndent.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("RightIndent", frame.RightIndent.ToString(CultureInfo.InvariantCulture)); if (frame.FirstLineHanging != 0) - writer.WriteElementString("FirstLineHanging", frame.FirstLineHanging.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("FirstLineHanging", frame.FirstLineHanging.ToString(CultureInfo.InvariantCulture)); if (frame.FirstLineIndent != 0) - writer.WriteElementString("FirstLineIndent", frame.FirstLineIndent.ToString(CultureInfo.InvariantCulture)); + _writer.WriteElementString("FirstLineIndent", frame.FirstLineIndent.ToString(CultureInfo.InvariantCulture)); - writer.WriteStartElement("CustomItem"); + _writer.WriteStartElement("CustomItem"); foreach (var frameItem in frame.CustomItems) { WriteCustomItem(frameItem); } - writer.WriteEndElement(/**/); - writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); + _writer.WriteEndElement(/**/); } } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjects.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjects.cs index 993c3d0d2..d86a4f96c 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjects.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjects.cs @@ -21,6 +21,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. // boudaries, therefore the objects provide a GUID based machanism to // preserve the information. // + using System; using System.Globalization; using System.Collections; @@ -190,7 +191,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } } -#endregion + #endregion #region Shape Info Classes @@ -282,7 +283,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal abstract partial class FreeFormatEntry : FormatEntryInfo { - public List formatValueList = new List (); + public List formatValueList = new List(); } internal sealed partial class ListViewEntry : FormatEntryInfo @@ -291,7 +292,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } - public List listViewFieldList = new List (); + public List listViewFieldList = new List(); } internal sealed partial class ListViewField : FormatInfoData @@ -311,7 +312,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } - public List formatPropertyFieldList = new List (); + public List formatPropertyFieldList = new List(); public bool multiLine = false; } @@ -368,7 +369,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #endregion -#region Format Values + #region Format Values internal abstract class FormatValue : FormatInfoData { @@ -404,9 +405,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal const string CLSID = "fba029a113a5458d932a2ed4871fadf2"; - public FormatEntry () + public FormatEntry() { - formatValueList = new List (); + formatValueList = new List(); } public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } @@ -430,5 +431,5 @@ namespace Microsoft.PowerShell.Commands.Internal.Format public int firstLine = 0; } -#endregion + #endregion } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjectsDeserializer.cs index 58a63a43f..f85341ffb 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Reflection; using System.Collections; @@ -24,12 +25,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// private const string TabExpansionString = " "; - internal FormatObjectDeserializer (TerminatingErrorContext errorContext) + internal FormatObjectDeserializer(TerminatingErrorContext errorContext) { TerminatingErrorContext = errorContext; } - internal bool IsFormatInfoData (PSObject so) + internal bool IsFormatInfoData(PSObject so) { var fid = PSObject.Base(so) as FormatInfoData; if (fid != null) @@ -44,7 +45,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // we have an unexpected type (CLSID not matching): this should never happen - ProcessUnknownInvalidClassId (fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId"); + ProcessUnknownInvalidClassId(fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId"); return false; } @@ -56,7 +57,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { return false; } - string classId = GetProperty (so, FormatInfoData.classidProperty) as string; + string classId = GetProperty(so, FormatInfoData.classidProperty) as string; if (classId == null) { @@ -65,17 +66,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // it's one of ours, get the right class and deserialize it accordingly - if (IsClass (classId, FormatStartData.CLSID) || - IsClass (classId, FormatEndData.CLSID) || - IsClass (classId, GroupStartData.CLSID) || - IsClass (classId, GroupEndData.CLSID) || - IsClass (classId, FormatEntryData.CLSID)) + if (IsClass(classId, FormatStartData.CLSID) || + IsClass(classId, FormatEndData.CLSID) || + IsClass(classId, GroupStartData.CLSID) || + IsClass(classId, GroupEndData.CLSID) || + IsClass(classId, FormatEntryData.CLSID)) { return true; } // we have an unknown type (CLSID not matching): this should never happen - ProcessUnknownInvalidClassId (classId, so, "FormatObjectDeserializerIsFormatInfoDataInvalidClassId"); + ProcessUnknownInvalidClassId(classId, so, "FormatObjectDeserializerIsFormatInfoDataInvalidClassId"); return false; } @@ -87,7 +88,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to deserialize /// deserialized object or null - internal object Deserialize (PSObject so) + internal object Deserialize(PSObject so) { var fid = PSObject.Base(so) as FormatInfoData; if (fid != null) @@ -102,7 +103,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // we have an unexpected type (CLSID not matching): this should never happen - ProcessUnknownInvalidClassId (fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId"); + ProcessUnknownInvalidClassId(fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId"); return null; } @@ -114,7 +115,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return so; } - string classId = GetProperty (so, FormatInfoData.classidProperty) as string; + string classId = GetProperty(so, FormatInfoData.classidProperty) as string; if (classId == null) { @@ -124,38 +125,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // it's one of ours, get the right class and deserialize it accordingly - if (IsClass (classId, FormatStartData.CLSID) || - IsClass (classId, FormatEndData.CLSID) || - IsClass (classId, GroupStartData.CLSID) || - IsClass (classId, GroupEndData.CLSID) || - IsClass (classId, FormatEntryData.CLSID)) + if (IsClass(classId, FormatStartData.CLSID) || + IsClass(classId, FormatEndData.CLSID) || + IsClass(classId, GroupStartData.CLSID) || + IsClass(classId, GroupEndData.CLSID) || + IsClass(classId, FormatEntryData.CLSID)) { - return DeserializeObject (so); + return DeserializeObject(so); } // we have an unknown type (CLSID not matching): this should never happen - ProcessUnknownInvalidClassId (classId, so, "FormatObjectDeserializerDeserializeInvalidClassId"); + ProcessUnknownInvalidClassId(classId, so, "FormatObjectDeserializerDeserializeInvalidClassId"); return null; } - private void ProcessUnknownInvalidClassId (string classId, object obj, string errorId) + private void ProcessUnknownInvalidClassId(string classId, object obj, string errorId) { string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_ClassIdInvalid, classId); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("classId"), errorId, ErrorCategory.InvalidData, obj); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.TerminatingErrorContext.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } - #region Helper Methods - private static bool IsClass (string x, string y) + #region Helper Methods + private static bool IsClass(string x, string y) { - return string.Compare (x,y, StringComparison.OrdinalIgnoreCase) == 0; + return string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0; } #if _UNUSED @@ -192,10 +193,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return retVal; } #endif - -#endregion - internal static object GetProperty (PSObject so, string name) + #endregion + + internal static object GetProperty(PSObject so, string name) { PSMemberInfo member = so.Properties[name]; if (member == null) @@ -208,9 +209,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // returns null on error - internal FormatInfoData DeserializeMemberObject (PSObject so, string property) + internal FormatInfoData DeserializeMemberObject(PSObject so, string property) { - object memberRaw = GetProperty (so, property); + object memberRaw = GetProperty(so, property); if (memberRaw == null) return null; if (so == memberRaw) @@ -226,32 +227,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format errorRecord.ErrorDetails = new ErrorDetails(msg); this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } - return DeserializeObject (PSObject.AsPSObject(memberRaw)); + return DeserializeObject(PSObject.AsPSObject(memberRaw)); } - internal FormatInfoData DeserializeMandatoryMemberObject (PSObject so, string property) + internal FormatInfoData DeserializeMandatoryMemberObject(PSObject so, string property) { FormatInfoData fid = DeserializeMemberObject(so, property); - VerifyDataNotNull (fid, property); + VerifyDataNotNull(fid, property); return fid; } - private object DeserializeMemberVariable (PSObject so, string property, System.Type t, bool cannotBeNull) + private object DeserializeMemberVariable(PSObject so, string property, System.Type t, bool cannotBeNull) { - object objRaw = GetProperty (so, property); + object objRaw = GetProperty(so, property); if (cannotBeNull) - VerifyDataNotNull (objRaw, property); + VerifyDataNotNull(objRaw, property); - if (objRaw != null && t != objRaw.GetType ()) + if (objRaw != null && t != objRaw.GetType()) { string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidPropertyType, t.Name, property); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("property"), "FormatObjectDeserializerInvalidPropertyType", ErrorCategory.InvalidData, so); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.TerminatingErrorContext.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } return objRaw; } @@ -262,9 +263,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// object whose the property belogs to /// name of the string property /// string out of the MsObject - internal string DeserializeStringMemberVariableRaw (PSObject so, string property) + internal string DeserializeStringMemberVariableRaw(PSObject so, string property) { - return (string)DeserializeMemberVariable (so, property, typeof(string), false /* cannotBeNull */); + return (string)DeserializeMemberVariable(so, property, typeof(string), false /* cannotBeNull */); } /// @@ -273,23 +274,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// object whose the property belogs to /// name of the string property /// string out of the MsObject - internal string DeserializeStringMemberVariable (PSObject so, string property) + internal string DeserializeStringMemberVariable(PSObject so, string property) { - string val = (string)DeserializeMemberVariable (so, property, typeof(string), false /* cannotBeNull */); + string val = (string)DeserializeMemberVariable(so, property, typeof(string), false /* cannotBeNull */); // expand TAB's - if (string.IsNullOrEmpty (val)) + if (string.IsNullOrEmpty(val)) return val; - return val.Replace ("\t", TabExpansionString); + return val.Replace("\t", TabExpansionString); } - - internal int DeserializeIntMemberVariable (PSObject so, string property) + + internal int DeserializeIntMemberVariable(PSObject so, string property) { - return (int)DeserializeMemberVariable (so, property, typeof(int), true /* cannotBeNull */); + return (int)DeserializeMemberVariable(so, property, typeof(int), true /* cannotBeNull */); } - internal bool DeserializeBoolMemberVariable (PSObject so, string property) + internal bool DeserializeBoolMemberVariable(PSObject so, string property) { - return (bool)DeserializeMemberVariable (so, property, typeof(bool), true /* cannotBeNull */); + return (bool)DeserializeMemberVariable(so, property, typeof(bool), true /* cannotBeNull */); } internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) @@ -321,38 +322,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // returns null on error - internal FormatInfoData DeserializeObject (PSObject so) + internal FormatInfoData DeserializeObject(PSObject so) { - FormatInfoData fid = FormatInfoDataClassFactory.CreateInstance (so, this); + FormatInfoData fid = FormatInfoDataClassFactory.CreateInstance(so, this); if (fid != null) - fid.Deserialize (so, this); + fid.Deserialize(so, this); return fid; } - - internal void VerifyDataNotNull (object obj, string name) + + internal void VerifyDataNotNull(object obj, string name) { if (obj != null) return; string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_NullDataMember, name); - ErrorRecord errorRecord = new ErrorRecord ( - new ArgumentException (), + ErrorRecord errorRecord = new ErrorRecord( + new ArgumentException(), "FormatObjectDeserializerNullDataMember", ErrorCategory.InvalidData, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.TerminatingErrorContext.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } } internal static class FormatInfoDataClassFactory { - static FormatInfoDataClassFactory () + static FormatInfoDataClassFactory() { - constructors = new Dictionary> + s_constructors = new Dictionary> { {FormatStartData.CLSID, () => new FormatStartData()}, {FormatEndData.CLSID, () => new FormatEndData()}, @@ -383,11 +384,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } // returns null on error - internal static FormatInfoData CreateInstance (PSObject so, FormatObjectDeserializer deserializer) + internal static FormatInfoData CreateInstance(PSObject so, FormatObjectDeserializer deserializer) { if (so == null) { - throw PSTraceSource.NewArgumentNullException ("so"); + throw PSTraceSource.NewArgumentNullException("so"); } // look for the property that defines the type of object @@ -396,25 +397,25 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidClassidProperty); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("classid"), "FormatObjectDeserializerInvalidClassidProperty", ErrorCategory.InvalidData, so); - errorRecord.ErrorDetails = new ErrorDetails (msg); - deserializer.TerminatingErrorContext.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + deserializer.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } - FormatInfoData fid = CreateInstance (classId, deserializer); + FormatInfoData fid = CreateInstance(classId, deserializer); return fid; } // returns null on failure - private static FormatInfoData CreateInstance (string clsid, FormatObjectDeserializer deserializer) + private static FormatInfoData CreateInstance(string clsid, FormatObjectDeserializer deserializer) { Func ctor; - if (!constructors.TryGetValue(clsid, out ctor)) + if (!s_constructors.TryGetValue(clsid, out ctor)) { CreateInstanceError(PSTraceSource.NewArgumentException("clsid"), clsid, deserializer); return null; @@ -476,56 +477,56 @@ namespace Microsoft.PowerShell.Commands.Internal.Format deserializer.TerminatingErrorContext.ThrowTerminatingError(errorRecord); } - private static readonly Dictionary> constructors; + private static readonly Dictionary> s_constructors; } internal static class FormatInfoDataListDeserializer where T : FormatInfoData { - private static void ReadListHelper (IEnumerable en, List lst, FormatObjectDeserializer deserializer) + private static void ReadListHelper(IEnumerable en, List lst, FormatObjectDeserializer deserializer) { - deserializer.VerifyDataNotNull (en, "enumerable"); + deserializer.VerifyDataNotNull(en, "enumerable"); foreach (object obj in en) { FormatInfoData fid = deserializer.DeserializeObject(PSObjectHelper.AsPSObject(obj)); T entry = fid as T; - deserializer.VerifyDataNotNull (entry, "entry"); - lst.Add (entry); + deserializer.VerifyDataNotNull(entry, "entry"); + lst.Add(entry); } } - internal static void ReadList (PSObject so, string property, List lst, FormatObjectDeserializer deserializer) + internal static void ReadList(PSObject so, string property, List lst, FormatObjectDeserializer deserializer) { if (lst == null) { - throw PSTraceSource.NewArgumentNullException ("lst"); + throw PSTraceSource.NewArgumentNullException("lst"); } object memberRaw = FormatObjectDeserializer.GetProperty(so, property); - ReadListHelper (PSObjectHelper.GetEnumerable(memberRaw), lst, deserializer); + ReadListHelper(PSObjectHelper.GetEnumerable(memberRaw), lst, deserializer); } } - -#region Formatting Objects Deserializer + + #region Formatting Objects Deserializer internal abstract partial class FormatInfoData { - internal virtual void Deserialize (PSObject so, FormatObjectDeserializer deserializer) { } + internal virtual void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { } } internal abstract partial class ControlInfoData : PacketInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); + base.Deserialize(so, deserializer); //optional - this.groupingEntry = (GroupingEntry)deserializer.DeserializeMemberObject (so, "groupingEntry"); + this.groupingEntry = (GroupingEntry)deserializer.DeserializeMemberObject(so, "groupingEntry"); } } internal abstract partial class StartData : ControlInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { base.Deserialize(so, deserializer); this.shapeInfo = (ShapeInfo)deserializer.DeserializeMemberObject(so, "shapeInfo"); @@ -534,32 +535,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed partial class AutosizeInfo : FormatInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.objectCount = deserializer.DeserializeIntMemberVariable (so, "objectCount"); + base.Deserialize(so, deserializer); + this.objectCount = deserializer.DeserializeIntMemberVariable(so, "objectCount"); } } internal sealed partial class FormatStartData : StartData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); + base.Deserialize(so, deserializer); // for the base class the shapeInfo is optional, but it's mandatory for this class - deserializer.VerifyDataNotNull (this.shapeInfo, "shapeInfo"); - this.pageHeaderEntry = (PageHeaderEntry)deserializer.DeserializeMemberObject (so, "pageHeaderEntry"); + deserializer.VerifyDataNotNull(this.shapeInfo, "shapeInfo"); + this.pageHeaderEntry = (PageHeaderEntry)deserializer.DeserializeMemberObject(so, "pageHeaderEntry"); this.pageFooterEntry = (PageFooterEntry)deserializer.DeserializeMemberObject(so, "pageFooterEntry"); this.autosizeInfo = (AutosizeInfo)deserializer.DeserializeMemberObject(so, "autosizeInfo"); } } internal sealed partial class FormatEntryData : PacketInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.formatEntryInfo = (FormatEntryInfo)deserializer.DeserializeMandatoryMemberObject (so, "formatEntryInfo"); - this.outOfBand = deserializer.DeserializeBoolMemberVariable (so, "outOfBand"); + base.Deserialize(so, deserializer); + this.formatEntryInfo = (FormatEntryInfo)deserializer.DeserializeMandatoryMemberObject(so, "formatEntryInfo"); + this.outOfBand = deserializer.DeserializeBoolMemberVariable(so, "outOfBand"); this.writeStream = deserializer.DeserializeWriteStreamTypeMemberVariable(so); this.isHelpObject = so.IsHelpObject; } @@ -567,131 +568,130 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed partial class WideViewHeaderInfo : ShapeInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); + base.Deserialize(so, deserializer); - this.columns = deserializer.DeserializeIntMemberVariable (so, "columns"); + this.columns = deserializer.DeserializeIntMemberVariable(so, "columns"); } } internal sealed partial class TableHeaderInfo : ShapeInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.hideHeader = deserializer.DeserializeBoolMemberVariable (so, "hideHeader"); - FormatInfoDataListDeserializer.ReadList (so, "tableColumnInfoList", this.tableColumnInfoList, deserializer); + base.Deserialize(so, deserializer); + this.hideHeader = deserializer.DeserializeBoolMemberVariable(so, "hideHeader"); + FormatInfoDataListDeserializer.ReadList(so, "tableColumnInfoList", this.tableColumnInfoList, deserializer); } } internal sealed partial class TableColumnInfo : FormatInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.width = deserializer.DeserializeIntMemberVariable (so, "width"); - this.alignment = deserializer.DeserializeIntMemberVariable (so, "alignment"); - this.label = deserializer.DeserializeStringMemberVariable (so, "label"); - this.propertyName = deserializer.DeserializeStringMemberVariable (so, "propertyName"); + base.Deserialize(so, deserializer); + this.width = deserializer.DeserializeIntMemberVariable(so, "width"); + this.alignment = deserializer.DeserializeIntMemberVariable(so, "alignment"); + this.label = deserializer.DeserializeStringMemberVariable(so, "label"); + this.propertyName = deserializer.DeserializeStringMemberVariable(so, "propertyName"); } } internal sealed partial class RawTextFormatEntry : FormatEntryInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.text = deserializer.DeserializeStringMemberVariableRaw (so, "text"); + base.Deserialize(so, deserializer); + this.text = deserializer.DeserializeStringMemberVariableRaw(so, "text"); } } internal abstract partial class FreeFormatEntry : FormatEntryInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - FormatInfoDataListDeserializer.ReadList (so, "formatValueList", this.formatValueList, deserializer); + base.Deserialize(so, deserializer); + FormatInfoDataListDeserializer.ReadList(so, "formatValueList", this.formatValueList, deserializer); } } internal sealed partial class ListViewEntry : FormatEntryInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - FormatInfoDataListDeserializer.ReadList (so, "listViewFieldList", this.listViewFieldList, deserializer); + base.Deserialize(so, deserializer); + FormatInfoDataListDeserializer.ReadList(so, "listViewFieldList", this.listViewFieldList, deserializer); } } internal sealed partial class ListViewField : FormatInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.label = deserializer.DeserializeStringMemberVariable (so, "label"); - this.propertyName = deserializer.DeserializeStringMemberVariable (so, "propertyName"); - this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject (so, "formatPropertyField"); + base.Deserialize(so, deserializer); + this.label = deserializer.DeserializeStringMemberVariable(so, "label"); + this.propertyName = deserializer.DeserializeStringMemberVariable(so, "propertyName"); + this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject(so, "formatPropertyField"); } } internal sealed partial class TableRowEntry : FormatEntryInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - FormatInfoDataListDeserializer.ReadList (so, "formatPropertyFieldList", this.formatPropertyFieldList, deserializer); - this.multiLine = deserializer.DeserializeBoolMemberVariable (so, "multiLine"); + base.Deserialize(so, deserializer); + FormatInfoDataListDeserializer.ReadList(so, "formatPropertyFieldList", this.formatPropertyFieldList, deserializer); + this.multiLine = deserializer.DeserializeBoolMemberVariable(so, "multiLine"); } } internal sealed partial class WideViewEntry : FormatEntryInfo { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject (so, "formatPropertyField"); + base.Deserialize(so, deserializer); + this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject(so, "formatPropertyField"); } } - + internal sealed partial class FormatTextField : FormatValue { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.text = deserializer.DeserializeStringMemberVariable (so, "text"); + base.Deserialize(so, deserializer); + this.text = deserializer.DeserializeStringMemberVariable(so, "text"); } } internal sealed partial class FormatPropertyField : FormatValue { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.propertyValue = deserializer.DeserializeStringMemberVariable (so, "propertyValue"); + base.Deserialize(so, deserializer); + this.propertyValue = deserializer.DeserializeStringMemberVariable(so, "propertyValue"); this.alignment = deserializer.DeserializeIntMemberVariable(so, "alignment"); } } internal sealed partial class FormatEntry : FormatValue { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - FormatInfoDataListDeserializer.ReadList (so, "formatValueList", this.formatValueList, deserializer); + base.Deserialize(so, deserializer); + FormatInfoDataListDeserializer.ReadList(so, "formatValueList", this.formatValueList, deserializer); this.frameInfo = (FrameInfo)deserializer.DeserializeMemberObject(so, "frameInfo"); } } internal sealed partial class FrameInfo : FormatInfoData { - internal override void Deserialize (PSObject so, FormatObjectDeserializer deserializer) + internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { - base.Deserialize (so, deserializer); - this.leftIndentation = deserializer.DeserializeIntMemberVariable (so, "leftIndentation"); - this.rightIndentation = deserializer.DeserializeIntMemberVariable (so, "rightIndentation"); - this.firstLine = deserializer.DeserializeIntMemberVariable (so, "firstLine"); + base.Deserialize(so, deserializer); + this.leftIndentation = deserializer.DeserializeIntMemberVariable(so, "leftIndentation"); + this.rightIndentation = deserializer.DeserializeIntMemberVariable(so, "rightIndentation"); + this.firstLine = deserializer.DeserializeIntMemberVariable(so, "firstLine"); } } -#endregion - + #endregion } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ILineOutput.cs index d0626a167..639ddf1fe 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ILineOutput.cs @@ -8,10 +8,9 @@ using System.Text; using System.Globalization; // interfaces for host interaction + namespace Microsoft.PowerShell.Commands.Internal.Format { - - /// /// Base class providing support for string manipulation. /// This class is a tear off class provided by the LineOutput class @@ -24,7 +23,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal class DisplayCells { - internal virtual int Length(string str) + internal virtual int Length(string str) { return Length(str, 0); } @@ -143,19 +142,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// objects before any processing /// internal virtual bool RequiresBuffering { get { return false; } } - + /// /// delegate the implementor of ExecuteBufferPlayBack should /// call to cause the playback to happen when ready to execute /// - internal delegate void DoPlayBackCall (); + internal delegate void DoPlayBackCall(); /// /// if RequiresBuffering = true, this call will be made to /// start the playback /// - internal virtual void ExecuteBufferPlayBack (DoPlayBackCall playback ) { } + internal virtual void ExecuteBufferPlayBack(DoPlayBackCall playback) { } /// /// @@ -167,14 +166,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// The number of rows the current device has /// internal abstract int RowNumber { get; } - + /// /// Write a line to the output device. /// /// /// string to be written to the device /// - internal abstract void WriteLine (string s); + internal abstract void WriteLine(string s); internal WriteStreamType WriteStream { @@ -205,11 +204,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal virtual DisplayCells DisplayCells { - get + get { CheckStopProcessing(); // just return the default singelton implementation - return _displayCellsDefault; + return _displayCellsDefault; } } @@ -219,7 +218,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// implementation by overriding /// protected static DisplayCells _displayCellsDefault = new DisplayCells(); - } /// @@ -230,28 +228,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal class WriteLineHelper { #region callbacks - + /// /// delegate definition /// /// string to write - internal delegate void WriteCallback (string s); + internal delegate void WriteCallback(string s); /// /// instance of the delegate previously defined /// for line that has EXACTLY this.ncols characters /// - private WriteCallback writeCall = null; + private WriteCallback _writeCall = null; /// /// instance of the delegate previously defined /// for generic line, less that this.ncols characters /// - private WriteCallback writeLineCall = null; + private WriteCallback _writeLineCall = null; #endregion - private bool lineWrap; + private bool _lineWrap; /// /// construct an instance, given the two callbacks @@ -265,14 +263,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal WriteLineHelper(bool lineWrap, WriteCallback wlc, WriteCallback wc, DisplayCells displayCells) { if (wlc == null) - throw PSTraceSource.NewArgumentNullException ("wlc"); + throw PSTraceSource.NewArgumentNullException("wlc"); if (displayCells == null) throw PSTraceSource.NewArgumentNullException("displayCells"); - this._displayCells = displayCells; - this.writeLineCall = wlc; - this.writeCall = (wc != null) ? wc : wlc; - this.lineWrap = lineWrap; + _displayCells = displayCells; + _writeLineCall = wlc; + _writeCall = (wc != null) ? wc : wlc; + _lineWrap = lineWrap; } /// @@ -280,9 +278,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// string to process /// width of the device - internal void WriteLine (string s, int cols) + internal void WriteLine(string s, int cols) { - WriteLineInternal (s, cols); + WriteLineInternal(s, cols); } /// @@ -290,18 +288,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// string to process /// width of the device - private void WriteLineInternal (string val, int cols) + private void WriteLineInternal(string val, int cols) { - if (string.IsNullOrEmpty (val)) + if (string.IsNullOrEmpty(val)) { - this.writeLineCall (val); + _writeLineCall(val); return; } // If the output is being redirected, then we don't break val - if (!lineWrap) + if (!_lineWrap) { - this.writeCall(val); + _writeCall(val); return; } @@ -312,19 +310,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int k = 0; k < lines.Length; k++) { // compute the display length of the string - int displayLength = this._displayCells.Length(lines[k]); + int displayLength = _displayCells.Length(lines[k]); if (displayLength < cols) { // NOTE: this is the case where where System.Console.WriteLine() would work just fine - this.writeLineCall(lines[k]); + _writeLineCall(lines[k]); continue; } if (displayLength == cols) { // NOTE: this is the corner case where System.Console.WriteLine() cannot be called - this.writeCall (lines[k]); + _writeCall(lines[k]); continue; } @@ -335,15 +333,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // the string is still too long to fit, write the first cols characters // and go back for more wraparound - int splitLen = this._displayCells.GetHeadSplitLength(s, cols); + int splitLen = _displayCells.GetHeadSplitLength(s, cols); WriteLineInternal(s.Substring(0, splitLen), cols); // chop off the first fieldWidth characters, already printed s = s.Substring(splitLen); - if (this._displayCells.Length(s) <= cols) + if (_displayCells.Length(s) <= cols) { // if we fit, print the tail of the string and we are done - WriteLineInternal (s, cols); + WriteLineInternal(s, cols); break; } } @@ -351,7 +349,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } private DisplayCells _displayCells; - } /// @@ -360,51 +357,51 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal class TextWriterLineOutput : LineOutput { -#region ILineOutput methods + #region ILineOutput methods /// /// get the columns on the screen /// for files, it is settable at creation time /// - internal override int ColumnNumber - { - get + internal override int ColumnNumber + { + get { CheckStopProcessing(); - return columns; - } + return _columns; + } } /// /// get the # of rows on the screen: for files /// we return -1, meaning infinite /// - internal override int RowNumber - { - get + internal override int RowNumber + { + get { CheckStopProcessing(); - return -1; - } + return -1; + } } /// /// write a line by delegating to the writer underneath /// /// - internal override void WriteLine (string s) + internal override void WriteLine(string s) { CheckStopProcessing(); - if (suppressNewline) + if (_suppressNewline) { - this.writer.Write(s); + _writer.Write(s); } else { - this.writer.WriteLine(s); + _writer.WriteLine(s); } } -#endregion + #endregion /// /// initialization of the object. It must be called before @@ -412,10 +409,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// TextWriter to write to /// max columns widths for the text - internal TextWriterLineOutput (TextWriter writer, int columns) + internal TextWriterLineOutput(TextWriter writer, int columns) { - this.writer = writer; - this.columns = columns; + _writer = writer; + _columns = columns; } /// @@ -428,16 +425,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal TextWriterLineOutput(TextWriter writer, int columns, bool suppressNewline) : this(writer, columns) { - this.suppressNewline = suppressNewline; + _suppressNewline = suppressNewline; } - private int columns = 0; + private int _columns = 0; - private TextWriter writer = null; + private TextWriter _writer = null; - private bool suppressNewline = false; + private bool _suppressNewline = false; } - + /// /// TextWriter to generate data for the Monad pipeline in a streaming fashion: /// the provided callback will be called each time a line is written @@ -445,8 +442,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal class StreamingTextWriter : TextWriter { #region tracer - [TraceSource ("StreamingTextWriter", "StreamingTextWriter")] - private static PSTraceSource tracer = PSTraceSource.GetTracer ("StreamingTextWriter", "StreamingTextWriter"); + [TraceSource("StreamingTextWriter", "StreamingTextWriter")] + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("StreamingTextWriter", "StreamingTextWriter"); #endregion tracer /// @@ -454,28 +451,28 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// delegate to write to /// culture for this TextWriter - internal StreamingTextWriter (WriteLineCallback writeCall, CultureInfo culture) + internal StreamingTextWriter(WriteLineCallback writeCall, CultureInfo culture) : base(culture) { if (writeCall == null) - throw PSTraceSource.NewArgumentNullException ("writeCall"); + throw PSTraceSource.NewArgumentNullException("writeCall"); - this.writeCall = writeCall; + _writeCall = writeCall; } #region TextWriter overrides - public override Encoding Encoding { get { return new UnicodeEncoding (); } } + public override Encoding Encoding { get { return new UnicodeEncoding(); } } - public override void WriteLine (string s) + public override void WriteLine(string s) { - this.writeCall (s); + _writeCall(s); } #if CORECLR // TextWriter.Write(char value) is abstract method in CORE CLR public override void Write(char c) { - this.writeCall(char.ToString(c)); + _writeCall(char.ToString(c)); } #endif #endregion @@ -484,12 +481,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// delegate definition /// /// string to write - internal delegate void WriteLineCallback (string s); + internal delegate void WriteLineCallback(string s); /// /// instance of the delegate previously defined /// - private WriteLineCallback writeCall = null; + private WriteLineCallback _writeCall = null; } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ListWriter.cs index 01853e6ff..e8d470b7e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/ListWriter.cs @@ -14,21 +14,20 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal class ListWriter { - /// /// labels already padded with blanks, separator characters, etc. /// - private string[] propertyLabels; - + private string[] _propertyLabels; + /// /// display length of the property labels in the array (all the same length) /// - private int propertyLabelsDisplayLength = 0; + private int _propertyLabelsDisplayLength = 0; /// /// column width of the screen /// - private int columnWidth = 0; + private int _columnWidth = 0; /// /// @@ -36,17 +35,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// names of the properties to display /// column width of the screen /// instance of the DisplayCells helper object - internal void Initialize (string[] propertyNames, int screenColumnWidth, DisplayCells dc) + internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayCells dc) { - columnWidth = screenColumnWidth; + _columnWidth = screenColumnWidth; if (propertyNames == null || propertyNames.Length == 0) { // there is nothing to show - this.disabled = true; + _disabled = true; return; } - this.disabled = false; + _disabled = false; Debug.Assert(propertyNames != null, "propertyNames is null"); Debug.Assert(propertyNames.Length > 0, "propertyNames has zero length"); @@ -55,7 +54,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if ((screenColumnWidth - Separator.Length - MinFieldWidth - MinLabelWidth) < 0) { // we do not have enough space for any meaningful display - this.disabled = true; + _disabled = true; return; } @@ -63,46 +62,46 @@ namespace Microsoft.PowerShell.Commands.Internal.Format int maxAllowableLabelLength = screenColumnWidth - Separator.Length - MinFieldWidth; // find out the max display length (cell count) of the property names - this.propertyLabelsDisplayLength = 0; // reset max + _propertyLabelsDisplayLength = 0; // reset max // cache the cell lengths for each property int[] propertyNameCellCounts = new int[propertyNames.Length]; - for (int k=0; k this.propertyLabelsDisplayLength) - this.propertyLabelsDisplayLength = propertyNameCellCounts[k]; + if (propertyNameCellCounts[k] > _propertyLabelsDisplayLength) + _propertyLabelsDisplayLength = propertyNameCellCounts[k]; } - if (this.propertyLabelsDisplayLength > maxAllowableLabelLength) + if (_propertyLabelsDisplayLength > maxAllowableLabelLength) { // need to truncate - this.propertyLabelsDisplayLength = maxAllowableLabelLength; + _propertyLabelsDisplayLength = maxAllowableLabelLength; } - this.propertyLabels = new string[propertyNames.Length]; + _propertyLabels = new string[propertyNames.Length]; - for (int k=0; k this.propertyLabelsDisplayLength) + else if (propertyNameCellCounts[k] > _propertyLabelsDisplayLength) { // longer than the max, clip - propertyLabels[k] = propertyNames[k].Substring(0, dc.GetHeadSplitLength(propertyNames[k], this.propertyLabelsDisplayLength)); + _propertyLabels[k] = propertyNames[k].Substring(0, dc.GetHeadSplitLength(propertyNames[k], _propertyLabelsDisplayLength)); } else { - propertyLabels[k] = propertyNames[k]; + _propertyLabels[k] = propertyNames[k]; } - propertyLabels[k] += Separator; + _propertyLabels[k] += Separator; } - this.propertyLabelsDisplayLength += Separator.Length; + _propertyLabelsDisplayLength += Separator.Length; } /// @@ -110,24 +109,24 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// array with the values in form of formatted strings /// LineOutput interface to write to - internal void WriteProperties (string[] values, LineOutput lo) + internal void WriteProperties(string[] values, LineOutput lo) { - if (this.disabled) + if (_disabled) return; string[] valuesToPrint = null; if (values == null) { // we have nothing, but we have to create an empty array - valuesToPrint = new string[this.propertyLabels.Length]; - for (int k = 0; k < this.propertyLabels.Length; k++) + valuesToPrint = new string[_propertyLabels.Length]; + for (int k = 0; k < _propertyLabels.Length; k++) valuesToPrint[k] = ""; } - else if (values.Length < this.propertyLabels.Length) + else if (values.Length < _propertyLabels.Length) { // need to pad to the end of the array - valuesToPrint = new string[this.propertyLabels.Length]; - for (int k = 0; k < this.propertyLabels.Length; k++) + valuesToPrint = new string[_propertyLabels.Length]; + for (int k = 0; k < _propertyLabels.Length; k++) { if (k < values.Length) valuesToPrint[k] = values[k]; @@ -135,11 +134,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format valuesToPrint[k] = ""; } } - else if (values.Length > this.propertyLabels.Length) + else if (values.Length > _propertyLabels.Length) { // need to trim - valuesToPrint = new string[this.propertyLabels.Length]; - for (int k = 0; k < this.propertyLabels.Length; k++) + valuesToPrint = new string[_propertyLabels.Length]; + for (int k = 0; k < _propertyLabels.Length; k++) valuesToPrint[k] = values[k]; } else @@ -150,9 +149,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format Debug.Assert(lo != null, "LineOutput is null"); - for (int k=0; kindex of property to write /// string value of the property to write /// LineOutput interface to write to - private void WriteProperty (int k, string propertyValue, LineOutput lo) + private void WriteProperty(int k, string propertyValue, LineOutput lo) { if (propertyValue == null) propertyValue = ""; @@ -179,18 +178,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format string prependString = null; if (i == 0) - prependString = propertyLabels[k]; + prependString = _propertyLabels[k]; else { if (padding == null) - padding = prependString = new string(' ', propertyLabelsDisplayLength); + padding = prependString = new string(' ', _propertyLabelsDisplayLength); prependString = padding; } - WriteSingleLineHelper (prependString, lines[i], lo); + WriteSingleLineHelper(prependString, lines[i], lo); } - } /// @@ -200,19 +198,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// string to add to the left /// line to print /// LineOuput to write to - private void WriteSingleLineHelper (string prependString, string line, LineOutput lo) + private void WriteSingleLineHelper(string prependString, string line, LineOutput lo) { if (line == null) line = ""; // compute the width of the field for the value string (in screen cells) - int fieldCellCount = this.columnWidth - propertyLabelsDisplayLength; + int fieldCellCount = _columnWidth - _propertyLabelsDisplayLength; // split the lines StringCollection sc = StringManipulationHelper.GenerateLines(lo.DisplayCells, line, fieldCellCount, fieldCellCount); // padding to use in the lines after the first - string padding = new string(' ', propertyLabelsDisplayLength); + string padding = new string(' ', _propertyLabelsDisplayLength); // display the string collection for (int k = 0; k < sc.Count; k++) @@ -231,7 +229,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// set to true when the width of the screen is too small to do anything useful /// - private bool disabled = false; + private bool _disabled = false; private const string Separator = " : "; diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputManager.cs index a88bfc8b5..5eec3ca0e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputManager.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Specialized; @@ -10,7 +11,6 @@ using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { - /// /// inner command class used to manage the sub pipelines /// it determines which command should process the incoming objects @@ -21,38 +21,38 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class OutputManagerInner : ImplementationCommandBase { #region tracer - [TraceSource ("format_out_OutputManagerInner", "OutputManagerInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer ("format_out_OutputManagerInner", "OutputManagerInner"); + [TraceSource("format_out_OutputManagerInner", "OutputManagerInner")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); #endregion tracer -#region LineOutput + #region LineOutput internal LineOutput LineOutput { set { - lock (this.syncRoot) + lock (_syncRoot) { - this.lo = value; + _lo = value; - if (this.isStopped) + if (_isStopped) { - this.lo.StopProcessing(); + _lo.StopProcessing(); } } } } - private LineOutput lo = null; -#endregion + private LineOutput _lo = null; + #endregion /// /// handler for processing each object coming through the pipeline /// it forwards the call to the pipeline manager object /// - internal override void ProcessRecord () + internal override void ProcessRecord() { - PSObject so = this.ReadObject (); + PSObject so = this.ReadObject(); if (so == null || so == AutomationNull.Value) { @@ -61,10 +61,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // on demand initialization when the first pipeline // object is initialized - if (mgr == null) + if (_mgr == null) { - this.mgr = new SubPipelineManager (); - this.mgr.Initialize (this.lo, this.OuterCmdlet ().Context); + _mgr = new SubPipelineManager(); + _mgr.Initialize(_lo, this.OuterCmdlet().Context); } #if false @@ -84,7 +84,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } #else - this.mgr.Process (so); + _mgr.Process(so); #endif } @@ -92,35 +92,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// handler for processing shut down. It forwards the call to the /// pipeline manager object /// - internal override void EndProcessing () + internal override void EndProcessing() { // shut down only if we ever processed a pipeline object - if (mgr != null) - mgr.ShutDown (); + if (_mgr != null) + _mgr.ShutDown(); } internal override void StopProcessing() { - lock (this.syncRoot) + lock (_syncRoot) { - if (this.lo != null) + if (_lo != null) { - this.lo.StopProcessing(); + _lo.StopProcessing(); } - this.isStopped = true; + _isStopped = true; } } /// /// make sure we dispose of the sub pipeline manager /// - protected override void InternalDispose () + protected override void InternalDispose() { - base.InternalDispose (); - if (mgr != null) + base.InternalDispose(); + if (_mgr != null) { - mgr.Dispose (); - mgr = null; + _mgr.Dispose(); + _mgr = null; } } @@ -128,17 +128,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// instance of the pipeline manager object /// - private SubPipelineManager mgr = null; + private SubPipelineManager _mgr = null; /// /// True if the cmdlet has been stopped /// - private bool isStopped = false; + private bool _isStopped = false; /// /// Lock object /// - private object syncRoot = new object(); + private object _syncRoot = new object(); } /// @@ -156,18 +156,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// instance of pipeline wrapper object /// - internal CommandWrapper command = new CommandWrapper (); + internal CommandWrapper command = new CommandWrapper(); /// /// /// /// ETS type name of the object to process /// true if there is a match - internal bool AppliesToType (string typeName) + internal bool AppliesToType(string typeName) { - foreach (String s in this.applicableTypes) + foreach (String s in _applicableTypes) { - if (string.Equals (s, typeName, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(s, typeName, StringComparison.OrdinalIgnoreCase)) return true; } @@ -177,19 +177,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// just dispose of the inner command wrapper /// - public void Dispose () + public void Dispose() { if (this.command == null) return; - this.command.Dispose (); + this.command.Dispose(); this.command = null; } /// /// ordered list of ETS type names this object is handling /// - private StringCollection applicableTypes = new StringCollection (); + private StringCollection _applicableTypes = new StringCollection(); } /// @@ -197,10 +197,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// LineOutput to pass to the child pipelines /// ExecutionContext to pass to the child pipelines - internal void Initialize (LineOutput lineOutput, ExecutionContext context) + internal void Initialize(LineOutput lineOutput, ExecutionContext context) { - lo = lineOutput; - InitializeCommandsHardWired (context); + _lo = lineOutput; + InitializeCommandsHardWired(context); } /// @@ -210,7 +210,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private void InitializeCommandsHardWired(ExecutionContext context) { // set the default handler - RegisterCommandDefault (context, "out-lineoutput", typeof(OutLineOutputCommand)); + RegisterCommandDefault(context, "out-lineoutput", typeof(OutLineOutputCommand)); /* NOTE: This is the spot where we could add new specialized handlers for @@ -245,61 +245,61 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// ExecutionContext to pass to the child pipeline /// name of the command to execute /// Type of the command to execute - private void RegisterCommandDefault (ExecutionContext context, string commandName, Type commandType) + private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType) { - CommandEntry ce = new CommandEntry (); + CommandEntry ce = new CommandEntry(); - ce.command.Initialize (context, commandName, commandType); - ce.command.AddNamedParameter ("LineOutput", this.lo); - this.defaultCommandEntry = ce; + ce.command.Initialize(context, commandName, commandType); + ce.command.AddNamedParameter("LineOutput", _lo); + _defaultCommandEntry = ce; } /// /// process an incoming parent pipeline object /// /// pipeline object to process - internal void Process (PSObject so) + internal void Process(PSObject so) { // select which pipeline should handle the object - CommandEntry ce = this.GetActiveCommandEntry (so); + CommandEntry ce = this.GetActiveCommandEntry(so); - Diagnostics.Assert (ce != null, "CommandEntry ce must not be null"); + Diagnostics.Assert(ce != null, "CommandEntry ce must not be null"); // delegate the processing - ce.command.Process (so); + ce.command.Process(so); } /// /// shut down the child pipelines /// - internal void ShutDown () + internal void ShutDown() { // we assume that command entries are never null - foreach (CommandEntry ce in this.commandEntryList) + foreach (CommandEntry ce in _commandEntryList) { - Diagnostics.Assert (ce != null, "ce != null"); - ce.command.ShutDown (); + Diagnostics.Assert(ce != null, "ce != null"); + ce.command.ShutDown(); ce.command = null; } // we assume we always have a default command entry - Diagnostics.Assert (this.defaultCommandEntry != null, "defaultCommandEntry != null"); - this.defaultCommandEntry.command.ShutDown (); - this.defaultCommandEntry.command = null; + Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); + _defaultCommandEntry.command.ShutDown(); + _defaultCommandEntry.command = null; } - public void Dispose () + public void Dispose() { // we assume that command entries are never null - foreach (CommandEntry ce in this.commandEntryList) + foreach (CommandEntry ce in _commandEntryList) { - Diagnostics.Assert (ce != null, "ce != null"); - ce.Dispose (); + Diagnostics.Assert(ce != null, "ce != null"); + ce.Dispose(); } // we assume we always have a default command entry - Diagnostics.Assert (this.defaultCommandEntry != null, "defaultCommandEntry != null"); - this.defaultCommandEntry.Dispose (); + Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); + _defaultCommandEntry.Dispose(); } /// @@ -308,30 +308,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// pipeline object to be processed /// applicable command entry - private CommandEntry GetActiveCommandEntry (PSObject so) + private CommandEntry GetActiveCommandEntry(PSObject so) { string typeName = PSObjectHelper.PSObjectIsOfExactType(so.InternalTypeNames); - foreach (CommandEntry ce in this.commandEntryList) + foreach (CommandEntry ce in _commandEntryList) { - if (ce.AppliesToType(typeName)) return ce; } // falied any match: return the default handler - return this.defaultCommandEntry; + return _defaultCommandEntry; } - private LineOutput lo = null; + private LineOutput _lo = null; /// /// list of command entries, each with a set of applicable types /// - private List commandEntryList = new List (); + private List _commandEntryList = new List(); /// /// default command entry to be executed when all type matches fail /// - CommandEntry defaultCommandEntry = new CommandEntry (); + private CommandEntry _defaultCommandEntry = new CommandEntry(); } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputQueue.cs index 05a755b7a..d3a0d444b 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/OutputQueue.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Diagnostics; using System.Collections; @@ -9,7 +10,6 @@ using System.Management.Automation; namespace Microsoft.PowerShell.Commands.Internal.Format { - /// /// queue to provide sliding window capabilities for auto size functionality /// It provides caching capabilities (either the first N objects in a group @@ -22,10 +22,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// notification callback to be called when the desired number of objects is reached /// max number of objects to be cached - internal OutputGroupQueue (FormattedObjectsCache.ProcessCachedGroupNotification callBack, int objectCount) + internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, int objectCount) { - this.notificationCallBack = callBack; - this.objectCount = objectCount; + _notificationCallBack = callBack; + _objectCount = objectCount; } /// @@ -35,8 +35,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// max amount of time to cache of objects internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification callBack, TimeSpan groupingDuration) { - this.notificationCallBack = callBack; - this.groupingDuration = groupingDuration; + _notificationCallBack = callBack; + _groupingDuration = groupingDuration; } @@ -45,82 +45,82 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to add /// objects the cache needs to return. It can be null - internal List Add (PacketInfoData o) + internal List Add(PacketInfoData o) { FormatStartData fsd = o as FormatStartData; if (fsd != null) { // just cache the reference (used during the notification call) - formatStartData = fsd; + _formatStartData = fsd; } - UpdateObjectCount (o); + UpdateObjectCount(o); // STATE TRANSITION: we are not processing and we start - if (!processingGroup && (o is GroupStartData)) + if (!_processingGroup && (o is GroupStartData)) { // just set the flag and start caching - processingGroup = true; - this.currentObjectCount = 0; + _processingGroup = true; + _currentObjectCount = 0; - if (this.groupingDuration > TimeSpan.MinValue) + if (_groupingDuration > TimeSpan.MinValue) { - this.groupingTimer = Stopwatch.StartNew(); + _groupingTimer = Stopwatch.StartNew(); } - queue.Enqueue (o); + _queue.Enqueue(o); return null; } // STATE TRANSITION: we are processing and we stop - if (processingGroup && + if (_processingGroup && ((o is GroupEndData) || - (this.objectCount > 0) && (this.currentObjectCount >= this.objectCount)) || - ((this.groupingTimer != null) && (this.groupingTimer.Elapsed > this.groupingDuration)) + (_objectCount > 0) && (_currentObjectCount >= _objectCount)) || + ((_groupingTimer != null) && (_groupingTimer.Elapsed > _groupingDuration)) ) { // reset the object count - this.currentObjectCount = 0; + _currentObjectCount = 0; - if(this.groupingTimer != null) + if (_groupingTimer != null) { - this.groupingTimer.Stop(); - this.groupingTimer = null; + _groupingTimer.Stop(); + _groupingTimer = null; } // add object to queue, to be picked up - queue.Enqueue (o); + _queue.Enqueue(o); // we are at the end of a group, drain the queue - Notify (); - processingGroup = false; + Notify(); + _processingGroup = false; - List retVal = new List (); + List retVal = new List(); - while (this.queue.Count > 0) + while (_queue.Count > 0) { - retVal.Add (queue.Dequeue ()); + retVal.Add(_queue.Dequeue()); } return retVal; } // NO STATE TRANSITION: check the state we are in - if (processingGroup) + if (_processingGroup) { // we are in the caching state - queue.Enqueue (o); + _queue.Enqueue(o); return null; } // we are not processing, so just return it - List ret = new List (); + List ret = new List(); - ret.Add (o); + ret.Add(o); return ret; } - private void UpdateObjectCount (PacketInfoData o) + private void UpdateObjectCount(PacketInfoData o) { // add only of it's not a control message // and it's not out of band @@ -129,82 +129,82 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (fed == null || fed.outOfBand) return; - this.currentObjectCount++; + _currentObjectCount++; } - private void Notify () + private void Notify() { - if (notificationCallBack == null) + if (_notificationCallBack == null) return; // filter out the out of band data, since they do not participate in the // auto resize algorithm - List validObjects = new List (); + List validObjects = new List(); - foreach (PacketInfoData x in this.queue) + foreach (PacketInfoData x in _queue) { FormatEntryData fed = x as FormatEntryData; if (fed != null && fed.outOfBand) continue; - validObjects.Add (x); + validObjects.Add(x); } - notificationCallBack (this.formatStartData, validObjects); + _notificationCallBack(_formatStartData, validObjects); } /// /// remove a single object from the queue /// /// object retrieved, null if queue is empty - internal PacketInfoData Dequeue () + internal PacketInfoData Dequeue() { - if (queue.Count == 0) + if (_queue.Count == 0) return null; - return queue.Dequeue (); + return _queue.Dequeue(); } /// /// queue to store the currently cached objects /// - private Queue queue = new Queue (); + private Queue _queue = new Queue(); /// /// number of objects to compute the best fit. /// Zero: all the objects /// a positive number N: use the first N /// - private int objectCount = 0; + private int _objectCount = 0; /// /// Maximum amount of time for record processing to compute the best fit. /// MaxValue: all the objects. /// A positive timespan: use all objects that have been processed within the timeframe. /// - private TimeSpan groupingDuration = TimeSpan.MinValue; - private Stopwatch groupingTimer = null; + private TimeSpan _groupingDuration = TimeSpan.MinValue; + private Stopwatch _groupingTimer = null; /// /// notification callback to be called when we have accumulated enough /// data to compute a hint /// - private FormattedObjectsCache.ProcessCachedGroupNotification notificationCallBack = null; + private FormattedObjectsCache.ProcessCachedGroupNotification _notificationCallBack = null; /// /// reference kept to be used during notification /// - private FormatStartData formatStartData = null; + private FormatStartData _formatStartData = null; /// /// state flag to signal we are queuing /// - private bool processingGroup = false; + private bool _processingGroup = false; /// /// current object count /// - private int currentObjectCount = 0; + private int _currentObjectCount = 0; } /// @@ -217,16 +217,16 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// current Fs control message /// enumeration of PacketInfoData objects - internal delegate void ProcessCachedGroupNotification (FormatStartData formatStartData, List objects); + internal delegate void ProcessCachedGroupNotification(FormatStartData formatStartData, List objects); /// /// decide right away if we need a front end cache (e.g. printing) /// /// if true, create a front end cache object - internal FormattedObjectsCache (bool cacheFrontEnd) + internal FormattedObjectsCache(bool cacheFrontEnd) { if (cacheFrontEnd) - this.frontEndQueue = new Queue (); + _frontEndQueue = new Queue(); } /// @@ -234,10 +234,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// notification callback to be called when the desired number of objects is reached /// max number of objects to be cached - internal void EnableGroupCaching (ProcessCachedGroupNotification callBack, int objectCount) + internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, int objectCount) { if (callBack != null) - this.groupQueue = new OutputGroupQueue (callBack, objectCount); + _groupQueue = new OutputGroupQueue(callBack, objectCount); } /// @@ -248,7 +248,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, TimeSpan groupingDuration) { if (callBack != null) - this.groupQueue = new OutputGroupQueue(callBack, groupingDuration); + _groupQueue = new OutputGroupQueue(callBack, groupingDuration); } /// @@ -257,72 +257,72 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// object to add /// list of objects the cache is flushing - internal List Add (PacketInfoData o) + internal List Add(PacketInfoData o) { // if neither there, pass thru - if (this.frontEndQueue == null && this.groupQueue == null) + if (_frontEndQueue == null && _groupQueue == null) { - List retVal = new List (); - retVal.Add (o); + List retVal = new List(); + retVal.Add(o); return retVal; } // if front present, add to front - if (this.frontEndQueue != null) + if (_frontEndQueue != null) { - this.frontEndQueue.Enqueue (o); + _frontEndQueue.Enqueue(o); return null; } // if back only, add to back - return this.groupQueue.Add (o); + return _groupQueue.Add(o); } /// /// remove all the objects from the cache /// /// all the objects that were in the cache - internal List Drain () + internal List Drain() { // if neither there,we did not cache at all - if (this.frontEndQueue == null && this.groupQueue == null) + if (_frontEndQueue == null && _groupQueue == null) { return null; } - List retVal = new List (); + List retVal = new List(); - if (this.frontEndQueue != null) + if (_frontEndQueue != null) { - if (this.groupQueue == null) + if (_groupQueue == null) { // drain the front queue and return the data - while (this.frontEndQueue.Count > 0) - retVal.Add (this.frontEndQueue.Dequeue ()); + while (_frontEndQueue.Count > 0) + retVal.Add(_frontEndQueue.Dequeue()); return retVal; } // move from the front to the back queue - while (this.frontEndQueue.Count > 0) + while (_frontEndQueue.Count > 0) { - List groupQueueOut = this.groupQueue.Add (this.frontEndQueue.Dequeue ()); + List groupQueueOut = _groupQueue.Add(_frontEndQueue.Dequeue()); if (groupQueueOut != null) foreach (PacketInfoData x in groupQueueOut) - retVal.Add (x); + retVal.Add(x); } } // drain the back queue while (true) { - PacketInfoData obj = this.groupQueue.Dequeue (); + PacketInfoData obj = _groupQueue.Dequeue(); if (obj == null) break; - retVal.Add (obj); + retVal.Add(obj); } return retVal; @@ -332,12 +332,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// front end queue (if present, cache ALL, if not, bypass) /// - private Queue frontEndQueue; + private Queue _frontEndQueue; /// /// back end grouping queue /// - private OutputGroupQueue groupQueue = null; + private OutputGroupQueue _groupQueue = null; } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/TableWriter.cs index b19e6bff2..28d2dd1bd 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/TableWriter.cs @@ -37,9 +37,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal ColumnInfo[] columnInfo = null; } - private ScreenInfo si; + private ScreenInfo _si; - internal static int ComputeWideViewBestItemsPerRowFit (int stringLen, int screenColumns) + internal static int ComputeWideViewBestItemsPerRowFit(int stringLen, int screenColumns) { if (stringLen <= 0 || screenColumns < 1) return 1; @@ -79,30 +79,30 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// array of specified column widths /// array of alignment flags /// if true, suppress header printing - internal void Initialize (int leftMarginIndent, int screenColumns, int[] columnWidths, int[] alignment, bool suppressHeader) + internal void Initialize(int leftMarginIndent, int screenColumns, int[] columnWidths, int[] alignment, bool suppressHeader) { //Console.WriteLine(" 1 2 3 4 5 6 7"); //Console.WriteLine("01234567890123456789012345678901234567890123456789012345678901234567890123456789"); - + if (leftMarginIndent < 0) { leftMarginIndent = 0; } - if (screenColumns-leftMarginIndent < ScreenInfo.minimumScreenColumns) + if (screenColumns - leftMarginIndent < ScreenInfo.minimumScreenColumns) { - disabled = true; + _disabled = true; return; } - startColumn = leftMarginIndent; + _startColumn = leftMarginIndent; - hideHeader = suppressHeader; + _hideHeader = suppressHeader; // make sure the column widths are correct; if not, take appropriate action - ColumnWidthManager manager = new ColumnWidthManager (screenColumns-leftMarginIndent, - ScreenInfo.minimumColumnWidth, + ColumnWidthManager manager = new ColumnWidthManager(screenColumns - leftMarginIndent, + ScreenInfo.minimumColumnWidth, ScreenInfo.separatorCharacterCount); - manager.CalculateColumnWidths (columnWidths); + manager.CalculateColumnWidths(columnWidths); // if all the columns are hidden, just disable bool oneValid = false; @@ -118,33 +118,33 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (!oneValid) { - this.disabled = true; + _disabled = true; return; } // now set the run time data structures - si = new ScreenInfo(); - si.screenColumns = screenColumns; - si.columnInfo = new ColumnInfo[columnWidths.Length]; + _si = new ScreenInfo(); + _si.screenColumns = screenColumns; + _si.columnInfo = new ColumnInfo[columnWidths.Length]; - int startCol = startColumn; + int startCol = _startColumn; for (int k = 0; k < columnWidths.Length; k++) { - si.columnInfo[k] = new ColumnInfo(); - si.columnInfo[k].startCol = startCol; - si.columnInfo[k].width = columnWidths[k]; - si.columnInfo[k].alignment = alignment[k]; + _si.columnInfo[k] = new ColumnInfo(); + _si.columnInfo[k].startCol = startCol; + _si.columnInfo[k].width = columnWidths[k]; + _si.columnInfo[k].alignment = alignment[k]; startCol += columnWidths[k] + ScreenInfo.separatorCharacterCount; //Console.WriteLine("start = {0} width = {1}", si.columnInfo[k].startCol, si.columnInfo[k].width); } } - internal void GenerateHeader (string[] values, LineOutput lo) + internal void GenerateHeader(string[] values, LineOutput lo) { - if (this.disabled) + if (_disabled) return; - if (this.hideHeader) + if (_hideHeader) return; // generate the row with the header labels @@ -153,17 +153,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // generate an array of "--" as header markers below // the column header labels string[] breakLine = new string[values.Length]; - for (int k=0; k< si.columnInfo.Length; k++) + for (int k = 0; k < _si.columnInfo.Length; k++) { // the column can be hidden - if (si.columnInfo[k].width <= 0) + if (_si.columnInfo[k].width <= 0) { breakLine[k] = ""; continue; } // the title can be larger than the width - int count = si.columnInfo[k].width; - if (!string.IsNullOrEmpty (values[k])) + int count = _si.columnInfo[k].width; + if (!string.IsNullOrEmpty(values[k])) { int labelDisplayCells = lo.DisplayCells.Length(values[k]); if (labelDisplayCells < count) @@ -179,18 +179,18 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, int[] alignment, DisplayCells dc) { - if (this.disabled) + if (_disabled) return; // build the current row aligment settings - int cols = si.columnInfo.Length; + int cols = _si.columnInfo.Length; int[] currentAlignment = new int[cols]; if (alignment == null) { for (int i = 0; i < cols; i++) { - currentAlignment[i] = si.columnInfo[i].alignment; + currentAlignment[i] = _si.columnInfo[i].alignment; } } else @@ -198,7 +198,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int i = 0; i < cols; i++) { if (alignment[i] == TextAlignment.Undefined) - currentAlignment[i] = si.columnInfo[i].alignment; + currentAlignment[i] = _si.columnInfo[i].alignment; else currentAlignment[i] = alignment[i]; } @@ -211,7 +211,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int k = 0; k < lines.Length; k++) { - lo.WriteLine (lines[k]); + lo.WriteLine(lines[k]); } } else @@ -223,11 +223,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private string[] GenerateTableRow(string[] values, int[] alignment, DisplayCells ds) { // select the active columns (skip hidden ones) - int[] validColumnArray = new int[si.columnInfo.Length]; + int[] validColumnArray = new int[_si.columnInfo.Length]; int validColumnCount = 0; - for (int k = 0; k < si.columnInfo.Length; k++) + for (int k = 0; k < _si.columnInfo.Length; k++) { - if (si.columnInfo[k].width > 0) + if (_si.columnInfo[k].width > 0) { validColumnArray[validColumnCount++] = k; } @@ -241,7 +241,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int k = 0; k < scArray.Length; k++) { // obtain a set of tokens for each field - scArray[k] = GenerateMultiLineRowField (values[validColumnArray[k]], validColumnArray[k], + scArray[k] = GenerateMultiLineRowField(values[validColumnArray[k]], validColumnArray[k], alignment[validColumnArray[k]], ds); // NOTE: the following padding operations assume that we @@ -251,17 +251,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // skipping the first ones, add a separator for catenation for (int j = 0; j < scArray[k].Count; j++) { - scArray[k][j] = new string (' ', ScreenInfo.separatorCharacterCount) + scArray[k][j]; + scArray[k][j] = new string(' ', ScreenInfo.separatorCharacterCount) + scArray[k][j]; } } else { // add indentation padding if needed - if (this.startColumn > 0) + if (_startColumn > 0) { for (int j = 0; j < scArray[k].Count; j++) { - scArray[k][j] = new string (' ', this.startColumn) + scArray[k][j]; + scArray[k][j] = new string(' ', _startColumn) + scArray[k][j]; } } } @@ -279,47 +279,47 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // add padding for the colums that are shorter for (int col = 0; col < scArray.Length; col++) { - int paddingBlanks = si.columnInfo[validColumnArray[col]].width; + int paddingBlanks = _si.columnInfo[validColumnArray[col]].width; if (col > 0) paddingBlanks += ScreenInfo.separatorCharacterCount; else { - paddingBlanks += this.startColumn; + paddingBlanks += _startColumn; } int paddingEntries = screenRows - scArray[col].Count; if (paddingEntries > 0) { for (int j = 0; j < paddingEntries; j++) { - scArray[col].Add (new string (' ', paddingBlanks)); + scArray[col].Add(new string(' ', paddingBlanks)); } } } // finally, build an array of strings string[] rows = new string[screenRows]; - for (int row = 0; row < rows.Length; row++ ) + for (int row = 0; row < rows.Length; row++) { - StringBuilder sb = new StringBuilder (); + StringBuilder sb = new StringBuilder(); // for a give row, walk the columns for (int col = 0; col < scArray.Length; col++) { - sb.Append (scArray[col][row]); + sb.Append(scArray[col][row]); } - rows[row] = sb.ToString (); + rows[row] = sb.ToString(); } return rows; } - private StringCollection GenerateMultiLineRowField (string val, int k, int aligment, DisplayCells dc) + private StringCollection GenerateMultiLineRowField(string val, int k, int aligment, DisplayCells dc) { StringCollection sc = StringManipulationHelper.GenerateLines(dc, val, - si.columnInfo[k].width, si.columnInfo[k].width); + _si.columnInfo[k].width, _si.columnInfo[k].width); // if length is shorter, do some padding for (int col = 0; col < sc.Count; col++) { - if (dc.Length(sc[col]) < si.columnInfo[k].width) - sc[col] = GenerateRowField (sc[col], si.columnInfo[k].width, aligment, dc); + if (dc.Length(sc[col]) < _si.columnInfo[k].width) + sc[col] = GenerateRowField(sc[col], _si.columnInfo[k].width, aligment, dc); } return sc; } @@ -329,9 +329,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { StringBuilder sb = new StringBuilder(); - for (int k=0; k< si.columnInfo.Length; k++) + for (int k = 0; k < _si.columnInfo.Length; k++) { - if (si.columnInfo[k].width <= 0) + if (_si.columnInfo[k].width <= 0) { // skip columns that are not at least a single character wide continue; @@ -347,21 +347,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format else { // add indentation padding if needed - if (this.startColumn > 0) + if (_startColumn > 0) { - sb.Append(new string(' ', this.startColumn)); + sb.Append(new string(' ', _startColumn)); } } - sb.Append(GenerateRowField(values[k], si.columnInfo[k].width, alignment[k], dc)); + sb.Append(GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc)); } return sb.ToString(); } - - private static string GenerateRowField (string val, int width, int alignment, DisplayCells dc) + + private static string GenerateRowField(string val, int width, int alignment, DisplayCells dc) { // make sure the string does not have any embedded in it - string s = StringManipulationHelper.TruncateAtNewLine (val); + string s = StringManipulationHelper.TruncateAtNewLine(val); if (s == null) s = ""; @@ -388,7 +388,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format int padLeft = padCount / 2; int padRight = padCount - padLeft; - s = new string (' ', padLeft) + s + new string (' ', padRight); + s = new string(' ', padLeft) + s + new string(' ', padRight); } break; @@ -508,12 +508,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private const string ellipsis = "..."; - private bool disabled = false; + private bool _disabled = false; - private bool hideHeader = false; - - private int startColumn = 0; + private bool _hideHeader = false; + private int _startColumn = 0; } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshObjectUtil.cs index 685d83ff5..c170921b6 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text; using System.Collections; @@ -21,7 +22,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal const string ellipses = "..."; - internal static string PSObjectIsOfExactType (Collection typeNames) + internal static string PSObjectIsOfExactType(Collection typeNames) { if (typeNames.Count != 0) return typeNames[0]; @@ -117,7 +118,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// shell object to process /// expression factory to create MshExpression /// resolved MshExpression; null if no match was found - internal static MshExpression GetDisplayNameExpression (PSObject target, MshExpressionFactory expressionFactory) + internal static MshExpression GetDisplayNameExpression(PSObject target, MshExpressionFactory expressionFactory) { // first try to get the expression from the object (types.ps1xml data) MshExpression expressionFromObject = GetDefaultNameExpression(target); @@ -135,7 +136,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // go over the patterns, looking for the first match foreach (string pattern in knownPatterns) { - MshExpression ex = new MshExpression (pattern); + MshExpression ex = new MshExpression(pattern); List exprList = ex.ResolveNames(target); while ((exprList.Count > 0) && ( @@ -172,8 +173,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return null; // evaluate the expression - List resList = ex.GetValues (target); - + List resList = ex.GetValues(target); + if (resList.Count == 0 || resList[0].Exception != null) { // no results or the retrieval on the first one failed @@ -215,11 +216,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return PSObjectHelper.AsPSObject(x).ToString(); } } - + private static string GetObjectName(object x, MshExpressionFactory expressionFactory) { string objName; - + // check if the underlying object is of primitive type // if so just return its value if (x is PSObject && @@ -245,7 +246,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } else { - MshExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { @@ -368,15 +368,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } - return ""; + return ""; } } - private static readonly PSObject emptyPSObject = new PSObject(""); + private static readonly PSObject s_emptyPSObject = new PSObject(""); internal static PSObject AsPSObject(object obj) { - return (obj == null) ? emptyPSObject : PSObject.AsPSObject (obj); + return (obj == null) ? s_emptyPSObject : PSObject.AsPSObject(obj); } /// @@ -388,11 +388,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// formatting error object, if present /// expression factory to create MshExpression /// string representation - internal static string FormatField (FieldFormattingDirective directive, object val, int enumerationLimit, + internal static string FormatField(FieldFormattingDirective directive, object val, int enumerationLimit, StringFormatError formatErrorObject, MshExpressionFactory expressionFactory) { PSObject so = PSObjectHelper.AsPSObject(val); - if (directive != null && !string.IsNullOrEmpty (directive.formatString)) + if (directive != null && !string.IsNullOrEmpty(directive.formatString)) { // we have a formatting directive, apply it // NOTE: with a format directive, we do not make any attempt @@ -401,14 +401,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { // use some heuristics to determine if we have "composite formatting" // 2004/11/16-JonN This is heuristic but should be safe enough - if (directive.formatString.Contains ("{0") || directive.formatString.Contains ("}")) + if (directive.formatString.Contains("{0") || directive.formatString.Contains("}")) { // we do have it, just use it - return String.Format (CultureInfo.CurrentCulture, directive.formatString, so); + return String.Format(CultureInfo.CurrentCulture, directive.formatString, so); } // we fall back to the PSObject's IFormattable.ToString() // pass a null IFormatProvider - return so.ToString (directive.formatString, null); + return so.ToString(directive.formatString, null); } catch (Exception e) // 2004/11/17-JonN This covers exceptions thrown in // String.Format and PSObject.ToString(). @@ -429,7 +429,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we do not have a formatting directive or we failed the formatting (fallback) // but we did not report as an error; // this call would deal with IEnumerable if the object implements it - return PSObjectHelper.SmartToString (so, expressionFactory, enumerationLimit, formatErrorObject); + return PSObjectHelper.SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject); } private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) @@ -480,7 +480,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// shell object to process /// resolved expression; empty list if not found - internal static List GetDefaultPropertySet (PSObject so) + internal static List GetDefaultPropertySet(PSObject so) { List retVal = GetDefaultPropertySet(so.PSStandardMembers); if (retVal.Count == 0) @@ -511,7 +511,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } - return null; + return null; } private static MshExpression GetDefaultNameExpression(PSObject so) @@ -536,17 +536,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// expression factory to create MshExpression /// not null if an error condition arose /// formatted string - internal static string GetExpressionDisplayValue ( - PSObject so, + internal static string GetExpressionDisplayValue( + PSObject so, int enumerationLimit, MshExpression ex, - FieldFormattingDirective directive, - StringFormatError formatErrorObject, + FieldFormattingDirective directive, + StringFormatError formatErrorObject, MshExpressionFactory expressionFactory, out MshExpressionResult result) { result = null; - List resList = ex.GetValues (so); + List resList = ex.GetValues(so); if (resList.Count == 0) { @@ -585,8 +585,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } catch (ArgumentException) { - // ignore any exceptions thrown retrieving the *ComputerName properties - // from the object + // ignore any exceptions thrown retrieving the *ComputerName properties + // from the object } catch (ExtendedTypeSystemException) { @@ -616,7 +616,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal Exception exception; } - internal delegate ScriptBlock CreateScriptBlockFromString (string scriptBlockString); + internal delegate ScriptBlock CreateScriptBlockFromString(string scriptBlockString); /// /// helper class to create MshExpression's from format.ps1xml data structures @@ -624,7 +624,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class MshExpressionFactory { /// - internal void VerifyScriptBlockText (string scriptText) + internal void VerifyScriptBlockText(string scriptText) { ScriptBlock.Create(scriptText); } @@ -683,10 +683,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format sb.LanguageMode = PSLanguageMode.FullLanguage; } - MshExpression ex = new MshExpression (sb); + MshExpression ex = new MshExpression(sb); + + _expressionCache.Add(et, ex); - _expressionCache.Add (et, ex); - return ex; } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameter.cs index bf24195c3..488bc7813 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -17,7 +18,6 @@ using System.Reflection; namespace Microsoft.PowerShell.Commands.Internal.Format { - /// /// normalized parameter class to be constructed from the command line parameters /// using the metadata information provided by an instance of CommandParameterDefinition @@ -27,9 +27,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { internal Hashtable hash = null; - internal object GetEntry (string key) + internal object GetEntry(string key) { - if (this.hash.ContainsKey (key)) + if (this.hash.ContainsKey(key)) return this.hash[key]; return AutomationNull.Value; @@ -55,26 +55,26 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal HashtableEntryDefinition(string name, IEnumerable secondaryNames, Type[] types, bool mandatory) : this(name, types, mandatory) { - this.secondaryNames = secondaryNames; + _secondaryNames = secondaryNames; } - internal HashtableEntryDefinition (string name, Type[] types, bool mandatory) + internal HashtableEntryDefinition(string name, Type[] types, bool mandatory) { - this.key = name; - this.allowedTypes = types; - this.mandatory = mandatory; + _key = name; + _allowedTypes = types; + _mandatory = mandatory; } - internal HashtableEntryDefinition (string name, Type[] types) + internal HashtableEntryDefinition(string name, Type[] types) : this(name, types, false) { } - internal virtual Hashtable CreateHashtableFromSingleType (object val) + internal virtual Hashtable CreateHashtableFromSingleType(object val) { // NOTE: must override for the default type(s) entry // this entry will have to expand the object into a hash table - throw PSTraceSource.NewNotSupportedException (); + throw PSTraceSource.NewNotSupportedException(); } internal bool IsKeyMatch(string key) @@ -98,33 +98,33 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - internal virtual object Verify (object val, - TerminatingErrorContext invocationContext, + internal virtual object Verify(object val, + TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { return null; } - internal virtual object ComputeDefaultValue () + internal virtual object ComputeDefaultValue() { return AutomationNull.Value; } - internal string KeyName { get { return this.key; } } + internal string KeyName { get { return _key; } } - internal Type[] AllowedTypes { get { return this.allowedTypes; } } + internal Type[] AllowedTypes { get { return _allowedTypes; } } - internal bool Mandatory { get { return this.mandatory; } } + internal bool Mandatory { get { return _mandatory; } } - internal IEnumerable SecondaryNames { get { return this.secondaryNames; } } + internal IEnumerable SecondaryNames { get { return _secondaryNames; } } - private string key; + private string _key; - private Type[] allowedTypes; + private Type[] _allowedTypes; - private bool mandatory; + private bool _mandatory; - private IEnumerable secondaryNames; + private IEnumerable _secondaryNames; } /// @@ -133,14 +133,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal abstract class CommandParameterDefinition { [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] - internal CommandParameterDefinition () + internal CommandParameterDefinition() { - SetEntries (); + SetEntries(); } - protected abstract void SetEntries (); + protected abstract void SetEntries(); - internal virtual MshParameter CreateInstance () { return new MshParameter (); } + internal virtual MshParameter CreateInstance() { return new MshParameter(); } /// /// for a key name, verify it is a legal entry: @@ -152,10 +152,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// invocation context for error reporting /// matching hash table entry /// - internal HashtableEntryDefinition MatchEntry (string keyName, TerminatingErrorContext invocationContext) + internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorContext invocationContext) { - if (string.IsNullOrEmpty (keyName)) - PSTraceSource.NewArgumentNullException ("keyName"); + if (string.IsNullOrEmpty(keyName)) + PSTraceSource.NewArgumentNullException("keyName"); HashtableEntryDefinition matchingEntry = null; for (int k = 0; k < this.hashEntries.Count; k++) @@ -172,7 +172,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format else { // we already had a match, we have an ambiguous key - ProcessAmbiguousKey (invocationContext, keyName, matchingEntry, this.hashEntries[k]); + ProcessAmbiguousKey(invocationContext, keyName, matchingEntry, this.hashEntries[k]); } } } @@ -183,23 +183,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return matchingEntry; } // we did not have a match - ProcessIllegalKey (invocationContext, keyName); + ProcessIllegalKey(invocationContext, keyName); return null; } - internal static bool FindPartialMatch (string key, string normalizedKey) + internal static bool FindPartialMatch(string key, string normalizedKey) { if (key.Length < normalizedKey.Length) { // shorter, could be an abbreviation - if (string.Equals (key, normalizedKey.Substring (0, key.Length), StringComparison.OrdinalIgnoreCase)) + if (string.Equals(key, normalizedKey.Substring(0, key.Length), StringComparison.OrdinalIgnoreCase)) { // found abbreviation return true; } } - if (string.Equals (key, normalizedKey, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(key, normalizedKey, StringComparison.OrdinalIgnoreCase)) { // found full match return true; @@ -211,7 +211,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Error Processing - private static void ProcessAmbiguousKey (TerminatingErrorContext invocationContext, + private static void ProcessAmbiguousKey(TerminatingErrorContext invocationContext, string keyName, HashtableEntryDefinition matchingEntry, HashtableEntryDefinition currentEntry) @@ -219,19 +219,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format string msg = StringUtil.Format(FormatAndOut_MshParameter.AmbiguousKeyError, keyName, matchingEntry.KeyName, currentEntry.KeyName); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyAmbiguous", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyAmbiguous", msg); } - private static void ProcessIllegalKey (TerminatingErrorContext invocationContext, + private static void ProcessIllegalKey(TerminatingErrorContext invocationContext, string keyName) { - string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalKeyError,keyName); + string msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalKeyError, keyName); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyIllegal", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyIllegal", msg); } #endregion - internal List hashEntries = new List (); + internal List hashEntries = new List(); } @@ -243,71 +243,71 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class ParameterProcessor { #region tracer - [TraceSource ("ParameterProcessor", "ParameterProcessor")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer ("ParameterProcessor", "ParameterProcessor"); + [TraceSource("ParameterProcessor", "ParameterProcessor")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); #endregion tracer - internal static void ThrowParameterBindingException (TerminatingErrorContext invocationContext, + internal static void ThrowParameterBindingException(TerminatingErrorContext invocationContext, string errorId, string msg) { - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( new NotSupportedException(), errorId, ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - invocationContext.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + invocationContext.ThrowTerminatingError(errorRecord); } - internal ParameterProcessor (CommandParameterDefinition p) + internal ParameterProcessor(CommandParameterDefinition p) { - this.paramDef = p; + _paramDef = p; } /// - internal List ProcessParameters (object[] p, TerminatingErrorContext invocationContext) + internal List ProcessParameters(object[] p, TerminatingErrorContext invocationContext) { if (p == null || p.Length == 0) return null; - List retVal = new List (); + List retVal = new List(); MshParameter currParam; bool originalParameterWasHashTable = false; for (int k = 0; k < p.Length; k++) { // we always copy into a fresh hash table - currParam = this.paramDef.CreateInstance (); + currParam = _paramDef.CreateInstance(); var actualObject = PSObject.Base(p[k]); if (actualObject is IDictionary) { originalParameterWasHashTable = true; - currParam.hash = VerifyHashTable ((IDictionary)actualObject, invocationContext); + currParam.hash = VerifyHashTable((IDictionary)actualObject, invocationContext); } - else if ( (actualObject != null) && MatchesAllowedTypes(actualObject.GetType(), this.paramDef.hashEntries[0].AllowedTypes)) + else if ((actualObject != null) && MatchesAllowedTypes(actualObject.GetType(), _paramDef.hashEntries[0].AllowedTypes)) { // a simple type was specified, build a hash with one entry - currParam.hash = this.paramDef.hashEntries[0].CreateHashtableFromSingleType(actualObject); + currParam.hash = _paramDef.hashEntries[0].CreateHashtableFromSingleType(actualObject); } else { // unknown type, error // provide error message (the user did not enter a hash table) - ProcessUnknownParameterType(invocationContext, actualObject, this.paramDef.hashEntries[0].AllowedTypes); + ProcessUnknownParameterType(invocationContext, actualObject, _paramDef.hashEntries[0].AllowedTypes); } // value range validation and post processing on the hash table - VerifyAndNormalizeParameter (currParam, invocationContext, originalParameterWasHashTable); - retVal.Add (currParam); + VerifyAndNormalizeParameter(currParam, invocationContext, originalParameterWasHashTable); + retVal.Add(currParam); } return retVal; } - private static bool MatchesAllowedTypes (Type t, Type[] allowedTypes) + private static bool MatchesAllowedTypes(Type t, Type[] allowedTypes) { for (int k = 0; k < allowedTypes.Length; k++) { @@ -319,32 +319,32 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } /// - private Hashtable VerifyHashTable (IDictionary hash, TerminatingErrorContext invocationContext) + private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invocationContext) { // full blown hash, need to: // 1. verify names(keys) and expand names if there are partial matches // 2. verify value types - Hashtable retVal = new Hashtable (); + Hashtable retVal = new Hashtable(); foreach (DictionaryEntry e in hash) { if (e.Key == null) { - ProcessNullHashTableKey (invocationContext); + ProcessNullHashTableKey(invocationContext); } - + string currentStringKey = e.Key as string; if (currentStringKey == null) { - ProcessNonStringHashTableKey (invocationContext, e.Key); + ProcessNonStringHashTableKey(invocationContext, e.Key); } // find a match for the key - HashtableEntryDefinition def = this.paramDef.MatchEntry (currentStringKey, invocationContext); - if (retVal.Contains (def.KeyName)) + HashtableEntryDefinition def = _paramDef.MatchEntry(currentStringKey, invocationContext); + if (retVal.Contains(def.KeyName)) { // duplicate key error - ProcessDuplicateHashTableKey (invocationContext, currentStringKey, def.KeyName); + ProcessDuplicateHashTableKey(invocationContext, currentStringKey, def.KeyName); } // now the key is verified, need to check the type @@ -362,7 +362,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (e.Value == null) { - ProcessMissingKeyValue (invocationContext, currentStringKey); + ProcessMissingKeyValue(invocationContext, currentStringKey); } if (def.AllowedTypes[t].IsAssignableFrom(e.Value.GetType())) @@ -376,48 +376,48 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (!matchType) { // bad type error - ProcessIllegalHashTableKeyValue (invocationContext, currentStringKey, e.Value.GetType (), def.AllowedTypes); + ProcessIllegalHashTableKeyValue(invocationContext, currentStringKey, e.Value.GetType(), def.AllowedTypes); } - retVal.Add (def.KeyName, e.Value); + retVal.Add(def.KeyName, e.Value); } return retVal; } /// - private void VerifyAndNormalizeParameter (MshParameter parameter, + private void VerifyAndNormalizeParameter(MshParameter parameter, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { - for (int k = 0; k < this.paramDef.hashEntries.Count; k++) + for (int k = 0; k < _paramDef.hashEntries.Count; k++) { - if (parameter.hash.ContainsKey (this.paramDef.hashEntries[k].KeyName)) + if (parameter.hash.ContainsKey(_paramDef.hashEntries[k].KeyName)) { // we have a key, just do some post processing normalization // retrieve the value - object val = parameter.hash[this.paramDef.hashEntries[k].KeyName]; - object newVal = this.paramDef.hashEntries[k].Verify (val, invocationContext, originalParameterWasHashTable); + object val = parameter.hash[_paramDef.hashEntries[k].KeyName]; + object newVal = _paramDef.hashEntries[k].Verify(val, invocationContext, originalParameterWasHashTable); if (newVal != null) { // if a new value is provided, we need to update the hash entry - parameter.hash[this.paramDef.hashEntries[k].KeyName] = newVal; + parameter.hash[_paramDef.hashEntries[k].KeyName] = newVal; } } else { // we do not have the key, we might want to have a default value - object defaultValue = this.paramDef.hashEntries[k].ComputeDefaultValue (); + object defaultValue = _paramDef.hashEntries[k].ComputeDefaultValue(); if (defaultValue != AutomationNull.Value) { // we have a default value, add it - parameter.hash[this.paramDef.hashEntries[k].KeyName] = defaultValue; + parameter.hash[_paramDef.hashEntries[k].KeyName] = defaultValue; } - else if (this.paramDef.hashEntries[k].Mandatory) + else if (_paramDef.hashEntries[k].Mandatory) { // no default value and mandatory: we cannot proceed - ProcessMissingMandatoryKey (invocationContext, this.paramDef.hashEntries[k].KeyName); + ProcessMissingMandatoryKey(invocationContext, _paramDef.hashEntries[k].KeyName); } } } @@ -426,9 +426,9 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Error Processing - private static void ProcessUnknownParameterType (TerminatingErrorContext invocationContext, object actualObject, Type[] allowedTypes) + private static void ProcessUnknownParameterType(TerminatingErrorContext invocationContext, object actualObject, Type[] allowedTypes) { - string allowedTypesList = CatenateTypeArray (allowedTypes); + string allowedTypesList = CatenateTypeArray(allowedTypes); string msg; if (actualObject != null) @@ -441,36 +441,36 @@ namespace Microsoft.PowerShell.Commands.Internal.Format msg = StringUtil.Format(FormatAndOut_MshParameter.NullParameterTypeError, allowedTypesList); } - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyUnknownType", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyUnknownType", msg); } - private static void ProcessDuplicateHashTableKey (TerminatingErrorContext invocationContext, string duplicateKey, string existingKey) + private static void ProcessDuplicateHashTableKey(TerminatingErrorContext invocationContext, string duplicateKey, string existingKey) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DuplicateKeyError, duplicateKey, existingKey); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyDuplicate", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyDuplicate", msg); } - private static void ProcessNullHashTableKey (TerminatingErrorContext invocationContext) + private static void ProcessNullHashTableKey(TerminatingErrorContext invocationContext) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNullError); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyNull", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNull", msg); } - private static void ProcessNonStringHashTableKey (TerminatingErrorContext invocationContext, object key) + private static void ProcessNonStringHashTableKey(TerminatingErrorContext invocationContext, object key) { string msg = StringUtil.Format(FormatAndOut_MshParameter.DictionaryKeyNonStringError, key.GetType().Name); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyNonString", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyNonString", msg); } - private static void ProcessIllegalHashTableKeyValue (TerminatingErrorContext invocationContext, string key, Type actualType, Type[] allowedTypes) + private static void ProcessIllegalHashTableKeyValue(TerminatingErrorContext invocationContext, string key, Type actualType, Type[] allowedTypes) { string msg; string errorID; if (allowedTypes.Length > 1) { - string legalTypes = CatenateTypeArray (allowedTypes); + string legalTypes = CatenateTypeArray(allowedTypes); msg = StringUtil.Format(FormatAndOut_MshParameter.IllegalTypeMultiError, key, @@ -491,19 +491,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format errorID = "DictionaryKeyIllegalValue2"; } - ParameterProcessor.ThrowParameterBindingException (invocationContext, errorID, msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, errorID, msg); } - private static void ProcessMissingKeyValue (TerminatingErrorContext invocationContext, string keyName) + private static void ProcessMissingKeyValue(TerminatingErrorContext invocationContext, string keyName) { string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyValueError, keyName); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyMissingValue", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyMissingValue", msg); } - private static void ProcessMissingMandatoryKey (TerminatingErrorContext invocationContext, string keyName) + private static void ProcessMissingMandatoryKey(TerminatingErrorContext invocationContext, string keyName) { string msg = StringUtil.Format(FormatAndOut_MshParameter.MissingKeyMandatoryEntryError, keyName); - ParameterProcessor.ThrowParameterBindingException (invocationContext, "DictionaryKeyMandatoryEntry", msg); + ParameterProcessor.ThrowParameterBindingException(invocationContext, "DictionaryKeyMandatoryEntry", msg); } @@ -511,35 +511,35 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Utilities - private static string CatenateTypeArray (Type[] arr) + private static string CatenateTypeArray(Type[] arr) { string[] strings = new string[arr.Length]; for (int k = 0; k < arr.Length; k++) { strings[k] = arr[k].FullName; } - return CatenateStringArray (strings); + return CatenateStringArray(strings); } - internal static string CatenateStringArray (string[] arr) + internal static string CatenateStringArray(string[] arr) { - StringBuilder sb = new StringBuilder (); - sb.Append ("{"); + StringBuilder sb = new StringBuilder(); + sb.Append("{"); for (int k = 0; k < arr.Length; k++) { if (k > 0) { - sb.Append (", "); + sb.Append(", "); } - sb.Append (arr[k]); + sb.Append(arr[k]); } - sb.Append ("}"); - return sb.ToString (); + sb.Append("}"); + return sb.ToString(); } #endregion - CommandParameterDefinition paramDef = null; + private CommandParameterDefinition _paramDef = null; } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index aef8ae4be..6e308fe56 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Collections; @@ -15,30 +16,29 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal sealed class MshResolvedExpressionParameterAssociation { - #region tracer - [TraceSource ("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer ("MshResolvedExpressionParameterAssociation", + [TraceSource("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation"); #endregion tracer internal MshResolvedExpressionParameterAssociation(MshParameter parameter, MshExpression expression) { if (expression == null) - throw PSTraceSource.NewArgumentNullException ("expression"); + throw PSTraceSource.NewArgumentNullException("expression"); - this._originatingParameter = parameter; - this._resolvedExpression = expression; + _originatingParameter = parameter; + _resolvedExpression = expression; } internal MshExpression ResolvedExpression { - get { return this._resolvedExpression; } + get { return _resolvedExpression; } } internal MshParameter OriginatingParameter { - get { return this._originatingParameter; } + get { return _originatingParameter; } } private MshExpression _resolvedExpression; @@ -48,14 +48,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal static class AssociationManager { - internal static List SetupActiveProperties (List rawMshParameterList, - PSObject target, MshExpressionFactory expressionFactory) + internal static List SetupActiveProperties(List rawMshParameterList, + PSObject target, MshExpressionFactory expressionFactory) { // check if we received properties from the command line if (rawMshParameterList != null && rawMshParameterList.Count > 0) { - return AssociationManager.ExpandParameters (rawMshParameterList, target); - } + return AssociationManager.ExpandParameters(rawMshParameterList, target); + } // we did not get any properties: //try to get properties from the default property set of the object @@ -76,49 +76,49 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we failed to get anything from the default property set // just get all the properties - activeAssociationList = AssociationManager.ExpandAll (target); + activeAssociationList = AssociationManager.ExpandAll(target); // Remove PSComputerName and PSShowComputerName from the display as needed. - AssociationManager.HandleComputerNameProperties(target, activeAssociationList); + AssociationManager.HandleComputerNameProperties(target, activeAssociationList); return activeAssociationList; } - internal static List ExpandTableParameters (List parameters, PSObject target) + internal static List ExpandTableParameters(List parameters, PSObject target) { - List retVal = new List (); + List retVal = new List(); foreach (MshParameter par in parameters) { - MshExpression expression = par.GetEntry (FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; - List expandedExpressionList = expression.ResolveNames (target); + MshExpression expression = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; + List expandedExpressionList = expression.ResolveNames(target); if (!expression.HasWildCardCharacters && expandedExpressionList.Count == 0) { // we did not find anything, mark as unresolved - retVal.Add (new MshResolvedExpressionParameterAssociation (par, expression)); + retVal.Add(new MshResolvedExpressionParameterAssociation(par, expression)); } foreach (MshExpression ex in expandedExpressionList) { - retVal.Add (new MshResolvedExpressionParameterAssociation (par, ex)); + retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex)); } } return retVal; } - internal static List ExpandParameters (List parameters, PSObject target) + internal static List ExpandParameters(List parameters, PSObject target) { - List retVal = new List (); + List retVal = new List(); foreach (MshParameter par in parameters) { - MshExpression expression = par.GetEntry (FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; - List expandedExpressionList = expression.ResolveNames (target); + MshExpression expression = par.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; + List expandedExpressionList = expression.ResolveNames(target); foreach (MshExpression ex in expandedExpressionList) { - retVal.Add (new MshResolvedExpressionParameterAssociation (par, ex)); + retVal.Add(new MshResolvedExpressionParameterAssociation(par, ex)); } } @@ -127,12 +127,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal static List ExpandDefaultPropertySet(PSObject target, MshExpressionFactory expressionFactory) { - List retVal = new List (); + List retVal = new List(); List expandedExpressionList = PSObjectHelper.GetDefaultPropertySet(target); foreach (MshExpression ex in expandedExpressionList) { - retVal.Add (new MshResolvedExpressionParameterAssociation (null, ex)); + retVal.Add(new MshResolvedExpressionParameterAssociation(null, ex)); } return retVal; @@ -140,14 +140,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private static List GetPropertyNamesFromView(PSObject source, PSMemberViewTypes viewType) { - Collection> memberCollection = + Collection> memberCollection = PSObject.GetMemberCollection(viewType); PSMemberInfoIntegratingCollection membersToSearch = new PSMemberInfoIntegratingCollection(source, memberCollection); - ReadOnlyPSMemberInfoCollection matchedMembers = - membersToSearch.Match( "*", PSMemberTypes.Properties); + ReadOnlyPSMemberInfoCollection matchedMembers = + membersToSearch.Match("*", PSMemberTypes.Properties); List retVal = new List(); foreach (PSMemberInfo member in matchedMembers) @@ -157,7 +157,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return retVal; } - internal static List ExpandAll (PSObject target) + internal static List ExpandAll(PSObject target) { List adaptedProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Adapted); List baseProperties = GetPropertyNamesFromView(target, PSMemberViewTypes.Base); @@ -234,8 +234,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } } - } - } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/Mshexpression.cs index 124685e58..815db46c8 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Microsoft.PowerShell.Commands; @@ -17,7 +18,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// internal class MshExpressionResult { - internal MshExpressionResult (object res, MshExpression re, Exception e) + internal MshExpressionResult(object res, MshExpression re, Exception e) { _result = res; _resolvedExpression = re; @@ -63,11 +64,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// expression /// true if no further attempts should be made to resolve wildcards /// - internal MshExpression (string s, bool isResolved) + internal MshExpression(string s, bool isResolved) { - if (string.IsNullOrEmpty (s)) + if (string.IsNullOrEmpty(s)) { - throw PSTraceSource.NewArgumentNullException ("s"); + throw PSTraceSource.NewArgumentNullException("s"); } _stringValue = s; _isResolved = isResolved; @@ -82,7 +83,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException ("scriptBlock"); + throw PSTraceSource.NewArgumentNullException("scriptBlock"); } _script = scriptBlock; } @@ -92,46 +93,46 @@ namespace Microsoft.PowerShell.Commands.Internal.Format get { return _script; } } - public override string ToString () + public override string ToString() { if (_script != null) - return _script.ToString (); + return _script.ToString(); return _stringValue; } - internal List ResolveNames (PSObject target) + internal List ResolveNames(PSObject target) { - return ResolveNames (target, true); + return ResolveNames(target, true); } internal bool HasWildCardCharacters { get { - if (this._script != null) + if (_script != null) return false; - return WildcardPattern.ContainsWildcardCharacters (this._stringValue); + return WildcardPattern.ContainsWildcardCharacters(_stringValue); } } - internal List ResolveNames (PSObject target, bool expand) + internal List ResolveNames(PSObject target, bool expand) { - List retVal = new List (); + List retVal = new List(); - if (this._isResolved) + if (_isResolved) { - retVal.Add (this); + retVal.Add(this); return retVal; } if (_script != null) { // script block, just add it to the list and be done - MshExpression ex = new MshExpression (_script); + MshExpression ex = new MshExpression(_script); ex._isResolved = true; - retVal.Add (ex); + retVal.Add(ex); return retVal; } @@ -140,25 +141,25 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (HasWildCardCharacters) { // get the members first: this will expand the globbing on each parameter - members = target.Members.Match (this._stringValue, + members = target.Members.Match(_stringValue, PSMemberTypes.Properties | PSMemberTypes.PropertySet); } else { // we have no globbing: try an exact match, because this is quicker. - PSMemberInfo x = target.Members[this._stringValue]; - - List temp = new List (); + PSMemberInfo x = target.Members[_stringValue]; + + List temp = new List(); if (x != null) { - temp.Add (x); + temp.Add(x); } members = temp; } // we now have a list of members, we have to expand property sets // and remove duplicates - List temporaryMemberList = new List (); + List temporaryMemberList = new List(); foreach (PSMemberInfo member in members) { @@ -176,10 +177,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format for (int j = 0; j < references.Count; j++) { ReadOnlyPSMemberInfoCollection propertyMembers = - target.Properties.Match (references[j]); + target.Properties.Match(references[j]); for (int jj = 0; jj < propertyMembers.Count; jj++) { - temporaryMemberList.Add (propertyMembers[jj]); + temporaryMemberList.Add(propertyMembers[jj]); } } } @@ -188,22 +189,22 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // it can be a property if (member is PSPropertyInfo) { - temporaryMemberList.Add (member); + temporaryMemberList.Add(member); } } - Hashtable hash = new Hashtable (); + Hashtable hash = new Hashtable(); // build the list of unique values: remove the possible duplicates // from property set expansion foreach (PSMemberInfo m in temporaryMemberList) { - if (!hash.ContainsKey (m.Name)) + if (!hash.ContainsKey(m.Name)) { MshExpression ex = new MshExpression(m.Name); ex._isResolved = true; - retVal.Add (ex); + retVal.Add(ex); hash.Add(m.Name, null); } } @@ -211,31 +212,31 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return retVal; } - internal List GetValues (PSObject target) + internal List GetValues(PSObject target) { - return GetValues (target, true, true); + return GetValues(target, true, true); } - internal List GetValues (PSObject target, bool expand, bool eatExceptions) + internal List GetValues(PSObject target, bool expand, bool eatExceptions) { - List retVal = new List (); + List retVal = new List(); // process the script case if (_script != null) { - MshExpression scriptExpression = new MshExpression (_script); - MshExpressionResult r = scriptExpression.GetValue (target, eatExceptions); - retVal.Add (r); + MshExpression scriptExpression = new MshExpression(_script); + MshExpressionResult r = scriptExpression.GetValue(target, eatExceptions); + retVal.Add(r); return retVal; } // process the expression - List resolvedExpressionList = this.ResolveNames (target, expand); + List resolvedExpressionList = this.ResolveNames(target, expand); foreach (MshExpression re in resolvedExpressionList) { - MshExpressionResult r = re.GetValue (target, eatExceptions); - retVal.Add (r); + MshExpressionResult r = re.GetValue(target, eatExceptions); + retVal.Add(r); } return retVal; @@ -243,7 +244,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format #region Private Members - private MshExpressionResult GetValue (PSObject target, bool eatExceptions) + private MshExpressionResult GetValue(PSObject target, bool eatExceptions) { try { @@ -252,12 +253,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (_script != null) { result = _script.DoInvokeReturnAsIs( - useLocalScope: true, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: target, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: Utils.EmptyArray()); + useLocalScope: true, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, + dollarUnder: target, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: Utils.EmptyArray()); } else { @@ -269,7 +270,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format result = member.Value; } - return new MshExpressionResult (result, this, null); + return new MshExpressionResult(result, this, null); } catch (RuntimeException e) { @@ -283,12 +284,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format } } } - - + + // private members - string _stringValue; - ScriptBlock _script = null; - bool _isResolved = false; + private string _stringValue; + private ScriptBlock _script = null; + private bool _isResolved = false; #endregion Private Members } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/format-default/format-default.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/format-default/format-default.cs index 55a9f9455..5d75d4dde 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/format-default/format-default.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/format-default/format-default.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using Microsoft.PowerShell.Commands.Internal.Format; @@ -10,15 +11,15 @@ namespace Microsoft.PowerShell.Commands /// /// implementation for the format-default command /// - [Cmdlet ("Format", "Default")] + [Cmdlet("Format", "Default")] public class FormatDefaultCommand : FrontEndCommandBase { /// /// constructor to set the inner command /// - public FormatDefaultCommand () + public FormatDefaultCommand() { - this.implementation = new InnerFormatShapeCommand (FormatShape.Undefined); + this.implementation = new InnerFormatShapeCommand(FormatShape.Undefined); } } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/ConsoleLineOutput.cs index ebcbc876a..04797cc2e 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -19,9 +19,9 @@ using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; // interfaces for host interaction + namespace Microsoft.PowerShell.Commands.Internal.Format { - #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE /// @@ -150,8 +150,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal sealed class ConsoleLineOutput : LineOutput { #region tracer - [TraceSource ("ConsoleLineOutput", "ConsoleLineOutput")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer ("ConsoleLineOutput", "ConsoleLineOutput"); + [TraceSource("ConsoleLineOutput", "ConsoleLineOutput")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer #region LineOutput implementation @@ -165,7 +165,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format get { CheckStopProcessing(); - PSHostRawUserInterface raw = this.console.RawUI; + PSHostRawUserInterface raw = _console.RawUI; // IMPORTANT NOTE: we subtract one because // we want to make sure the console's last column @@ -175,14 +175,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format try { - return forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width; + return _forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width; } catch (HostException) { //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } - return forceNewLine ? this.fallbackRawConsoleColumnNumber - 1 : this.fallbackRawConsoleColumnNumber; + return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber; } } @@ -196,7 +196,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format get { CheckStopProcessing(); - PSHostRawUserInterface raw = this.console.RawUI; + PSHostRawUserInterface raw = _console.RawUI; try { @@ -207,7 +207,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format //thrown when external host rawui is not implemented, in which case //we will fallback to the default value. } - return this.fallbackRawConsoleRowNumber; + return _fallbackRawConsoleRowNumber; } } @@ -215,13 +215,13 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// write a line to the output device /// /// line to write - internal override void WriteLine (string s) + internal override void WriteLine(string s) { CheckStopProcessing(); // delegate the action to the helper, // that will properly break the string into // screen lines - this.writeLineHelper.WriteLine (s, this.ColumnNumber); + _writeLineHelper.WriteLine(s, this.ColumnNumber); } internal override DisplayCells DisplayCells @@ -245,15 +245,15 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// PSHostUserInterface to wrap /// true if we require prompting for page breaks /// error context to throw exceptions - internal ConsoleLineOutput (PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) + internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) { if (hostConsole == null) - throw PSTraceSource.NewArgumentNullException ("hostConsole"); + throw PSTraceSource.NewArgumentNullException("hostConsole"); if (errorContext == null) - throw PSTraceSource.NewArgumentNullException ("errorContext"); + throw PSTraceSource.NewArgumentNullException("errorContext"); - this.console = hostConsole; - this.errorContext = errorContext; + _console = hostConsole; + _errorContext = errorContext; if (paging) { @@ -261,11 +261,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // if we need to do paging, instantiate a prompt handler // that will take care of the screen interaction string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt); - this.prompt = new PromptHandler (promptString, this); + _prompt = new PromptHandler(promptString, this); } - PSHostRawUserInterface raw = this.console.RawUI; + PSHostRawUserInterface raw = _console.RawUI; if (raw != null) { tracer.WriteLine("there is a valid raw interface"); @@ -274,21 +274,21 @@ namespace Microsoft.PowerShell.Commands.Internal.Format this._displayCellsPSHost = new DisplayCellsTest(); #else // set only if we have a valid raw interface - this._displayCellsPSHost = new DisplayCellsPSHost(raw); + _displayCellsPSHost = new DisplayCellsPSHost(raw); #endif } // instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called - WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback (this.OnWriteLine); - WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback (this.OnWrite); + WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine); + WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite); - if (forceNewLine) + if (_forceNewLine) { - this.writeLineHelper = new WriteLineHelper (/*lineWrap*/false, wl, null, this.DisplayCells); + _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, null, this.DisplayCells); } else { - this.writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells); + _writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells); } } @@ -296,45 +296,45 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// callback to be called when ILineOutput.WriteLine() is called by WriteLineHelper /// /// string to write - private void OnWriteLine (string s) + private void OnWriteLine(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif // Do any default transcription. - this.console.TranscribeResult(s); + _console.TranscribeResult(s); switch (this.WriteStream) { case WriteStreamType.Error: - this.console.WriteErrorLine(s); + _console.WriteErrorLine(s); break; case WriteStreamType.Warning: - this.console.WriteWarningLine(s); + _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: - this.console.WriteVerboseLine(s); + _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: - this.console.WriteDebugLine(s); + _console.WriteDebugLine(s); break; default: // If the host is in "transcribe only" // mode (due to an implicitly added call to Out-Default -Transcribe), // then don't call the actual host API. - if (! console.TranscribeOnly) + if (!_console.TranscribeOnly) { - this.console.WriteLine(s); + _console.WriteLine(s); } - + break; } - LineWrittenEvent (); + LineWrittenEvent(); } /// @@ -343,7 +343,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// is the same as the width of the screen buffer /// /// string to write - private void OnWrite (string s) + private void OnWrite(string s) { #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); @@ -351,66 +351,66 @@ namespace Microsoft.PowerShell.Commands.Internal.Format switch (this.WriteStream) { case WriteStreamType.Error: - this.console.WriteErrorLine(s); + _console.WriteErrorLine(s); break; case WriteStreamType.Warning: - this.console.WriteWarningLine(s); + _console.WriteWarningLine(s); break; case WriteStreamType.Verbose: - this.console.WriteVerboseLine(s); + _console.WriteVerboseLine(s); break; case WriteStreamType.Debug: - this.console.WriteDebugLine(s); + _console.WriteDebugLine(s); break; default: - this.console.Write(s); + _console.Write(s); break; } - LineWrittenEvent (); + LineWrittenEvent(); } /// /// called when a line was written to console /// - private void LineWrittenEvent () + private void LineWrittenEvent() { // check to avoid reeentrancy from the prompt handler // writing during the PropmtUser() call - if (this.disableLineWrittenEvent) + if (_disableLineWrittenEvent) return; // if there is no promting, we are done - if (this.prompt == null) + if (_prompt == null) return; // increment the count of lines written to the screen - this.linesWritten++; + _linesWritten++; // check if we need to put out a prompt if (this.NeedToPrompt) { // put out the prompt - this.disableLineWrittenEvent = true; - PromptHandler.PromptResponse response = this.prompt.PromptUser(this.console); - this.disableLineWrittenEvent = false; + _disableLineWrittenEvent = true; + PromptHandler.PromptResponse response = _prompt.PromptUser(_console); + _disableLineWrittenEvent = false; switch (response) { case PromptHandler.PromptResponse.NextPage: { // reset the counter, since we are starting a new page - this.linesWritten = 0; + _linesWritten = 0; } break; case PromptHandler.PromptResponse.NextLine: { // roll back the counter by one, since we allow one more line - this.linesWritten--; + _linesWritten--; } break; case PromptHandler.PromptResponse.Quit: @@ -418,8 +418,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // HaltCommandException will cause the command // to stop, but not be reported as an error. throw new HaltCommandException(); - } - + } } } @@ -442,7 +441,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // the prompt will occupy some lines, so we need to subtract them form the total // screen line count - int computedPromptLines = this.prompt.ComputePromptLines (this.DisplayCells, this.ColumnNumber); + int computedPromptLines = _prompt.ComputePromptLines(this.DisplayCells, this.ColumnNumber); int availableLines = this.RowNumber - computedPromptLines; if (availableLines <= 0) @@ -452,11 +451,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format return false; } - return this.linesWritten >= availableLines; + return _linesWritten >= availableLines; } } -#region Private Members + #region Private Members /// /// object to manage prompting /// @@ -472,8 +471,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format if (string.IsNullOrEmpty(s)) throw PSTraceSource.NewArgumentNullException("s"); - promptString = s; - callingCmdlet = cmdlet; + _promptString = s; + _callingCmdlet = cmdlet; } /// @@ -485,8 +484,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format internal int ComputePromptLines(DisplayCells displayCells, int cols) { // split the prompt string into lines - this.actualPrompt = StringManipulationHelper.GenerateLines(displayCells, this.promptString, cols, cols); - return this.actualPrompt.Count; + _actualPrompt = StringManipulationHelper.GenerateLines(displayCells, _promptString, cols, cols); + return _actualPrompt.Count; } /// @@ -509,17 +508,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // write out the prompt line(s). The last one will not have a new line // at the end because we leave the prompt at the end of the line - for (int k = 0; k < this.actualPrompt.Count; k++) + for (int k = 0; k < _actualPrompt.Count; k++) { - if (k < (this.actualPrompt.Count - 1)) - console.WriteLine(this.actualPrompt[k]); // intermediate line(s) + if (k < (_actualPrompt.Count - 1)) + console.WriteLine(_actualPrompt[k]); // intermediate line(s) else - console.Write(this.actualPrompt[k]); // last line + console.Write(_actualPrompt[k]); // last line } while (true) { - callingCmdlet.CheckStopProcessing(); + _callingCmdlet.CheckStopProcessing(); KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho); char key = ki.Character; if (key == 'q' || key == 'Q') @@ -540,25 +539,23 @@ namespace Microsoft.PowerShell.Commands.Internal.Format console.WriteLine(); return PromptResponse.NextLine; } - } } /// /// cached string(s) valid during a sequence of ComputePromptLines()/PromptUser() /// - private StringCollection actualPrompt; + private StringCollection _actualPrompt; /// /// prompt string as passed at initialization /// - private string promptString; + private string _promptString; /// /// The cmdlet that uses this prompt helper /// - private ConsoleLineOutput callingCmdlet = null; - + private ConsoleLineOutput _callingCmdlet = null; } /// @@ -566,40 +563,40 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// usable width to N-1 (e.g. 80-1) and forcing a call /// to WriteLine() /// - private bool forceNewLine = true; + private bool _forceNewLine = true; /// /// use this if IRawConsole is null; /// - private int fallbackRawConsoleColumnNumber = 80; + private int _fallbackRawConsoleColumnNumber = 80; /// /// use this if IRawConsole is null; /// - private int fallbackRawConsoleRowNumber = 40; + private int _fallbackRawConsoleRowNumber = 40; - private WriteLineHelper writeLineHelper; + private WriteLineHelper _writeLineHelper; /// /// handler to prompt the user for page breaks /// if this handler is not null, we have promting /// - private PromptHandler prompt = null; + private PromptHandler _prompt = null; /// /// conter for the # of lines written when prompting is on /// - private long linesWritten = 0; + private long _linesWritten = 0; /// /// flag to avoid renetrancy on promting /// - private bool disableLineWrittenEvent = false; + private bool _disableLineWrittenEvent = false; /// /// refecence to the PSHostUserInterface interface we use /// - private PSHostUserInterface console = null; + private PSHostUserInterface _console = null; /// /// Msh host specific string manipulation helper @@ -609,8 +606,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format /// /// reference to error context to throw Msh exceptions /// - private TerminatingErrorContext errorContext = null; + private TerminatingErrorContext _errorContext = null; -#endregion + #endregion } } diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/OutConsole.cs index d313bb712..1af735639 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-console/OutConsole.cs @@ -29,7 +29,7 @@ namespace Microsoft.PowerShell.Commands /// /// input PSObject /// - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// /// This parameter specifies the current pipeline object @@ -37,16 +37,16 @@ namespace Microsoft.PowerShell.Commands [Parameter(ValueFromPipeline = true)] public PSObject InputObject { - set { this.inputObject = value; } - get { return this.inputObject; } + set { _inputObject = value; } + get { return _inputObject; } } /// /// /// Do nothing /// - protected override void ProcessRecord() - { + protected override void ProcessRecord() + { // explicitely overriden: // do not do any processing } @@ -95,7 +95,7 @@ namespace Microsoft.PowerShell.Commands mrt.MergeUnclaimedPreviousErrorResults = true; } - savedTranscribeOnly = Host.UI.TranscribeOnly; + _savedTranscribeOnly = Host.UI.TranscribeOnly; if (Transcript) { Host.UI.TranscribeOnly = true; @@ -107,7 +107,7 @@ namespace Microsoft.PowerShell.Commands if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList != null) { - outVarResults = new ArrayList(); + _outVarResults = new ArrayList(); } } @@ -123,18 +123,18 @@ namespace Microsoft.PowerShell.Commands // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. - if (outVarResults != null) + if (_outVarResults != null) { Object inputObjectBase = PSObject.Base(InputObject); // Ignore errors and formatting records, as those can't be captured if ( (inputObjectBase != null) && - (! (inputObjectBase is ErrorRecord)) && - (! inputObjectBase.GetType().FullName.StartsWith( + (!(inputObjectBase is ErrorRecord)) && + (!inputObjectBase.GetType().FullName.StartsWith( "Microsoft.PowerShell.Commands.Internal.Format", StringComparison.OrdinalIgnoreCase))) { - outVarResults.Add(InputObject); + _outVarResults.Add(InputObject); } } @@ -148,26 +148,26 @@ namespace Microsoft.PowerShell.Commands { // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. - if ((outVarResults != null) && (outVarResults.Count > 0)) + if ((_outVarResults != null) && (_outVarResults.Count > 0)) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Clear(); - foreach (Object item in outVarResults) + foreach (Object item in _outVarResults) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Add(item); } - outVarResults = null; + _outVarResults = null; } base.EndProcessing(); if (Transcript) { - Host.UI.TranscribeOnly = savedTranscribeOnly; + Host.UI.TranscribeOnly = _savedTranscribeOnly; } } - ArrayList outVarResults = null; - bool savedTranscribeOnly = false; + private ArrayList _outVarResults = null; + private bool _savedTranscribeOnly = false; } /// @@ -181,7 +181,7 @@ namespace Microsoft.PowerShell.Commands /// /// non positional parameter to specify paging /// - private bool paging; + private bool _paging; #endregion @@ -192,7 +192,7 @@ namespace Microsoft.PowerShell.Commands { this.implementation = new OutputManagerInner(); } - + /// /// optional, non positional parameter to specify paging /// FALSE: names only @@ -201,8 +201,8 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter Paging { - get { return this.paging; } - set { this.paging = value; } + get { return _paging; } + set { _paging = value; } } /// @@ -211,10 +211,10 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { PSHostUserInterface console = this.Host.UI; - ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, this.paging, new TerminatingErrorContext(this)); + ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, _paging, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; base.BeginProcessing(); - } + } } } \ No newline at end of file diff --git a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-textInterface/OutTextInterface.cs b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-textInterface/OutTextInterface.cs index ff18f91ae..b84c55768 100644 --- a/src/System.Management.Automation/commands/utility/FormatAndOutput/out-textInterface/OutTextInterface.cs +++ b/src/System.Management.Automation/commands/utility/FormatAndOutput/out-textInterface/OutTextInterface.cs @@ -12,13 +12,12 @@ using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { - /// /// implementation for the out-lineoutput command /// it provides a wrapper for the OutCommandInner class, /// which is the general purpose output command /// - [Cmdlet ("Out", "LineOutput")] + [Cmdlet("Out", "LineOutput")] public class OutLineOutputCommand : FrontEndCommandBase { /// @@ -28,69 +27,69 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, Position = 0)] public object LineOutput { - get { return lineOutput; } - set { lineOutput = value; } + get { return _lineOutput; } + set { _lineOutput = value; } } - private object lineOutput = null; + private object _lineOutput = null; /// /// set inner command /// - public OutLineOutputCommand () + public OutLineOutputCommand() { - this.implementation = new OutCommandInner (); + this.implementation = new OutCommandInner(); } /// /// /// - protected override void BeginProcessing () + protected override void BeginProcessing() { - if (this.lineOutput == null) + if (_lineOutput == null) { - ProcessNullLineOutput (); + ProcessNullLineOutput(); } - LineOutput lo = this.lineOutput as LineOutput; + LineOutput lo = _lineOutput as LineOutput; if (lo == null) { - ProcessWrongTypeLineOutput (this.lineOutput); + ProcessWrongTypeLineOutput(_lineOutput); } ((OutCommandInner)this.implementation).LineOutput = lo; - base.BeginProcessing (); + base.BeginProcessing(); } - private void ProcessNullLineOutput () + private void ProcessNullLineOutput() { string msg = StringUtil.Format(FormatAndOut_out_xxx.OutLineOutput_NullLineOutputParameter); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentNullException("LineOutput"), "OutLineOutputNullLineOutputParameter", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); } - private void ProcessWrongTypeLineOutput (object obj) + private void ProcessWrongTypeLineOutput(object obj) { string msg = StringUtil.Format(FormatAndOut_out_xxx.OutLineOutput_InvalidLineOutputParameterType, obj.GetType().FullName, typeof(LineOutput).FullName); - ErrorRecord errorRecord = new ErrorRecord ( - new InvalidCastException (), + ErrorRecord errorRecord = new ErrorRecord( + new InvalidCastException(), "OutLineOutputInvalidLineOutputParameterType", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - this.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); } } } diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index f2dd3dc65..15b1a465e 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -42,7 +43,7 @@ namespace System.Management.Automation /// internal AliasInfo(string name, string definition, ExecutionContext context) : base(name, CommandTypes.Alias) { - this._definition = definition; + _definition = definition; this.Context = context; if (context != null) @@ -80,26 +81,26 @@ namespace System.Management.Automation /// /// internal AliasInfo( - string name, - string definition, + string name, + string definition, ExecutionContext context, ScopedItemOptions options) : base(name, CommandTypes.Alias) { - this._definition = definition; + _definition = definition; this.Context = context; - this.options = options; + _options = options; if (context != null) { this.Module = context.SessionState.Internal.Module; } } - + #endregion ctor internal override HelpCategory HelpCategory { - get { return HelpCategory.Alias; } + get { return HelpCategory.Alias; } } /// @@ -163,7 +164,7 @@ namespace System.Management.Automation List cyclePrevention = new List(); cyclePrevention.Add(Name); - string commandNameToResolve = this._definition; + string commandNameToResolve = _definition; result = ReferencedCommand; while (result != null && result.CommandType == CommandTypes.Alias) { @@ -191,7 +192,7 @@ namespace System.Management.Automation // points to, remember the defintion so that we can // provide better error reporting. - unresolvedCommandName = commandNameToResolve; + _unresolvedCommandName = commandNameToResolve; } } @@ -231,8 +232,8 @@ namespace System.Management.Automation { // Check to see if the variable is writable - if ((options & ScopedItemOptions.Constant ) != 0 || - (!force && (options & ScopedItemOptions.ReadOnly) != 0)) + if ((_options & ScopedItemOptions.Constant) != 0 || + (!force && (_options & ScopedItemOptions.ReadOnly) != 0)) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -244,8 +245,7 @@ namespace System.Management.Automation throw e; } - this._definition = definition; - + _definition = definition; } // SetDefinition /// @@ -260,7 +260,7 @@ namespace System.Management.Automation { get { - return options; + return _options; } set @@ -286,7 +286,7 @@ namespace System.Management.Automation // Check to see if the variable is constant, if so // throw an exception because the options cannot be changed. - if ((options & ScopedItemOptions.Constant) != 0) + if ((_options & ScopedItemOptions.Constant) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -301,7 +301,7 @@ namespace System.Management.Automation // Check to see if the variable is readonly, if so // throw an exception because the options cannot be changed. - if (!force && (options & ScopedItemOptions.ReadOnly) != 0) + if (!force && (_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -333,7 +333,7 @@ namespace System.Management.Automation } if ((newOptions & ScopedItemOptions.AllScope) == 0 && - (options & ScopedItemOptions.AllScope) != 0) + (_options & ScopedItemOptions.AllScope) != 0) { // user is trying to remove the AllScope option from the alias. // Do not allow this (as per spec). @@ -348,9 +348,9 @@ namespace System.Management.Automation throw e; } - options = newOptions; + _options = newOptions; } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// /// Gets or sets the description for the alias @@ -359,15 +359,15 @@ namespace System.Management.Automation { get { - return description; + return _description; } set { - description = value; - } + _description = value; + } } - private string description = String.Empty; + private string _description = String.Empty; /// @@ -381,10 +381,10 @@ namespace System.Management.Automation { get { - return unresolvedCommandName; + return _unresolvedCommandName; } } - private string unresolvedCommandName; + private string _unresolvedCommandName; /// /// The objects output from an alias are the objects output from the resolved diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index 1fd87b33a..044dcaef9 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Diagnostics; using System.Collections.ObjectModel; @@ -53,24 +54,24 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("context"); } - this.path = path; - this.extension = System.IO.Path.GetExtension(path); - this.context = context; + _path = path; + _extension = System.IO.Path.GetExtension(path); + _context = context; } // ApplicationInfo ctor - private ExecutionContext context; + private ExecutionContext _context; #endregion ctor - /// + /// /// Gets the path for the application file. /// public string Path { get { - return path; + return _path; } }// Path - private string path = String.Empty; + private string _path = String.Empty; /// /// Gets the extension of the application file. @@ -79,10 +80,10 @@ namespace System.Management.Automation { get { - return extension; + return _extension; } } // Extension - private string extension = String.Empty; + private string _extension = String.Empty; /// /// Gets the path of the application file. @@ -112,7 +113,7 @@ namespace System.Management.Automation { if (_version == null) { - FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(path); + FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(_path); _version = new Version(versionInfo.ProductMajorPart, versionInfo.ProductMinorPart, versionInfo.ProductBuildPart, versionInfo.ProductPrivatePart); } @@ -127,9 +128,9 @@ namespace System.Management.Automation /// public override SessionStateEntryVisibility Visibility { - get + get { - return context.EngineSessionState.CheckApplicationVisibility(path); + return _context.EngineSessionState.CheckApplicationVisibility(_path); } set { throw PSTraceSource.NewNotImplementedException(); } } @@ -150,6 +151,6 @@ namespace System.Management.Automation return _outputType; } } - ReadOnlyCollection _outputType = null; + private ReadOnlyCollection _outputType = null; } // ApplicationInfo } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 8c26c7cd0..1716c8dd9 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -62,12 +62,12 @@ namespace System.Management.Automation // No Conversion should be done. if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference))) { - object temp; + object temp; PSObject mshObject = result as PSObject; if (mshObject != null) temp = mshObject.BaseObject; else - temp = result; + temp = result; PSReference reference = temp as PSReference; @@ -84,7 +84,7 @@ namespace System.Management.Automation if (mshObject != null) temp = mshObject.BaseObject; else - temp = result; + temp = result; // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. PSReference reference = temp as PSReference; @@ -141,7 +141,7 @@ namespace System.Management.Automation } } - result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture); + result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture); // Do validation of invalid direct variable assignments which are allowed to // be used for parameters. @@ -153,7 +153,7 @@ namespace System.Management.Automation // during variable assignment (here) - "Ignore" is blocked during variable retrieval. if (_convertTypes[i] == typeof(ActionPreference)) { - ActionPreference resultPreference = (ActionPreference) result; + ActionPreference resultPreference = (ActionPreference)result; if (resultPreference == ActionPreference.Suspend) { @@ -163,7 +163,7 @@ namespace System.Management.Automation } } } - catch(PSInvalidCastException e) + catch (PSInvalidCastException e) { throw new ArgumentTransformationMetadataException(e.Message, e); } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 01f17989e..8cb3aa7b6 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -123,7 +123,7 @@ namespace System.Management.Automation /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public abstract class ValidateArgumentsAttribute: CmdletMetadataAttribute + public abstract class ValidateArgumentsAttribute : CmdletMetadataAttribute { /// /// Overridden by subclasses to implement the validation of the parameter arguments @@ -160,7 +160,7 @@ namespace System.Management.Automation { Validate(o, engineIntrinsics); } - + /// /// Initializes a new instance of a class derived from ValidateArgumentsAttribute /// @@ -209,12 +209,12 @@ namespace System.Management.Automation /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public abstract class ValidateEnumeratedArgumentsAttribute: ValidateArgumentsAttribute + public abstract class ValidateEnumeratedArgumentsAttribute : ValidateArgumentsAttribute { /// /// Initializes a new instance of a class derived from ValidateEnumeratedArgumentsAttribute /// - protected ValidateEnumeratedArgumentsAttribute(): base() + protected ValidateEnumeratedArgumentsAttribute() : base() { } /// @@ -279,10 +279,10 @@ namespace System.Management.Automation /// /// To specify RunAs behavior for the class /// /// - public enum DSCResourceRunAsCredential + public enum DSCResourceRunAsCredential { /// Default is same as optional. - Default , + Default, /// /// PsDscRunAsCredential can not be used for this DSC Resource /// @@ -294,20 +294,20 @@ namespace System.Management.Automation /// /// PsDscRunAsCredential can or can not be specified /// - Optional = Default , - } + Optional = Default, + } /// /// Indicates the class defines a DSC resource. /// [AttributeUsage(AttributeTargets.Class)] public class DscResourceAttribute : CmdletMetadataAttribute - { + { /// /// To specify RunAs Behavior for the resource. /// - public DSCResourceRunAsCredential RunAsCredential { get; set; } - } + public DSCResourceRunAsCredential RunAsCredential { get; set; } + } /// /// When specified on a property or field of a DSC Resource, the property @@ -353,14 +353,14 @@ namespace System.Management.Automation /// Gets and sets the cmdlet default parameter set /// public string DefaultParameterSetName - { - get { return defaultParameterSetName; } + { + get { return _defaultParameterSetName; } set { - defaultParameterSetName = value; + _defaultParameterSetName = value; } } - private string defaultParameterSetName; + private string _defaultParameterSetName; /// /// Gets and sets a Boolean value that indicates the Cmdlet supports ShouldProcess. By default @@ -368,13 +368,13 @@ namespace System.Management.Automation /// public bool SupportsShouldProcess { - get { return supportsShouldProcess; } + get { return _supportsShouldProcess; } set { - supportsShouldProcess = value; + _supportsShouldProcess = value; } } - private bool supportsShouldProcess = false; + private bool _supportsShouldProcess = false; /// /// Gets and sets a Boolean value that indicates the Cmdlet supports Paging. By default @@ -382,13 +382,13 @@ namespace System.Management.Automation /// public bool SupportsPaging { - get { return supportsPaging; } + get { return _supportsPaging; } set { - supportsPaging = value; + _supportsPaging = value; } } - private bool supportsPaging = false; + private bool _supportsPaging = false; /// /// Gets and sets a Boolean value that indicates the Cmdlet supports Transactions. By default @@ -396,19 +396,19 @@ namespace System.Management.Automation /// public bool SupportsTransactions { - get { return supportsTransactions; } + get { return _supportsTransactions; } set { #if !CORECLR - supportsTransactions = value; + _supportsTransactions = value; #else // Disable 'SupportsTransactions' in CoreCLR // No transaction supported on CSS due to the lack of System.Transactions namespace - supportsTransactions = false; + _supportsTransactions = false; #endif } } - private bool supportsTransactions = false; + private bool _supportsTransactions = false; /// /// Gets and sets a ConfirmImpact value that indicates @@ -418,13 +418,13 @@ namespace System.Management.Automation /// public ConfirmImpact ConfirmImpact { - get { return confirmImpact; } + get { return _confirmImpact; } set { - confirmImpact = value; + _confirmImpact = value; } } - private ConfirmImpact confirmImpact = ConfirmImpact.Medium; + private ConfirmImpact _confirmImpact = ConfirmImpact.Medium; /// /// Gets and sets a HelpUri value that indicates @@ -435,13 +435,13 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string HelpUri { - get { return helpUri; } + get { return _helpUri; } set { - helpUri = value; + _helpUri = value; } } - private string helpUri = String.Empty; + private string _helpUri = String.Empty; /// /// Gets and sets the RemotingBehavior value that declares how this cmdlet should interact @@ -449,13 +449,13 @@ namespace System.Management.Automation /// public RemotingCapability RemotingCapability { - get { return remotingCapability; } + get { return _remotingCapability; } set { - remotingCapability = value; + _remotingCapability = value; } } - private RemotingCapability remotingCapability = RemotingCapability.PowerShell; + private RemotingCapability _remotingCapability = RemotingCapability.PowerShell; } /// @@ -464,18 +464,18 @@ namespace System.Management.Automation [AttributeUsage(AttributeTargets.Class)] public sealed class CmdletAttribute : CmdletCommonMetadataAttribute { - private string nounName; - private string verbName; + private string _nounName; + private string _verbName; /// /// Gets the cmdlet noun /// - public string NounName { get { return nounName; } } + public string NounName { get { return _nounName; } } /// /// Gets the cmdlet verb /// - public string VerbName { get { return verbName; } } + public string VerbName { get { return _verbName; } } /// /// Initializes a new instance of the CmdletAttribute class @@ -487,7 +487,7 @@ namespace System.Management.Automation { //NounName,VerbName have to be Non-Null strings if (string.IsNullOrEmpty(nounName)) - { + { throw PSTraceSource.NewArgumentException("nounName"); } @@ -496,8 +496,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("verbName"); } - this.nounName = nounName; - this.verbName = verbName; + _nounName = nounName; + _verbName = verbName; } } @@ -534,7 +534,7 @@ namespace System.Management.Automation /// internal OutputTypeAttribute(Type type) { - Type = new[] {new PSTypeName(type)}; + Type = new[] { new PSTypeName(type) }; } /// @@ -542,7 +542,7 @@ namespace System.Management.Automation /// internal OutputTypeAttribute(string typeName) { - Type = new[] {new PSTypeName(typeName)}; + Type = new[] { new PSTypeName(typeName) }; } @@ -608,7 +608,7 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ParameterSetName { - get { return _parameterSetName ?? (_parameterSetName = new [] { ParameterAttribute.AllParameterSets }); } + get { return _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets }); } set { _parameterSetName = value; } } private string[] _parameterSetName; @@ -630,9 +630,9 @@ namespace System.Management.Automation /// Declares an alternative name for a parameter /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] - public sealed class AliasAttribute: ParsingBaseAttribute + public sealed class AliasAttribute : ParsingBaseAttribute { - internal string [] aliasNames; + internal string[] aliasNames; /// /// Gets the alias names passed to the constructor @@ -652,14 +652,13 @@ namespace System.Management.Automation /// for invalid arguments public AliasAttribute(params string[] aliasNames) { - if (aliasNames==null) + if (aliasNames == null) { throw PSTraceSource.NewArgumentNullException("aliasNames"); } this.aliasNames = aliasNames; } - } /// @@ -679,25 +678,25 @@ namespace System.Management.Automation public ParameterAttribute() { } - private int position = int.MinValue; - private string parameterSetName = ParameterAttribute.AllParameterSets; - private bool mandatory = false; + private int _position = int.MinValue; + private string _parameterSetName = ParameterAttribute.AllParameterSets; + private bool _mandatory = false; - private bool valueFromRemainingArguments = false; + private bool _valueFromRemainingArguments = false; - private string helpMessage; - private string helpMessageBaseName; - private string helpMessageResourceId; + private string _helpMessage; + private string _helpMessageBaseName; + private string _helpMessageResourceId; /// /// Gets and sets the parameter position. If not set, the parameter is named. /// public int Position { - get { return position; } + get { return _position; } set { - position = value; + _position = value; } } @@ -707,13 +706,13 @@ namespace System.Management.Automation /// public string ParameterSetName { - get { return parameterSetName; } + get { return _parameterSetName; } set { - parameterSetName = value; - if (String.IsNullOrEmpty(parameterSetName)) + _parameterSetName = value; + if (String.IsNullOrEmpty(_parameterSetName)) { - parameterSetName = ParameterAttribute.AllParameterSets; + _parameterSetName = ParameterAttribute.AllParameterSets; } } } @@ -724,28 +723,28 @@ namespace System.Management.Automation /// public bool Mandatory { - get { return mandatory; } + get { return _mandatory; } set { - mandatory = value; + _mandatory = value; } } - bool valueFromPipeline; + private bool _valueFromPipeline; /// /// Gets and sets a flag that specifies that this parameter can take values /// from the incoming pipeline object. When it is not specified, false is assumed. /// public bool ValueFromPipeline { - get { return valueFromPipeline; } + get { return _valueFromPipeline; } set { - valueFromPipeline = value; + _valueFromPipeline = value; } } - bool valueFromPipelineByPropertyName; + private bool _valueFromPipelineByPropertyName; /// /// Gets and sets a flag that specifies that this parameter can take values from a property /// in the incoming pipeline object with the same name as the parameter. When it @@ -753,10 +752,10 @@ namespace System.Management.Automation /// public bool ValueFromPipelineByPropertyName { - get { return valueFromPipelineByPropertyName; } + get { return _valueFromPipelineByPropertyName; } set { - valueFromPipelineByPropertyName = value; + _valueFromPipelineByPropertyName = value; } } @@ -767,10 +766,10 @@ namespace System.Management.Automation /// public bool ValueFromRemainingArguments { - get { return valueFromRemainingArguments; } + get { return _valueFromRemainingArguments; } set { - valueFromRemainingArguments = value; + _valueFromRemainingArguments = value; } } @@ -782,7 +781,7 @@ namespace System.Management.Automation { get { - return helpMessage; + return _helpMessage; } set { @@ -790,7 +789,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value"); } - helpMessage = value; + _helpMessage = value; } } @@ -803,7 +802,7 @@ namespace System.Management.Automation { get { - return helpMessageBaseName; + return _helpMessageBaseName; } set { @@ -811,7 +810,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value"); } - helpMessageBaseName = value; + _helpMessageBaseName = value; } } @@ -824,7 +823,7 @@ namespace System.Management.Automation { get { - return helpMessageResourceId; + return _helpMessageResourceId; } set { @@ -832,7 +831,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value"); } - helpMessageResourceId = value; + _helpMessageResourceId = value; } } @@ -867,7 +866,7 @@ namespace System.Management.Automation /// Creates a new PSTypeNameAttribute /// /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public PSTypeNameAttribute(string psTypeName) { if (string.IsNullOrEmpty(psTypeName)) @@ -926,20 +925,20 @@ namespace System.Management.Automation /// Validates that the length of each parameter argument's Length falls in the range /// specified by MinLength and MaxLength /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property )] - public sealed class ValidateLengthAttribute: ValidateEnumeratedArgumentsAttribute + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribute { - private int minLength; + private int _minLength; /// /// Gets the attribute's minimum length /// - public int MinLength { get { return minLength; } } + public int MinLength { get { return _minLength; } } - private int maxLength; + private int _maxLength; /// /// Gets the attribute's maximum length /// - public int MaxLength { get { return maxLength; } } + public int MaxLength { get { return _maxLength; } } /// /// Validates that the length of each parameter argument's Length falls in the range @@ -960,18 +959,18 @@ namespace System.Management.Automation int len = objectString.Length; - if (len < this.minLength) + if (len < _minLength) { throw new ValidationMetadataException("ValidateLengthMinLengthFailure", null, Metadata.ValidateLengthMinLengthFailure, - this.minLength, len); + _minLength, len); } - if (len > this.maxLength) + if (len > _maxLength) { throw new ValidationMetadataException("ValidateLengthMaxLengthFailure", null, Metadata.ValidateLengthMaxLengthFailure, - this.maxLength, len); + _maxLength, len); } } @@ -998,38 +997,38 @@ namespace System.Management.Automation throw new ValidationMetadataException("ValidateLengthMaxLengthSmallerThanMinLength", null, Metadata.ValidateLengthMaxLengthSmallerThanMinLength); } - this.minLength = minLength; - this.maxLength = maxLength; + _minLength = minLength; + _maxLength = maxLength; } } - + /// /// Validates that each parameter argument falls in the range /// specified by MinRange and MaxRange /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class ValidateRangeAttribute: ValidateEnumeratedArgumentsAttribute + public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribute { - private object minRange; + private object _minRange; /// /// Gets the attribute's minimum range /// - public object MinRange { get { return minRange; } } - private IComparable minComparable; - - private object maxRange; + public object MinRange { get { return _minRange; } } + private IComparable _minComparable; + + private object _maxRange; /// /// Gets the attribute's maximum range /// - public object MaxRange { get { return maxRange; } } - private IComparable maxComparable; + public object MaxRange { get { return _maxRange; } } + private IComparable _maxComparable; /// /// The range values and the value to validate will all be converted to the promoted type. /// If minRange and maxRange are the same type, /// - private Type promotedType; + private Type _promotedType; /// /// Validates that each parameter argument falls in the range @@ -1059,10 +1058,10 @@ namespace System.Management.Automation // minRange and maxRange have the same type, so we just need // to compare to one of them - if (element.GetType() != promotedType) + if (element.GetType() != _promotedType) { object resultValue; - if (LanguagePrimitives.TryConvertTo(element, promotedType, out resultValue)) + if (LanguagePrimitives.TryConvertTo(element, _promotedType, out resultValue)) { element = resultValue; } @@ -1070,23 +1069,23 @@ namespace System.Management.Automation { throw new ValidationMetadataException("ValidationRangeElementType", null, Metadata.ValidateRangeElementType, - element.GetType().Name, this.minRange.GetType().Name); + element.GetType().Name, _minRange.GetType().Name); } } // They are the same type and are all IComparable, so this should not throw - if (minComparable.CompareTo(element) > 0) + if (_minComparable.CompareTo(element) > 0) { throw new ValidationMetadataException("ValidateRangeTooSmall", null, Metadata.ValidateRangeSmallerThanMinRangeFailure, - element.ToString(), this.minRange.ToString()); + element.ToString(), _minRange.ToString()); } - if(maxComparable.CompareTo(element) < 0) + if (_maxComparable.CompareTo(element) < 0) { throw new ValidationMetadataException("ValidateRangeTooBig", null, Metadata.ValidateRangeGreaterThanMaxRangeFailure, - element.ToString(), this.maxRange.ToString()); + element.ToString(), _maxRange.ToString()); } } @@ -1102,7 +1101,7 @@ namespace System.Management.Automation /// if maxRange, minRange are not IComparable /// public ValidateRangeAttribute(object minRange, object maxRange) : base() - { + { if (minRange == null) { throw PSTraceSource.NewArgumentNullException("minRange"); @@ -1114,14 +1113,14 @@ namespace System.Management.Automation if (maxRange.GetType() != minRange.GetType()) { bool failure = true; - promotedType = GetCommonType(minRange.GetType(), maxRange.GetType()); - if (promotedType != null) + _promotedType = GetCommonType(minRange.GetType(), maxRange.GetType()); + if (_promotedType != null) { object resultValue; - if (LanguagePrimitives.TryConvertTo(minRange, promotedType, out resultValue)) + if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out resultValue)) { minRange = resultValue; - if (LanguagePrimitives.TryConvertTo(maxRange, promotedType, out resultValue)) + if (LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out resultValue)) { maxRange = resultValue; failure = false; @@ -1137,30 +1136,30 @@ namespace System.Management.Automation } else { - promotedType = minRange.GetType(); + _promotedType = minRange.GetType(); } - - minComparable = minRange as IComparable; + + _minComparable = minRange as IComparable; // minRange and maxRange have the same type, so we just need // to check one of them - if (minComparable==null) + if (_minComparable == null) { throw new ValidationMetadataException("MinRangeNotIComparable", null, Metadata.ValidateRangeNotIComparable); } - maxComparable = maxRange as IComparable; - Diagnostics.Assert(maxComparable != null, "maxComparable comes from a type that is IComparable"); + _maxComparable = maxRange as IComparable; + Diagnostics.Assert(_maxComparable != null, "maxComparable comes from a type that is IComparable"); // Thanks to the IComparable if above this will not throw. They have the same type // and are IComparable - if (minComparable.CompareTo(maxRange) > 0) + if (_minComparable.CompareTo(maxRange) > 0) { throw new ValidationMetadataException("MaxRangeSmallerThanMinRange", null, Metadata.ValidateRangeMaxRangeSmallerThanMinRange); } - this.minRange = minRange; - this.maxRange = maxRange; + _minRange = minRange; + _maxRange = maxRange; } private static Type GetCommonType(Type minType, Type maxType) @@ -1209,22 +1208,22 @@ namespace System.Management.Automation /// Validates that each parameter argument matches the RegexPattern /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class ValidatePatternAttribute: ValidateEnumeratedArgumentsAttribute + public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttribute { - private string regexPattern; + private string _regexPattern; /// /// Gets the Regex pattern to be used in the validation /// public string RegexPattern { - get { return regexPattern; } + get { return _regexPattern; } } - private RegexOptions options = RegexOptions.IgnoreCase; + private RegexOptions _options = RegexOptions.IgnoreCase; /// /// Gets or sets the Regex options to be used in the validation /// - public RegexOptions Options { set { options = value; } get { return options; } } + public RegexOptions Options { set { _options = value; } get { return _options; } } /// /// Validates that each parameter argument matches the RegexPattern @@ -1245,15 +1244,15 @@ namespace System.Management.Automation string objectString = element.ToString(); Regex regex = null; - regex = new Regex(regexPattern, options); + regex = new Regex(_regexPattern, _options); Match match = regex.Match(objectString); if (!match.Success) { throw new ValidationMetadataException("ValidatePatternFailure", null, Metadata.ValidatePatternFailure, - objectString, regexPattern); + objectString, _regexPattern); } - } + } /// /// Initializes a new instance of the ValidatePatternAttribute class @@ -1267,7 +1266,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("regexPattern"); } - this.regexPattern = regexPattern; + _regexPattern = regexPattern; } } @@ -1302,14 +1301,14 @@ namespace System.Management.Automation } object result = _scriptBlock.DoInvokeReturnAsIs( - useLocalScope: true, + useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: LanguagePrimitives.AsPSObjectOrNull(element), - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: Utils.EmptyArray()); + dollarUnder: LanguagePrimitives.AsPSObjectOrNull(element), + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: Utils.EmptyArray()); - if(!LanguagePrimitives.IsTrue(result)) + if (!LanguagePrimitives.IsTrue(result)) { throw new ValidationMetadataException("ValidateScriptFailure", null, Metadata.ValidateScriptFailure, @@ -1336,20 +1335,20 @@ namespace System.Management.Automation /// /// Validates that the parameter argument count is in the specified range /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property )] - public sealed class ValidateCountAttribute: ValidateArgumentsAttribute + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateCountAttribute : ValidateArgumentsAttribute { - private int minLength; - private int maxLength; + private int _minLength; + private int _maxLength; /// /// Gets the minimum length of this attribute /// - public int MinLength { get { return minLength; } } + public int MinLength { get { return _minLength; } } /// /// Gets the maximum length of this attribute /// - public int MaxLength { get { return maxLength; } } - + public int MaxLength { get { return _maxLength; } } + /// /// Validates that the parameter argument count is in the specified range /// @@ -1388,7 +1387,7 @@ namespace System.Management.Automation else if ((ie = arguments as IEnumerable) != null) { IEnumerator e = ie.GetEnumerator(); - for ( ; e.MoveNext() == true; len++) + for (; e.MoveNext() == true; len++) ; } else if ((ienumerator = arguments as IEnumerator) != null) @@ -1403,18 +1402,18 @@ namespace System.Management.Automation null, Metadata.ValidateCountNotInArray); } - if (len < this.minLength) + if (len < _minLength) { throw new ValidationMetadataException("ValidateCountSmallerThanMin", null, Metadata.ValidateCountMinLengthFailure, - this.minLength,len); + _minLength, len); } - if (len > this.maxLength) + if (len > _maxLength) { throw new ValidationMetadataException("ValidateCountGreaterThanMax", null, Metadata.ValidateCountMaxLengthFailure, - this.maxLength, len); + _maxLength, len); } } @@ -1442,8 +1441,8 @@ namespace System.Management.Automation throw new ValidationMetadataException("ValidateRangeMaxLengthSmallerThanMinLength", null, Metadata.ValidateCountMaxLengthSmallerThanMinLength); } - this.minLength = minLength; - this.maxLength = maxLength; + _minLength = minLength; + _maxLength = maxLength; } } @@ -1451,21 +1450,21 @@ namespace System.Management.Automation /// Validates that each parameter argument is present in a specified set /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class ValidateSetAttribute: ValidateEnumeratedArgumentsAttribute + public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute { - private string[] validValues; - private bool ignoreCase = true; - + private string[] _validValues; + private bool _ignoreCase = true; + /// /// Gets a flag specifying if we should ignore the case when performing string comparison. The /// default is true. /// public bool IgnoreCase { - get { return this.ignoreCase; } - set { this.ignoreCase = value; } + get { return _ignoreCase; } + set { _ignoreCase = value; } } - + /// /// Gets the values in the set /// @@ -1473,7 +1472,7 @@ namespace System.Management.Automation { get { - return this.validValues; + return _validValues; } } @@ -1496,14 +1495,14 @@ namespace System.Management.Automation } string objString = element.ToString(); - for (int setIndex = 0; setIndex < validValues.Length; setIndex++) + for (int setIndex = 0; setIndex < _validValues.Length; setIndex++) { - string setString = validValues[setIndex]; + string setString = _validValues[setIndex]; if (CultureInfo.InvariantCulture. - CompareInfo.Compare(setString, objString, - this.ignoreCase - ? CompareOptions.IgnoreCase + CompareInfo.Compare(setString, objString, + _ignoreCase + ? CompareOptions.IgnoreCase : CompareOptions.None) == 0) { @@ -1517,7 +1516,7 @@ namespace System.Management.Automation private string SetAsString() { - return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, validValues); + return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, _validValues); } /// @@ -1538,7 +1537,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentOutOfRangeException("validValues", validValues); } - this.validValues = validValues; + _validValues = validValues; } } @@ -1553,7 +1552,7 @@ namespace System.Management.Automation /// /// Initializes a new instance of the AllowNullAttribute class /// - public AllowNullAttribute() {} + public AllowNullAttribute() { } } /// @@ -1565,7 +1564,7 @@ namespace System.Management.Automation /// /// Initializes a new instance of the AllowEmptyStringAttribute class /// - public AllowEmptyStringAttribute() {} + public AllowEmptyStringAttribute() { } } /// @@ -1683,7 +1682,7 @@ namespace System.Management.Automation /// Initializes a new instance of the ValidateUserDrivePathAttribute class /// public ValidateUserDriveAttribute() - : base(new string[] { "User" } ) + : base(new string[] { "User" }) { } } @@ -1723,7 +1722,7 @@ namespace System.Management.Automation { throw new ValidationMetadataException( "ArgumentIsNull", - null, + null, Metadata.ValidateNotNullFailure); } else if ((ienum = arguments as IEnumerable) != null) @@ -1741,7 +1740,7 @@ namespace System.Management.Automation } else if ((itor = arguments as IEnumerator) != null) { - for (; itor.MoveNext() == true; ) + for (; itor.MoveNext() == true;) { if (itor.Current == null || itor.Current == AutomationNull.Value) { @@ -1753,7 +1752,6 @@ namespace System.Management.Automation } } } - } /// @@ -1839,7 +1837,7 @@ namespace System.Management.Automation else if ((itor = arguments as IEnumerator) != null) { int validElements = 0; - for (; itor.MoveNext() == true; ) + for (; itor.MoveNext() == true;) { validElements++; if (itor.Current == null || itor.Current == AutomationNull.Value) @@ -1859,7 +1857,6 @@ namespace System.Management.Automation } } } - } #endregion NULL validation attributes @@ -1899,7 +1896,7 @@ namespace System.Management.Automation /// of the previous transformation. /// /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property )] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public abstract class ArgumentTransformationAttribute : CmdletMetadataAttribute { /// diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index d6920f0f9..192d14a66 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -15,7 +15,7 @@ namespace System.Management.Automation /// This class aggregates the objects necessary for the Monad /// engine to run. /// - internal class AutomationEngine + internal class AutomationEngine { // Holds the parser to use for this instance of the engine... internal Language.Parser EngineParser; @@ -41,11 +41,11 @@ namespace System.Management.Automation { get { - return commandDiscovery; + return _commandDiscovery; } } - private CommandDiscovery commandDiscovery; - + private CommandDiscovery _commandDiscovery; + /// /// The principal constructor that most hosts will use when creating @@ -74,8 +74,8 @@ namespace System.Management.Automation } if (!cplExist) { - pathext = (pathext == string.Empty) ? ".CPL" : - pathext.EndsWith(";", StringComparison.OrdinalIgnoreCase) + pathext = (pathext == string.Empty) ? ".CPL" : + pathext.EndsWith(";", StringComparison.OrdinalIgnoreCase) ? (pathext + ".CPL") : (pathext + ";.CPL"); Environment.SetEnvironmentVariable("PathEXT", pathext); } @@ -90,7 +90,7 @@ namespace System.Management.Automation } EngineParser = new Language.Parser(); - commandDiscovery = new CommandDiscovery(_context); + _commandDiscovery = new CommandDiscovery(_context); // Initialize providers before loading types so that any ScriptBlocks in the // types.ps1xml file can be parsed. @@ -109,7 +109,7 @@ namespace System.Management.Automation InitialSessionState.SetSessionStateDrive(_context, true); - InitialSessionState.CreateQuestionVariable(_context); + InitialSessionState.CreateQuestionVariable(_context); } /// diff --git a/src/System.Management.Automation/engine/AutomationNull.cs b/src/System.Management.Automation/engine/AutomationNull.cs index 293457c29..7da16f530 100644 --- a/src/System.Management.Automation/engine/AutomationNull.cs +++ b/src/System.Management.Automation/engine/AutomationNull.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; @@ -21,7 +22,7 @@ namespace System.Management.Automation.Internal #region private_members // Private member for Value. - private static readonly PSObject value1 = new PSObject(); + private static readonly PSObject s_value1 = new PSObject(); #endregion private_members @@ -34,7 +35,7 @@ namespace System.Management.Automation.Internal { get { - return value1; + return s_value1; } // no setter. It is a readonly; So, Value can not be modified. (Immutable). } diff --git a/src/System.Management.Automation/engine/COM/ComAdapter.cs b/src/System.Management.Automation/engine/COM/ComAdapter.cs index 376c6d7e1..ecec00ea4 100644 --- a/src/System.Management.Automation/engine/COM/ComAdapter.cs +++ b/src/System.Management.Automation/engine/COM/ComAdapter.cs @@ -174,9 +174,9 @@ namespace System.Management.Automation prop.SetValue(property.baseObject, setValue); } - - - + + + /// /// Returns true if the property is settable @@ -226,7 +226,7 @@ namespace System.Management.Automation return prop.ToString(); } - + #region Methods @@ -249,7 +249,7 @@ namespace System.Management.Automation /// the return of GetMethodData /// protected override Collection MethodDefinitions(PSMethod method) - { + { ComMethod commethod = (ComMethod)method.adapterData; return commethod.MethodDefinitions(); } @@ -300,7 +300,6 @@ namespace System.Management.Automation { ComProperty prop = (ComProperty)property.adapterData; return prop.GetValue(property.baseObject, arguments); - } /// @@ -333,10 +332,10 @@ namespace System.Management.Automation protected override Collection ParameterizedPropertyDefinitions(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; - Collection returnValue = new Collection {prop.GetDefinition()}; + Collection returnValue = new Collection { prop.GetDefinition() }; return returnValue; } #endregion parameterized property } -} +} diff --git a/src/System.Management.Automation/engine/COM/ComDispatch.cs b/src/System.Management.Automation/engine/COM/ComDispatch.cs index ea9c80925..489e491ef 100644 --- a/src/System.Management.Automation/engine/COM/ComDispatch.cs +++ b/src/System.Management.Automation/engine/COM/ComDispatch.cs @@ -20,14 +20,14 @@ namespace System.Management.Automation [PreserveSig] int GetTypeInfo(int iTInfo, int lcid, out COM.ITypeInfo ppTInfo); - + void GetIDsOfNames( [MarshalAs(UnmanagedType.LPStruct)] Guid iid, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] rgszNames, int cNames, int lcid, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4)] int[] rgDispId); - + void Invoke( int dispIdMember, [MarshalAs(UnmanagedType.LPStruct)] Guid iid, @@ -38,4 +38,4 @@ namespace System.Management.Automation out ComInvoker.EXCEPINFO pExcepInfo, out uint puArgErr); } -} \ No newline at end of file +} \ No newline at end of file diff --git a/src/System.Management.Automation/engine/COM/ComInvoker.cs b/src/System.Management.Automation/engine/COM/ComInvoker.cs index be6295be3..0e34723df 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -22,9 +22,9 @@ namespace System.Management.Automation // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms221242(v=vs.85).aspx for details. private const int DISPID_PROPERTYPUT = -3; // Alias of GUID_NULL. It's a GUID set to all zero - private static readonly Guid IID_NULL = new Guid(); + private static readonly Guid s_IID_NULL = new Guid(); // Size of the Variant struct - private static readonly int VariantSize = ClrFacade.SizeOf(); + private static readonly int s_variantSize = ClrFacade.SizeOf(); /// /// Make a by-Ref VARIANT value based on the passed-in VARIANT argument @@ -43,7 +43,7 @@ namespace System.Management.Automation // These cannot combine with VT_BYREF. Should try passing as a variant reference // We follow the code in ComBinder to handle 'VT_EMPTY' and 'VT_NULL' destVariant->_typeUnion._unionTypes._byref = new IntPtr(srcVariant); - destVariant->_typeUnion._vt = (ushort) VarEnum.VT_VARIANT | (ushort) VarEnum.VT_BYREF; + destVariant->_typeUnion._vt = (ushort)VarEnum.VT_VARIANT | (ushort)VarEnum.VT_BYREF; return; case VarEnum.VT_RECORD: @@ -78,18 +78,18 @@ namespace System.Management.Automation /// Pointer to the array private static unsafe IntPtr NewVariantArray(int length) { - IntPtr variantArray = Marshal.AllocCoTaskMem(VariantSize * length); + IntPtr variantArray = Marshal.AllocCoTaskMem(s_variantSize * length); for (int i = 0; i < length; i++) { - IntPtr currentVarPtr = variantArray + VariantSize * i; + IntPtr currentVarPtr = variantArray + s_variantSize * i; var currentVar = (Variant*)currentVarPtr; currentVar->_typeUnion._vt = (ushort)VarEnum.VT_EMPTY; } return variantArray; } - + /// /// Generate the ByRef array indicating whether the corresponding argument is by-reference. /// @@ -138,7 +138,7 @@ namespace System.Management.Automation internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind) { Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in."); - Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length, + Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length, "If 'args' and 'byRef' are not null, then they should be one-on-one mapping."); int argCount = args != null ? args.Length : 0; @@ -157,7 +157,7 @@ namespace System.Management.Automation { // !! The arguments should be in REVERSED order!! int actualIndex = argCount - i - 1; - IntPtr varArgPtr = variantArgArray + VariantSize * actualIndex; + IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex; // If need to pass by ref, create a by-ref variant if (byRef != null && byRef[i]) @@ -169,7 +169,7 @@ namespace System.Management.Automation } // Create a VARIANT that the by-ref VARIANT points to - IntPtr tmpVarPtr = tmpVariants + VariantSize * refIndex; + IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex; Marshal.GetNativeVariantForObject(args[i], tmpVarPtr); // Create the by-ref VARIANT @@ -212,7 +212,7 @@ namespace System.Management.Automation // 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'. // Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it. uint puArgErrNotUsed = 0; - target.Invoke(dispId, IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed); + target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed); } catch (Exception innerException) { @@ -229,7 +229,7 @@ namespace System.Management.Automation // Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception. int code = info.scode != 0 ? info.scode : info.wCode; innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException; - + // Get the richer error description if it's available. if (info.bstrDescription != IntPtr.Zero) { @@ -265,7 +265,7 @@ namespace System.Management.Automation // If need to pass by ref, back propagate if (byRef != null && byRef[i]) { - args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + VariantSize * actualIndex); + args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex); } } } @@ -279,7 +279,7 @@ namespace System.Management.Automation { for (int i = 0; i < argCount; i++) { - VariantClear(variantArgArray + VariantSize * i); + VariantClear(variantArgArray + s_variantSize * i); } Marshal.FreeCoTaskMem(variantArgArray); } @@ -295,7 +295,7 @@ namespace System.Management.Automation { for (int i = 0; i < refCount; i++) { - VariantClear(tmpVariants + VariantSize * i); + VariantClear(tmpVariants + s_variantSize * i); } Marshal.FreeCoTaskMem(tmpVariants); } diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index 941293578..0b9324660 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -17,7 +17,7 @@ namespace System.Management.Automation internal readonly COM.INVOKEKIND InvokeKind; internal ComMethodInformation(bool hasvarargs, bool hasoptional, ParameterInformation[] arguments, Type returnType, int dispId, COM.INVOKEKIND invokekind) - :base(hasvarargs, hasoptional, arguments) + : base(hasvarargs, hasoptional, arguments) { this.ReturnType = returnType; this.DispId = dispId; @@ -30,17 +30,17 @@ namespace System.Management.Automation /// internal class ComMethod { - private Collection methods = new Collection(); - private COM.ITypeInfo typeInfo; - private string name; + private Collection _methods = new Collection(); + private COM.ITypeInfo _typeInfo; + private string _name; /// /// Initializes new instance of ComMethod class. /// internal ComMethod(COM.ITypeInfo typeinfo, string name) { - this.typeInfo = typeinfo; - this.name = name; + _typeInfo = typeinfo; + _name = name; } /// @@ -50,7 +50,7 @@ namespace System.Management.Automation { get { - return name; + return _name; } } @@ -60,7 +60,7 @@ namespace System.Management.Automation /// index of funcdesc for method in type information. internal void AddFuncDesc(int index) { - methods.Add(index); + _methods.Add(index); } @@ -68,24 +68,24 @@ namespace System.Management.Automation /// Returns the different method overloads signatures. /// /// - internal Collection MethodDefinitions() + internal Collection MethodDefinitions() { Collection result = new Collection(); - - foreach (int index in methods) + + foreach (int index in _methods) { IntPtr pFuncDesc; - typeInfo.GetFuncDesc(index, out pFuncDesc); + _typeInfo.GetFuncDesc(index, out pFuncDesc); COM.FUNCDESC funcdesc = ClrFacade.PtrToStructure(pFuncDesc); - string signature = ComUtil.GetMethodSignatureFromFuncDesc(typeInfo, funcdesc, false); - result.Add(signature); + string signature = ComUtil.GetMethodSignatureFromFuncDesc(_typeInfo, funcdesc, false); + result.Add(signature); - typeInfo.ReleaseFuncDesc(pFuncDesc); + _typeInfo.ReleaseFuncDesc(pFuncDesc); } - + return result; } @@ -99,8 +99,8 @@ namespace System.Management.Automation { try { - object [] newarguments; - var methods = ComUtil.GetMethodInformationArray(this.typeInfo, this.methods, false); + object[] newarguments; + var methods = ComUtil.GetMethodInformationArray(_typeInfo, _methods, false); var bestMethod = (ComMethodInformation)Adapter.GetBestMethodAndArguments(Name, methods, arguments, out newarguments); object returnValue = ComInvoker.Invoke(method.baseObject as IDispatch, @@ -116,7 +116,7 @@ namespace System.Management.Automation { //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); - + var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 8298afff1..c4ef49794 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -16,16 +16,16 @@ namespace System.Management.Automation /// internal class ComProperty { - private bool hasSetter = false; - private bool hasSetterByRef = false; - private bool hasGetter = false; - private int dispId; - private int setterIndex; - private int setterByRefIndex; - private int getterIndex; - private COM.ITypeInfo typeInfo; - private string name; - private bool isparameterizied = false; + private bool _hasSetter = false; + private bool _hasSetterByRef = false; + private bool _hasGetter = false; + private int _dispId; + private int _setterIndex; + private int _setterByRefIndex; + private int _getterIndex; + private COM.ITypeInfo _typeInfo; + private string _name; + private bool _isparameterizied = false; /// @@ -35,8 +35,8 @@ namespace System.Management.Automation /// name of the property being created. internal ComProperty(COM.ITypeInfo typeinfo, string name) { - this.typeInfo = typeinfo; - this.name = name; + _typeInfo = typeinfo; + _name = name; } /// @@ -46,11 +46,11 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private Type cachedType; + private Type _cachedType; /// /// Defines the type of the property. @@ -59,40 +59,40 @@ namespace System.Management.Automation { get { - this.cachedType = null; + _cachedType = null; - if (this.cachedType == null) + if (_cachedType == null) { IntPtr pFuncDesc = IntPtr.Zero; try { - this.typeInfo.GetFuncDesc(GetFuncDescIndex(), out pFuncDesc); + _typeInfo.GetFuncDesc(GetFuncDescIndex(), out pFuncDesc); COM.FUNCDESC funcdesc = ClrFacade.PtrToStructure(pFuncDesc); - if (this.hasGetter) + if (_hasGetter) { // use the return type of the getter - this.cachedType = ComUtil.GetTypeFromTypeDesc(funcdesc.elemdescFunc.tdesc); + _cachedType = ComUtil.GetTypeFromTypeDesc(funcdesc.elemdescFunc.tdesc); } else { // use the type of the first argument to the setter ParameterInformation[] parameterInformation = ComUtil.GetParameterInformation(funcdesc, false); Diagnostics.Assert(parameterInformation.Length == 1, "Invalid number of parameters in a property setter"); - this.cachedType = parameterInformation[0].parameterType; + _cachedType = parameterInformation[0].parameterType; } } finally { if (pFuncDesc != IntPtr.Zero) { - typeInfo.ReleaseFuncDesc(pFuncDesc); + _typeInfo.ReleaseFuncDesc(pFuncDesc); } } } - return this.cachedType; + return _cachedType; } } @@ -101,18 +101,18 @@ namespace System.Management.Automation /// private int GetFuncDescIndex() { - if (this.hasGetter) + if (_hasGetter) { - return this.getterIndex; + return _getterIndex; } - else if (this.hasSetter) + else if (_hasSetter) { - return this.setterIndex; + return _setterIndex; } else { - Diagnostics.Assert(this.hasSetterByRef, "Invalid property setter type"); - return this.setterByRefIndex; + Diagnostics.Assert(_hasSetterByRef, "Invalid property setter type"); + return _setterByRefIndex; } } @@ -123,7 +123,7 @@ namespace System.Management.Automation { get { - return isparameterizied; + return _isparameterizied; } } @@ -147,7 +147,7 @@ namespace System.Management.Automation { get { - return hasSetter | hasSetterByRef; + return _hasSetter | _hasSetterByRef; } } @@ -158,7 +158,7 @@ namespace System.Management.Automation { get { - return hasGetter; + return _hasGetter; } } @@ -172,14 +172,13 @@ namespace System.Management.Automation { try { - return ComInvoker.Invoke(target as IDispatch, dispId, null, null, COM.INVOKEKIND.INVOKE_PROPERTYGET); + return ComInvoker.Invoke(target as IDispatch, _dispId, null, null, COM.INVOKEKIND.INVOKE_PROPERTYGET); } catch (TargetInvocationException te) { - //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); - + var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { @@ -194,7 +193,7 @@ namespace System.Management.Automation } } - return null; + return null; } /// @@ -208,8 +207,8 @@ namespace System.Management.Automation try { object[] newarguments; - var getterCollection = new Collection {this.getterIndex}; - var methods = ComUtil.GetMethodInformationArray(this.typeInfo, getterCollection, false); + var getterCollection = new Collection { _getterIndex }; + var methods = ComUtil.GetMethodInformationArray(_typeInfo, getterCollection, false); var bestMethod = (ComMethodInformation)Adapter.GetBestMethodAndArguments(Name, methods, arguments, out newarguments); object returnValue = ComInvoker.Invoke(target as IDispatch, @@ -256,16 +255,16 @@ namespace System.Management.Automation object[] propValue = new object[1]; setValue = Adapter.PropertySetAndMethodArgumentConvertTo(setValue, this.Type, CultureInfo.InvariantCulture); propValue[0] = setValue; - + try { - ComInvoker.Invoke(target as IDispatch, dispId, propValue, null, COM.INVOKEKIND.INVOKE_PROPERTYPUT); + ComInvoker.Invoke(target as IDispatch, _dispId, propValue, null, COM.INVOKEKIND.INVOKE_PROPERTYPUT); } catch (TargetInvocationException te) { //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); - + var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { @@ -290,8 +289,8 @@ namespace System.Management.Automation internal void SetValue(Object target, Object setValue, Object[] arguments) { object[] newarguments; - var setterCollection = new Collection { hasSetterByRef ? setterByRefIndex : setterIndex }; - var methods = ComUtil.GetMethodInformationArray(this.typeInfo, setterCollection, true); + var setterCollection = new Collection { _hasSetterByRef ? _setterByRefIndex : _setterIndex }; + var methods = ComUtil.GetMethodInformationArray(_typeInfo, setterCollection, true); var bestMethod = (ComMethodInformation)Adapter.GetBestMethodAndArguments(Name, methods, arguments, out newarguments); var finalArguments = new object[newarguments.Length + 1]; @@ -316,7 +315,7 @@ namespace System.Management.Automation { //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); - + var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { @@ -340,35 +339,35 @@ namespace System.Management.Automation /// index of function descriptor in type information internal void UpdateFuncDesc(COM.FUNCDESC desc, int index) { - dispId = desc.memid; + _dispId = desc.memid; switch (desc.invkind) { case COM.INVOKEKIND.INVOKE_PROPERTYGET: - hasGetter = true; - getterIndex = index; + _hasGetter = true; + _getterIndex = index; if (desc.cParams > 0) { - isparameterizied = true; + _isparameterizied = true; } break; case COM.INVOKEKIND.INVOKE_PROPERTYPUT: - hasSetter = true; - setterIndex = index; + _hasSetter = true; + _setterIndex = index; if (desc.cParams > 1) { - isparameterizied = true; + _isparameterizied = true; } break; case COM.INVOKEKIND.INVOKE_PROPERTYPUTREF: - setterByRefIndex = index; - hasSetterByRef = true; + _setterByRefIndex = index; + _hasSetterByRef = true; if (desc.cParams > 1) { - isparameterizied = true; + _isparameterizied = true; } break; } @@ -380,16 +379,16 @@ namespace System.Management.Automation try { - this.typeInfo.GetFuncDesc(GetFuncDescIndex(), out pFuncDesc); + _typeInfo.GetFuncDesc(GetFuncDescIndex(), out pFuncDesc); COM.FUNCDESC funcdesc = ClrFacade.PtrToStructure(pFuncDesc); - return ComUtil.GetMethodSignatureFromFuncDesc(typeInfo, funcdesc, !this.hasGetter); + return ComUtil.GetMethodSignatureFromFuncDesc(_typeInfo, funcdesc, !_hasGetter); } finally { if (pFuncDesc != IntPtr.Zero) { - typeInfo.ReleaseFuncDesc(pFuncDesc); + _typeInfo.ReleaseFuncDesc(pFuncDesc); } } } @@ -398,27 +397,26 @@ namespace System.Management.Automation /// Returns the property signature string /// /// property signature - public override string ToString() + public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(this.GetDefinition()); builder.Append(" "); - if (hasGetter) + if (_hasGetter) { builder.Append("{get} "); } - if (hasSetter) + if (_hasSetter) { builder.Append("{set} "); } - if (hasSetterByRef) + if (_hasSetterByRef) { builder.Append("{set by ref}"); } return builder.ToString(); } - } } diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index ab9bb3998..e49800110 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -10,7 +10,6 @@ using COM = System.Runtime.InteropServices.ComTypes; namespace System.Management.Automation { - /// /// A Wrapper class for COM object's Type Information /// @@ -19,10 +18,10 @@ namespace System.Management.Automation /// /// Member variables. /// - private Dictionary properties = null; - private Dictionary methods = null; - private COM.ITypeInfo typeinfo = null; - private Guid guid = Guid.Empty; + private Dictionary _properties = null; + private Dictionary _methods = null; + private COM.ITypeInfo _typeinfo = null; + private Guid _guid = Guid.Empty; /// @@ -31,11 +30,11 @@ namespace System.Management.Automation /// ITypeInfo object being wrapped by this object internal ComTypeInfo(COM.ITypeInfo info) { - typeinfo = info; - properties = new Dictionary(StringComparer.OrdinalIgnoreCase); - methods = new Dictionary(StringComparer.OrdinalIgnoreCase); + _typeinfo = info; + _properties = new Dictionary(StringComparer.OrdinalIgnoreCase); + _methods = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (typeinfo != null) + if (_typeinfo != null) { Initialize(); } @@ -49,7 +48,7 @@ namespace System.Management.Automation { get { - return properties; + return _properties; } } @@ -60,7 +59,7 @@ namespace System.Management.Automation { get { - return methods; + return _methods; } } @@ -73,7 +72,7 @@ namespace System.Management.Automation { get { - return guid.ToString(); + return _guid.ToString(); } } @@ -82,16 +81,16 @@ namespace System.Management.Automation /// private void Initialize() { - if (typeinfo != null) + if (_typeinfo != null) { - COM.TYPEATTR typeattr = GetTypeAttr(typeinfo); - + COM.TYPEATTR typeattr = GetTypeAttr(_typeinfo); + //Initialize the type information guid - guid = typeattr.guid; + _guid = typeattr.guid; for (int i = 0; i < typeattr.cFuncs; i++) { - COM.FUNCDESC funcdesc = GetFuncDesc(typeinfo, i); + COM.FUNCDESC funcdesc = GetFuncDesc(_typeinfo, i); if ((funcdesc.wFuncFlags & 0x1) == 0x1) { // http://msdn.microsoft.com/en-us/library/ee488948.aspx @@ -104,7 +103,7 @@ namespace System.Management.Automation continue; } - String strName = ComUtil.GetNameFromFuncDesc(typeinfo, funcdesc); + String strName = ComUtil.GetNameFromFuncDesc(_typeinfo, funcdesc); switch (funcdesc.invkind) { @@ -118,7 +117,6 @@ namespace System.Management.Automation AddMethod(strName, i); break; } - } } } @@ -159,29 +157,29 @@ namespace System.Management.Automation return result; } - + private void AddProperty(string strName, COM.FUNCDESC funcdesc, int index) { ComProperty prop; - if (!properties.TryGetValue(strName, out prop)) + if (!_properties.TryGetValue(strName, out prop)) { - prop = new ComProperty(typeinfo, strName); - properties[strName] = prop; + prop = new ComProperty(_typeinfo, strName); + _properties[strName] = prop; } if (prop != null) { prop.UpdateFuncDesc(funcdesc, index); - } + } } - private void AddMethod(string strName,int index) + private void AddMethod(string strName, int index) { ComMethod method; - if (!methods.TryGetValue(strName, out method)) + if (!_methods.TryGetValue(strName, out method)) { - method = new ComMethod(typeinfo, strName); - methods[strName] = method; + method = new ComMethod(_typeinfo, strName); + _methods[strName] = method; } if (method != null) @@ -237,7 +235,7 @@ namespace System.Management.Automation { // We need the typeinfo for Dispatch Interface typeinfo.GetRefTypeOfImplType(-1, out href); - typeinfo.GetRefTypeInfo(href, out dispinfo); + typeinfo.GetRefTypeInfo(href, out dispinfo); } catch (COMException ce) { @@ -277,7 +275,7 @@ namespace System.Management.Automation // Is this interface IDispatch compatible interface? if (typeattr.typekind == COM.TYPEKIND.TKIND_DISPATCH) { - return interfaceinfo; + return interfaceinfo; } //Nope. Is this a dual interface @@ -291,11 +289,9 @@ namespace System.Management.Automation return interfaceinfo; } } - } return null; } - } } diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index c2131d0da..8f0f56f0e 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -53,7 +53,6 @@ namespace System.Management.Automation for (int i = 0; i < funcdesc.cParams; i++) { - COM.ELEMDESC ElementDescription; int ElementDescriptionArrayByteOffset; IntPtr ElementDescriptionPointer; @@ -61,8 +60,8 @@ namespace System.Management.Automation ElementDescription = new COM.ELEMDESC(); ElementDescriptionArrayByteOffset = i * ElementDescriptionSize; -//Disable PRefast warning for converting to int32 and converting back into intptr. -//Code below takes into account 32 bit vs 64 bit conversions + //Disable PRefast warning for converting to int32 and converting back into intptr. + //Code below takes into account 32 bit vs 64 bit conversions #pragma warning disable 56515 if (IntPtr.Size == 4) { @@ -73,7 +72,7 @@ namespace System.Management.Automation ElementDescriptionPointer = (IntPtr)(ElementDescriptionArrayPtr.ToInt64() + ElementDescriptionArrayByteOffset); } #pragma warning restore 56515 - + ElementDescription = ClrFacade.PtrToStructure(ElementDescriptionPointer); string paramstring = GetStringFromTypeDesc(typeinfo, ElementDescription.tdesc); @@ -91,7 +90,6 @@ namespace System.Management.Automation builder.Append(", "); } } - } builder.Append(")"); @@ -105,7 +103,7 @@ namespace System.Management.Automation /// ITypeInfo interface of the type /// FuncDesc of property of method /// name of the method or property - internal static string GetNameFromFuncDesc(COM.ITypeInfo typeinfo, COM.FUNCDESC funcdesc) + internal static string GetNameFromFuncDesc(COM.ITypeInfo typeinfo, COM.FUNCDESC funcdesc) { //Get the method or property name. String strName, strDoc, strHelp; @@ -135,10 +133,9 @@ namespace System.Management.Automation return strName; } return "UnknownCustomtype"; - } -// Disable obsolete warning about VarEnum in CoreCLR + // Disable obsolete warning about VarEnum in CoreCLR #pragma warning disable 618 /// @@ -194,14 +191,14 @@ namespace System.Management.Automation case VarEnum.VT_UI2: return "ushort"; - + case VarEnum.VT_UI4: case VarEnum.VT_UINT: return "uint"; - + case VarEnum.VT_UI8: return "uint64"; - + case VarEnum.VT_BSTR: case VarEnum.VT_LPSTR: case VarEnum.VT_LPWSTR: @@ -212,7 +209,7 @@ namespace System.Management.Automation case VarEnum.VT_BOOL: return "bool"; - + case VarEnum.VT_CY: return "currency"; @@ -221,10 +218,10 @@ namespace System.Management.Automation case VarEnum.VT_CLSID: return "clsid"; - + case VarEnum.VT_DISPATCH: return "IDispatch"; - + case VarEnum.VT_UNKNOWN: return "IUnknown"; @@ -233,7 +230,7 @@ namespace System.Management.Automation case VarEnum.VT_VOID: return "void"; - + case VarEnum.VT_ARRAY: return "object[]"; @@ -263,7 +260,7 @@ namespace System.Management.Automation /// private static ComMethodInformation GetMethodInformation(COM.FUNCDESC funcdesc, bool skipLastParameter) { - Type returntype = GetTypeFromTypeDesc(funcdesc.elemdescFunc.tdesc); + Type returntype = GetTypeFromTypeDesc(funcdesc.elemdescFunc.tdesc); ParameterInformation[] parameters = GetParameterInformation(funcdesc, skipLastParameter); bool hasOptional = false; foreach (ParameterInformation p in parameters) @@ -316,7 +313,7 @@ namespace System.Management.Automation } #pragma warning enable 56515 - + ElementDescription = ClrFacade.PtrToStructure(ElementDescriptionPointer); //get the type of parameter @@ -358,4 +355,4 @@ namespace System.Management.Automation return returnValue; } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs index be844d7e0..c743b68a9 100644 --- a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs @@ -1,9 +1,10 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -41,11 +42,11 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.sessionState = cmdlet.Context.EngineSessionState; + _cmdlet = cmdlet; + _sessionState = cmdlet.Context.EngineSessionState; } // ChildItemCmdletProviderIntrinsics internal - /// + /// /// Constructs a facade over the "real" session state API /// /// @@ -64,7 +65,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // ChildItemCmdletProviderIntrinsics internal #endregion Constructors @@ -120,12 +121,12 @@ namespace System.Management.Automation public Collection Get(string path, bool recurse) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildItems(new string[] { path }, recurse, uint.MaxValue, false, false); + return _sessionState.GetChildItems(new string[] { path }, recurse, uint.MaxValue, false, false); } // GetChildItems /// @@ -189,12 +190,12 @@ namespace System.Management.Automation public Collection Get(string[] path, bool recurse, uint depth, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildItems(path, recurse, depth, force, literalPath); + return _sessionState.GetChildItems(path, recurse, depth, force, literalPath); } /// @@ -254,7 +255,7 @@ namespace System.Management.Automation public Collection Get(string[] path, bool recurse, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -315,18 +316,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Get( - string path, - bool recurse, + string path, + bool recurse, uint depth, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.GetChildItems(path, recurse, depth, context); + _sessionState.GetChildItems(path, recurse, depth, context); } // GetChildItems /// @@ -374,19 +375,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object GetChildItemsDynamicParameters( - string path, - bool recurse, + string path, + bool recurse, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildItemsDynamicParameters(path, recurse, context); + return _sessionState.GetChildItemsDynamicParameters(path, recurse, context); } // GetChildItemsDynamicParameters - + #endregion GetChildItems @@ -444,19 +445,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection GetNames( - string path, - ReturnContainers returnContainers, + string path, + ReturnContainers returnContainers, bool recurse) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildNames(new string[] { path }, returnContainers, recurse, uint.MaxValue, false, false); + return _sessionState.GetChildNames(new string[] { path }, returnContainers, recurse, uint.MaxValue, false, false); } // GetChildNames - + /// /// Gets the child names of the container at the given path. /// @@ -525,10 +526,10 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.GetChildNames(path, returnContainers, recurse, uint.MaxValue, force, literalPath); + return _sessionState.GetChildNames(path, returnContainers, recurse, uint.MaxValue, force, literalPath); } /// @@ -604,10 +605,10 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.GetChildNames(path, returnContainers, recurse, depth, force, literalPath); + return _sessionState.GetChildNames(path, returnContainers, recurse, depth, force, literalPath); } /// @@ -669,19 +670,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void GetNames( - string path, - ReturnContainers returnContainers, + string path, + ReturnContainers returnContainers, bool recurse, uint depth, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.GetChildNames(path, returnContainers, recurse, depth, context); + _sessionState.GetChildNames(path, returnContainers, recurse, depth, context); } // GetChildNames /// @@ -723,16 +724,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object GetChildNamesDynamicParameters( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildNamesDynamicParameters(path, context); + return _sessionState.GetChildNamesDynamicParameters(path, context); } // GetChildNamesDynamicParameters #endregion GetChildNames @@ -780,12 +781,12 @@ namespace System.Management.Automation public bool HasChild(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.HasChildItems(path, false, false); + return _sessionState.HasChildItems(path, false, false); } // HasChildItems /// @@ -837,12 +838,12 @@ namespace System.Management.Automation public bool HasChild(string path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.HasChildItems(path, force, literalPath); + return _sessionState.HasChildItems(path, force, literalPath); } /// @@ -888,16 +889,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal bool HasChild( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.HasChildItems(path, context); + return _sessionState.HasChildItems(path, context); } // HasChildItems @@ -907,8 +908,8 @@ namespace System.Management.Automation #region private data - private Cmdlet cmdlet; - private SessionStateInternal sessionState; + private Cmdlet _cmdlet; + private SessionStateInternal _sessionState; #endregion private data } // ChildItemCmdletProviderIntrinsics diff --git a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs index c05569ad4..5f507bd04 100644 --- a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs @@ -1,8 +1,9 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Management.Automation.Internal; namespace System.Management.Automation @@ -45,15 +46,15 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.item = new ItemCmdletProviderIntrinsics(cmdlet); - this.childItem = new ChildItemCmdletProviderIntrinsics(cmdlet); - this.content = new ContentCmdletProviderIntrinsics(cmdlet); - this.property = new PropertyCmdletProviderIntrinsics(cmdlet); + _cmdlet = cmdlet; + _item = new ItemCmdletProviderIntrinsics(cmdlet); + _childItem = new ChildItemCmdletProviderIntrinsics(cmdlet); + _content = new ContentCmdletProviderIntrinsics(cmdlet); + _property = new PropertyCmdletProviderIntrinsics(cmdlet); #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER this.propertyValue = new PropertyValueCmdletProviderIntrinsics(cmdlet); #endif - this.securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); + _securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet); #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release @@ -76,14 +77,14 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.item = new ItemCmdletProviderIntrinsics(sessionState); - this.childItem = new ChildItemCmdletProviderIntrinsics(sessionState); - this.content = new ContentCmdletProviderIntrinsics(sessionState); - this.property = new PropertyCmdletProviderIntrinsics(sessionState); + _item = new ItemCmdletProviderIntrinsics(sessionState); + _childItem = new ChildItemCmdletProviderIntrinsics(sessionState); + _content = new ContentCmdletProviderIntrinsics(sessionState); + _property = new PropertyCmdletProviderIntrinsics(sessionState); #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER this.propertyValue = new PropertyValueCmdletProviderIntrinsics(sessionState); #endif - this.securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(sessionState); + _securityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(sessionState); #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release @@ -100,7 +101,7 @@ namespace System.Management.Automation /// public ItemCmdletProviderIntrinsics Item { - get { return item; } + get { return _item; } } /// @@ -108,7 +109,7 @@ namespace System.Management.Automation /// public ChildItemCmdletProviderIntrinsics ChildItem { - get { return childItem; } + get { return _childItem; } } /// @@ -116,7 +117,7 @@ namespace System.Management.Automation /// public ContentCmdletProviderIntrinsics Content { - get { return content; } + get { return _content; } } /// @@ -124,7 +125,7 @@ namespace System.Management.Automation /// public PropertyCmdletProviderIntrinsics Property { - get { return property; } + get { return _property; } } #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER @@ -143,9 +144,9 @@ namespace System.Management.Automation /// public SecurityDescriptorCmdletProviderIntrinsics SecurityDescriptor { - get { return securityDescriptor; } + get { return _securityDescriptor; } } - + #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release @@ -162,15 +163,15 @@ namespace System.Management.Automation #region private data - private InternalCommand cmdlet; - private ItemCmdletProviderIntrinsics item; - private ChildItemCmdletProviderIntrinsics childItem; - private ContentCmdletProviderIntrinsics content; - private PropertyCmdletProviderIntrinsics property; + private InternalCommand _cmdlet; + private ItemCmdletProviderIntrinsics _item; + private ChildItemCmdletProviderIntrinsics _childItem; + private ContentCmdletProviderIntrinsics _content; + private PropertyCmdletProviderIntrinsics _property; #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER private PropertyValueCmdletProviderIntrinsics propertyValue; #endif - private SecurityDescriptorCmdletProviderIntrinsics securityDescriptor; + private SecurityDescriptorCmdletProviderIntrinsics _securityDescriptor; #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index fab902cbc..44c21c180 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Collections.Generic; @@ -59,7 +60,7 @@ namespace System.Management.Automation } // Get the verb and noun from the name - if (! SplitCmdletName(name, out verb, out noun)) + if (!SplitCmdletName(name, out _verb, out _noun)) { throw PSTraceSource.NewArgumentException( @@ -68,10 +69,10 @@ namespace System.Management.Automation name); } - this.implementingType = implementingType; - this.helpFilePath = helpFile; - this._PSSnapin = PSSnapin; - this.options = ScopedItemOptions.ReadOnly; + _implementingType = implementingType; + _helpFilePath = helpFile; + _PSSnapin = PSSnapin; + _options = ScopedItemOptions.ReadOnly; this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } @@ -81,12 +82,12 @@ namespace System.Management.Automation internal CmdletInfo(CmdletInfo other) : base(other) { - this.verb = other.verb; - this.noun = other.noun; - this.implementingType = other.implementingType; - this.helpFilePath = other.helpFilePath; - this._PSSnapin = other._PSSnapin; - this.options = ScopedItemOptions.ReadOnly; + _verb = other._verb; + _noun = other._noun; + _implementingType = other._implementingType; + _helpFilePath = other._helpFilePath; + _PSSnapin = other._PSSnapin; + _options = ScopedItemOptions.ReadOnly; } /// @@ -127,7 +128,7 @@ namespace System.Management.Automation } // Get the verb and noun from the name - if (!SplitCmdletName(name, out verb, out noun)) + if (!SplitCmdletName(name, out _verb, out _noun)) { throw PSTraceSource.NewArgumentException( @@ -136,10 +137,10 @@ namespace System.Management.Automation name); } - this.implementingType = implementingType; - this.helpFilePath = string.Empty; - this._PSSnapin = null; - this.options = ScopedItemOptions.ReadOnly; + _implementingType = implementingType; + _helpFilePath = string.Empty; + _PSSnapin = null; + _options = ScopedItemOptions.ReadOnly; } #endregion ctor @@ -153,10 +154,10 @@ namespace System.Management.Automation { get { - return verb; + return _verb; } } // Verb - private string verb = String.Empty; + private string _verb = String.Empty; /// /// Gets the noun of the cmdlet. @@ -165,10 +166,10 @@ namespace System.Management.Automation { get { - return noun; + return _noun; } } // Noun - private string noun = String.Empty; + private string _noun = String.Empty; internal static bool SplitCmdletName(string name, out string verb, out string noun) { @@ -201,19 +202,19 @@ namespace System.Management.Automation { get { - return helpFilePath; + return _helpFilePath; } internal set { - helpFilePath = value; + _helpFilePath = value; } } // HelpFile - private string helpFilePath = String.Empty; + private string _helpFilePath = String.Empty; internal override HelpCategory HelpCategory { - get { return HelpCategory.Cmdlet; } - } + get { return HelpCategory.Cmdlet; } + } /// /// Gets the Snap-in in which the cmdlet is implemented. @@ -257,7 +258,7 @@ namespace System.Management.Automation { _version = base.Version; } - else if(_PSSnapin != null) + else if (_PSSnapin != null) { _version = _PSSnapin.Version; } @@ -276,10 +277,10 @@ namespace System.Management.Automation { get { - return implementingType; + return _implementingType; } } - private Type implementingType = null; + private Type _implementingType = null; /// /// Gets the synopsis of the cmdlet @@ -299,9 +300,9 @@ namespace System.Management.Automation String.Format( System.Globalization.CultureInfo.CurrentCulture, "{0}{1}{2} {3}", - verb, + _verb, StringLiterals.CommandVerbNounSeparator, - noun, + _noun, parameterSet.ToString((this.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow))); } } @@ -312,9 +313,9 @@ namespace System.Management.Automation String.Format( System.Globalization.CultureInfo.CurrentCulture, "{0}{1}{2}", - verb, + _verb, StringLiterals.CommandVerbNounSeparator, - noun)); + _noun)); } return synopsis.ToString(); @@ -367,7 +368,7 @@ namespace System.Management.Automation for (int i = 0; i < Arguments.Length - 1; i++) { var arg = Arguments[i] as string; - if (arg != null && + if (arg != null && (arg.Equals("-Path", StringComparison.OrdinalIgnoreCase) || (arg.Equals("-LiteralPath", StringComparison.OrdinalIgnoreCase)))) { @@ -410,7 +411,7 @@ namespace System.Management.Automation { get { - return options; + return _options; } set @@ -418,7 +419,7 @@ namespace System.Management.Automation SetOptions(value, false); } } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// /// Sets the options for the cmdlet and allows changes ReadOnly options only if force is specified. @@ -437,7 +438,7 @@ namespace System.Management.Automation // Check to see if the cmdlet is readonly, if so // throw an exception because the options cannot be changed. - if ((options & ScopedItemOptions.ReadOnly) != 0) + if ((_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -449,7 +450,7 @@ namespace System.Management.Automation throw e; } - options = newOptions; + _options = newOptions; } #endregion public members @@ -486,7 +487,7 @@ namespace System.Management.Automation // If this is a high-fidelity object then extract full-name normally. if (psObject.BaseObject is CmdletInfo) { - CmdletInfo cmdletInfo = (CmdletInfo) psObject.BaseObject; + CmdletInfo cmdletInfo = (CmdletInfo)psObject.BaseObject; return GetFullName(cmdletInfo); } @@ -494,10 +495,10 @@ namespace System.Management.Automation else { // Handle the case in one or both of the properties might not be defined. - PSPropertyInfo nameProperty = psObject.Properties["Name"]; + PSPropertyInfo nameProperty = psObject.Properties["Name"]; PSPropertyInfo psSnapInProperty = psObject.Properties["PSSnapIn"]; - string nameString = nameProperty == null ? "" : (string) nameProperty.Value; - string psSnapInString = psSnapInProperty == null ? "" : (string) psSnapInProperty.Value; + string nameString = nameProperty == null ? "" : (string)nameProperty.Value; + string psSnapInString = psSnapInProperty == null ? "" : (string)psSnapInProperty.Value; return GetFullName(psSnapInString, nameString); } } @@ -540,14 +541,14 @@ namespace System.Management.Automation { get { - if (cmdletMetadata == null) + if (_cmdletMetadata == null) { - cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context); + _cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context); } - return cmdletMetadata; + return _cmdletMetadata; } } - private CommandMetadata cmdletMetadata; + private CommandMetadata _cmdletMetadata; internal override bool ImplementsDynamicParameters { @@ -561,7 +562,6 @@ namespace System.Management.Automation { return false; } - } } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index c783d700b..ab526e521 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -25,7 +26,7 @@ namespace System.Management.Automation #region tracer [TraceSource("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s).")] - private static readonly PSTraceSource _tracer = PSTraceSource.GetTracer("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s)."); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s)."); #endregion tracer @@ -53,8 +54,8 @@ namespace System.Management.Automation CommandMetadata commandMetadata, ParameterBinderBase parameterBinder) : base( - cmdlet.MyInvocation, - cmdlet.Context, + cmdlet.MyInvocation, + cmdlet.Context, parameterBinder) { if (cmdlet == null) @@ -68,8 +69,8 @@ namespace System.Management.Automation } this.Command = cmdlet; - this._commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime; - this._commandMetadata = commandMetadata; + _commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime; + _commandMetadata = commandMetadata; // Add the static parameter metadata to the bindable parameters // And add them to the unbound parameters list @@ -113,12 +114,12 @@ namespace System.Management.Automation /// internal void BindCommandLineParameters(Collection arguments) { - _tracer.WriteLine("Argument count: {0}", arguments.Count); + s_tracer.WriteLine("Argument count: {0}", arguments.Count); BindCommandLineParametersNoValidation(arguments); // Is pipeline input expected? - bool isPipelineInputExpected = !(this._commandRuntime.IsClosed && this._commandRuntime.InputPipe.Empty); + bool isPipelineInputExpected = !(_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty); int validParameterSetCount; @@ -142,7 +143,7 @@ namespace System.Management.Automation // If the parameter set is determined and the default parameters are not used // we try the default parameter binding again because it may contain some mandatory // parameters - if(validParameterSetCount == 1 && !DefaultParameterBindingInUse) + if (validParameterSetCount == 1 && !DefaultParameterBindingInUse) { ApplyDefaultParameterBinding("Mandatory Checking", false); } @@ -162,7 +163,7 @@ namespace System.Management.Automation using (ParameterBinderBase.bindingTracer.TraceScope( "MANDATORY PARAMETER CHECK on cmdlet [{0}]", - this._commandMetadata.Name)) + _commandMetadata.Name)) { try { @@ -182,7 +183,7 @@ namespace System.Management.Automation } catch (ParameterBindingException pbex) { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw; } @@ -226,11 +227,11 @@ namespace System.Management.Automation UnboundArguments.Add(argument); } - CommandMetadata cmdletMetadata = this._commandMetadata; + CommandMetadata cmdletMetadata = _commandMetadata; // Clear the warningSet at the beginning. - this._warningSet.Clear(); + _warningSet.Clear(); // Parse $PSDefaultParameterValues to get all valid pairs - this._allDefaultParameterValuePairs = this.GetDefaultParameterValuePairs(true); + _allDefaultParameterValuePairs = this.GetDefaultParameterValuePairs(true); // Set to false at the beginning DefaultParameterBindingInUse = false; // Clear the bound default parameters at the beginning @@ -241,7 +242,7 @@ namespace System.Management.Automation using (ParameterBinderBase.bindingTracer.TraceScope( "BIND NAMED cmd line args [{0}]", - this._commandMetadata.Name)) + _commandMetadata.Name)) { // Bind the actual arguments UnboundArguments = BindParameters(_currentParameterSetFlag, this.UnboundArguments); @@ -252,7 +253,7 @@ namespace System.Management.Automation using (ParameterBinderBase.bindingTracer.TraceScope( "BIND POSITIONAL cmd line args [{0}]", - this._commandMetadata.Name)) + _commandMetadata.Name)) { // Now that we know the parameter set, bind the positional parameters UnboundArguments = @@ -328,9 +329,9 @@ namespace System.Management.Automation continue; } - var matchingParameterSetMetadata = + var matchingParameterSetMetadata = parameter.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag); - + foreach (ParameterSetSpecificMetadata parameterSetMetadata in matchingParameterSetMetadata) { if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName) @@ -373,12 +374,12 @@ namespace System.Management.Automation /// private void ApplyDefaultParameterBinding(string bindingStage, bool isDynamic) { - if(!_useDefaultParameterBinding) + if (!_useDefaultParameterBinding) { return; } - if(isDynamic) + if (isDynamic) { // Get user defined default parameter value pairs again, so that the // dynamic parameter value pairs could be involved. @@ -391,7 +392,7 @@ namespace System.Management.Automation bool isSuccess = false; using (ParameterBinderBase.bindingTracer.TraceScope( "BIND DEFAULT pairs after [{0}] for [{1}]", - bindingStage, this._commandMetadata.Name)) + bindingStage, _commandMetadata.Name)) { isSuccess = BindDefaultParameters(_currentParameterSetFlag, qualifiedParameterValuePairs); if (isSuccess && !DefaultParameterBindingInUse) @@ -400,7 +401,7 @@ namespace System.Management.Automation } } - _tracer.WriteLine("BIND DEFAULT after [{0}] result [{1}]", bindingStage, isSuccess); + s_tracer.WriteLine("BIND DEFAULT after [{0}] result [{1}]", bindingStage, isSuccess); } return; } @@ -427,7 +428,7 @@ namespace System.Management.Automation try { ScriptBlock scriptBlockArg = argumentValue as ScriptBlock; - if(scriptBlockArg != null) + if (scriptBlockArg != null) { // Get the current binding state, and pass it to the ScriptBlock as the argument // The 'arg' includes HashSet properties 'BoundParameters', 'BoundPositionalParameters', @@ -435,11 +436,11 @@ namespace System.Management.Automation // to a parameter depending on the current binding state. PSObject arg = WrapBindingState(); Collection results = scriptBlockArg.Invoke(arg); - if(results == null || results.Count == 0) + if (results == null || results.Count == 0) { continue; } - else if(results.Count == 1) + else if (results.Count == 1) { argumentValue = results[0]; } @@ -461,12 +462,12 @@ namespace System.Management.Automation parameter, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock); - if(bindResult && !ret) + if (bindResult && !ret) { ret = true; } - if(bindResult) + if (bindResult) { BoundDefaultParameters.Add(parameterName); } @@ -475,14 +476,14 @@ namespace System.Management.Automation { // We don't want the failures in default binding affect the command line binding, // so we write out a warning and ignore this binding failure - if (!_warningSet.Contains(this._commandMetadata.Name + Separator + parameterName)) + if (!_warningSet.Contains(_commandMetadata.Name + Separator + parameterName)) { string message = String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.FailToBindDefaultParameter, LanguagePrimitives.IsNull(argumentValue) ? "null" : argumentValue.ToString(), parameterName, ex.Message); - this._commandRuntime.WriteWarning(message); - _warningSet.Add(this._commandMetadata.Name + Separator + parameterName); + _commandRuntime.WriteWarning(message); + _warningSet.Add(_commandMetadata.Name + Separator + parameterName); } continue; } @@ -498,7 +499,7 @@ namespace System.Management.Automation private PSObject WrapBindingState() { HashSet boundParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); - HashSet boundPositionalParameterNames = + HashSet boundPositionalParameterNames = this.DefaultParameterBinder.CommandLineParameters.CopyBoundPositionalParameters(); HashSet boundDefaultParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -532,7 +533,7 @@ namespace System.Management.Automation uint currentParameterSetFlag, Dictionary availableParameterValuePairs) { - if(availableParameterValuePairs == null) + if (availableParameterValuePairs == null) { return null; } @@ -547,14 +548,14 @@ namespace System.Management.Automation { continue; } - - if(BoundArguments.ContainsKey(param.Parameter.Name)) + + if (BoundArguments.ContainsKey(param.Parameter.Name)) { continue; } // check if this param's set confilcts with other possible params. - if(param.Parameter.ParameterSetFlags != 0) + if (param.Parameter.ParameterSetFlags != 0) { possibleParameterFlag &= param.Parameter.ParameterSetFlags; if (possibleParameterFlag == 0) @@ -565,8 +566,8 @@ namespace System.Management.Automation result.Add(param, pair.Value); } - - if(result.Count > 0) + + if (result.Count > 0) { return result; } @@ -628,13 +629,13 @@ namespace System.Management.Automation if (needToGetAlias && DefaultParameterValues.Count > 0) { // Get all aliases of the current cmdlet - this._aliasList = GetAliasOfCurrentCmdlet(); + _aliasList = GetAliasOfCurrentCmdlet(); } // Set flag to true by default _useDefaultParameterBinding = true; - string currentCmdletName = this._commandMetadata.Name; + string currentCmdletName = _commandMetadata.Name; IDictionary bindableParameters = BindableParameters.BindableParameters; IDictionary bindableAlias = BindableParameters.AliasedParameters; @@ -746,7 +747,7 @@ namespace System.Management.Automation // The parameterPattern matches more than one parameters, so we write out a warning message and ignore this setting if (!_warningSet.Contains(cmdletName + Separator + parameterName)) { - this._commandRuntime.WriteWarning( + _commandRuntime.WriteWarning( String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.MultipleParametersMatched, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } @@ -765,7 +766,7 @@ namespace System.Management.Automation { if (!_warningSet.Contains(cmdletName + Separator + parameterName)) { - this._commandRuntime.WriteWarning( + _commandRuntime.WriteWarning( String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } @@ -790,7 +791,7 @@ namespace System.Management.Automation string formatString = multipleKeys ? ParameterBinderStrings.MultipleKeysInBadFormat : ParameterBinderStrings.SingleKeyInBadFormat; - this._commandRuntime.WriteWarning( + _commandRuntime.WriteWarning( String.Format(CultureInfo.InvariantCulture, formatString, keysInError)); } @@ -803,7 +804,7 @@ namespace System.Management.Automation { return availablePairs; } - + return null; } @@ -818,7 +819,7 @@ namespace System.Management.Automation /// /// private void GetDefaultParameterValuePairsHelper( - string cmdletName, string paramName, object paramValue, + string cmdletName, string paramName, object paramValue, IDictionary bindableParameters, IDictionary bindableAlias, Dictionary result, @@ -864,7 +865,7 @@ namespace System.Management.Automation if (writeWarning && !_warningSet.Contains(cmdletName + Separator + paramName)) { - this._commandRuntime.WriteWarning( + _commandRuntime.WriteWarning( String.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, paramName)); _warningSet.Add(cmdletName + Separator + paramName); } @@ -942,7 +943,7 @@ namespace System.Management.Automation "ParameterArgumentTransformationErrorMessageOnly", e.Message); - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw bindingException; } @@ -952,7 +953,7 @@ namespace System.Management.Automation } } } - + bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, @@ -965,7 +966,7 @@ namespace System.Management.Automation "PositionalParameterNotFound"); } } - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw bindingException; } @@ -1013,7 +1014,6 @@ namespace System.Management.Automation } } } - } /// @@ -1032,7 +1032,7 @@ namespace System.Management.Automation /// True if the parameter was restored correctly, or false otherwise. /// /// - bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter) + private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter) { switch (parameter.BinderAssociation) { @@ -1046,7 +1046,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( - this._commandMetadata.SupportsShouldProcess, + _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); @@ -1054,7 +1054,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( - this._commandMetadata.SupportsPaging, + _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); @@ -1062,7 +1062,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( - this._commandMetadata.SupportsTransactions, + _commandMetadata.SupportsTransactions, "The metadata for the TransactionParameters should only be available if the command supports Transactions"); TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); @@ -1070,7 +1070,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( - this._commandMetadata.ImplementsDynamicParameters, + _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) @@ -1192,14 +1192,13 @@ namespace System.Management.Automation } catch (ParameterBindingException pbex) { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw; } ThrowElaboratedBindingException(pbex); } - } else if (argument.ParameterName.Equals(Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal)) { @@ -1280,10 +1279,10 @@ namespace System.Management.Automation } } while (false); - _tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", result); + s_tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", result); return result; } - + /// /// Binds the specified parameters to the cmdlet /// @@ -1357,13 +1356,12 @@ namespace System.Management.Automation if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) && !IsParameterScriptBlockBindable(parameter)) { - // Now check to see if the command expects to have pipeline input. // If not, we should throw an exception now to inform the // user with more information than they would get if it was // considered an unbound mandatory parameter. - if (this._commandRuntime.IsClosed && this._commandRuntime.InputPipe.Empty) + if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty) { ParameterBindingException bindingException = new ParameterBindingException( @@ -1388,7 +1386,7 @@ namespace System.Management.Automation DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument; if (delayedArg == null) { - delayedArg = new DelayedScriptBlockArgument {_argument = argument, _parameterBinder = this}; + delayedArg = new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this }; } if (!_delayBindScriptBlocks.ContainsKey(parameter)) { @@ -1454,7 +1452,7 @@ namespace System.Management.Automation return result; } - + /// /// Binds the specified argument to the specified parameter using the appropriate /// parameter binder. @@ -1504,7 +1502,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( - this._commandMetadata.SupportsShouldProcess, + _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); result = @@ -1516,7 +1514,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( - this._commandMetadata.SupportsPaging, + _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); result = @@ -1528,7 +1526,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( - this._commandMetadata.SupportsTransactions, + _commandMetadata.SupportsTransactions, "The metadata for the TransactionsParameters should only be available if the command supports transactions"); result = @@ -1540,7 +1538,7 @@ namespace System.Management.Automation case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( - this._commandMetadata.ImplementsDynamicParameters, + _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) @@ -1643,7 +1641,7 @@ namespace System.Management.Automation "AmbiguousParameterSet"); // Might be caused by the default parameter binding - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw bindingException; } @@ -1711,7 +1709,7 @@ namespace System.Management.Automation } else { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw; } @@ -1750,13 +1748,12 @@ namespace System.Management.Automation { outgoingBindingException = null; - if (this._commandMetadata.ImplementsDynamicParameters) + if (_commandMetadata.ImplementsDynamicParameters) { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND cmd line args to DYNAMIC parameters.")) { - - _tracer.WriteLine("The Cmdlet supports the dynamic parameter interface"); + s_tracer.WriteLine("The Cmdlet supports the dynamic parameter interface"); IDynamicParameters dynamicParameterCmdlet = this.Command as IDynamicParameters; @@ -1764,7 +1761,7 @@ namespace System.Management.Automation { if (_dynamicParameterBinder == null) { - _tracer.WriteLine("Getting the bindable object from the Cmdlet"); + s_tracer.WriteLine("Getting the bindable object from the Cmdlet"); var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; if (psCompiledScriptCmdlet != null) @@ -1811,7 +1808,7 @@ namespace System.Management.Automation "DYNAMIC parameter object: [{0}]", dynamicParamBindableObject.GetType()); - _tracer.WriteLine("Creating a new parameter binder for the dynamic parameter object"); + s_tracer.WriteLine("Creating a new parameter binder for the dynamic parameter object"); InternalParameterMetadata dynamicParameterMetadata; @@ -1827,7 +1824,6 @@ namespace System.Management.Automation runtimeParamDictionary, this.Command, this.CommandLineParameters); - } else { @@ -1863,7 +1859,7 @@ namespace System.Management.Automation if (_dynamicParameterBinder == null) { - _tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet"); + s_tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet"); return; } @@ -1887,7 +1883,7 @@ namespace System.Management.Automation BindPositionalParameters( UnboundArguments, _currentParameterSetFlag, - this._commandMetadata.DefaultParameterSetFlag, + _commandMetadata.DefaultParameterSetFlag, out outgoingBindingException); } } @@ -2746,7 +2742,7 @@ namespace System.Management.Automation } // There are multiple valid parameter sets but at least one parameter set takes // pipeline input - else if (prePipelineInput && + else if (prePipelineInput && AtLeastOneUnboundValidParameterSetTakesPipelineInput(_currentParameterSetFlag)) { // We haven't fixated on a valid parameter set yet, but will wait for pipeline input to @@ -2773,8 +2769,8 @@ namespace System.Management.Automation // number of parameter sets that were defined for the cmdlet or 1 if // none were defined. - validParameterSetCount = - (this.BindableParameters.ParameterSetCount > 0) ? + validParameterSetCount = + (this.BindableParameters.ParameterSetCount > 0) ? this.BindableParameters.ParameterSetCount : 1; if (prePipelineInput && @@ -2783,11 +2779,11 @@ namespace System.Management.Automation // Don't fixate on the default parameter set yet. Wait until after // we have processed pipeline input. } - else if (this._commandMetadata.DefaultParameterSetFlag != 0) + else if (_commandMetadata.DefaultParameterSetFlag != 0) { if (setDefault) { - _currentParameterSetFlag = this._commandMetadata.DefaultParameterSetFlag; + _currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; validParameterSetCount = 1; } } @@ -2822,7 +2818,7 @@ namespace System.Management.Automation ) { uint remainingParameterSetsWithNoMandatoryUnboundParameters = _currentParameterSetFlag; - + IEnumerable allParameterSetMetadatas = boundParameters.Values .Concat(unboundParameters) .SelectMany(p => p.Parameter.ParameterSetData.Values); @@ -2862,7 +2858,7 @@ namespace System.Management.Automation private void ThrowAmbiguousParameterSetException(uint parameterSetFlags, MergedCommandParameterMetadata bindableParameters) { - ParameterBindingException bindingException = + ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, @@ -2876,7 +2872,7 @@ namespace System.Management.Automation // Trace the parameter sets still active uint currentParameterSet = 1; - + while (parameterSetFlags != 0) { uint currentParameterSetActive = parameterSetFlags & 0x1; @@ -2884,7 +2880,7 @@ namespace System.Management.Automation if (currentParameterSetActive == 1) { string parameterSetName = bindableParameters.GetParameterSetName(currentParameterSet); - if(! String.IsNullOrEmpty(parameterSetName)) + if (!String.IsNullOrEmpty(parameterSetName)) { ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", parameterSetName); } @@ -2893,8 +2889,8 @@ namespace System.Management.Automation parameterSetFlags >>= 1; currentParameterSet <<= 1; } - - if(!DefaultParameterBindingInUse) + + if (!DefaultParameterBindingInUse) { throw bindingException; } @@ -2958,7 +2954,7 @@ namespace System.Management.Automation false, out missingMandatoryParameters); } - + /// /// Checks for unbound mandatory paramters. If any are found and promptForMandatory is true, /// the user will be prompted for the missing mandatory parameters. @@ -3013,7 +3009,7 @@ namespace System.Management.Automation { // If the host interface wasn't specified or we were instructed not to prmopt, then throw // an exception instead - if ((Context.EngineHostInterface == null) || (! promptForMandatory)) + if ((Context.EngineHostInterface == null) || (!promptForMandatory)) { Diagnostics.Assert( Context.EngineHostInterface != null, @@ -3069,7 +3065,6 @@ namespace System.Management.Automation Diagnostics.Assert( result, "Any error in binding the parameter with type coercion should result in an exception"); - } result = true; } @@ -3119,7 +3114,7 @@ namespace System.Management.Automation if (error != null) { - ParameterBinderBase.bindingTracer.WriteLine ( + ParameterBinderBase.bindingTracer.WriteLine( "ERROR: host does not support prompting for missing mandatory parameters"); string missingParameters = BuildMissingParamsString(missingMandatoryParameters); @@ -3138,9 +3133,9 @@ namespace System.Management.Automation throw bindingException; } - if((parameters == null) || (parameters.Count == 0)) + if ((parameters == null) || (parameters.Count == 0)) { - ParameterBinderBase.bindingTracer.WriteLine ( + ParameterBinderBase.bindingTracer.WriteLine( "ERROR: still missing mandatory parameters after PROMPTING"); string missingParameters = BuildMissingParamsString(missingMandatoryParameters); @@ -3297,7 +3292,7 @@ namespace System.Management.Automation return label.ToString(); } - + /// /// Gets the parameter set name for the current parameter set. /// @@ -3307,10 +3302,10 @@ namespace System.Management.Automation get { string currentParameterSetName = BindableParameters.GetParameterSetName(_currentParameterSetFlag); - _tracer.WriteLine("CurrentParameterSetName = {0}", currentParameterSetName); + s_tracer.WriteLine("CurrentParameterSetName = {0}", currentParameterSetName); return currentParameterSetName; } - } + } /// /// Binds the specified object or its properties to parameters @@ -3334,7 +3329,7 @@ namespace System.Management.Automation { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND PIPELINE object to parameters: [{0}]", - this._commandMetadata.Name)) + _commandMetadata.Name)) { // First run any of the delay bind ScriptBlocks and bind the // result to the appropriate parameter. @@ -3500,7 +3495,7 @@ namespace System.Management.Automation ValidateParameterSets(true, true); validParameterSets = _currentParameterSetFlag; } - + result = true; } } @@ -3519,7 +3514,7 @@ namespace System.Management.Automation ValidateParameterSets(false, true); - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { ApplyDefaultParameterBinding("PIPELINE BIND", false); } @@ -3568,7 +3563,7 @@ namespace System.Management.Automation validParameterSets); } - _tracer.WriteLine("aParameterWasBound = {0}", aParameterWasBound); + s_tracer.WriteLine("aParameterWasBound = {0}", aParameterWasBound); return aParameterWasBound; } @@ -3633,7 +3628,6 @@ namespace System.Management.Automation inputToOperateOn != null) { bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.None); - } // The third step is to attempt to bind the value from the pipeline with // type coercion. @@ -3714,9 +3708,9 @@ namespace System.Management.Automation bindResult = false; } - if(parameterBindingException != null) + if (parameterBindingException != null) { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw parameterBindingException; } @@ -3789,9 +3783,9 @@ namespace System.Management.Automation bindResult = false; } - if(parameterBindingException != null) + if (parameterBindingException != null) { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw parameterBindingException; } @@ -4017,7 +4011,7 @@ namespace System.Management.Automation { MergedCompiledCommandParameter matchingParameter = BindableParameters.GetMatchingParameter( - name, + name, false, true, null); @@ -4076,7 +4070,7 @@ namespace System.Management.Automation internal Cmdlet Command { get; private set; } #region DefaultParameterBindingStructures - + /// /// The separator used in GetDefaultParameterValuePairs function /// @@ -4144,7 +4138,7 @@ namespace System.Management.Automation if (_shouldProcessParameterBinder == null) { // Construct a new instance of the should process parameters object - ShouldProcessParameters shouldProcessParameters = new ShouldProcessParameters(this._commandRuntime); + ShouldProcessParameters shouldProcessParameters = new ShouldProcessParameters(_commandRuntime); // Create reflection binder for this object @@ -4169,7 +4163,7 @@ namespace System.Management.Automation if (_pagingParameterBinder == null) { // Construct a new instance of the should process parameters object - PagingParameters pagingParameters = new PagingParameters(this._commandRuntime); + PagingParameters pagingParameters = new PagingParameters(_commandRuntime); // Create reflection binder for this object @@ -4194,7 +4188,7 @@ namespace System.Management.Automation if (_transactionParameterBinder == null) { // Construct a new instance of the transactions parameters object - TransactionParameters transactionParameters = new TransactionParameters(this._commandRuntime); + TransactionParameters transactionParameters = new TransactionParameters(_commandRuntime); // Create reflection binder for this object @@ -4220,7 +4214,7 @@ namespace System.Management.Automation if (_commonParametersBinder == null) { // Construct a new instance of the user feedback parameters object - CommonParameters commonParameters = new CommonParameters(this._commandRuntime); + CommonParameters commonParameters = new CommonParameters(_commandRuntime); // Create reflection binder for this object @@ -4291,7 +4285,7 @@ namespace System.Management.Automation /// If the parameter binder encounters an error getting the default value. /// /// - bool BindPipelineParameter( + private bool BindPipelineParameter( object parameterValue, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) @@ -4300,7 +4294,7 @@ namespace System.Management.Automation if (parameterValue != AutomationNull.Value) { - _tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", + s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", parameter.Parameter.Name, parameterValue ?? "null"); // Backup the default value @@ -4347,7 +4341,7 @@ namespace System.Management.Automation /// If the parameter binder encounters an error getting the default value. /// /// - void BackupDefaultParameter(MergedCompiledCommandParameter parameter) + private void BackupDefaultParameter(MergedCompiledCommandParameter parameter) { if (!_defaultParameterValues.ContainsKey(parameter.Parameter.Name)) { @@ -4374,7 +4368,7 @@ namespace System.Management.Automation /// If is null. /// /// - void RestoreDefaultParameterValues(IEnumerable parameters) + private void RestoreDefaultParameterValues(IEnumerable parameters) { if (parameters == null) { @@ -4423,7 +4417,7 @@ namespace System.Management.Automation if (error != null) { Type specifiedType = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType(); - ParameterBindingException bindingException = + ParameterBindingException bindingException = new ParameterBindingException( error, ErrorCategory.WriteError, @@ -4664,7 +4658,7 @@ namespace System.Management.Automation var strKey = key as string; if (strKey == null) { return null; } - + string keyAfterTrim = strKey.Trim(); return base[keyAfterTrim]; } diff --git a/src/System.Management.Automation/engine/CodeMethods.cs b/src/System.Management.Automation/engine/CodeMethods.cs index 68e29b31e..c1cd88a7d 100644 --- a/src/System.Management.Automation/engine/CodeMethods.cs +++ b/src/System.Management.Automation/engine/CodeMethods.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Reflection; diff --git a/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs index 548fed6d9..8f386b0c7 100644 --- a/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ArgBuilder.cs @@ -10,14 +10,16 @@ using System.Linq.Expressions; using Microsoft.Scripting.Ast; #endif -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// ArgBuilder provides an argument value used by the MethodBinder. One ArgBuilder exists for each /// physical parameter defined on a method. /// /// Contrast this with ParameterWrapper which represents the logical argument passed to the method. /// - internal abstract class ArgBuilder { + internal abstract class ArgBuilder + { /// /// Provides the Expression which provides the value to be passed to the argument. /// @@ -27,7 +29,8 @@ namespace System.Management.Automation.ComInterop { /// Provides the Expression which provides the value to be passed to the argument. /// This method is called when result is intended to be used ByRef. /// - internal virtual Expression MarshalToRef(Expression parameter) { + internal virtual Expression MarshalToRef(Expression parameter) + { return Marshal(parameter); } @@ -35,7 +38,8 @@ namespace System.Management.Automation.ComInterop { /// Provides an Expression which will update the provided value after a call to the method. /// May return null if no update is required. /// - internal virtual Expression UnmarshalFromRef(Expression newValue) { + internal virtual Expression UnmarshalFromRef(Expression newValue) + { return newValue; } } diff --git a/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs index d0939bfe9..476ff9cd8 100644 --- a/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/BoolArgBuilder.cs @@ -16,14 +16,18 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -namespace System.Management.Automation.ComInterop { - internal sealed class BoolArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal sealed class BoolArgBuilder : SimpleArgBuilder + { internal BoolArgBuilder(Type parameterType) - : base(parameterType) { + : base(parameterType) + { Debug.Assert(parameterType == typeof(bool)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { // parameter ? -1 : 0 return Expression.Condition( Marshal(parameter), @@ -32,7 +36,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { //parameter = temp != 0 return base.UnmarshalFromRef( Expression.NotEqual( diff --git a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs index b36efe37f..1ff0a095a 100644 --- a/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs +++ b/src/System.Management.Automation/engine/ComInterop/BoundDispEvent.cs @@ -16,13 +16,16 @@ using System.Security; using System.Security.Permissions; //using Microsoft.Scripting.Utils; -namespace System.Management.Automation.ComInterop { - internal sealed class BoundDispEvent : DynamicObject { +namespace System.Management.Automation.ComInterop +{ + internal sealed class BoundDispEvent : DynamicObject + { private object _rcw; private Guid _sourceIid; private int _dispid; - internal BoundDispEvent(object rcw, Guid sourceIid, int dispid) { + internal BoundDispEvent(object rcw, Guid sourceIid, int dispid) + { _rcw = rcw; _sourceIid = sourceIid; _dispid = dispid; @@ -35,13 +38,16 @@ namespace System.Management.Automation.ComInterop { /// The handler for the operation. /// The result of the operation. /// true if the operation is complete, false if the call site should determine behavior. - public override bool TryBinaryOperation(BinaryOperationBinder binder, object handler, out object result) { - if (binder.Operation == ExpressionType.AddAssign) { + public override bool TryBinaryOperation(BinaryOperationBinder binder, object handler, out object result) + { + if (binder.Operation == ExpressionType.AddAssign) + { result = InPlaceAdd(handler); return true; } - if (binder.Operation == ExpressionType.SubtractAssign) { + if (binder.Operation == ExpressionType.SubtractAssign) + { result = InPlaceSubtract(handler); return true; } @@ -50,16 +56,20 @@ namespace System.Management.Automation.ComInterop { return false; } - private static void VerifyHandler(object handler) { - if (handler is Delegate && handler.GetType() != typeof(Delegate)) { + private static void VerifyHandler(object handler) + { + if (handler is Delegate && handler.GetType() != typeof(Delegate)) + { return; // delegate } - if (handler is IDynamicMetaObjectProvider) { + if (handler is IDynamicMetaObjectProvider) + { return; // IDMOP } - if (handler is DispCallable) { + if (handler is DispCallable) + { return; } @@ -71,7 +81,8 @@ namespace System.Management.Automation.ComInterop { /// /// The handler to be added. /// The original event with handler added. - private object InPlaceAdd(object handler) { + private object InPlaceAdd(object handler) + { VerifyHandler(handler); ComEventSink comEventSink = ComEventSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, true); @@ -84,11 +95,13 @@ namespace System.Management.Automation.ComInterop { /// /// The handler to be removed. /// The original event with handler removed. - private object InPlaceSubtract(object handler) { + private object InPlaceSubtract(object handler) + { VerifyHandler(handler); ComEventSink comEventSink = ComEventSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, false); - if (comEventSink != null) { + if (comEventSink != null) + { comEventSink.RemoveHandler(_dispid, handler); } diff --git a/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs b/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs index 1be7f3a41..883ca5ee3 100644 --- a/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs +++ b/src/System.Management.Automation/engine/ComInterop/CollectionExtensions.cs @@ -7,29 +7,34 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System; -namespace System.Management.Automation.ComInterop { - internal static class CollectionExtensions { - - internal static T[] RemoveFirst(this T[] array) { +namespace System.Management.Automation.ComInterop +{ + internal static class CollectionExtensions + { + internal static T[] RemoveFirst(this T[] array) + { T[] result = new T[array.Length - 1]; Array.Copy(array, 1, result, 0, result.Length); return result; } - internal static T[] AddFirst(this IList list, T item) { + internal static T[] AddFirst(this IList list, T item) + { T[] res = new T[list.Count + 1]; res[0] = item; list.CopyTo(res, 1); return res; } - internal static T[] ToArray(this IList list) { + internal static T[] ToArray(this IList list) + { T[] res = new T[list.Count]; list.CopyTo(res, 0); return res; } - internal static T[] AddLast(this IList list, T item) { + internal static T[] AddLast(this IList list, T item) + { T[] res = new T[list.Count + 1]; list.CopyTo(res, 0); res[list.Count] = item; diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs index adedd7928..2644e5c6c 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs @@ -21,26 +21,28 @@ using System.Linq; [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Dynamic")] -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// Provides helper methods to bind COM objects dynamically. /// - internal static class ComBinder { - + internal static class ComBinder + { /// /// Determines if an object is a COM object. /// /// The object to test. /// true if the object is a COM object, false otherwise. - public static bool IsComObject(object value) { + public static bool IsComObject(object value) + { return (value != null) && - (! WinRTHelper.IsWinRTType(value.GetType())) && + (!WinRTHelper.IsWinRTType(value.GetType())) && ComObject.IsComObject(value); } - public static bool CanComBind(object value) { + public static bool CanComBind(object value) + { return IsComObject(value) || value is IPseudoComObject; } @@ -52,19 +54,23 @@ namespace System.Management.Automation.ComInterop { /// The new representing the result of the binding. /// true if member evaluation may be delayed. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation) { - - if (TryGetMetaObject(ref instance)) { + public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation) + { + if (TryGetMetaObject(ref instance)) + { var comGetMember = new ComGetMemberBinder(binder, delayInvocation); result = instance.BindGetMember(comGetMember); - if (result.Expression.Type.IsValueType) { + if (result.Expression.Type.IsValueType) + { result = new DynamicMetaObject( Expression.Convert(result.Expression, typeof(object)), result.Restrictions ); } return true; - } else { + } + else + { result = null; return false; } @@ -77,7 +83,8 @@ namespace System.Management.Automation.ComInterop { /// The target of the dynamic operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) { + public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) + { return TryBindGetMember(binder, instance, out result, false); } @@ -89,13 +96,16 @@ namespace System.Management.Automation.ComInterop { /// The representing the value for the set member operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result) { - - if (TryGetMetaObject(ref instance)) { + public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result) + { + if (TryGetMetaObject(ref instance)) + { result = instance.BindSetMember(binder, value); result = new DynamicMetaObject(result.Expression, result.Restrictions.Merge(value.PSGetMethodArgumentRestriction())); return true; - } else { + } + else + { result = null; return false; } @@ -109,12 +119,15 @@ namespace System.Management.Automation.ComInterop { /// An array of instances - arguments to the invoke member operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - - if (TryGetMetaObjectInvoke(ref instance)) { + public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) + { + if (TryGetMetaObjectInvoke(ref instance)) + { result = instance.BindInvoke(binder, args); return true; - } else { + } + else + { result = null; return false; } @@ -131,7 +144,8 @@ namespace System.Management.Automation.ComInterop { /// true if operation was bound successfully; otherwise, false. public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProperty, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - if (TryGetMetaObject(ref instance)) { + if (TryGetMetaObject(ref instance)) + { var comInvokeMember = new ComInvokeMemberBinder(binder, isSetProperty); result = instance.BindInvokeMember(comInvokeMember, args); @@ -152,7 +166,9 @@ namespace System.Management.Automation.ComInterop { } return true; - } else { + } + else + { result = null; return false; } @@ -166,12 +182,15 @@ namespace System.Management.Automation.ComInterop { /// An array of instances - arguments to the invoke member operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - - if (TryGetMetaObjectInvoke(ref instance)) { + public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) + { + if (TryGetMetaObjectInvoke(ref instance)) + { result = instance.BindGetIndex(binder, args); return true; - } else { + } + else + { result = null; return false; } @@ -186,14 +205,17 @@ namespace System.Management.Automation.ComInterop { /// The representing the value for the set index operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result) { - - if (TryGetMetaObjectInvoke(ref instance)) { + public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result) + { + if (TryGetMetaObjectInvoke(ref instance)) + { result = instance.BindSetIndex(binder, args, value); result = new DynamicMetaObject(result.Expression, result.Restrictions.Merge(value.PSGetMethodArgumentRestriction())); return true; - } else { + } + else + { result = null; return false; } @@ -206,13 +228,14 @@ namespace System.Management.Automation.ComInterop { /// The target of the dynamic operation. /// The new representing the result of the binding. /// true if operation was bound successfully; otherwise, false. - public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) { - - if (IsComObject(instance.Value)) { - + public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) + { + if (IsComObject(instance.Value)) + { // Converting a COM object to any interface is always considered possible - it will result in // a QueryInterface at runtime - if (binder.Type.IsInterface) { + if (binder.Type.IsInterface) + { result = new DynamicMetaObject( Expression.Convert( instance.Expression, @@ -239,8 +262,8 @@ namespace System.Management.Automation.ComInterop { /// /// The object for which member names are requested. /// The collection of member names. - public static IEnumerable GetDynamicMemberNames(object value) { - + public static IEnumerable GetDynamicMemberNames(object value) + { return ComObject.ObjectToComObject(value).GetMemberNames(false); } @@ -251,8 +274,8 @@ namespace System.Management.Automation.ComInterop { /// The object for which member names are requested. /// The collection of member names. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal static IList GetDynamicDataMemberNames(object value) { - + internal static IList GetDynamicDataMemberNames(object value) + { return ComObject.ObjectToComObject(value).GetMemberNames(true); } @@ -265,20 +288,22 @@ namespace System.Management.Automation.ComInterop { /// The collection of pairs that represent data member's names and their data. [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal static IList> GetDynamicDataMembers(object value, IEnumerable names) { - - + internal static IList> GetDynamicDataMembers(object value, IEnumerable names) + { return ComObject.ObjectToComObject(value).GetMembers(names); } - private static bool TryGetMetaObject(ref DynamicMetaObject instance) { + private static bool TryGetMetaObject(ref DynamicMetaObject instance) + { // If we're already a COM MO don't make a new one // (we do this to prevent recursion if we call Fallback from COM) - if (instance is ComUnwrappedMetaObject) { + if (instance is ComUnwrappedMetaObject) + { return false; } - if (IsComObject(instance.Value)) { + if (IsComObject(instance.Value)) + { instance = new ComMetaObject(instance.Expression, instance.Restrictions, instance.Value); return true; } @@ -286,14 +311,17 @@ namespace System.Management.Automation.ComInterop { return false; } - private static bool TryGetMetaObjectInvoke(ref DynamicMetaObject instance) { + private static bool TryGetMetaObjectInvoke(ref DynamicMetaObject instance) + { // If we're already a COM MO don't make a new one // (we do this to prevent recursion if we call Fallback from COM) - if (TryGetMetaObject(ref instance)) { + if (TryGetMetaObject(ref instance)) + { return true; } - if (instance.Value is IPseudoComObject) { + if (instance.Value is IPseudoComObject) + { instance = ((IPseudoComObject)instance.Value).GetMetaObject(instance.Expression); return true; } @@ -304,25 +332,30 @@ namespace System.Management.Automation.ComInterop { /// /// Special binder that indicates special semantics for COM GetMember operation. /// - internal class ComGetMemberBinder : GetMemberBinder { + internal class ComGetMemberBinder : GetMemberBinder + { private readonly GetMemberBinder _originalBinder; internal bool _CanReturnCallables; internal ComGetMemberBinder(GetMemberBinder originalBinder, bool CanReturnCallables) : - base(originalBinder.Name, originalBinder.IgnoreCase) { + base(originalBinder.Name, originalBinder.IgnoreCase) + { _originalBinder = originalBinder; _CanReturnCallables = CanReturnCallables; } - public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + { return _originalBinder.FallbackGetMember(target, errorSuggestion); } - public override int GetHashCode() { + public override int GetHashCode() + { return _originalBinder.GetHashCode() ^ (_CanReturnCallables ? 1 : 0); } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { ComGetMemberBinder other = obj as ComGetMemberBinder; return other != null && _CanReturnCallables == other._CanReturnCallables && diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs index bac37e919..22a635f9f 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinderHelpers.cs @@ -20,10 +20,12 @@ using System.Globalization; using System.Management.Automation; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { - internal static class ComBinderHelpers { - - internal static bool PreferPut(Type type, bool holdsNull) { +namespace System.Management.Automation.ComInterop +{ + internal static class ComBinderHelpers + { + internal static bool PreferPut(Type type, bool holdsNull) + { Debug.Assert(type != null); if (type.IsValueType || type.IsArray) return true; @@ -32,20 +34,24 @@ namespace System.Management.Automation.ComInterop { type == typeof(DBNull) || holdsNull || type == typeof(System.Reflection.Missing) || - type == typeof(CurrencyWrapper)) { - + type == typeof(CurrencyWrapper)) + { return true; - } else { + } + else + { return false; } } - internal static bool IsByRef(DynamicMetaObject mo) { + internal static bool IsByRef(DynamicMetaObject mo) + { ParameterExpression pe = mo.Expression as ParameterExpression; return pe != null && pe.IsByRef; } - internal static bool IsPSReferenceArg(DynamicMetaObject o) { + internal static bool IsPSReferenceArg(DynamicMetaObject o) + { Type t = o.LimitType; return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(PSReference<>); } @@ -60,18 +66,23 @@ namespace System.Management.Automation.ComInterop { DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length]; bool[] isByRefArg = new bool[args.Length]; - for (int i = 0; i < args.Length; i++) { + for (int i = 0; i < args.Length; i++) + { DynamicMetaObject curArgument = args[i]; // set new arg infos to their original values or set default ones // we will do this fixup early so that we can assume we always have // arginfos in COM binder. - if (IsByRef(curArgument)) { + if (IsByRef(curArgument)) + { newArgs[i] = curArgument; isByRefArg[i] = true; - } else { - if (IsPSReferenceArg(curArgument)) { + } + else + { + if (IsPSReferenceArg(curArgument)) + { var restrictions = curArgument.Restrictions.Merge( GetTypeRestrictionForDynamicMetaObject(curArgument) ); @@ -95,7 +106,9 @@ namespace System.Management.Automation.ComInterop { ); isByRefArg[i] = true; - } else { + } + else + { if ((method.ParameterInformation != null) && (i < method.ParameterInformation.Length)) { newArgs[i] = new DynamicMetaObject(curArgument.CastOrConvertMethodArgument( @@ -119,8 +132,10 @@ namespace System.Management.Automation.ComInterop { return isByRefArg; } - internal static BindingRestrictions GetTypeRestrictionForDynamicMetaObject(DynamicMetaObject obj) { - if (obj.Value == null && obj.HasValue) { + internal static BindingRestrictions GetTypeRestrictionForDynamicMetaObject(DynamicMetaObject obj) + { + if (obj.Value == null && obj.HasValue) + { //If the meta object holds a null value, create an instance restriction for checking null return BindingRestrictions.GetInstanceRestriction(obj.Expression, null); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs index 86849c11d..9eb545bcc 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComClassMetaObject.cs @@ -15,14 +15,17 @@ using System.Dynamic; using System.Management.Automation.Interpreter; using AstUtils = System.Management.Automation.Interpreter.Utils; -namespace System.Management.Automation.ComInterop { - - internal class ComClassMetaObject : DynamicMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal class ComClassMetaObject : DynamicMetaObject + { internal ComClassMetaObject(Expression expression, ComTypeClassDesc cls) - : base(expression, BindingRestrictions.Empty, cls) { + : base(expression, BindingRestrictions.Empty, cls) + { } - public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) + { return new DynamicMetaObject( Expression.Call( AstUtils.Convert(Expression, typeof(ComTypeClassDesc)), diff --git a/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs b/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs index c1332c0e7..6092d81d4 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComDispIds.cs @@ -4,8 +4,10 @@ Copyright (c) Microsoft Corporation. All rights reserved. #if !SILVERLIGHT // ComObject -namespace System.Management.Automation.ComInterop { - internal static class ComDispIds { +namespace System.Management.Automation.ComInterop +{ + internal static class ComDispIds + { internal const int DISPID_VALUE = 0; internal const int DISPID_PROPERTYPUT = -3; internal const int DISPID_NEWENUM = -4; diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs index 3c1238e06..f35661aa5 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventDesc.cs @@ -6,8 +6,10 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -namespace System.Management.Automation.ComInterop { - internal class ComEventDesc { +namespace System.Management.Automation.ComInterop +{ + internal class ComEventDesc + { internal Guid sourceIID; internal int dispid; }; diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs index 5e2eb2530..e3ba55ee9 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs @@ -14,7 +14,8 @@ using System.Security; using ComTypes = System.Runtime.InteropServices.ComTypes; //using Microsoft.Scripting.Utils; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// This class implements an event sink for a particular RCW. /// Unlike the implementation of events in TlbImp'd assemblies, @@ -30,8 +31,8 @@ namespace System.Management.Automation.ComInterop { /// ComEventSinksContainer finalizer. Notice that lifetime of ComEventSinksContainer /// is bound to the lifetime of the RCW. /// - internal sealed class ComEventSink : MarshalByRefObject, IReflect, IDisposable { - + internal sealed class ComEventSink : MarshalByRefObject, IReflect, IDisposable + { #region private fields private Guid _sourceIid; @@ -48,7 +49,8 @@ namespace System.Management.Automation.ComInterop { /// Contains a methods DISPID (in a string formatted of "[DISPID=N]" /// and a chained list of delegates to invoke /// - private class ComEventSinkMethod { + private class ComEventSinkMethod + { public string _name; public Func _handlers; } @@ -56,13 +58,15 @@ namespace System.Management.Automation.ComInterop { #region ctor - private ComEventSink(object rcw, Guid sourceIid) { + private ComEventSink(object rcw, Guid sourceIid) + { Initialize(rcw, sourceIid); } #endregion - private void Initialize(object rcw, Guid sourceIid) { + private void Initialize(object rcw, Guid sourceIid) + { _sourceIid = sourceIid; _adviseCookie = -1; @@ -83,21 +87,27 @@ namespace System.Management.Automation.ComInterop { #region static methods - public static ComEventSink FromRuntimeCallableWrapper(object rcw, Guid sourceIid, bool createIfNotFound) { + public static ComEventSink FromRuntimeCallableWrapper(object rcw, Guid sourceIid, bool createIfNotFound) + { List comEventSinks = ComEventSinksContainer.FromRuntimeCallableWrapper(rcw, createIfNotFound); - if (comEventSinks == null) { + if (comEventSinks == null) + { return null; } ComEventSink comEventSink = null; - lock (comEventSinks) { - - foreach (ComEventSink sink in comEventSinks) { - if (sink._sourceIid == sourceIid) { + lock (comEventSinks) + { + foreach (ComEventSink sink in comEventSinks) + { + if (sink._sourceIid == sourceIid) + { comEventSink = sink; break; - } else if (sink._sourceIid == Guid.Empty) { + } + else if (sink._sourceIid == Guid.Empty) + { // we found a ComEventSink object that // was previously disposed. Now we will reuse it. sink.Initialize(rcw, sourceIid); @@ -105,7 +115,8 @@ namespace System.Management.Automation.ComInterop { } } - if (comEventSink == null && createIfNotFound == true) { + if (comEventSink == null && createIfNotFound == true) + { comEventSink = new ComEventSink(rcw, sourceIid); comEventSinks.Add(comEventSink); } @@ -116,15 +127,19 @@ namespace System.Management.Automation.ComInterop { #endregion - public void AddHandler(int dispid, object func) { + public void AddHandler(int dispid, object func) + { string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid); - lock (_lockObject) { + lock (_lockObject) + { ComEventSinkMethod sinkMethod; sinkMethod = FindSinkMethod(name); - if (sinkMethod == null) { - if (_comEventSinkMethods == null) { + if (sinkMethod == null) + { + if (_comEventSinkMethods == null) + { _comEventSinkMethods = new List(); } @@ -137,14 +152,15 @@ namespace System.Management.Automation.ComInterop { } } - public void RemoveHandler(int dispid, object func) { - + public void RemoveHandler(int dispid, object func) + { string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid); - lock (_lockObject) { - + lock (_lockObject) + { ComEventSinkMethod sinkEntry = FindSinkMethod(name); - if (sinkEntry == null){ + if (sinkEntry == null) + { return; } @@ -154,9 +170,11 @@ namespace System.Management.Automation.ComInterop { // easy since we Target property of the delegate object // is a ComEventCallContext object. Delegate[] delegates = sinkEntry._handlers.GetInvocationList(); - foreach (Delegate d in delegates) { + foreach (Delegate d in delegates) + { SplatCallSite callContext = d.Target as SplatCallSite; - if (callContext != null && callContext._callable.Equals(func)) { + if (callContext != null && callContext._callable.Equals(func)) + { sinkEntry._handlers -= d as Func; break; } @@ -170,7 +188,8 @@ namespace System.Management.Automation.ComInterop { // We can Unadvise from the ConnectionPoint if no more sink entries // are registered for this interface //(calling Dispose will call IConnectionPoint.Unadvise). - if (_comEventSinkMethods.Count == 0) { + if (_comEventSinkMethods.Count == 0) + { // notice that we do not remove // ComEventSinkEntry from the list, we will re-use this data structure // if a new handler needs to be attached. @@ -179,11 +198,13 @@ namespace System.Management.Automation.ComInterop { } } - public object ExecuteHandler(string name, object[] args) { + public object ExecuteHandler(string name, object[] args) + { ComEventSinkMethod site; site = FindSinkMethod(name); - if (site != null && site._handlers != null) { + if (site != null && site._handlers != null) + { return site._handlers(args); } @@ -194,50 +215,62 @@ namespace System.Management.Automation.ComInterop { #region Unimplemented members - public FieldInfo GetField(string name, BindingFlags bindingAttr) { + public FieldInfo GetField(string name, BindingFlags bindingAttr) + { return null; } - public FieldInfo[] GetFields(BindingFlags bindingAttr) { + public FieldInfo[] GetFields(BindingFlags bindingAttr) + { return Utils.EmptyArray(); } - public MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { + public MemberInfo[] GetMember(string name, BindingFlags bindingAttr) + { return Utils.EmptyArray(); } - public MemberInfo[] GetMembers(BindingFlags bindingAttr) { + public MemberInfo[] GetMembers(BindingFlags bindingAttr) + { return Utils.EmptyArray(); } - public MethodInfo GetMethod(string name, BindingFlags bindingAttr) { + public MethodInfo GetMethod(string name, BindingFlags bindingAttr) + { return null; } - public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { + public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) + { return null; } - public MethodInfo[] GetMethods(BindingFlags bindingAttr) { + public MethodInfo[] GetMethods(BindingFlags bindingAttr) + { return Utils.EmptyArray(); } - public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { + public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + { return null; } - public PropertyInfo GetProperty(string name, BindingFlags bindingAttr) { + public PropertyInfo GetProperty(string name, BindingFlags bindingAttr) + { return null; } - public PropertyInfo[] GetProperties(BindingFlags bindingAttr) { + public PropertyInfo[] GetProperties(BindingFlags bindingAttr) + { return Utils.EmptyArray(); } #endregion - public Type UnderlyingSystemType { - get { + public Type UnderlyingSystemType + { + get + { return typeof(object); } } @@ -250,8 +283,8 @@ namespace System.Management.Automation.ComInterop { object[] args, ParameterModifier[] modifiers, CultureInfo culture, - string[] namedParameters) { - + string[] namedParameters) + { return ExecuteHandler(name, args); } @@ -259,27 +292,33 @@ namespace System.Management.Automation.ComInterop { #region IDisposable - public void Dispose() { + public void Dispose() + { DisposeAll(); GC.SuppressFinalize(this); } #endregion - ~ComEventSink() { + ~ComEventSink() + { DisposeAll(); } - private void DisposeAll() { - if (_connectionPoint == null) { + private void DisposeAll() + { + if (_connectionPoint == null) + { return; } - if (_adviseCookie == -1) { + if (_adviseCookie == -1) + { return; } - try { + try + { _connectionPoint.Unadvise(_adviseCookie); // _connectionPoint has entered the CLR in the constructor @@ -288,23 +327,29 @@ namespace System.Management.Automation.ComInterop { // hence it is safe to call RCO on it w/o worrying about // killing the RCW for other objects that link to it. Marshal.ReleaseComObject(_connectionPoint); - } catch (Exception ex) { + } + catch (Exception ex) + { // if something has gone wrong, and the object is no longer attached to the CLR, // the Unadvise is going to throw. In this case, since we're going away anyway, // we'll ignore the failure and quietly go on our merry way. COMException exCOM = ex as COMException; - if (exCOM != null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION) { + if (exCOM != null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION) + { Debug.Assert(false, "IConnectionPoint::Unadvise returned CONNECT_E_NOCONNECTION."); throw; } - } finally { + } + finally + { _connectionPoint = null; _adviseCookie = -1; _sourceIid = Guid.Empty; } } - private ComEventSinkMethod FindSinkMethod(string name) { + private ComEventSinkMethod FindSinkMethod(string name) + { if (_comEventSinkMethods == null) return null; diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs index 93e433ee2..80760543f 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSinkProxy.cs @@ -15,7 +15,8 @@ using System.Security; using System.Security.Permissions; //using Microsoft.Scripting.Utils; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// ComEventSinkProxy class is responsible for handling QIs for sourceIid /// on instances of ComEventSink. @@ -36,19 +37,21 @@ namespace System.Management.Automation.ComInterop { /// "I implement this interface" for event sinks only since the common /// practice is to use IDistpach.Invoke when calling into event sinks). /// - internal sealed class ComEventSinkProxy : RealProxy { - + internal sealed class ComEventSinkProxy : RealProxy + { private Guid _sinkIid; private ComEventSink _sink; - private static readonly MethodInfo _methodInfoInvokeMember = typeof(ComEventSink).GetMethod("InvokeMember", BindingFlags.Instance | BindingFlags.Public); - + private static readonly MethodInfo s_methodInfoInvokeMember = typeof(ComEventSink).GetMethod("InvokeMember", BindingFlags.Instance | BindingFlags.Public); + #region ctors - private ComEventSinkProxy() { + private ComEventSinkProxy() + { } public ComEventSinkProxy(ComEventSink sink, Guid sinkIid) - : base(typeof(ComEventSink)) { + : base(typeof(ComEventSink)) + { _sink = sink; _sinkIid = sinkIid; } @@ -57,9 +60,11 @@ namespace System.Management.Automation.ComInterop { #region Base Class Overrides - public override IntPtr SupportsInterface(ref Guid iid) { + public override IntPtr SupportsInterface(ref Guid iid) + { // if the iid is the sink iid, we ask the base class for an rcw to IDispatch - if (iid == _sinkIid) { + if (iid == _sinkIid) + { IntPtr retVal = IntPtr.Zero; retVal = Marshal.GetIDispatchForObject(_sink); return retVal; @@ -69,8 +74,8 @@ namespace System.Management.Automation.ComInterop { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - public override IMessage Invoke(IMessage msg) { - + public override IMessage Invoke(IMessage msg) + { //Only know how to handle method calls (property and fields accessors count as methods) IMethodCallMessage methodCallMessage = msg as IMethodCallMessage; if (methodCallMessage == null) @@ -86,10 +91,12 @@ namespace System.Management.Automation.ComInterop { // Since we don't use namedParameters in ComEventSink.InvokeMember - we simply ignore it here // and pass-in null. MethodInfo methodInfo = (MethodInfo)methodCallMessage.MethodBase; - if (methodInfo == _methodInfoInvokeMember) { + if (methodInfo == s_methodInfoInvokeMember) + { object retVal = null; - try { + try + { // InvokeMember(string name, BindingFlags bindingFlags, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) retVal = ((IReflect)_sink).InvokeMember( /*name*/ methodCallMessage.Args[0] as string, @@ -100,7 +107,9 @@ namespace System.Management.Automation.ComInterop { /*modifiers*/ methodCallMessage.Args[5] as ParameterModifier[], /*culture*/ methodCallMessage.Args[6] as CultureInfo, /*namedParameters*/ null); - } catch (Exception ex) { + } + catch (Exception ex) + { return new ReturnMessage(ex.InnerException, methodCallMessage); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs index ee74a3a6c..44bf9ae1d 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs @@ -9,36 +9,44 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// ComEventSinksContainer is just a regular list with a finalizer. /// This list is usually attached as a custom data for RCW object and /// is finalized whenever RCW is finalized. /// - internal class ComEventSinksContainer : List, IDisposable { - private ComEventSinksContainer() { + internal class ComEventSinksContainer : List, IDisposable + { + private ComEventSinksContainer() + { } - private static readonly object _ComObjectEventSinksKey = new object(); + private static readonly object s_comObjectEventSinksKey = new object(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] - public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool createIfNotFound) { + public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool createIfNotFound) + { // !!! Marshal.Get/SetComObjectData has a LinkDemand for UnmanagedCode which will turn into // a full demand. We need to avoid this by making this method SecurityCritical - object data = Marshal.GetComObjectData(rcw, _ComObjectEventSinksKey); - if (data != null || createIfNotFound == false) { + object data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey); + if (data != null || createIfNotFound == false) + { return (ComEventSinksContainer)data; } - lock (_ComObjectEventSinksKey) { - data = Marshal.GetComObjectData(rcw, _ComObjectEventSinksKey); - if (data != null) { + lock (s_comObjectEventSinksKey) + { + data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey); + if (data != null) + { return (ComEventSinksContainer)data; } ComEventSinksContainer comEventSinks = new ComEventSinksContainer(); - if (!Marshal.SetComObjectData(rcw, _ComObjectEventSinksKey, comEventSinks)) { + if (!Marshal.SetComObjectData(rcw, s_comObjectEventSinksKey, comEventSinks)) + { throw Error.SetComObjectDataFailed(); } @@ -48,20 +56,24 @@ namespace System.Management.Automation.ComInterop { #region IDisposable Members - public void Dispose() { + public void Dispose() + { DisposeAll(); GC.SuppressFinalize(this); } #endregion - private void DisposeAll() { - foreach (ComEventSink sink in this) { + private void DisposeAll() + { + foreach (ComEventSink sink in this) + { sink.Dispose(); } } - ~ComEventSinksContainer() { + ~ComEventSinksContainer() + { DisposeAll(); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs index 1e2b0f41e..4bdc0acd0 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs @@ -15,7 +15,8 @@ using System.Diagnostics; //using Microsoft.Scripting.Utils; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ // // ComFallbackMetaObject just delegates everything to the binder. // @@ -24,32 +25,40 @@ namespace System.Management.Automation.ComInterop { // // Also: we don't need to implement these for any operations other than those // supported by ComBinder - internal class ComFallbackMetaObject : DynamicMetaObject { + internal class ComFallbackMetaObject : DynamicMetaObject + { internal ComFallbackMetaObject(Expression expression, BindingRestrictions restrictions, object arg) - : base(expression, restrictions, arg) { + : base(expression, restrictions, arg) + { } - public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { + public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) + { return binder.FallbackGetIndex(UnwrapSelf(), indexes); } - public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { + public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) + { return binder.FallbackSetIndex(UnwrapSelf(), indexes, value); } - public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { return binder.FallbackGetMember(UnwrapSelf()); } - public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) + { return binder.FallbackInvokeMember(UnwrapSelf(), args); } - public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { + public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) + { return binder.FallbackSetMember(UnwrapSelf(), value); } - protected virtual ComUnwrappedMetaObject UnwrapSelf() { + protected virtual ComUnwrappedMetaObject UnwrapSelf() + { return new ComUnwrappedMetaObject( ComObject.RcwFromComObject(Expression), Restrictions.Merge(ComBinderHelpers.GetTypeRestrictionForDynamicMetaObject(this)), @@ -60,9 +69,11 @@ namespace System.Management.Automation.ComInterop { // This type exists as a signal type, so ComBinder knows not to try to bind // again when we're trying to fall back - internal sealed class ComUnwrappedMetaObject : DynamicMetaObject { + internal sealed class ComUnwrappedMetaObject : DynamicMetaObject + { internal ComUnwrappedMetaObject(Expression expression, BindingRestrictions restrictions, object value) - : base(expression, restrictions, value) { + : base(expression, restrictions, value) + { } } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComHresults.cs b/src/System.Management.Automation/engine/ComInterop/ComHresults.cs index 951364f03..c90954cc5 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComHresults.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComHresults.cs @@ -4,10 +4,10 @@ Copyright (c) Microsoft Corporation. All rights reserved. #if !SILVERLIGHT // ComObject -namespace System.Management.Automation.ComInterop { - - internal static class ComHresults { - +namespace System.Management.Automation.ComInterop +{ + internal static class ComHresults + { internal const int S_OK = 0; internal const int CONNECT_E_NOCONNECTION = unchecked((int)0x80040200); diff --git a/src/System.Management.Automation/engine/ComInterop/ComInterop.cs b/src/System.Management.Automation/engine/ComInterop/ComInterop.cs index 2d5b445a5..452cba824 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInterop.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInterop.cs @@ -8,15 +8,16 @@ using System; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ [ ComImport, InterfaceType(ComInterfaceType.InterfaceIsIDispatch), Guid("00020400-0000-0000-C000-000000000046") ] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces")] - internal interface IDispatchForReflection { + internal interface IDispatchForReflection + { } [ @@ -24,8 +25,8 @@ namespace System.Management.Automation.ComInterop { InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046"), ] - internal interface IDispatch { - + internal interface IDispatch + { [PreserveSig] int TryGetTypeInfoCount(out uint pctinfo); @@ -58,12 +59,13 @@ namespace System.Management.Automation.ComInterop { /// /// Layout of the IDispatch vtable /// - internal enum IDispatchMethodIndices { + internal enum IDispatchMethodIndices + { IUnknown_QueryInterface, IUnknown_AddRef, IUnknown_Release, - IDispatch_GetTypeInfoCount , + IDispatch_GetTypeInfoCount, IDispatch_GetTypeInfo, IDispatch_GetIDsOfNames, IDispatch_Invoke @@ -74,10 +76,10 @@ namespace System.Management.Automation.ComInterop { InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B196B283-BAB4-101A-B69C-00AA00341D07") ] - internal interface IProvideClassInfo { + internal interface IProvideClassInfo + { void GetClassInfo(out IntPtr info); } - } #endif diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs index 2e9ad0143..b55d93324 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeAction.cs @@ -18,26 +18,33 @@ using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// Invokes the object. If it falls back, just produce an error. /// - internal sealed class ComInvokeAction : InvokeBinder { + internal sealed class ComInvokeAction : InvokeBinder + { internal ComInvokeAction(CallInfo callInfo) - : base(callInfo) { + : base(callInfo) + { } - public override int GetHashCode() { + public override int GetHashCode() + { return base.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { return base.Equals(obj as ComInvokeAction); } - public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { + public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) + { DynamicMetaObject res; - if (ComBinder.TryBindInvoke(this, target, args, out res)) { + if (ComBinder.TryBindInvoke(this, target, args, out res)) + { return res; } @@ -57,11 +64,13 @@ namespace System.Management.Automation.ComInterop { /// Splats the arguments to another nested dynamic site, which does the /// real invocation of the IDynamicMetaObjectProvider. /// - internal sealed class SplatInvokeBinder : CallSiteBinder { + internal sealed class SplatInvokeBinder : CallSiteBinder + { internal readonly static SplatInvokeBinder Instance = new SplatInvokeBinder(); // Just splat the args and dispatch through a nested site - public override Expression Bind(object[] args, ReadOnlyCollection parameters, LabelTarget returnLabel) { + public override Expression Bind(object[] args, ReadOnlyCollection parameters, LabelTarget returnLabel) + { Debug.Assert(args.Length == 2); int count = ((object[])args[1]).Length; @@ -72,7 +81,8 @@ namespace System.Management.Automation.ComInterop { nestedArgs.Add(parameters[0]); delegateArgs[0] = typeof(CallSite); delegateArgs[1] = typeof(object); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { nestedArgs.Add(Expression.ArrayAccess(array, Expression.Constant(i))); delegateArgs[i + 2] = typeof(object).MakeByRefType(); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index f5588edb6..e42ea3b7e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -18,8 +18,10 @@ using ComTypes = System.Runtime.InteropServices.ComTypes; using System.Linq; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { - internal sealed class ComInvokeBinder { +namespace System.Management.Automation.ComInterop +{ + internal sealed class ComInvokeBinder + { private readonly ComMethodDesc _methodDesc; private readonly Expression _method; // ComMethodDesc to be called private readonly Expression _dispatch; // IDispatch @@ -46,15 +48,15 @@ namespace System.Management.Automation.ComInterop { private ParameterExpression _propertyPutDispId; internal ComInvokeBinder( - CallInfo callInfo, + CallInfo callInfo, DynamicMetaObject[] args, bool[] isByRef, - BindingRestrictions restrictions, - Expression method, - Expression dispatch, + BindingRestrictions restrictions, + Expression method, + Expression dispatch, ComMethodDesc methodDesc - ) { - + ) + { Debug.Assert(callInfo != null, "arguments"); Debug.Assert(args != null, "args"); Debug.Assert(isByRef != null, "isByRef"); @@ -77,62 +79,78 @@ namespace System.Management.Automation.ComInterop { _instance = dispatch; } - private ParameterExpression DispatchObjectVariable { + private ParameterExpression DispatchObjectVariable + { get { return EnsureVariable(ref _dispatchObject, typeof(IDispatch), "dispatchObject"); } } - private ParameterExpression DispatchPointerVariable { + private ParameterExpression DispatchPointerVariable + { get { return EnsureVariable(ref _dispatchPointer, typeof(IntPtr), "dispatchPointer"); } } - private ParameterExpression DispIdVariable { + private ParameterExpression DispIdVariable + { get { return EnsureVariable(ref _dispId, typeof(int), "dispId"); } } - private ParameterExpression DispParamsVariable { + private ParameterExpression DispParamsVariable + { get { return EnsureVariable(ref _dispParams, typeof(ComTypes.DISPPARAMS), "dispParams"); } } - private ParameterExpression InvokeResultVariable { + private ParameterExpression InvokeResultVariable + { get { return EnsureVariable(ref _invokeResult, typeof(Variant), "invokeResult"); } } - private ParameterExpression ReturnValueVariable { + private ParameterExpression ReturnValueVariable + { get { return EnsureVariable(ref _returnValue, typeof(object), "returnValue"); } } - private ParameterExpression DispIdsOfKeywordArgsPinnedVariable { + private ParameterExpression DispIdsOfKeywordArgsPinnedVariable + { get { return EnsureVariable(ref _dispIdsOfKeywordArgsPinned, typeof(GCHandle), "dispIdsOfKeywordArgsPinned"); } } - private ParameterExpression PropertyPutDispIdVariable { + private ParameterExpression PropertyPutDispIdVariable + { get { return EnsureVariable(ref _propertyPutDispId, typeof(int), "propertyPutDispId"); } } - private ParameterExpression ParamVariantsVariable { - get { - if (_paramVariants == null) { + private ParameterExpression ParamVariantsVariable + { + get + { + if (_paramVariants == null) + { _paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"); } return _paramVariants; } } - private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name) { - if (var != null) { + private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name) + { + if (var != null) + { return var; } return var = Expression.Variable(type, name); } - private static Type MarshalType(DynamicMetaObject mo, bool isByRef) { + private static Type MarshalType(DynamicMetaObject mo, bool isByRef) + { Type marshalType = (mo.Value == null && mo.HasValue && !mo.LimitType.IsValueType) ? null : mo.LimitType; // we are not checking that mo.Expression is writeable or whether evaluating it has no sideeffects // the assumption is that whoever matched it with ByRef arginfo took care of this. - if (isByRef) { + if (isByRef) + { // Null just means that null was supplied. - if (marshalType == null) { + if (marshalType == null) + { marshalType = mo.Expression.Type; } marshalType = marshalType.MakeByRefType(); @@ -140,14 +158,16 @@ namespace System.Management.Automation.ComInterop { return marshalType; } - internal DynamicMetaObject Invoke() { + internal DynamicMetaObject Invoke() + { _keywordArgNames = _callInfo.ArgumentNames.ToArray(); _totalExplicitArgs = _args.Length; - + Type[] marshalArgTypes = new Type[_args.Length]; // We already tested the instance, so no need to test it again - for (int i = 0; i < _args.Length; i++) { + for (int i = 0; i < _args.Length; i++) + { DynamicMetaObject curMo = _args[i]; marshalArgTypes[i] = MarshalType(curMo, _isByRef[i]); } @@ -160,11 +180,13 @@ namespace System.Management.Automation.ComInterop { ); } - private static void AddNotNull(List list, ParameterExpression var) { + private static void AddNotNull(List list, ParameterExpression var) + { if (var != null) list.Add(var); } - private Expression CreateScope(Expression expression) { + private Expression CreateScope(Expression expression) + { List vars = new List(); AddNotNull(vars, _dispatchObject); AddNotNull(vars, _dispatchPointer); @@ -178,7 +200,8 @@ namespace System.Management.Automation.ComInterop { return vars.Count > 0 ? Expression.Block(vars, expression) : expression; } - private Expression GenerateTryBlock() { + private Expression GenerateTryBlock() + { // // Declare variables // @@ -189,7 +212,8 @@ namespace System.Management.Automation.ComInterop { List tryStatements = new List(); Expression expr; - if (_keywordArgNames.Length > 0) { + if (_keywordArgNames.Length > 0) + { string[] names = _keywordArgNames.AddFirst(_methodDesc.Name); tryStatements.Add( @@ -223,12 +247,16 @@ namespace System.Management.Automation.ComInterop { int reverseIndex = _varEnumSelector.VariantBuilders.Length - 1; int positionalArgs = _varEnumSelector.VariantBuilders.Length - _keywordArgNames.Length; // args passed by position order and not by name - for (int i = 0; i < _varEnumSelector.VariantBuilders.Length; i++, reverseIndex--) { + for (int i = 0; i < _varEnumSelector.VariantBuilders.Length; i++, reverseIndex--) + { int variantIndex; - if (i >= positionalArgs) { + if (i >= positionalArgs) + { // Named arguments are in order at the start of rgArgs variantIndex = i - positionalArgs; - } else { + } + else + { // Positial arguments are in reverse order at the tail of rgArgs variantIndex = reverseIndex; } @@ -239,7 +267,8 @@ namespace System.Management.Automation.ComInterop { parameters[i + 1] ); - if (marshal != null) { + if (marshal != null) + { tryStatements.Add(marshal); } } @@ -250,13 +279,19 @@ namespace System.Management.Automation.ComInterop { // ComTypes.INVOKEKIND invokeKind; - if (_methodDesc.IsPropertyPut) { - if (_methodDesc.IsPropertyPutRef) { + if (_methodDesc.IsPropertyPut) + { + if (_methodDesc.IsPropertyPutRef) + { invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF; - } else { + } + else + { invokeKind = ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT; } - } else { + } + else + { // INVOKE_PROPERTYGET should only be needed for COM objects without typeinfo, where we might have to treat properties as methods invokeKind = ComTypes.INVOKEKIND.INVOKE_FUNC | ComTypes.INVOKEKIND.INVOKE_PROPERTYGET; } @@ -305,9 +340,11 @@ namespace System.Management.Automation.ComInterop { Expression[] parametersForUpdates = MakeArgumentExpressions(); tryStatements.Add(Expression.Assign(ReturnValueVariable, invokeResultObject)); - for (int i = 0, n = variants.Length; i < n; i++) { + for (int i = 0, n = variants.Length; i < n; i++) + { Expression updateFromReturn = variants[i].UpdateFromReturn(parametersForUpdates[i + 1]); - if (updateFromReturn != null) { + if (updateFromReturn != null) + { tryStatements.Add(updateFromReturn); } } @@ -317,7 +354,8 @@ namespace System.Management.Automation.ComInterop { return Expression.Block(new[] { excepInfo, argErr, hresult }, tryStatements); } - private Expression GenerateFinallyBlock() { + private Expression GenerateFinallyBlock() + { List finallyStatements = new List(); // @@ -333,9 +371,11 @@ namespace System.Management.Automation.ComInterop { // // Clear memory allocated for marshalling // - for (int i = 0, n = _varEnumSelector.VariantBuilders.Length; i < n; i++) { + for (int i = 0, n = _varEnumSelector.VariantBuilders.Length; i < n; i++) + { Expression clear = _varEnumSelector.VariantBuilders[i].Clear(); - if (clear != null) { + if (clear != null) + { finallyStatements.Add(clear); } } @@ -354,7 +394,8 @@ namespace System.Management.Automation.ComInterop { // // _dispIdsOfKeywordArgsPinned.Free() // - if (_dispIdsOfKeywordArgsPinned != null) { + if (_dispIdsOfKeywordArgsPinned != null) + { finallyStatements.Add( Expression.Call( DispIdsOfKeywordArgsPinnedVariable, @@ -371,7 +412,8 @@ namespace System.Management.Automation.ComInterop { /// Create a stub for the target of the optimized lopop. /// /// - private Expression MakeIDispatchInvokeTarget() { + private Expression MakeIDispatchInvokeTarget() + { Debug.Assert(_varEnumSelector.VariantBuilders.Length == _totalExplicitArgs); List exprs = new List(); @@ -389,7 +431,8 @@ namespace System.Management.Automation.ComInterop { // // _dispParams.rgvararg = RuntimeHelpers.UnsafeMethods.ConvertVariantByrefToPtr(ref _paramVariants._element0) // - if (_totalExplicitArgs != 0) { + if (_totalExplicitArgs != 0) + { exprs.Add( Expression.Assign( Expression.Field( @@ -417,7 +460,8 @@ namespace System.Management.Automation.ComInterop { ) ); - if (_methodDesc.IsPropertyPut) { + if (_methodDesc.IsPropertyPut) + { // // dispParams.cNamedArgs = 1; // dispParams.rgdispidNamedArgs = RuntimeHelpers.UnsafeMethods.GetNamedArgsForPropertyPut() @@ -451,7 +495,9 @@ namespace System.Management.Automation.ComInterop { ) ) ); - } else { + } + else + { // // _dispParams.cNamedArgs = N; // @@ -490,8 +536,10 @@ namespace System.Management.Automation.ComInterop { exprs.Add(ReturnValueVariable); var vars = new List(); - foreach (var variant in _varEnumSelector.VariantBuilders) { - if (variant.TempVariable != null) { + foreach (var variant in _varEnumSelector.VariantBuilders) + { + if (variant.TempVariable != null) + { vars.Add(variant.TempVariable); } } @@ -502,23 +550,28 @@ namespace System.Management.Automation.ComInterop { exprs.Add(System.Management.Automation.Language.ExpressionCache.AutomationNullConstant); } - return Expression.Block(vars, exprs);; + return Expression.Block(vars, exprs); ; } /// /// Gets expressions to access all the arguments. This includes the instance argument. /// - private Expression[] MakeArgumentExpressions() { + private Expression[] MakeArgumentExpressions() + { Expression[] res; int copy = 0; - if (_instance != null) { + if (_instance != null) + { res = new Expression[_args.Length + 1]; res[copy++] = _instance; - } else { + } + else + { res = new Expression[_args.Length]; } - for (int i = 0; i < _args.Length; i++) { + for (int i = 0; i < _args.Length; i++) + { res[copy++] = _args[i].Expression; } return res; diff --git a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs index 09be6a229..d2fbc3273 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs @@ -15,39 +15,48 @@ using System.Collections.Generic; //using Microsoft.Scripting.Utils; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ // Note: we only need to support the operations used by ComBinder - internal class ComMetaObject : DynamicMetaObject { + internal class ComMetaObject : DynamicMetaObject + { internal ComMetaObject(Expression expression, BindingRestrictions restrictions, object arg) - : base(expression, restrictions, arg) { + : base(expression, restrictions, arg) + { } - public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) + { return binder.Defer(args.AddFirst(WrapSelf())); } - public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) + { return binder.Defer(args.AddFirst(WrapSelf())); } - public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { return binder.Defer(WrapSelf()); } - public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { + public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) + { return binder.Defer(WrapSelf(), value); } - public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { + public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) + { return binder.Defer(WrapSelf(), indexes); } - public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { + public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) + { return binder.Defer(WrapSelf(), indexes.AddLast(value)); } - private DynamicMetaObject WrapSelf() { + private DynamicMetaObject WrapSelf() + { return new DynamicMetaObject( ComObject.RcwToComObject(Expression), BindingRestrictions.GetExpressionRestriction( diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 3433e3a82..e297a72e5 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -12,33 +12,36 @@ using System.Globalization; using Marshal = System.Runtime.InteropServices.Marshal; using VarEnum = System.Runtime.InteropServices.VarEnum; -namespace System.Management.Automation.ComInterop { - - internal class ComMethodDesc { - +namespace System.Management.Automation.ComInterop +{ + internal class ComMethodDesc + { private readonly int _memid; // this is the member id extracted from FUNCDESC.memid private readonly string _name; internal readonly INVOKEKIND InvokeKind; private readonly int _paramCnt; - private ComMethodDesc(int dispId) { + private ComMethodDesc(int dispId) + { _memid = dispId; } internal ComMethodDesc(string name, int dispId) - : this(dispId) { + : this(dispId) + { // no ITypeInfo constructor _name = name; } internal ComMethodDesc(string name, int dispId, INVOKEKIND invkind) - : this(name, dispId) { + : this(name, dispId) + { InvokeKind = invkind; } internal ComMethodDesc(ITypeInfo typeInfo, FUNCDESC funcDesc) - : this(funcDesc.memid) { - + : this(funcDesc.memid) + { InvokeKind = funcDesc.invkind; int cNames; @@ -46,7 +49,8 @@ namespace System.Management.Automation.ComInterop { typeInfo.GetNames(_memid, rgNames, rgNames.Length, out cNames); bool skipLast = false; - if (IsPropertyPut && rgNames[rgNames.Length - 1] == null) { + if (IsPropertyPut && rgNames[rgNames.Length - 1] == null) + { rgNames[rgNames.Length - 1] = "value"; cNames++; skipLast = true; @@ -55,32 +59,40 @@ namespace System.Management.Automation.ComInterop { _name = rgNames[0]; _paramCnt = funcDesc.cParams; - + ReturnType = ComUtil.GetTypeFromTypeDesc(funcDesc.elemdescFunc.tdesc); ParameterInformation = ComUtil.GetParameterInformation(funcDesc, skipLast); } - public string Name { - get { + public string Name + { + get + { Debug.Assert(_name != null); return _name; } } - public int DispId { + public int DispId + { get { return _memid; } } - public bool IsPropertyGet { - get { + public bool IsPropertyGet + { + get + { return (InvokeKind & INVOKEKIND.INVOKE_PROPERTYGET) != 0; } } - public bool IsDataMember { - get { + public bool IsDataMember + { + get + { //must be regular get - if (!IsPropertyGet || DispId == ComDispIds.DISPID_NEWENUM) { + if (!IsPropertyGet || DispId == ComDispIds.DISPID_NEWENUM) + { return false; } @@ -89,20 +101,26 @@ namespace System.Management.Automation.ComInterop { } } - public bool IsPropertyPut { - get { + public bool IsPropertyPut + { + get + { return (InvokeKind & (INVOKEKIND.INVOKE_PROPERTYPUT | INVOKEKIND.INVOKE_PROPERTYPUTREF)) != 0; } } - public bool IsPropertyPutRef { - get { + public bool IsPropertyPutRef + { + get + { return (InvokeKind & INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0; } } - - internal int ParamCount { - get { + + internal int ParamCount + { + get + { return _paramCnt; } } @@ -115,7 +133,6 @@ namespace System.Management.Automation.ComInterop { get; set; } - } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComObject.cs b/src/System.Management.Automation/engine/ComInterop/ComObject.cs index 72feba2a6..6b77da703 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComObject.cs @@ -18,53 +18,63 @@ using System.Security; using System.Security.Permissions; using System.Dynamic; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// This is a helper class for runtime-callable-wrappers of COM instances. We create one instance of this type /// for every generic RCW instance. /// - internal class ComObject : IDynamicMetaObjectProvider { + internal class ComObject : IDynamicMetaObjectProvider + { /// /// The runtime-callable wrapper /// private readonly object _rcw; - internal ComObject(object rcw) { + internal ComObject(object rcw) + { Debug.Assert(ComObject.IsComObject(rcw)); _rcw = rcw; } - internal object RuntimeCallableWrapper { - get { + internal object RuntimeCallableWrapper + { + get + { return _rcw; } } - private readonly static object _ComObjectInfoKey = new object(); + private readonly static object s_comObjectInfoKey = new object(); /// /// This is the factory method to get the ComObject corresponding to an RCW /// /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - public static ComObject ObjectToComObject(object rcw) { + public static ComObject ObjectToComObject(object rcw) + { Debug.Assert(ComObject.IsComObject(rcw)); // Marshal.Get/SetComObjectData has a LinkDemand for UnmanagedCode which will turn into // a full demand. We could avoid this by making this method SecurityCritical - object data = Marshal.GetComObjectData(rcw, _ComObjectInfoKey); - if (data != null) { + object data = Marshal.GetComObjectData(rcw, s_comObjectInfoKey); + if (data != null) + { return (ComObject)data; } - lock (_ComObjectInfoKey) { - data = Marshal.GetComObjectData(rcw, _ComObjectInfoKey); - if (data != null) { + lock (s_comObjectInfoKey) + { + data = Marshal.GetComObjectData(rcw, s_comObjectInfoKey); + if (data != null) + { return (ComObject)data; } ComObject comObjectInfo = CreateComObject(rcw); - if (!Marshal.SetComObjectData(rcw, _ComObjectInfoKey, comObjectInfo)) { + if (!Marshal.SetComObjectData(rcw, s_comObjectInfoKey, comObjectInfo)) + { throw Error.SetComObjectDataFailed(); } @@ -73,7 +83,8 @@ namespace System.Management.Automation.ComInterop { } // Expression that unwraps ComObject - internal static MemberExpression RcwFromComObject(Expression comObject) { + internal static MemberExpression RcwFromComObject(Expression comObject) + { Debug.Assert(comObject != null && typeof(ComObject).IsAssignableFrom(comObject.Type), "must be ComObject"); return Expression.Property( @@ -83,16 +94,19 @@ namespace System.Management.Automation.ComInterop { } // Expression that finds or creates a ComObject that corresponds to given Rcw - internal static MethodCallExpression RcwToComObject(Expression rcw) { + internal static MethodCallExpression RcwToComObject(Expression rcw) + { return Expression.Call( typeof(ComObject).GetMethod("ObjectToComObject"), Helpers.Convert(rcw, typeof(object)) ); } - private static ComObject CreateComObject(object rcw) { + private static ComObject CreateComObject(object rcw) + { IDispatch dispatchObject = rcw as IDispatch; - if (dispatchObject != null) { + if (dispatchObject != null) + { // We can do method invocations on IDispatch objects return new IDispatchComObject(dispatchObject); } @@ -101,25 +115,28 @@ namespace System.Management.Automation.ComInterop { return new ComObject(rcw); } - internal virtual IList GetMemberNames(bool dataOnly) { + internal virtual IList GetMemberNames(bool dataOnly) + { return Utils.EmptyArray(); } - internal virtual IList> GetMembers(IEnumerable names) { + internal virtual IList> GetMembers(IEnumerable names) + { return Utils.EmptyArray>(); } - DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { return new ComFallbackMetaObject(parameter, BindingRestrictions.Empty, this); } - private static readonly Type ComObjectType = typeof(object).Assembly.GetType("System.__ComObject"); + private static readonly Type s_comObjectType = typeof(object).Assembly.GetType("System.__ComObject"); - internal static bool IsComObject(object obj) { + internal static bool IsComObject(object obj) + { // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust - return obj != null && ComObjectType.IsAssignableFrom(obj.GetType()); + return obj != null && s_comObjectType.IsAssignableFrom(obj.GetType()); } - } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs index 097ab7c1e..799de11e1 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs @@ -10,12 +10,13 @@ using System.Text; using Marshal = System.Runtime.InteropServices.Marshal; using VarEnum = System.Runtime.InteropServices.VarEnum; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// The parameter description of a method defined in a type library /// - internal class ComParamDesc { + internal class ComParamDesc + { # region private fields private readonly bool _isOut; // is an output parameter? @@ -34,16 +35,18 @@ namespace System.Management.Automation.ComInterop { /// /// Creates a representation for the paramter of a COM method /// - internal ComParamDesc(ref ELEMDESC elemDesc, string name) { + internal ComParamDesc(ref ELEMDESC elemDesc, string name) + { // Ensure _defaultValue is set to DBNull.Value regardless of whether or not the // default value is extracted from the parameter description. Failure to do so // yields a runtime exception in the ToString() function. _defaultValue = DBNull.Value; - if (!String.IsNullOrEmpty(name)) { + if (!String.IsNullOrEmpty(name)) + { // This is a parameter, not a return value - this._isOut = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOUT) != 0; - this._isOpt = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOPT) != 0; + _isOut = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOUT) != 0; + _isOpt = (elemDesc.desc.paramdesc.wParamFlags & PARAMFLAG.PARAMFLAG_FOPT) != 0; // TODO: The PARAMDESCEX struct has a memory issue that needs to be resolved. For now, we ignore it. //_defaultValue = PARAMDESCEX.GetDefaultValue(ref elemDesc.desc.paramdesc); } @@ -51,12 +54,18 @@ namespace System.Management.Automation.ComInterop { _name = name; _vt = (VarEnum)elemDesc.tdesc.vt; TYPEDESC typeDesc = elemDesc.tdesc; - while (true) { - if (_vt == VarEnum.VT_PTR) { - this._byRef = true; - } else if (_vt == VarEnum.VT_ARRAY) { - this._isArray = true; - } else { + while (true) + { + if (_vt == VarEnum.VT_PTR) + { + _byRef = true; + } + else if (_vt == VarEnum.VT_ARRAY) + { + _isArray = true; + } + else + { break; } @@ -66,7 +75,8 @@ namespace System.Management.Automation.ComInterop { } VarEnum vtWithoutByref = _vt; - if ((_vt & VarEnum.VT_BYREF) != 0) { + if ((_vt & VarEnum.VT_BYREF) != 0) + { vtWithoutByref = (_vt & ~VarEnum.VT_BYREF); _byRef = true; } @@ -79,33 +89,40 @@ namespace System.Management.Automation.ComInterop { /// TODO: Return values should be represented by a different type /// internal ComParamDesc(ref ELEMDESC elemDesc) - : this(ref elemDesc, String.Empty) { + : this(ref elemDesc, String.Empty) + { } - public override string ToString() { + public override string ToString() + { StringBuilder result = new StringBuilder(); - if (_isOpt) { + if (_isOpt) + { result.Append("[Optional] "); } - if (_isOut) { + if (_isOut) + { result.Append("[out]"); } result.Append(_type.Name); - if (_isArray) { + if (_isArray) + { result.Append("[]"); } - if (_byRef) { + if (_byRef) + { result.Append("&"); } result.Append(" "); result.Append(_name); - if (_defaultValue != DBNull.Value) { + if (_defaultValue != DBNull.Value) + { result.Append("="); result.Append(_defaultValue.ToString()); } @@ -117,24 +134,30 @@ namespace System.Management.Automation.ComInterop { # region properties - public bool IsOut { + public bool IsOut + { get { return _isOut; } } - public bool IsOptional { + public bool IsOptional + { get { return _isOpt; } } - public bool ByReference { + public bool ByReference + { get { return _byRef; } } - public bool IsArray { + public bool IsArray + { get { return _isArray; } } - public Type ParameterType { - get { + public Type ParameterType + { + get + { return _type; } } @@ -142,8 +165,10 @@ namespace System.Management.Automation.ComInterop { /// /// DBNull.Value if there is no default value /// - internal object DefaultValue { - get { + internal object DefaultValue + { + get + { return _defaultValue; } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs index c43e5fe94..3269d6875 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs @@ -14,10 +14,10 @@ using System.Security; using System.Security.Permissions; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - - internal static class ComRuntimeHelpers { - +namespace System.Management.Automation.ComInterop +{ + internal static class ComRuntimeHelpers + { [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "1#")] public static void CheckThrowException(int hresult, ref ExcepInfo excepInfo, ComMethodDesc method, object[] args, uint argErr) @@ -29,7 +29,8 @@ namespace System.Management.Automation.ComInterop { Exception parameterException = null; - switch (hresult) { + switch (hresult) + { case ComHresults.DISP_E_BADPARAMCOUNT: // The number of elements provided to DISPPARAMS is different from the number of arguments // accepted by the method or property. @@ -95,15 +96,15 @@ namespace System.Management.Automation.ComInterop { string originalValueString = originalValue.ToString(); string originalTypeName = Microsoft.PowerShell.ToStringCodeMethods.Type(originalValue.GetType(), true); - + // ByRef arguments should be displayed in the error message as a PSReference - if(destinationType == typeof(Object) && method.ParameterInformation[argErr].isByRef) + if (destinationType == typeof(Object) && method.ParameterInformation[argErr].isByRef) { destinationType = typeof(PSReference); } string destinationTypeName = Microsoft.PowerShell.ToStringCodeMethods.Type(destinationType, true); - + parameterException = Error.DispTypeMismatch(method.Name, originalValueString, originalTypeName, destinationTypeName); ThrowWrappedInvocationException(method, parameterException); break; @@ -146,21 +147,24 @@ namespace System.Management.Automation.ComInterop { throw parameterException; } - internal static void GetInfoFromType(ComTypes.ITypeInfo typeInfo, out string name, out string documentation) { + internal static void GetInfoFromType(ComTypes.ITypeInfo typeInfo, out string name, out string documentation) + { int dwHelpContext; string strHelpFile; typeInfo.GetDocumentation(-1, out name, out documentation, out dwHelpContext, out strHelpFile); } - internal static string GetNameOfMethod(ComTypes.ITypeInfo typeInfo, int memid) { + internal static string GetNameOfMethod(ComTypes.ITypeInfo typeInfo, int memid) + { int cNames; string[] rgNames = new string[1]; typeInfo.GetNames(memid, rgNames, 1, out cNames); return rgNames[0]; } - internal static string GetNameOfLib(ComTypes.ITypeLib typeLib) { + internal static string GetNameOfLib(ComTypes.ITypeLib typeLib) + { string name; string strDocString; int dwHelpContext; @@ -170,7 +174,8 @@ namespace System.Management.Automation.ComInterop { return name; } - internal static string GetNameOfType(ComTypes.ITypeInfo typeInfo) { + internal static string GetNameOfType(ComTypes.ITypeInfo typeInfo) + { string name; string documentation; GetInfoFromType(typeInfo, out name, out documentation); @@ -187,7 +192,8 @@ namespace System.Management.Automation.ComInterop { /// Some COM objects do intend to expose typeinfo, but may not be able to do so if the type-library is not properly /// registered. This will be considered as acceptable or as an error condition depending on throwIfMissingExpectedTypeInfo /// - internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch, bool throwIfMissingExpectedTypeInfo) { + internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch, bool throwIfMissingExpectedTypeInfo) + { uint typeCount; int hresult = dispatch.TryGetTypeInfoCount(out typeCount); @@ -201,28 +207,35 @@ namespace System.Management.Automation.ComInterop { } Debug.Assert(typeCount <= 1); - if (typeCount == 0) { + if (typeCount == 0) + { return null; } IntPtr typeInfoPtr = IntPtr.Zero; hresult = dispatch.TryGetTypeInfo(0, 0, out typeInfoPtr); - if (! Utils.Succeeded(hresult)) { + if (!Utils.Succeeded(hresult)) + { CheckIfMissingTypeInfoIsExpected(hresult, throwIfMissingExpectedTypeInfo); return null; } - if (typeInfoPtr == IntPtr.Zero) { // be defensive against components that return IntPtr.Zero - if (throwIfMissingExpectedTypeInfo) { + if (typeInfoPtr == IntPtr.Zero) + { // be defensive against components that return IntPtr.Zero + if (throwIfMissingExpectedTypeInfo) + { Marshal.ThrowExceptionForHR(ComHresults.E_FAIL); } return null; } ComTypes.ITypeInfo typeInfo = null; - try { + try + { typeInfo = Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo; - } finally { + } + finally + { Marshal.Release(typeInfoPtr); } @@ -238,12 +251,14 @@ namespace System.Management.Automation.ComInterop { /// However, if accessing the typeinfo is failing in a transient way, we might want to throw /// an exception so that we will eagerly predictably indicate the problem. /// - private static void CheckIfMissingTypeInfoIsExpected(int hresult, bool throwIfMissingExpectedTypeInfo) { - Debug.Assert(! Utils.Succeeded(hresult)); + private static void CheckIfMissingTypeInfoIsExpected(int hresult, bool throwIfMissingExpectedTypeInfo) + { + Debug.Assert(!Utils.Succeeded(hresult)); // Word.Basic always returns this because of an incorrect implementation of IDispatch.GetTypeInfo // Any implementation that returns E_NOINTERFACE is likely to do so in all environments - if (hresult == ComHresults.E_NOINTERFACE) { + if (hresult == ComHresults.E_NOINTERFACE) + { return; } @@ -252,50 +267,63 @@ namespace System.Management.Automation.ComInterop { // can investigate the scenarios to ensure that there is no bug in our own code. Debug.Assert(hresult == ComHresults.TYPE_E_LIBNOTREGISTERED); - if (throwIfMissingExpectedTypeInfo) { + if (throwIfMissingExpectedTypeInfo) + { Marshal.ThrowExceptionForHR(hresult); } } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo) { + internal static ComTypes.TYPEATTR GetTypeAttrForTypeInfo(ComTypes.ITypeInfo typeInfo) + { IntPtr pAttrs = IntPtr.Zero; typeInfo.GetTypeAttr(out pAttrs); // GetTypeAttr should never return null, this is just to be safe - if (pAttrs == IntPtr.Zero) { + if (pAttrs == IntPtr.Zero) + { throw Error.CannotRetrieveTypeInformation(); } - try { + try + { return (ComTypes.TYPEATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPEATTR)); - } finally { + } + finally + { typeInfo.ReleaseTypeAttr(pAttrs); } } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib) { + internal static ComTypes.TYPELIBATTR GetTypeAttrForTypeLib(ComTypes.ITypeLib typeLib) + { IntPtr pAttrs = IntPtr.Zero; typeLib.GetLibAttr(out pAttrs); // GetTypeAttr should never return null, this is just to be safe - if (pAttrs == IntPtr.Zero) { + if (pAttrs == IntPtr.Zero) + { throw Error.CannotRetrieveTypeInformation(); } - try { + try + { return (ComTypes.TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(ComTypes.TYPELIBATTR)); - } finally { + } + finally + { typeLib.ReleaseTLibAttr(pAttrs); } } - public static BoundDispEvent CreateComEvent(object rcw, Guid sourceIid, int dispid) { + public static BoundDispEvent CreateComEvent(object rcw, Guid sourceIid, int dispid) + { return new BoundDispEvent(rcw, sourceIid, dispid); } - public static DispCallable CreateDispCallable(IDispatchComObject dispatch, ComMethodDesc method) { + public static DispCallable CreateDispCallable(IDispatchComObject dispatch, ComMethodDesc method) + { return new DispCallable(dispatch, method.Name, method.DispId); } } @@ -306,7 +334,8 @@ namespace System.Management.Automation.ComInterop { /// and other problems. /// /// - internal static class UnsafeMethods { + internal static class UnsafeMethods + { [System.Runtime.Versioning.ResourceExposure(System.Runtime.Versioning.ResourceScope.None)] [System.Runtime.Versioning.ResourceConsumption(System.Runtime.Versioning.ResourceScope.Process, System.Runtime.Versioning.ResourceScope.Process)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] // TODO: fix @@ -319,15 +348,16 @@ namespace System.Management.Automation.ComInterop { [DllImport("oleaut32.dll", PreserveSig = false)] internal static extern ComTypes.ITypeLib LoadRegTypeLib(ref Guid clsid, short majorVersion, short minorVersion, int lcid); - #region public members + #region public members - private static readonly MethodInfo _ConvertByrefToPtr = Create_ConvertByrefToPtr(); + private static readonly MethodInfo s_convertByrefToPtr = Create_ConvertByrefToPtr(); public delegate IntPtr ConvertByrefToPtrDelegate(ref T value); - private static readonly ConvertByrefToPtrDelegate _ConvertVariantByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Variant))); + private static readonly ConvertByrefToPtrDelegate s_convertVariantByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Variant))); - private static MethodInfo Create_ConvertByrefToPtr() { + private static MethodInfo Create_ConvertByrefToPtr() + { // We dont use AssemblyGen.DefineMethod since that can create a anonymously-hosted DynamicMethod which cannot contain unverifiable code. var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("ComSnippets"), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule("ComSnippets"); @@ -354,19 +384,19 @@ namespace System.Management.Automation.ComInterop { // *** BEGIN GENERATED CODE *** // generated by function: gen_ConvertByrefToPtrDelegates from: generate_comdispatch.py - private static readonly ConvertByrefToPtrDelegate _ConvertSByteByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(SByte))); - private static readonly ConvertByrefToPtrDelegate _ConvertInt16ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Int16))); - private static readonly ConvertByrefToPtrDelegate _ConvertInt32ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Int32))); - private static readonly ConvertByrefToPtrDelegate _ConvertInt64ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Int64))); - private static readonly ConvertByrefToPtrDelegate _ConvertByteByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Byte))); - private static readonly ConvertByrefToPtrDelegate _ConvertUInt16ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(UInt16))); - private static readonly ConvertByrefToPtrDelegate _ConvertUInt32ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(UInt32))); - private static readonly ConvertByrefToPtrDelegate _ConvertUInt64ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(UInt64))); - private static readonly ConvertByrefToPtrDelegate _ConvertIntPtrByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(IntPtr))); - private static readonly ConvertByrefToPtrDelegate _ConvertUIntPtrByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(UIntPtr))); - private static readonly ConvertByrefToPtrDelegate _ConvertSingleByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Single))); - private static readonly ConvertByrefToPtrDelegate _ConvertDoubleByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Double))); - private static readonly ConvertByrefToPtrDelegate _ConvertDecimalByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), _ConvertByrefToPtr.MakeGenericMethod(typeof(Decimal))); + private static readonly ConvertByrefToPtrDelegate s_convertSByteByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(SByte))); + private static readonly ConvertByrefToPtrDelegate s_convertInt16ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Int16))); + private static readonly ConvertByrefToPtrDelegate s_convertInt32ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Int32))); + private static readonly ConvertByrefToPtrDelegate s_convertInt64ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Int64))); + private static readonly ConvertByrefToPtrDelegate s_convertByteByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Byte))); + private static readonly ConvertByrefToPtrDelegate s_convertUInt16ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(UInt16))); + private static readonly ConvertByrefToPtrDelegate s_convertUInt32ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(UInt32))); + private static readonly ConvertByrefToPtrDelegate s_convertUInt64ByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(UInt64))); + private static readonly ConvertByrefToPtrDelegate s_convertIntPtrByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(IntPtr))); + private static readonly ConvertByrefToPtrDelegate s_convertUIntPtrByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(UIntPtr))); + private static readonly ConvertByrefToPtrDelegate s_convertSingleByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Single))); + private static readonly ConvertByrefToPtrDelegate s_convertDoubleByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Double))); + private static readonly ConvertByrefToPtrDelegate s_convertDecimalByrefToPtr = (ConvertByrefToPtrDelegate)Delegate.CreateDelegate(typeof(ConvertByrefToPtrDelegate), s_convertByrefToPtr.MakeGenericMethod(typeof(Decimal))); // *** END GENERATED CODE *** @@ -378,56 +408,60 @@ namespace System.Management.Automation.ComInterop { // generated by function: gen_ConvertByrefToPtr from: generate_comdispatch.py [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertSByteByrefToPtr(ref SByte value) { return _ConvertSByteByrefToPtr(ref value); } + public static IntPtr ConvertSByteByrefToPtr(ref SByte value) { return s_convertSByteByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertInt16ByrefToPtr(ref Int16 value) { return _ConvertInt16ByrefToPtr(ref value); } + public static IntPtr ConvertInt16ByrefToPtr(ref Int16 value) { return s_convertInt16ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertInt32ByrefToPtr(ref Int32 value) { return _ConvertInt32ByrefToPtr(ref value); } + public static IntPtr ConvertInt32ByrefToPtr(ref Int32 value) { return s_convertInt32ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertInt64ByrefToPtr(ref Int64 value) { return _ConvertInt64ByrefToPtr(ref value); } + public static IntPtr ConvertInt64ByrefToPtr(ref Int64 value) { return s_convertInt64ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertByteByrefToPtr(ref Byte value) { return _ConvertByteByrefToPtr(ref value); } + public static IntPtr ConvertByteByrefToPtr(ref Byte value) { return s_convertByteByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertUInt16ByrefToPtr(ref UInt16 value) { return _ConvertUInt16ByrefToPtr(ref value); } + public static IntPtr ConvertUInt16ByrefToPtr(ref UInt16 value) { return s_convertUInt16ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertUInt32ByrefToPtr(ref UInt32 value) { return _ConvertUInt32ByrefToPtr(ref value); } + public static IntPtr ConvertUInt32ByrefToPtr(ref UInt32 value) { return s_convertUInt32ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertUInt64ByrefToPtr(ref UInt64 value) { return _ConvertUInt64ByrefToPtr(ref value); } + public static IntPtr ConvertUInt64ByrefToPtr(ref UInt64 value) { return s_convertUInt64ByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertIntPtrByrefToPtr(ref IntPtr value) { return _ConvertIntPtrByrefToPtr(ref value); } + public static IntPtr ConvertIntPtrByrefToPtr(ref IntPtr value) { return s_convertIntPtrByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertUIntPtrByrefToPtr(ref UIntPtr value) { return _ConvertUIntPtrByrefToPtr(ref value); } + public static IntPtr ConvertUIntPtrByrefToPtr(ref UIntPtr value) { return s_convertUIntPtrByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertSingleByrefToPtr(ref Single value) { return _ConvertSingleByrefToPtr(ref value); } + public static IntPtr ConvertSingleByrefToPtr(ref Single value) { return s_convertSingleByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertDoubleByrefToPtr(ref Double value) { return _ConvertDoubleByrefToPtr(ref value); } + public static IntPtr ConvertDoubleByrefToPtr(ref Double value) { return s_convertDoubleByrefToPtr(ref value); } [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertDecimalByrefToPtr(ref Decimal value) { return _ConvertDecimalByrefToPtr(ref value); } + public static IntPtr ConvertDecimalByrefToPtr(ref Decimal value) { return s_convertDecimalByrefToPtr(ref value); } // *** END GENERATED CODE *** #endregion [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - public static IntPtr ConvertVariantByrefToPtr(ref Variant value) { return _ConvertVariantByrefToPtr(ref value); } + public static IntPtr ConvertVariantByrefToPtr(ref Variant value) { return s_convertVariantByrefToPtr(ref value); } - internal static Variant GetVariantForObject(object obj) { + internal static Variant GetVariantForObject(object obj) + { Variant variant = default(Variant); - if (obj == null) { + if (obj == null) + { return variant; } InitVariantForObject(obj, ref variant); return variant; } - internal static void InitVariantForObject(object obj, ref Variant variant) { + internal static void InitVariantForObject(object obj, ref Variant variant) + { Debug.Assert(obj != null); // GetNativeVariantForObject is very expensive for values that marshal as VT_DISPATCH // also is is extremely common scenario when object at hand is an RCW. // Therefore we are going to test for IDispatch before defaulting to GetNativeVariantForObject. IDispatch disp = obj as IDispatch; - if (disp != null) { + if (disp != null) + { variant.AsDispatch = obj; return; } @@ -436,19 +470,23 @@ namespace System.Management.Automation.ComInterop { } [Obsolete("do not use this method", true)] - public static object GetObjectForVariant(Variant variant) { + public static object GetObjectForVariant(Variant variant) + { IntPtr ptr = UnsafeMethods.ConvertVariantByrefToPtr(ref variant); return System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(ptr); } [Obsolete("do not use this method", true)] - public static int IUnknownRelease(IntPtr interfacePointer) { - return _IUnknownRelease(interfacePointer); + public static int IUnknownRelease(IntPtr interfacePointer) + { + return s_IUnknownRelease(interfacePointer); } [Obsolete("do not use this method", true)] - public static void IUnknownReleaseNotZero(IntPtr interfacePointer) { - if (interfacePointer != IntPtr.Zero) { + public static void IUnknownReleaseNotZero(IntPtr interfacePointer) + { + if (interfacePointer != IntPtr.Zero) + { IUnknownRelease(interfacePointer); } } @@ -463,9 +501,9 @@ namespace System.Management.Automation.ComInterop { out Variant result, out ExcepInfo excepInfo, out uint argErr - ) { - - int hresult = _IDispatchInvoke( + ) + { + int hresult = s_IDispatchInvoke( dispatchPointer, memberDispId, flags, @@ -477,8 +515,8 @@ namespace System.Management.Automation.ComInterop { if (hresult == ComHresults.DISP_E_MEMBERNOTFOUND && (flags & ComTypes.INVOKEKIND.INVOKE_FUNC) != 0 - && (flags & (ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT | ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)) == 0) { - + && (flags & (ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT | ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)) == 0) + { // Re-invoke with no result argument to accomodate Word hresult = _IDispatchInvokeNoResult( dispatchPointer, @@ -493,16 +531,19 @@ namespace System.Management.Automation.ComInterop { } [Obsolete("do not use this method", true)] - public static IntPtr GetIdsOfNamedParameters(IDispatch dispatch, string[] names, int methodDispId, out GCHandle pinningHandle) { + public static IntPtr GetIdsOfNamedParameters(IDispatch dispatch, string[] names, int methodDispId, out GCHandle pinningHandle) + { pinningHandle = GCHandle.Alloc(null, GCHandleType.Pinned); int[] dispIds = new int[names.Length]; Guid empty = Guid.Empty; int hresult = dispatch.TryGetIDsOfNames(ref empty, names, (uint)names.Length, 0, dispIds); - if (hresult < 0) { + if (hresult < 0) + { Marshal.ThrowExceptionForHR(hresult); } - if (methodDispId != dispIds[0]) { + if (methodDispId != dispIds[0]) + { throw Error.GetIDsOfNamesInvalid(names[0]); } @@ -517,12 +558,14 @@ namespace System.Management.Automation.ComInterop { #region non-public members [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] - static UnsafeMethods() { + static UnsafeMethods() + { } - private static void EmitLoadArg(ILGenerator il, int index) { - - switch (index) { + private static void EmitLoadArg(ILGenerator il, int index) + { + switch (index) + { case 0: il.Emit(OpCodes.Ldarg_0); break; @@ -536,9 +579,12 @@ namespace System.Management.Automation.ComInterop { il.Emit(OpCodes.Ldarg_3); break; default: - if (index <= Byte.MaxValue) { + if (index <= Byte.MaxValue) + { il.Emit(OpCodes.Ldarg_S, (byte)index); - } else { + } + else + { il.Emit(OpCodes.Ldarg, index); } break; @@ -551,8 +597,10 @@ namespace System.Management.Automation.ComInterop { /// allowed "value" to be a pinned object. /// [Conditional("DEBUG")] - public static void AssertByrefPointsToStack(IntPtr ptr) { - if (Marshal.ReadInt32(ptr) == _dummyMarker) { + public static void AssertByrefPointsToStack(IntPtr ptr) + { + if (Marshal.ReadInt32(ptr) == _dummyMarker) + { // Prevent recursion return; } @@ -562,31 +610,36 @@ namespace System.Management.Automation.ComInterop { Debug.Assert((ptr.ToInt64() - ptrToLocal.ToInt64()) < (16 * 1024)); } - private static readonly object _lock = new object(); - private static ModuleBuilder _dynamicModule; + private static readonly object s_lock = new object(); + private static ModuleBuilder s_dynamicModule; - internal static ModuleBuilder DynamicModule { - get { - if (_dynamicModule != null) { - return _dynamicModule; + internal static ModuleBuilder DynamicModule + { + get + { + if (s_dynamicModule != null) + { + return s_dynamicModule; } - lock (_lock) { - if (_dynamicModule == null) { - var attributes = new[] { + lock (s_lock) + { + if (s_dynamicModule == null) + { + var attributes = new[] { new CustomAttributeBuilder(typeof(UnverifiableCodeAttribute).GetConstructor(Type.EmptyTypes), Utils.EmptyArray()), //PermissionSet(SecurityAction.Demand, Unrestricted = true) - new CustomAttributeBuilder(typeof(PermissionSetAttribute).GetConstructor(new Type[]{typeof(SecurityAction)}), + new CustomAttributeBuilder(typeof(PermissionSetAttribute).GetConstructor(new Type[]{typeof(SecurityAction)}), new object[]{SecurityAction.Demand}, - new PropertyInfo[]{typeof(PermissionSetAttribute).GetProperty("Unrestricted")}, + new PropertyInfo[]{typeof(PermissionSetAttribute).GetProperty("Unrestricted")}, new object[] {true}) }; string name = typeof(VariantArray).Namespace + ".DynamicAssembly"; var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run, attributes); assembly.DefineVersionInfoResource(); - _dynamicModule = assembly.DefineDynamicModule(name); + s_dynamicModule = assembly.DefineDynamicModule(name); } - return _dynamicModule; + return s_dynamicModule; } } } @@ -599,9 +652,10 @@ namespace System.Management.Automation.ComInterop { /// the JIT-compiler to do pinvoke-stub-inlining and calling the pinvoke target directly. /// private delegate int IUnknownReleaseDelegate(IntPtr interfacePointer); - private static readonly IUnknownReleaseDelegate _IUnknownRelease = Create_IUnknownRelease(); + private static readonly IUnknownReleaseDelegate s_IUnknownRelease = Create_IUnknownRelease(); - private static IUnknownReleaseDelegate Create_IUnknownRelease() { + private static IUnknownReleaseDelegate Create_IUnknownRelease() + { DynamicMethod dm = new DynamicMethod("IUnknownRelease", typeof(int), new Type[] { typeof(IntPtr) }, DynamicModule); ILGenerator method = dm.GetILGenerator(); @@ -629,10 +683,12 @@ namespace System.Management.Automation.ComInterop { internal static readonly IntPtr NullInterfaceId = GetNullInterfaceId(); - private static IntPtr GetNullInterfaceId() { + private static IntPtr GetNullInterfaceId() + { int size = Marshal.SizeOf(Guid.Empty); IntPtr ptr = Marshal.AllocHGlobal(size); - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { Marshal.WriteByte(ptr, i, 0); } return ptr; @@ -657,23 +713,29 @@ namespace System.Management.Automation.ComInterop { out uint argErr ); - private static readonly IDispatchInvokeDelegate _IDispatchInvoke = Create_IDispatchInvoke(true); - private static IDispatchInvokeDelegate _IDispatchInvokeNoResultImpl; + private static readonly IDispatchInvokeDelegate s_IDispatchInvoke = Create_IDispatchInvoke(true); + private static IDispatchInvokeDelegate s_IDispatchInvokeNoResultImpl; - private static IDispatchInvokeDelegate _IDispatchInvokeNoResult { - get { - if (_IDispatchInvokeNoResultImpl == null) { - lock (_IDispatchInvoke) { - if (_IDispatchInvokeNoResultImpl == null) { - _IDispatchInvokeNoResultImpl = Create_IDispatchInvoke(false); + private static IDispatchInvokeDelegate _IDispatchInvokeNoResult + { + get + { + if (s_IDispatchInvokeNoResultImpl == null) + { + lock (s_IDispatchInvoke) + { + if (s_IDispatchInvokeNoResultImpl == null) + { + s_IDispatchInvokeNoResultImpl = Create_IDispatchInvoke(false); } } } - return _IDispatchInvokeNoResultImpl; + return s_IDispatchInvokeNoResultImpl; } } - private static IDispatchInvokeDelegate Create_IDispatchInvoke(bool returnResult) { + private static IDispatchInvokeDelegate Create_IDispatchInvoke(bool returnResult) + { const int dispatchPointerIndex = 0; const int memberDispIdIndex = 1; const int flagsIndex = 2; @@ -704,9 +766,12 @@ namespace System.Management.Automation.ComInterop { // burn the address of our empty IID in directly. This is never freed, relocated, etc... // Note passing this as a Guid directly results in a ~30% perf hit for IDispatch invokes so // we also pass it directly as an IntPtr instead. - if (IntPtr.Size == 4) { + if (IntPtr.Size == 4) + { method.Emit(OpCodes.Ldc_I4, UnsafeMethods.NullInterfaceId.ToInt32()); // riid - } else { + } + else + { method.Emit(OpCodes.Ldc_I8, UnsafeMethods.NullInterfaceId.ToInt64()); // riid } method.Emit(OpCodes.Conv_I); @@ -716,9 +781,12 @@ namespace System.Management.Automation.ComInterop { EmitLoadArg(method, dispParamsIndex); - if (returnResult) { + if (returnResult) + { EmitLoadArg(method, resultIndex); - } else { + } + else + { method.Emit(OpCodes.Ldsfld, typeof(IntPtr).GetField("Zero")); } EmitLoadArg(method, exceptInfoIndex); @@ -733,7 +801,7 @@ namespace System.Management.Automation.ComInterop { method.Emit(OpCodes.Ldind_I); System.Reflection.Emit.SignatureHelper signature = System.Reflection.Emit.SignatureHelper.GetMethodSigHelper(CallingConvention.Winapi, typeof(int)); - Type[] invokeParamTypes = new Type[] { + Type[] invokeParamTypes = new Type[] { typeof(IntPtr), // dispatchPointer typeof(int), // memberDispId typeof(IntPtr), // riid @@ -755,7 +823,8 @@ namespace System.Management.Automation.ComInterop { } - internal static class NativeMethods { + internal static class NativeMethods + { [System.Runtime.Versioning.ResourceExposure(System.Runtime.Versioning.ResourceScope.None)] [System.Runtime.Versioning.ResourceConsumption(System.Runtime.Versioning.ResourceScope.Process, System.Runtime.Versioning.ResourceScope.Process)] [DllImport("oleaut32.dll", PreserveSig = false)] diff --git a/src/System.Management.Automation/engine/ComInterop/ComType.cs b/src/System.Management.Automation/engine/ComInterop/ComType.cs index 916e59373..97ab27365 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComType.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComType.cs @@ -4,9 +4,10 @@ Copyright (c) Microsoft Corporation. All rights reserved. #if !SILVERLIGHT // ComObject -namespace System.Management.Automation.ComInterop { - - internal enum ComType { +namespace System.Management.Automation.ComInterop +{ + internal enum ComType + { Class, Enum, Interface diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs index 62e56f7a2..fc4a5daf6 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs @@ -14,26 +14,31 @@ using System.Collections.Generic; using System.Dynamic; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - - internal class ComTypeClassDesc : ComTypeDesc, IDynamicMetaObjectProvider { +namespace System.Management.Automation.ComInterop +{ + internal class ComTypeClassDesc : ComTypeDesc, IDynamicMetaObjectProvider + { private LinkedList _itfs; // implemented interfaces private LinkedList _sourceItfs; // source interfaces supported by this coclass private Type _typeObj; - - public object CreateInstance() { - if (_typeObj == null) { + + public object CreateInstance() + { + if (_typeObj == null) + { _typeObj = System.Type.GetTypeFromCLSID(Guid); } return System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid)); } internal ComTypeClassDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : - base(typeInfo, ComType.Class, typeLibDesc) { + base(typeInfo, ComType.Class, typeLibDesc) + { ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); Guid = typeAttr.guid; - for (int i = 0; i < typeAttr.cImplTypes; i++) { + for (int i = 0; i < typeAttr.cImplTypes; i++) + { int hRefType; typeInfo.GetRefTypeOfImplType(i, out hRefType); ComTypes.ITypeInfo currentTypeInfo; @@ -47,23 +52,30 @@ namespace System.Management.Automation.ComInterop { } } - private void AddInterface(ComTypes.ITypeInfo itfTypeInfo, bool isSourceItf) { + private void AddInterface(ComTypes.ITypeInfo itfTypeInfo, bool isSourceItf) + { string itfName = ComRuntimeHelpers.GetNameOfType(itfTypeInfo); - if (isSourceItf) { - if (_sourceItfs == null) { + if (isSourceItf) + { + if (_sourceItfs == null) + { _sourceItfs = new LinkedList(); } _sourceItfs.AddLast(itfName); - } else { - if (_itfs == null) { + } + else + { + if (_itfs == null) + { _itfs = new LinkedList(); } _itfs.AddLast(itfName); } } - internal bool Implements(string itfName, bool isSourceItf) { + internal bool Implements(string itfName, bool isSourceItf) + { if (isSourceItf) return _sourceItfs.Contains(itfName); else @@ -72,7 +84,8 @@ namespace System.Management.Automation.ComInterop { #region IDynamicMetaObjectProvider Members - public DynamicMetaObject GetMetaObject(Expression parameter) { + public DynamicMetaObject GetMetaObject(Expression parameter) + { return new ComClassMetaObject(parameter, this); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index a76b00180..7e1abfa0b 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -11,9 +11,10 @@ using System.Runtime.InteropServices.ComTypes; using System.Threading; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - - internal class ComTypeDesc : ComTypeLibMemberDesc { +namespace System.Management.Automation.ComInterop +{ + internal class ComTypeDesc : ComTypeLibMemberDesc + { private string _typeName; private string _documentation; private Guid _guid; @@ -26,66 +27,84 @@ namespace System.Management.Automation.ComInterop { private ComMethodDesc _setItem; private Dictionary _events; private readonly ComTypeLibDesc _typeLibDesc; - private static readonly Dictionary _EmptyEventsDict = new Dictionary(); + private static readonly Dictionary s_emptyEventsDict = new Dictionary(); - internal ComTypeDesc(ITypeInfo typeInfo, ComType memberType, ComTypeLibDesc typeLibDesc) : base(memberType) { - if (typeInfo != null) { + internal ComTypeDesc(ITypeInfo typeInfo, ComType memberType, ComTypeLibDesc typeLibDesc) : base(memberType) + { + if (typeInfo != null) + { ComRuntimeHelpers.GetInfoFromType(typeInfo, out _typeName, out _documentation); } _typeLibDesc = typeLibDesc; } - - internal static ComTypeDesc FromITypeInfo(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr) { - if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS) { + + internal static ComTypeDesc FromITypeInfo(ComTypes.ITypeInfo typeInfo, ComTypes.TYPEATTR typeAttr) + { + if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS) + { return new ComTypeClassDesc(typeInfo, null); - } else if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_ENUM) { + } + else if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_ENUM) + { return new ComTypeEnumDesc(typeInfo, null); - } else if ((typeAttr.typekind == ComTypes.TYPEKIND.TKIND_DISPATCH) || - (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE)) { + } + else if ((typeAttr.typekind == ComTypes.TYPEKIND.TKIND_DISPATCH) || + (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE)) + { ComTypeDesc typeDesc = new ComTypeDesc(typeInfo, ComType.Interface, null); return typeDesc; - } else { + } + else + { throw new InvalidOperationException("Attempting to wrap an unsupported enum type."); } } - internal static ComTypeDesc CreateEmptyTypeDesc() { + internal static ComTypeDesc CreateEmptyTypeDesc() + { ComTypeDesc typeDesc = new ComTypeDesc(null, ComType.Interface, null); typeDesc._funcs = new Hashtable(); typeDesc._puts = new Hashtable(); typeDesc._putRefs = new Hashtable(); - typeDesc._events = _EmptyEventsDict; + typeDesc._events = s_emptyEventsDict; return typeDesc; } - internal static Dictionary EmptyEvents { - get { return _EmptyEventsDict; } + internal static Dictionary EmptyEvents + { + get { return s_emptyEventsDict; } } - internal Hashtable Funcs { + internal Hashtable Funcs + { get { return _funcs; } set { _funcs = value; } } - internal Hashtable Puts { + internal Hashtable Puts + { get { return _puts; } set { _puts = value; } } - internal Hashtable PutRefs { + internal Hashtable PutRefs + { set { _putRefs = value; } } - internal Dictionary Events { + internal Dictionary Events + { get { return _events; } set { _events = value; } } - internal bool TryGetFunc(string name, out ComMethodDesc method) { + internal bool TryGetFunc(string name, out ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - if (_funcs.ContainsKey(name)) { + if (_funcs.ContainsKey(name)) + { method = _funcs[name] as ComMethodDesc; return true; } @@ -93,16 +112,20 @@ namespace System.Management.Automation.ComInterop { return false; } - internal void AddFunc(string name, ComMethodDesc method) { + internal void AddFunc(string name, ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - lock (_funcs) { + lock (_funcs) + { _funcs[name] = method; } } - internal bool TryGetPut(string name, out ComMethodDesc method) { + internal bool TryGetPut(string name, out ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - if (_puts.ContainsKey(name)) { + if (_puts.ContainsKey(name)) + { method = _puts[name] as ComMethodDesc; return true; } @@ -110,65 +133,86 @@ namespace System.Management.Automation.ComInterop { return false; } - internal void AddPut(string name, ComMethodDesc method) { + internal void AddPut(string name, ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - lock (_puts) { + lock (_puts) + { _puts[name] = method; } } - internal bool TryGetPutRef(string name, out ComMethodDesc method) { + internal bool TryGetPutRef(string name, out ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - if (_putRefs.ContainsKey(name)) { + if (_putRefs.ContainsKey(name)) + { method = _putRefs[name] as ComMethodDesc; return true; } method = null; return false; } - internal void AddPutRef(string name, ComMethodDesc method) { + internal void AddPutRef(string name, ComMethodDesc method) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - lock (_putRefs) { + lock (_putRefs) + { _putRefs[name] = method; } } - internal bool TryGetEvent(string name, out ComEventDesc @event) { + internal bool TryGetEvent(string name, out ComEventDesc @event) + { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); return _events.TryGetValue(name, out @event); } - internal string[] GetMemberNames(bool dataOnly) { + internal string[] GetMemberNames(bool dataOnly) + { var names = new Dictionary(); - lock (_funcs) { - foreach (ComMethodDesc func in _funcs.Values) { - if (!dataOnly || func.IsDataMember) { + lock (_funcs) + { + foreach (ComMethodDesc func in _funcs.Values) + { + if (!dataOnly || func.IsDataMember) + { names.Add(func.Name, null); } } } - if (!dataOnly) { - lock (_puts) { - foreach (ComMethodDesc func in _puts.Values) { - if (!names.ContainsKey(func.Name)) { + if (!dataOnly) + { + lock (_puts) + { + foreach (ComMethodDesc func in _puts.Values) + { + if (!names.ContainsKey(func.Name)) + { names.Add(func.Name, null); } } } - lock (_putRefs) { - foreach (ComMethodDesc func in _putRefs.Values) { - if (!names.ContainsKey(func.Name)) { + lock (_putRefs) + { + foreach (ComMethodDesc func in _putRefs.Values) + { + if (!names.ContainsKey(func.Name)) + { names.Add(func.Name, null); } } } - if (_events != null && _events.Count > 0) { - foreach (string name in _events.Keys) { - if (!names.ContainsKey(name)) { + if (_events != null && _events.Count > 0) + { + foreach (string name in _events.Keys) + { + if (!names.ContainsKey(name)) + { names.Add(name, null); } } @@ -182,37 +226,45 @@ namespace System.Management.Automation.ComInterop { } // this property is public - accessed by an AST - public string TypeName { + public string TypeName + { get { return _typeName; } } - internal string Documentation { + internal string Documentation + { get { return _documentation; } } // this property is public - accessed by an AST - public ComTypeLibDesc TypeLib { + public ComTypeLibDesc TypeLib + { get { return _typeLibDesc; } } - internal Guid Guid { + internal Guid Guid + { get { return _guid; } set { _guid = value; } } - internal ComMethodDesc GetItem { + internal ComMethodDesc GetItem + { get { return _getItem; } } - internal void EnsureGetItem(ComMethodDesc candidate) { + internal void EnsureGetItem(ComMethodDesc candidate) + { Interlocked.CompareExchange(ref _getItem, candidate, null); } - internal ComMethodDesc SetItem { + internal ComMethodDesc SetItem + { get { return _setItem; } } - internal void EnsureSetItem(ComMethodDesc candidate) { + internal void EnsureSetItem(ComMethodDesc candidate) + { Interlocked.CompareExchange(ref _setItem, candidate, null); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs index a2db280bd..e3e1b88c1 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs @@ -16,18 +16,21 @@ using System.Dynamic; using System.Globalization; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - - internal sealed class ComTypeEnumDesc : ComTypeDesc, IDynamicMetaObjectProvider { +namespace System.Management.Automation.ComInterop +{ + internal sealed class ComTypeEnumDesc : ComTypeDesc, IDynamicMetaObjectProvider + { private readonly string[] _memberNames; private readonly object[] _memberValues; - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.CurrentCulture, "", TypeName); } internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : - base(typeInfo, ComType.Enum, typeLibDesc) { + base(typeInfo, ComType.Enum, typeLibDesc) + { ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); string[] memberNames = new string[typeAttr.cVars]; object[] memberValues = new object[typeAttr.cVars]; @@ -35,19 +38,24 @@ namespace System.Management.Automation.ComInterop { IntPtr p = IntPtr.Zero; // For each enum member get name and value. - for (int i = 0; i < typeAttr.cVars; i++) { + for (int i = 0; i < typeAttr.cVars; i++) + { typeInfo.GetVarDesc(i, out p); // Get the enum member value (as object). ComTypes.VARDESC varDesc; - try { + try + { varDesc = (ComTypes.VARDESC)Marshal.PtrToStructure(p, typeof(ComTypes.VARDESC)); - if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST) { + if (varDesc.varkind == ComTypes.VARKIND.VAR_CONST) + { memberValues[i] = Marshal.GetObjectForNativeVariant(varDesc.desc.lpvarValue); } - } finally { + } + finally + { typeInfo.ReleaseVarDesc(p); } @@ -59,13 +67,17 @@ namespace System.Management.Automation.ComInterop { _memberValues = memberValues; } - DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { return new TypeEnumMetaObject(this, parameter); } - public object GetValue(string enumValueName) { - for (int i = 0; i < _memberNames.Length; i++) { - if (_memberNames[i] == enumValueName) { + public object GetValue(string enumValueName) + { + for (int i = 0; i < _memberNames.Length; i++) + { + if (_memberNames[i] == enumValueName) + { return _memberValues[i]; } } @@ -73,8 +85,10 @@ namespace System.Management.Automation.ComInterop { throw new MissingMemberException(enumValueName); } - internal bool HasMember(string name) { - for (int i = 0; i < _memberNames.Length; i++) { + internal bool HasMember(string name) + { + for (int i = 0; i < _memberNames.Length; i++) + { if (_memberNames[i] == name) return true; } @@ -83,8 +97,9 @@ namespace System.Management.Automation.ComInterop { } // TODO: internal - public string[] GetMemberNames() { - return (string[])this._memberNames.Clone(); + public string[] GetMemberNames() + { + return (string[])_memberNames.Clone(); } } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 8313529a3..36881a615 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -16,41 +16,45 @@ using System.Dynamic; using System.Globalization; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// Cached information from a TLB. Only information that is required is saved. CoClasses are used /// for event hookup. Enums are stored for accessing symbolic names from scripts. /// - internal sealed class ComTypeLibDesc : IDynamicMetaObjectProvider { - + internal sealed class ComTypeLibDesc : IDynamicMetaObjectProvider + { // typically typelibs contain very small number of coclasses // so we will just use the linked list as it performs better // on small number of entities - LinkedList _classes; - Dictionary _enums; - string _typeLibName; - ComTypes.TYPELIBATTR _typeLibAttributes; + private LinkedList _classes; + private Dictionary _enums; + private string _typeLibName; + private ComTypes.TYPELIBATTR _typeLibAttributes; - private static Dictionary _CachedTypeLibDesc = new Dictionary(); + private static Dictionary s_cachedTypeLibDesc = new Dictionary(); - private ComTypeLibDesc() { + private ComTypeLibDesc() + { _enums = new Dictionary(); _classes = new LinkedList(); } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.CurrentCulture, "", _typeLibName); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] - public string Documentation { + public string Documentation + { get { return String.Empty; } } #region IDynamicMetaObjectProvider Members - DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { return new TypeLibMetaObject(parameter, this); } @@ -66,7 +70,8 @@ namespace System.Management.Automation.ComInterop { /// ComTypeLibDesc object [System.Runtime.Versioning.ResourceExposure(System.Runtime.Versioning.ResourceScope.Machine)] [System.Runtime.Versioning.ResourceConsumption(System.Runtime.Versioning.ResourceScope.Machine, System.Runtime.Versioning.ResourceScope.Machine)] - public static ComTypeLibInfo CreateFromGuid(Guid typeLibGuid) { + public static ComTypeLibInfo CreateFromGuid(Guid typeLibGuid) + { // passing majorVersion = -1, minorVersion = -1 will always // load the latest typelib ComTypes.ITypeLib typeLib = UnsafeMethods.LoadRegTypeLib(ref typeLibGuid, -1, -1, 0); @@ -82,8 +87,10 @@ namespace System.Management.Automation.ComInterop { /// /// OLE automation compatible RCW /// ComTypeLibDesc object - public static ComTypeLibInfo CreateFromObject(object rcw) { - if (Marshal.IsComObject(rcw) == false) { + public static ComTypeLibInfo CreateFromObject(object rcw) + { + if (Marshal.IsComObject(rcw) == false) + { throw new ArgumentException("COM object is expected."); } @@ -96,12 +103,15 @@ namespace System.Management.Automation.ComInterop { return new ComTypeLibInfo(GetFromTypeLib(typeLib)); } - internal static ComTypeLibDesc GetFromTypeLib(ComTypes.ITypeLib typeLib) { + internal static ComTypeLibDesc GetFromTypeLib(ComTypes.ITypeLib typeLib) + { // check whether we have already loaded this type library ComTypes.TYPELIBATTR typeLibAttr = ComRuntimeHelpers.GetTypeAttrForTypeLib(typeLib); ComTypeLibDesc typeLibDesc; - lock (_CachedTypeLibDesc) { - if (_CachedTypeLibDesc.TryGetValue(typeLibAttr.guid, out typeLibDesc)) { + lock (s_cachedTypeLibDesc) + { + if (s_cachedTypeLibDesc.TryGetValue(typeLibAttr.guid, out typeLibDesc)) + { return typeLibDesc; } } @@ -112,22 +122,28 @@ namespace System.Management.Automation.ComInterop { typeLibDesc._typeLibAttributes = typeLibAttr; int countTypes = typeLib.GetTypeInfoCount(); - for (int i = 0; i < countTypes; i++) { + for (int i = 0; i < countTypes; i++) + { ComTypes.TYPEKIND typeKind; typeLib.GetTypeInfoType(i, out typeKind); ComTypes.ITypeInfo typeInfo; typeLib.GetTypeInfo(i, out typeInfo); - if (typeKind == ComTypes.TYPEKIND.TKIND_COCLASS) { + if (typeKind == ComTypes.TYPEKIND.TKIND_COCLASS) + { ComTypeClassDesc classDesc = new ComTypeClassDesc(typeInfo, typeLibDesc); typeLibDesc._classes.AddLast(classDesc); - } else if (typeKind == ComTypes.TYPEKIND.TKIND_ENUM) { + } + else if (typeKind == ComTypes.TYPEKIND.TKIND_ENUM) + { ComTypeEnumDesc enumDesc = new ComTypeEnumDesc(typeInfo, typeLibDesc); typeLibDesc._enums.Add(enumDesc.TypeName, enumDesc); - } - else if (typeKind == ComTypes.TYPEKIND.TKIND_ALIAS) { + } + else if (typeKind == ComTypes.TYPEKIND.TKIND_ALIAS) + { ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); - if (typeAttr.tdescAlias.vt == (short)VarEnum.VT_USERDEFINED) { + if (typeAttr.tdescAlias.vt == (short)VarEnum.VT_USERDEFINED) + { string aliasName, documentation; ComRuntimeHelpers.GetInfoFromType(typeInfo, out aliasName, out documentation); @@ -137,7 +153,8 @@ namespace System.Management.Automation.ComInterop { ComTypes.TYPEATTR referencedTypeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(referencedTypeInfo); ComTypes.TYPEKIND referencedTypeKind = referencedTypeAttr.typekind; - if (referencedTypeKind == ComTypes.TYPEKIND.TKIND_ENUM) { + if (referencedTypeKind == ComTypes.TYPEKIND.TKIND_ENUM) + { ComTypeEnumDesc enumDesc = new ComTypeEnumDesc(referencedTypeInfo, typeLibDesc); typeLibDesc._enums.Add(aliasName, enumDesc); } @@ -146,16 +163,20 @@ namespace System.Management.Automation.ComInterop { } // cached the typelib using the guid as the dictionary key - lock (_CachedTypeLibDesc) { - _CachedTypeLibDesc.Add(typeLibAttr.guid, typeLibDesc); + lock (s_cachedTypeLibDesc) + { + s_cachedTypeLibDesc.Add(typeLibAttr.guid, typeLibDesc); } return typeLibDesc; } - public object GetTypeLibObjectDesc(string member) { - foreach (ComTypeClassDesc coclass in _classes) { - if (member == coclass.TypeName) { + public object GetTypeLibObjectDesc(string member) + { + foreach (ComTypeClassDesc coclass in _classes) + { + if (member == coclass.TypeName) + { return coclass; } } @@ -168,23 +189,29 @@ namespace System.Management.Automation.ComInterop { } // TODO: internal - public string[] GetMemberNames() { + public string[] GetMemberNames() + { string[] retval = new string[_enums.Count + _classes.Count]; int i = 0; - foreach (ComTypeClassDesc coclass in _classes) { + foreach (ComTypeClassDesc coclass in _classes) + { retval[i++] = coclass.TypeName; } - foreach (KeyValuePair enumDesc in _enums) { + foreach (KeyValuePair enumDesc in _enums) + { retval[i++] = enumDesc.Key; } return retval; } - internal bool HasMember(string member) { - foreach (ComTypeClassDesc coclass in _classes) { - if (member == coclass.TypeName) { + internal bool HasMember(string member) + { + foreach (ComTypeClassDesc coclass in _classes) + { + if (member == coclass.TypeName) + { return true; } } @@ -195,25 +222,32 @@ namespace System.Management.Automation.ComInterop { return false; } - public Guid Guid { + public Guid Guid + { get { return _typeLibAttributes.guid; } } - public short VersionMajor { + public short VersionMajor + { get { return _typeLibAttributes.wMajorVerNum; } } - public short VersionMinor { + public short VersionMinor + { get { return _typeLibAttributes.wMinorVerNum; } } - public string Name { + public string Name + { get { return _typeLibName; } } - internal ComTypeClassDesc GetCoClassForInterface(string itfName) { - foreach (ComTypeClassDesc coclass in _classes) { - if (coclass.Implements(itfName, false)) { + internal ComTypeClassDesc GetCoClassForInterface(string itfName) + { + foreach (ComTypeClassDesc coclass in _classes) + { + if (coclass.Implements(itfName, false)) + { return coclass; } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs index 39ea1e7b7..7018912f2 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs @@ -13,41 +13,50 @@ using Microsoft.Scripting.Ast; using System; using System.Dynamic; -namespace System.Management.Automation.ComInterop { - - internal sealed class ComTypeLibInfo : IDynamicMetaObjectProvider { +namespace System.Management.Automation.ComInterop +{ + internal sealed class ComTypeLibInfo : IDynamicMetaObjectProvider + { private readonly ComTypeLibDesc _typeLibDesc; - internal ComTypeLibInfo(ComTypeLibDesc typeLibDesc) { + internal ComTypeLibInfo(ComTypeLibDesc typeLibDesc) + { _typeLibDesc = typeLibDesc; } - public string Name { + public string Name + { get { return _typeLibDesc.Name; } } - public Guid Guid { + public Guid Guid + { get { return _typeLibDesc.Guid; } } - public short VersionMajor { + public short VersionMajor + { get { return _typeLibDesc.VersionMajor; } } - public short VersionMinor { + public short VersionMinor + { get { return _typeLibDesc.VersionMinor; } } - public ComTypeLibDesc TypeLibDesc { + public ComTypeLibDesc TypeLibDesc + { get { return _typeLibDesc; } } // TODO: internal - public string[] GetMemberNames() { + public string[] GetMemberNames() + { return new string[] { this.Name, "Guid", "Name", "VersionMajor", "VersionMinor" }; } - DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { return new TypeLibInfoMetaObject(parameter, this); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs index 5bca5cbb7..452e31c71 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs @@ -4,20 +4,22 @@ Copyright (c) Microsoft Corporation. All rights reserved. #if !SILVERLIGHT // ComObject -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ + internal class ComTypeLibMemberDesc + { + private readonly ComType _kind; - internal class ComTypeLibMemberDesc { - readonly ComType _kind; - - internal ComTypeLibMemberDesc(ComType kind) { + internal ComTypeLibMemberDesc(ComType kind) + { _kind = kind; } - public ComType Kind { + public ComType Kind + { get { return _kind; } } } - } #endif diff --git a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs index e40f25476..730558533 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs @@ -15,22 +15,26 @@ using System.Runtime.CompilerServices; //using Microsoft.Scripting.Utils; using System.Management.Automation.Interpreter; -namespace System.Management.Automation.ComInterop { - - internal class ConversionArgBuilder : ArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class ConversionArgBuilder : ArgBuilder + { private SimpleArgBuilder _innerBuilder; private Type _parameterType; - internal ConversionArgBuilder(Type parameterType, SimpleArgBuilder innerBuilder) { + internal ConversionArgBuilder(Type parameterType, SimpleArgBuilder innerBuilder) + { _parameterType = parameterType; _innerBuilder = innerBuilder; } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { return _innerBuilder.Marshal(Helpers.Convert(parameter, _parameterType)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { //we are not supporting conversion InOut throw Assert.Unreachable; } diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs index 7a881108e..6dc2f792a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs @@ -12,21 +12,26 @@ using Microsoft.Scripting.Ast; using System; -namespace System.Management.Automation.ComInterop { - internal class ConvertArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class ConvertArgBuilder : SimpleArgBuilder + { private readonly Type _marshalType; internal ConvertArgBuilder(Type parameterType, Type marshalType) - : base(parameterType) { + : base(parameterType) + { _marshalType = marshalType; } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { parameter = base.Marshal(parameter); return Expression.Convert(parameter, _marshalType); } - internal override Expression UnmarshalFromRef(Expression newValue) { + internal override Expression UnmarshalFromRef(Expression newValue) + { return base.UnmarshalFromRef(Expression.Convert(newValue, ParameterType)); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs index 351610caa..18526c863 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs @@ -15,17 +15,21 @@ using System.Globalization; //using Microsoft.Scripting.Utils; using System.Management.Automation.Interpreter; -namespace System.Management.Automation.ComInterop { - - internal class ConvertibleArgBuilder : ArgBuilder { - internal ConvertibleArgBuilder() { +namespace System.Management.Automation.ComInterop +{ + internal class ConvertibleArgBuilder : ArgBuilder + { + internal ConvertibleArgBuilder() + { } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { return Helpers.Convert(parameter, typeof(IConvertible)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { //we are not supporting convertible InOut throw Assert.Unreachable; } diff --git a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs index f3ecb9f5f..ad09f14f0 100644 --- a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs @@ -13,14 +13,18 @@ using System; using System.Diagnostics; using System.Runtime.InteropServices; -namespace System.Management.Automation.ComInterop { - internal sealed class CurrencyArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal sealed class CurrencyArgBuilder : SimpleArgBuilder + { internal CurrencyArgBuilder(Type parameterType) - : base(parameterType) { + : base(parameterType) + { Debug.Assert(parameterType == typeof(CurrencyWrapper)); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { // parameter.WrappedObject return Expression.Property( Helpers.Convert(base.Marshal(parameter), typeof(CurrencyWrapper)), @@ -28,7 +32,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { // Decimal.ToOACurrency(parameter.WrappedObject) return Expression.Call( typeof(Decimal).GetMethod("ToOACurrency"), @@ -36,7 +41,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // Decimal.FromOACurrency(value) return base.UnmarshalFromRef( Expression.New( diff --git a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs index e36b60db5..b85d9658c 100644 --- a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs @@ -15,14 +15,18 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -namespace System.Management.Automation.ComInterop { - internal sealed class DateTimeArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal sealed class DateTimeArgBuilder : SimpleArgBuilder + { internal DateTimeArgBuilder(Type parameterType) - : base(parameterType) { + : base(parameterType) + { Debug.Assert(parameterType == typeof(DateTime)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { // parameter.ToOADate() return Expression.Call( Marshal(parameter), @@ -30,7 +34,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // DateTime.FromOADate(value) return base.UnmarshalFromRef( Expression.Call( diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index dfe8e615f..ff5f7420a 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -13,53 +13,62 @@ using System; using System.Dynamic; using System.Globalization; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// This represents a bound dispmember on a IDispatch object. /// - internal sealed class DispCallable : IPseudoComObject { - + internal sealed class DispCallable : IPseudoComObject + { private readonly IDispatchComObject _dispatch; private readonly string _memberName; private readonly int _dispId; - internal DispCallable(IDispatchComObject dispatch, string memberName, int dispId) { + internal DispCallable(IDispatchComObject dispatch, string memberName, int dispId) + { _dispatch = dispatch; _memberName = memberName; _dispId = dispId; } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.CurrentCulture, "", _memberName); } - public IDispatchComObject DispatchComObject { + public IDispatchComObject DispatchComObject + { get { return _dispatch; } } - public IDispatch DispatchObject { + public IDispatch DispatchObject + { get { return _dispatch.DispatchObject; } } - public string MemberName { + public string MemberName + { get { return _memberName; } } - public int DispId { + public int DispId + { get { return _dispId; } } - public DynamicMetaObject GetMetaObject(Expression parameter) { + public DynamicMetaObject GetMetaObject(Expression parameter) + { return new DispCallableMetaObject(parameter, this); } - public override bool Equals(object obj) { + public override bool Equals(object obj) + { var other = obj as DispCallable; return other != null && other._dispatch == _dispatch && other._dispId == _dispId; } - public override int GetHashCode() { + public override int GetHashCode() + { return _dispatch.GetHashCode() ^ _dispId; } } diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs index f2280c79c..85cbfbf77 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs @@ -18,33 +18,39 @@ using System.Security.Permissions; using System.Collections.Generic; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { - internal class DispCallableMetaObject : DynamicMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal class DispCallableMetaObject : DynamicMetaObject + { private readonly DispCallable _callable; internal DispCallableMetaObject(Expression expression, DispCallable callable) - : base(expression, BindingRestrictions.Empty, callable) { + : base(expression, BindingRestrictions.Empty, callable) + { _callable = callable; } - public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { + public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) + { return BindGetOrInvoke(indexes, binder.CallInfo) ?? base.BindGetIndex(binder, indexes); } - public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) + { return BindGetOrInvoke(args, binder.CallInfo) ?? base.BindInvoke(binder, args); } - private DynamicMetaObject BindGetOrInvoke(DynamicMetaObject[] args, CallInfo callInfo) { + private DynamicMetaObject BindGetOrInvoke(DynamicMetaObject[] args, CallInfo callInfo) + { ComMethodDesc method; var target = _callable.DispatchComObject; var name = _callable.MemberName; if (target.TryGetMemberMethod(name, out method) || - target.TryGetMemberMethodExplicit(name, out method)) { - + target.TryGetMemberMethodExplicit(name, out method)) + { List temps = new List(); List initTemps = new List(); @@ -54,7 +60,8 @@ namespace System.Management.Automation.ComInterop { return null; } - public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { + public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) + { ComMethodDesc method; var target = _callable.DispatchComObject; var name = _callable.MemberName; @@ -118,7 +125,8 @@ namespace System.Management.Automation.ComInterop { return invoke; } - private BindingRestrictions DispCallableRestrictions() { + private BindingRestrictions DispCallableRestrictions() + { var callable = Expression; var callableTypeRestrictions = BindingRestrictions.GetTypeRestriction(callable, typeof(DispCallable)); diff --git a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs index ae543f809..dcedeb6a3 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs @@ -14,22 +14,25 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { - - internal class DispatchArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class DispatchArgBuilder : SimpleArgBuilder + { private readonly bool _isWrapper; internal DispatchArgBuilder(Type parameterType) - : base(parameterType) { - + : base(parameterType) + { _isWrapper = parameterType == typeof(DispatchWrapper); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { parameter = base.Marshal(parameter); // parameter.WrappedObject - if (_isWrapper) { + if (_isWrapper) + { parameter = Expression.Property( Helpers.Convert(parameter, typeof(DispatchWrapper)), typeof(DispatchWrapper).GetProperty("WrappedObject") @@ -39,7 +42,8 @@ namespace System.Management.Automation.ComInterop { return Helpers.Convert(parameter, typeof(object)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { parameter = Marshal(parameter); // parameter == null ? IntPtr.Zero : Marshal.GetIDispatchForObject(parameter); @@ -53,7 +57,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // value == IntPtr.Zero ? null : Marshal.GetObjectForIUnknown(value); Expression unmarshal = Expression.Condition( Expression.Equal(value, Expression.Constant(IntPtr.Zero)), @@ -64,7 +69,8 @@ namespace System.Management.Automation.ComInterop { ) ); - if (_isWrapper) { + if (_isWrapper) + { unmarshal = Expression.New( typeof(DispatchWrapper).GetConstructor(new Type[] { typeof(object) }), unmarshal @@ -72,7 +78,6 @@ namespace System.Management.Automation.ComInterop { } return base.UnmarshalFromRef(unmarshal); - } } } diff --git a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs index fdcf32f9c..38aa68fc2 100644 --- a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs @@ -15,15 +15,18 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { - internal class ErrorArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class ErrorArgBuilder : SimpleArgBuilder + { internal ErrorArgBuilder(Type parameterType) - : base(parameterType) { - + : base(parameterType) + { Debug.Assert(parameterType == typeof(ErrorWrapper)); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { // parameter.ErrorCode return Expression.Property( Helpers.Convert(base.Marshal(parameter), typeof(ErrorWrapper)), @@ -31,7 +34,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // new ErrorWrapper(value) return base.UnmarshalFromRef( Expression.New( diff --git a/src/System.Management.Automation/engine/ComInterop/Errors.cs b/src/System.Management.Automation/engine/ComInterop/Errors.cs index 072311322..43a980187 100644 --- a/src/System.Management.Automation/engine/ComInterop/Errors.cs +++ b/src/System.Management.Automation/engine/ComInterop/Errors.cs @@ -6,8 +6,8 @@ using System; using System.Management.Automation; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ #region Generated Com Exception Factory // *** BEGIN GENERATED CODE *** @@ -17,15 +17,18 @@ namespace System.Management.Automation.ComInterop { /// Strongly-typed and parameterized string factory. /// - internal static partial class Strings { - private static string FormatString(string format, params object[] args) { + internal static partial class Strings + { + private static string FormatString(string format, params object[] args) + { return string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args); } /// /// A string like "Unexpected VarEnum {0}." /// - internal static string UnexpectedVarEnum(object p0) { + internal static string UnexpectedVarEnum(object p0) + { return FormatString(ParserStrings.UnexpectedVarEnum, p0); } @@ -40,104 +43,118 @@ namespace System.Management.Automation.ComInterop { /// /// A string like "Error while invoking {0}." /// - internal static string DispMemberNotFound(object p0) { + internal static string DispMemberNotFound(object p0) + { return FormatString(ParserStrings.DispMemberNotFound, p0); } /// /// A string like "Error while invoking {0}. Named arguments are not supported." /// - internal static string DispNoNamedArgs(object p0) { + internal static string DispNoNamedArgs(object p0) + { return FormatString(ParserStrings.DispNoNamedArgs, p0); } /// /// A string like "Error while invoking {0}." /// - internal static string DispOverflow(object p0) { + internal static string DispOverflow(object p0) + { return FormatString(ParserStrings.DispOverflow, p0); } /// /// A string like "Exception setting "{0}": "Cannot convert the "{1}" value of type "{2}" to type "{3}"." /// - internal static string DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) { + internal static string DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) + { return FormatString(ParserStrings.DispTypeMismatch, method, value, originalTypeName, destinationTypeName); } /// /// A string like "Error while invoking {0}. A required parameter was omitted." /// - internal static string DispParamNotOptional(object p0) { + internal static string DispParamNotOptional(object p0) + { return FormatString(ParserStrings.DispParamNotOptional, p0); } /// /// A string like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// - internal static string GetIDsOfNamesInvalid(object p0) { + internal static string GetIDsOfNamesInvalid(object p0) + { return FormatString(ParserStrings.GetIDsOfNamesInvalid, p0); } /// /// A string like "Could not get dispatch ID for {0} (error: {1})." /// - internal static string CouldNotGetDispId(object p0, object p1) { + internal static string CouldNotGetDispId(object p0, object p1) + { return FormatString(ParserStrings.CouldNotGetDispId, p0, p1); } /// /// A string like "There are valid conversions from {0} to {1}." /// - internal static string AmbiguousConversion(object p0, object p1) { + internal static string AmbiguousConversion(object p0, object p1) + { return FormatString(ParserStrings.AmbiguousConversion, p0, p1); } /// /// A string like "Variant.GetAccessor cannot handle {0}." /// - internal static string VariantGetAccessorNYI(object p0) { + internal static string VariantGetAccessorNYI(object p0) + { return FormatString(ParserStrings.VariantGetAccessorNYI, p0); } - } /// /// Strongly-typed and parameterized exception factory. /// - internal static partial class Error { + internal static partial class Error + { /// /// ArgumentException with message like "COM object does not support events." /// - internal static Exception COMObjectDoesNotSupportEvents() { + internal static Exception COMObjectDoesNotSupportEvents() + { return new ArgumentException(ParserStrings.COMObjectDoesNotSupportEvents); } /// /// ArgumentException with message like "COM object does not support specified source interface." /// - internal static Exception COMObjectDoesNotSupportSourceInterface() { + internal static Exception COMObjectDoesNotSupportSourceInterface() + { return new ArgumentException(ParserStrings.COMObjectDoesNotSupportSourceInterface); } /// /// InvalidOperationException with message like "Marshal.SetComObjectData failed." /// - internal static Exception SetComObjectDataFailed() { + internal static Exception SetComObjectDataFailed() + { return new InvalidOperationException(ParserStrings.SetComObjectDataFailed); } /// /// InvalidOperationException with message like "This method exists only to keep the compiler happy." /// - internal static Exception MethodShouldNotBeCalled() { + internal static Exception MethodShouldNotBeCalled() + { return new InvalidOperationException(ParserStrings.MethodShouldNotBeCalled); } /// /// InvalidOperationException with message like "Unexpected VarEnum {0}." /// - internal static Exception UnexpectedVarEnum(object p0) { + internal static Exception UnexpectedVarEnum(object p0) + { return new InvalidOperationException(Strings.UnexpectedVarEnum(p0)); } @@ -152,92 +169,102 @@ namespace System.Management.Automation.ComInterop { /// /// MissingMemberException with message like "Error while invoking {0}." /// - internal static Exception DispMemberNotFound(object p0) { + internal static Exception DispMemberNotFound(object p0) + { return new MissingMemberException(Strings.DispMemberNotFound(p0)); } /// /// ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." /// - internal static Exception DispNoNamedArgs(object p0) { + internal static Exception DispNoNamedArgs(object p0) + { return new ArgumentException(Strings.DispNoNamedArgs(p0)); } /// /// OverflowException with message like "Error while invoking {0}." /// - internal static Exception DispOverflow(object p0) { + internal static Exception DispOverflow(object p0) + { return new OverflowException(Strings.DispOverflow(p0)); } /// /// ArgumentException with message like "Could not convert argument {0} for call to {1}." /// - internal static Exception DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) { + internal static Exception DispTypeMismatch(object method, string value, string originalTypeName, string destinationTypeName) + { return new ArgumentException(Strings.DispTypeMismatch(method, value, originalTypeName, destinationTypeName)); } /// /// ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." /// - internal static Exception DispParamNotOptional(object p0) { + internal static Exception DispParamNotOptional(object p0) + { return new ArgumentException(Strings.DispParamNotOptional(p0)); } /// /// InvalidOperationException with message like "ResolveComReference.CannotRetrieveTypeInformation." /// - internal static Exception CannotRetrieveTypeInformation() { + internal static Exception CannotRetrieveTypeInformation() + { return new InvalidOperationException(ParserStrings.CannotRetrieveTypeInformation); } /// /// ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." /// - internal static Exception GetIDsOfNamesInvalid(object p0) { + internal static Exception GetIDsOfNamesInvalid(object p0) + { return new ArgumentException(Strings.GetIDsOfNamesInvalid(p0)); } /// /// InvalidOperationException with message like "Attempting to wrap an unsupported enum type." /// - internal static Exception UnsupportedEnumType() { + internal static Exception UnsupportedEnumType() + { return new InvalidOperationException(ParserStrings.UnsupportedEnumType); } /// /// InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." /// - internal static Exception UnsupportedHandlerType() { + internal static Exception UnsupportedHandlerType() + { return new InvalidOperationException(ParserStrings.UnsupportedHandlerType); } /// /// MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." /// - internal static Exception CouldNotGetDispId(object p0, object p1) { + internal static Exception CouldNotGetDispId(object p0, object p1) + { return new MissingMemberException(Strings.CouldNotGetDispId(p0, p1)); } /// /// System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." /// - internal static Exception AmbiguousConversion(object p0, object p1) { + internal static Exception AmbiguousConversion(object p0, object p1) + { return new System.Reflection.AmbiguousMatchException(Strings.AmbiguousConversion(p0, p1)); } /// /// NotImplementedException with message like "Variant.GetAccessor cannot handle {0}." /// - internal static Exception VariantGetAccessorNYI(object p0) { + internal static Exception VariantGetAccessorNYI(object p0) + { return new NotImplementedException(Strings.VariantGetAccessorNYI(p0)); } - } // *** END GENERATED CODE *** #endregion - } diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index 4a7f97ad3..fea45856c 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -11,31 +11,36 @@ using System.Runtime.InteropServices; using System.Security; using ComTypes = System.Runtime.InteropServices.ComTypes; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshaling /// [StructLayout(LayoutKind.Sequential)] - internal struct ExcepInfo { - private short wCode; - private short wReserved; - private IntPtr bstrSource; - private IntPtr bstrDescription; - private IntPtr bstrHelpFile; - private int dwHelpContext; - private IntPtr pvReserved; - private IntPtr pfnDeferredFillIn; - private int scode; + internal struct ExcepInfo + { + private short _wCode; + private short _wReserved; + private IntPtr _bstrSource; + private IntPtr _bstrDescription; + private IntPtr _bstrHelpFile; + private int _dwHelpContext; + private IntPtr _pvReserved; + private IntPtr _pfnDeferredFillIn; + private int _scode; #if DEBUG [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2207:InitializeValueTypeStaticFieldsInline")] - static ExcepInfo() { + static ExcepInfo() + { Debug.Assert(Marshal.SizeOf(typeof(ExcepInfo)) == Marshal.SizeOf(typeof(ComTypes.EXCEPINFO))); } #endif - private static string ConvertAndFreeBstr(ref IntPtr bstr) { - if (bstr == IntPtr.Zero) { + private static string ConvertAndFreeBstr(ref IntPtr bstr) + { + if (bstr == IntPtr.Zero) + { return null; } @@ -45,51 +50,59 @@ namespace System.Management.Automation.ComInterop { return result; } - internal void Dummy() { - wCode = 0; - wReserved = 0; wReserved++; - bstrSource = IntPtr.Zero; - bstrDescription = IntPtr.Zero; - bstrHelpFile = IntPtr.Zero; - dwHelpContext = 0; - pfnDeferredFillIn = IntPtr.Zero; - pvReserved = IntPtr.Zero; - scode = 0; + internal void Dummy() + { + _wCode = 0; + _wReserved = 0; _wReserved++; + _bstrSource = IntPtr.Zero; + _bstrDescription = IntPtr.Zero; + _bstrHelpFile = IntPtr.Zero; + _dwHelpContext = 0; + _pfnDeferredFillIn = IntPtr.Zero; + _pvReserved = IntPtr.Zero; + _scode = 0; throw Error.MethodShouldNotBeCalled(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - internal Exception GetException() { - Debug.Assert(pfnDeferredFillIn == IntPtr.Zero); + internal Exception GetException() + { + Debug.Assert(_pfnDeferredFillIn == IntPtr.Zero); #if DEBUG - System.Diagnostics.Debug.Assert(wReserved != -1); - wReserved = -1; // to ensure that the method gets called only once + System.Diagnostics.Debug.Assert(_wReserved != -1); + _wReserved = -1; // to ensure that the method gets called only once #endif - int errorCode = (scode != 0) ? scode : wCode; + int errorCode = (_scode != 0) ? _scode : _wCode; Exception exception = Marshal.GetExceptionForHR(errorCode); - string message = ConvertAndFreeBstr(ref bstrDescription); - if (message != null) { + string message = ConvertAndFreeBstr(ref _bstrDescription); + if (message != null) + { // If we have a custom message, create a new Exception object with the message set correctly. // We need to create a new object because "exception.Message" is a read-only property. - if (exception is COMException) { + if (exception is COMException) + { exception = new COMException(message, errorCode); - } else { + } + else + { Type exceptionType = exception.GetType(); ConstructorInfo ctor = exceptionType.GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) { + if (ctor != null) + { exception = (Exception)ctor.Invoke(new object[] { message }); } } } - exception.Source = ConvertAndFreeBstr(ref bstrSource); + exception.Source = ConvertAndFreeBstr(ref _bstrSource); - string helpLink = ConvertAndFreeBstr(ref bstrHelpFile); - if (helpLink != null && dwHelpContext != 0) { - helpLink += "#" + dwHelpContext; + string helpLink = ConvertAndFreeBstr(ref _bstrHelpFile); + if (helpLink != null && _dwHelpContext != 0) + { + helpLink += "#" + _dwHelpContext; } exception.HelpLink = helpLink; diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 20d903ef3..db548da6d 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -10,13 +10,15 @@ using Microsoft.Scripting.Ast; using System; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ // Miscellaneous helpers that don't belong anywhere else - internal static class Helpers { - - internal static Expression Convert(Expression expression, Type type) { - if (expression.Type == type) { + internal static class Helpers + { + internal static Expression Convert(Expression expression, Type type) + { + if (expression.Type == type) + { return expression; } return Expression.Convert(expression, type); diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index 438433704..89ef7daf3 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -21,8 +21,8 @@ using System.Security.Permissions; using ComTypes = System.Runtime.InteropServices.ComTypes; using System.Dynamic; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// An object that implements IDispatch /// @@ -90,46 +90,55 @@ namespace System.Management.Automation.ComInterop { /// dispid. /// - internal sealed class IDispatchComObject : ComObject, IDynamicMetaObjectProvider { - + internal sealed class IDispatchComObject : ComObject, IDynamicMetaObjectProvider + { private readonly IDispatch _dispatchObject; private ComTypeDesc _comTypeDesc; - private static readonly Dictionary _CacheComTypeDesc = new Dictionary(); + private static readonly Dictionary s_cacheComTypeDesc = new Dictionary(); internal IDispatchComObject(IDispatch rcw) - : base(rcw) { + : base(rcw) + { _dispatchObject = rcw; } - public override string ToString() { + public override string ToString() + { ComTypeDesc ctd = _comTypeDesc; string typeName = null; - if (ctd != null) { + if (ctd != null) + { typeName = ctd.TypeName; } - if (String.IsNullOrEmpty(typeName)) { + if (String.IsNullOrEmpty(typeName)) + { typeName = "IDispatch"; } return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName); } - public ComTypeDesc ComTypeDesc { - get { + public ComTypeDesc ComTypeDesc + { + get + { EnsureScanDefinedMethods(); return _comTypeDesc; } } - public IDispatch DispatchObject { - get { + public IDispatch DispatchObject + { + get + { return _dispatchObject; } } - private static int GetIDsOfNames(IDispatch dispatch, string name, out int dispId) { + private static int GetIDsOfNames(IDispatch dispatch, string name, out int dispId) + { int[] dispIds = new int[1]; Guid emtpyRiid = Guid.Empty; int hresult = dispatch.TryGetIDsOfNames( @@ -143,7 +152,8 @@ namespace System.Management.Automation.ComInterop { return hresult; } - static int Invoke(IDispatch dispatch, int memberDispId, out object result) { + private static int Invoke(IDispatch dispatch, int memberDispId, out object result) + { Guid emtpyRiid = Guid.Empty; ComTypes.DISPPARAMS dispParams = new ComTypes.DISPPARAMS(); ComTypes.EXCEPINFO excepInfo = new ComTypes.EXCEPINFO(); @@ -161,9 +171,11 @@ namespace System.Management.Automation.ComInterop { return hresult; } - internal bool TryGetGetItem(out ComMethodDesc value) { + internal bool TryGetGetItem(out ComMethodDesc value) + { ComMethodDesc methodDesc = _comTypeDesc.GetItem; - if (methodDesc != null) { + if (methodDesc != null) + { value = methodDesc; return true; } @@ -171,13 +183,15 @@ namespace System.Management.Automation.ComInterop { return SlowTryGetGetItem(out value); } - private bool SlowTryGetGetItem(out ComMethodDesc value) { + private bool SlowTryGetGetItem(out ComMethodDesc value) + { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.GetItem; // Without type information, we really don't know whether or not we have a property getter. - if (methodDesc == null) { + if (methodDesc == null) + { string name = "[PROPERTYGET, DISPID(0)]"; _comTypeDesc.EnsureGetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYGET)); @@ -188,9 +202,11 @@ namespace System.Management.Automation.ComInterop { return true; } - internal bool TryGetSetItem(out ComMethodDesc value) { + internal bool TryGetSetItem(out ComMethodDesc value) + { ComMethodDesc methodDesc = _comTypeDesc.SetItem; - if (methodDesc != null) { + if (methodDesc != null) + { value = methodDesc; return true; } @@ -198,13 +214,15 @@ namespace System.Management.Automation.ComInterop { return SlowTryGetSetItem(out value); } - private bool SlowTryGetSetItem(out ComMethodDesc value) { + private bool SlowTryGetSetItem(out ComMethodDesc value) + { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.SetItem; // Without type information, we really don't know whether or not we have a property setter. - if (methodDesc == null) { + if (methodDesc == null) + { string name = "[PROPERTYPUT, DISPID(0)]"; _comTypeDesc.EnsureSetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT)); @@ -215,42 +233,52 @@ namespace System.Management.Automation.ComInterop { return true; } - internal bool TryGetMemberMethod(string name, out ComMethodDesc method) { + internal bool TryGetMemberMethod(string name, out ComMethodDesc method) + { EnsureScanDefinedMethods(); return _comTypeDesc.TryGetFunc(name, out method); } - internal bool TryGetMemberEvent(string name, out ComEventDesc @event) { + internal bool TryGetMemberEvent(string name, out ComEventDesc @event) + { EnsureScanDefinedEvents(); return _comTypeDesc.TryGetEvent(name, out @event); } - internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) { + internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) + { EnsureScanDefinedMethods(); int dispId; int hresult = GetIDsOfNames(_dispatchObject, name, out dispId); - if (hresult == ComHresults.S_OK) { + if (hresult == ComHresults.S_OK) + { ComMethodDesc cmd = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_FUNC); _comTypeDesc.AddFunc(name, cmd); method = cmd; return true; - } else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { + } + else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) + { method = null; return false; - } else { + } + else + { throw Error.CouldNotGetDispId(name, String.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } } - internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { + internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) + { EnsureScanDefinedMethods(); int dispId; int hresult = GetIDsOfNames(_dispatchObject, name, out dispId); - if (hresult == ComHresults.S_OK) { + if (hresult == ComHresults.S_OK) + { // we do not know whether we have put or putref here // and we will not guess and pretend we found both. ComMethodDesc put = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT); @@ -259,21 +287,29 @@ namespace System.Management.Automation.ComInterop { ComMethodDesc putref = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF); _comTypeDesc.AddPutRef(name, putref); - if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { + if (ComBinderHelpers.PreferPut(limitType, holdsNull)) + { method = put; - } else { + } + else + { method = putref; } return true; - } else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { + } + else if (hresult == ComHresults.DISP_E_UNKNOWNNAME) + { method = null; return false; - } else { + } + else + { throw Error.CouldNotGetDispId(name, String.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } } - internal override IList GetMemberNames(bool dataOnly) { + internal override IList GetMemberNames(bool dataOnly) + { EnsureScanDefinedMethods(); EnsureScanDefinedEvents(); @@ -281,22 +317,28 @@ namespace System.Management.Automation.ComInterop { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - internal override IList> GetMembers(IEnumerable names) { - if (names == null) { + internal override IList> GetMembers(IEnumerable names) + { + if (names == null) + { names = GetMemberNames(true); } Type comType = RuntimeCallableWrapper.GetType(); var members = new List>(); - foreach (string name in names) { - if (name == null) { + foreach (string name in names) + { + if (name == null) + { continue; } ComMethodDesc method; - if (ComTypeDesc.TryGetFunc(name, out method) && method.IsDataMember) { - try { + if (ComTypeDesc.TryGetFunc(name, out method) && method.IsDataMember) + { + try + { object value = comType.InvokeMember( method.Name, BindingFlags.GetProperty, @@ -308,7 +350,9 @@ namespace System.Management.Automation.ComInterop { members.Add(new KeyValuePair(method.Name, value)); //evaluation failed for some reason. pass exception out - } catch (Exception ex) { + } + catch (Exception ex) + { members.Add(new KeyValuePair(method.Name, ex)); } } @@ -317,18 +361,21 @@ namespace System.Management.Automation.ComInterop { return members.ToArray(); } - DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { EnsureScanDefinedMethods(); return new IDispatchMetaObject(parameter, this); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] - private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) { + private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) + { IntPtr pFuncDesc = IntPtr.Zero; typeInfo.GetFuncDesc(funcIndex, out pFuncDesc); // GetFuncDesc should never return null, this is just to be safe - if (pFuncDesc == IntPtr.Zero) { + if (pFuncDesc == IntPtr.Zero) + { throw Error.CannotRetrieveTypeInformation(); } @@ -336,26 +383,32 @@ namespace System.Management.Automation.ComInterop { funcDescHandle = pFuncDesc; } - private void EnsureScanDefinedEvents() { + private void EnsureScanDefinedEvents() + { // _comTypeDesc.Events is null if we have not yet attempted // to scan the object for events. - if (_comTypeDesc != null && _comTypeDesc.Events != null) { + if (_comTypeDesc != null && _comTypeDesc.Events != null) + { return; } // check type info in the type descriptions cache ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(_dispatchObject, true); - if (typeInfo == null) { + if (typeInfo == null) + { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); - if (_comTypeDesc == null) { - lock (_CacheComTypeDesc) { - if (_CacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && - _comTypeDesc.Events != null) { + if (_comTypeDesc == null) + { + lock (s_cacheComTypeDesc) + { + if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && + _comTypeDesc.Events != null) + { return; } } @@ -367,18 +420,24 @@ namespace System.Management.Automation.ComInterop { Dictionary events = null; var cpc = RuntimeCallableWrapper as ComTypes.IConnectionPointContainer; - if (cpc == null) { + if (cpc == null) + { // No ICPC - this object does not support events events = ComTypeDesc.EmptyEvents; - } else if ((classTypeInfo = GetCoClassTypeInfo(this.RuntimeCallableWrapper, typeInfo)) == null) { + } + else if ((classTypeInfo = GetCoClassTypeInfo(this.RuntimeCallableWrapper, typeInfo)) == null) + { // no class info found - this object may support events // but we could not discover those events = ComTypeDesc.EmptyEvents; - } else { + } + else + { events = new Dictionary(); ComTypes.TYPEATTR classTypeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(classTypeInfo); - for (int i = 0; i < classTypeAttr.cImplTypes; i++) { + for (int i = 0; i < classTypeAttr.cImplTypes; i++) + { int hRefType; classTypeInfo.GetRefTypeOfImplType(i, out hRefType); @@ -387,43 +446,54 @@ namespace System.Management.Automation.ComInterop { ComTypes.IMPLTYPEFLAGS flags; classTypeInfo.GetImplTypeFlags(i, out flags); - if ((flags & ComTypes.IMPLTYPEFLAGS.IMPLTYPEFLAG_FSOURCE) != 0) { + if ((flags & ComTypes.IMPLTYPEFLAGS.IMPLTYPEFLAG_FSOURCE) != 0) + { ScanSourceInterface(interfaceTypeInfo, ref events); } } - if (events.Count == 0) { + if (events.Count == 0) + { events = ComTypeDesc.EmptyEvents; } } - lock (_CacheComTypeDesc) { + lock (s_cacheComTypeDesc) + { ComTypeDesc cachedTypeDesc; - if (_CacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) { + if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) + { _comTypeDesc = cachedTypeDesc; - } else { + } + else + { _comTypeDesc = typeDesc; - _CacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); + s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Events = events; } } - private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref Dictionary events) { + private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref Dictionary events) + { ComTypes.TYPEATTR sourceTypeAttribute = ComRuntimeHelpers.GetTypeAttrForTypeInfo(sourceTypeInfo); - for (int index = 0; index < sourceTypeAttribute.cFuncs; index++) { + for (int index = 0; index < sourceTypeAttribute.cFuncs; index++) + { IntPtr funcDescHandleToRelease = IntPtr.Zero; - try { + try + { ComTypes.FUNCDESC funcDesc; GetFuncDescForDescIndex(sourceTypeInfo, index, out funcDesc, out funcDescHandleToRelease); // we are not interested in hidden or restricted functions for now. - if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FHIDDEN) != 0) { + if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FHIDDEN) != 0) + { continue; } - if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { + if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) + { continue; } @@ -434,33 +504,44 @@ namespace System.Management.Automation.ComInterop { // adding new events and putting them on new interfaces while keeping the // old interfaces around. This may cause name collisioning which we are // resolving by keeping only the first event with the same name. - if (events.ContainsKey(name) == false) { + if (events.ContainsKey(name) == false) + { ComEventDesc eventDesc = new ComEventDesc(); eventDesc.dispid = funcDesc.memid; eventDesc.sourceIID = sourceTypeAttribute.guid; events.Add(name, eventDesc); } - } finally { - if (funcDescHandleToRelease != IntPtr.Zero) { + } + finally + { + if (funcDescHandleToRelease != IntPtr.Zero) + { sourceTypeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } } - private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeInfo typeInfo) { + private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeInfo typeInfo) + { Debug.Assert(typeInfo != null); IProvideClassInfo provideClassInfo = rcw as IProvideClassInfo; - if (provideClassInfo != null) { + if (provideClassInfo != null) + { IntPtr typeInfoPtr = IntPtr.Zero; - try { + try + { provideClassInfo.GetClassInfo(out typeInfoPtr); - if (typeInfoPtr != IntPtr.Zero) { + if (typeInfoPtr != IntPtr.Zero) + { return Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo; } - } finally { - if (typeInfoPtr != IntPtr.Zero) { + } + finally + { + if (typeInfoPtr != IntPtr.Zero) + { Marshal.Release(typeInfoPtr); } } @@ -476,7 +557,8 @@ namespace System.Management.Automation.ComInterop { ComTypeLibDesc typeLibDesc = ComTypeLibDesc.GetFromTypeLib(typeLib); ComTypeClassDesc coclassDesc = typeLibDesc.GetCoClassForInterface(typeName); - if (coclassDesc == null) { + if (coclassDesc == null) + { return null; } @@ -486,23 +568,29 @@ namespace System.Management.Automation.ComInterop { return typeInfoCoClass; } - private void EnsureScanDefinedMethods() { - if (_comTypeDesc != null && _comTypeDesc.Funcs != null) { + private void EnsureScanDefinedMethods() + { + if (_comTypeDesc != null && _comTypeDesc.Funcs != null) + { return; } ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(_dispatchObject, true); - if (typeInfo == null) { + if (typeInfo == null) + { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); - if (_comTypeDesc == null) { - lock (_CacheComTypeDesc) { - if (_CacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && - _comTypeDesc.Funcs != null) { + if (_comTypeDesc == null) + { + lock (s_cacheComTypeDesc) + { + if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && + _comTypeDesc.Funcs != null) + { return; } } @@ -530,14 +618,17 @@ namespace System.Management.Automation.ComInterop { Hashtable puts = new Hashtable(); Hashtable putrefs = new Hashtable(); - for (int definedFuncIndex = 0; definedFuncIndex < typeAttr.cFuncs; definedFuncIndex++) { + for (int definedFuncIndex = 0; definedFuncIndex < typeAttr.cFuncs; definedFuncIndex++) + { IntPtr funcDescHandleToRelease = IntPtr.Zero; - try { + try + { ComTypes.FUNCDESC funcDesc; GetFuncDescForDescIndex(typeInfo, definedFuncIndex, out funcDesc, out funcDescHandleToRelease); - if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { + if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) + { // This function is not meant for the script user to use. continue; } @@ -545,26 +636,27 @@ namespace System.Management.Automation.ComInterop { ComMethodDesc method = new ComMethodDesc(typeInfo, funcDesc); string name = method.Name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); - if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT) != 0) { - + if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT) != 0) + { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) { - method.InputType = ((ComMethodDesc) funcs[name]).ReturnType; + method.InputType = ((ComMethodDesc)funcs[name]).ReturnType; } puts.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. - if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { + if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) + { setItem = method; } continue; } - if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0) { - + if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0) + { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) @@ -575,13 +667,15 @@ namespace System.Management.Automation.ComInterop { putrefs.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. - if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { + if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) + { setItem = method; } continue; } - if (funcDesc.memid == ComDispIds.DISPID_NEWENUM) { + if (funcDesc.memid == ComDispIds.DISPID_NEWENUM) + { funcs.Add("GETENUMERATOR", method); continue; } @@ -601,23 +695,31 @@ namespace System.Management.Automation.ComInterop { // for the special dispId == 0, we need to store the method descriptor // for the Do(GetItem) binder. - if (funcDesc.memid == ComDispIds.DISPID_VALUE) { + if (funcDesc.memid == ComDispIds.DISPID_VALUE) + { getItem = method; } - } finally { - if (funcDescHandleToRelease != IntPtr.Zero) { + } + finally + { + if (funcDescHandleToRelease != IntPtr.Zero) + { typeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } - lock (_CacheComTypeDesc) { + lock (s_cacheComTypeDesc) + { ComTypeDesc cachedTypeDesc; - if (_CacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) { + if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out cachedTypeDesc)) + { _comTypeDesc = cachedTypeDesc; - } else { + } + else + { _comTypeDesc = typeDesc; - _CacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); + s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Funcs = funcs; _comTypeDesc.Puts = puts; @@ -627,13 +729,17 @@ namespace System.Management.Automation.ComInterop { } } - internal bool TryGetPropertySetter(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { + internal bool TryGetPropertySetter(string name, out ComMethodDesc method, Type limitType, bool holdsNull) + { EnsureScanDefinedMethods(); - if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { + if (ComBinderHelpers.PreferPut(limitType, holdsNull)) + { return _comTypeDesc.TryGetPut(name, out method) || _comTypeDesc.TryGetPutRef(name, out method); - } else { + } + else + { return _comTypeDesc.TryGetPutRef(name, out method) || _comTypeDesc.TryGetPut(name, out method); } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index 3aef3cb4f..ade08a232 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -17,18 +17,20 @@ using System.Dynamic; using System.Runtime.InteropServices.ComTypes; using System.Management.Automation.Language; -namespace System.Management.Automation.ComInterop { - - internal sealed class IDispatchMetaObject : ComFallbackMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal sealed class IDispatchMetaObject : ComFallbackMetaObject + { private readonly IDispatchComObject _self; internal IDispatchMetaObject(Expression expression, IDispatchComObject self) - : base(expression, BindingRestrictions.Empty, self) { + : base(expression, BindingRestrictions.Empty, self) + { _self = self; } - public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - + public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) + { ComMethodDesc method = null; // See if this is actually a property set @@ -38,7 +40,7 @@ namespace System.Management.Automation.ComInterop { DynamicMetaObject value = args[args.Length - 1]; bool holdsNull = value.Value == null && value.HasValue; - if(! _self.TryGetPropertySetter(binder.Name, out method, value.LimitType, holdsNull)) + if (!_self.TryGetPropertySetter(binder.Name, out method, value.LimitType, holdsNull)) { _self.TryGetPropertySetterExplicit(binder.Name, out method, value.LimitType, holdsNull); } @@ -47,13 +49,13 @@ namespace System.Management.Automation.ComInterop { // Otherwise, try property get if (method == null) { - if(! _self.TryGetMemberMethod(binder.Name, out method)) + if (!_self.TryGetMemberMethod(binder.Name, out method)) { _self.TryGetMemberMethodExplicit(binder.Name, out method); } } - if(method != null) + if (method != null) { List temps = new List(); List initTemps = new List(); @@ -65,10 +67,11 @@ namespace System.Management.Automation.ComInterop { return base.BindInvokeMember(binder, args); } - public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - + public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) + { ComMethodDesc method; - if (_self.TryGetGetItem(out method)) { + if (_self.TryGetGetItem(out method)) + { List temps = new List(); List initTemps = new List(); @@ -146,15 +149,19 @@ namespace System.Management.Automation.ComInterop { } - private DynamicMetaObject BindGetMember(ComMethodDesc method, bool canReturnCallables) { - if (method.IsDataMember) { - if (method.ParamCount == 0) { + private DynamicMetaObject BindGetMember(ComMethodDesc method, bool canReturnCallables) + { + if (method.IsDataMember) + { + if (method.ParamCount == 0) + { return BindComInvoke(DynamicMetaObject.EmptyMetaObjects, method, new CallInfo(0), Utils.EmptyArray(), null, null); } } // ComGetMemberBinder does not expect callables. Try to call always. - if (!canReturnCallables) { + if (!canReturnCallables) + { return BindComInvoke(DynamicMetaObject.EmptyMetaObjects, method, new CallInfo(0), Utils.EmptyArray(), null, null); } @@ -168,7 +175,8 @@ namespace System.Management.Automation.ComInterop { ); } - private DynamicMetaObject BindEvent(ComEventDesc @event) { + private DynamicMetaObject BindEvent(ComEventDesc @event) + { // BoundDispEvent CreateComEvent(object rcw, Guid sourceIid, int dispid) Expression result = Expression.Call( @@ -184,10 +192,11 @@ namespace System.Management.Automation.ComInterop { ); } - public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - + public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) + { ComMethodDesc getItem; - if (_self.TryGetGetItem(out getItem)) { + if (_self.TryGetGetItem(out getItem)) + { List temps = new List(); List initTemps = new List(); @@ -198,10 +207,11 @@ namespace System.Management.Automation.ComInterop { return base.BindGetIndex(binder, indexes); } - public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - + public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) + { ComMethodDesc setItem; - if (_self.TryGetSetItem(out setItem)) { + if (_self.TryGetSetItem(out setItem)) + { List temps = new List(); List initTemps = new List(); @@ -228,8 +238,8 @@ namespace System.Management.Automation.ComInterop { return base.BindSetIndex(binder, indexes, value); } - public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - + public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) + { return // 1. Check for simple property put TryPropertyPut(binder, value) ?? @@ -241,11 +251,13 @@ namespace System.Management.Automation.ComInterop { base.BindSetMember(binder, value); } - private DynamicMetaObject TryPropertyPut(SetMemberBinder binder, DynamicMetaObject value) { + private DynamicMetaObject TryPropertyPut(SetMemberBinder binder, DynamicMetaObject value) + { ComMethodDesc method; bool holdsNull = value.Value == null && value.HasValue; if (_self.TryGetPropertySetter(binder.Name, out method, value.LimitType, holdsNull) || - _self.TryGetPropertySetterExplicit(binder.Name, out method, value.LimitType, holdsNull)) { + _self.TryGetPropertySetterExplicit(binder.Name, out method, value.LimitType, holdsNull)) + { BindingRestrictions restrictions = IDispatchRestriction(); Expression dispatch = Expression.Property( @@ -273,9 +285,11 @@ namespace System.Management.Automation.ComInterop { return null; } - private DynamicMetaObject TryEventHandlerNoop(SetMemberBinder binder, DynamicMetaObject value) { + private DynamicMetaObject TryEventHandlerNoop(SetMemberBinder binder, DynamicMetaObject value) + { ComEventDesc @event; - if (_self.TryGetMemberEvent(binder.Name, out @event) && value.LimitType == typeof(BoundDispEvent)) { + if (_self.TryGetMemberEvent(binder.Name, out @event) && value.LimitType == typeof(BoundDispEvent)) + { // Drop the event property set. return new DynamicMetaObject( Expression.Constant(null), @@ -286,11 +300,13 @@ namespace System.Management.Automation.ComInterop { return null; } - private BindingRestrictions IDispatchRestriction() { + private BindingRestrictions IDispatchRestriction() + { return IDispatchRestriction(Expression, _self.ComTypeDesc); } - internal static BindingRestrictions IDispatchRestriction(Expression expr, ComTypeDesc typeDesc) { + internal static BindingRestrictions IDispatchRestriction(Expression expr, ComTypeDesc typeDesc) + { return BindingRestrictions.GetTypeRestriction( expr, typeof(IDispatchComObject) ).Merge( @@ -306,7 +322,8 @@ namespace System.Management.Automation.ComInterop { ); } - protected override ComUnwrappedMetaObject UnwrapSelf() { + protected override ComUnwrappedMetaObject UnwrapSelf() + { return new ComUnwrappedMetaObject( ComObject.RcwFromComObject(Expression), IDispatchRestriction(), diff --git a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs index be7cce088..4a7c4cdf8 100644 --- a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs @@ -11,8 +11,10 @@ using Microsoft.Scripting.Ast; using System; using System.Dynamic; -namespace System.Management.Automation.ComInterop { - interface IPseudoComObject { +namespace System.Management.Automation.ComInterop +{ + internal interface IPseudoComObject + { DynamicMetaObject GetMetaObject(Expression expression); } } diff --git a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs index 08d7771e1..a4891ff24 100644 --- a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs @@ -12,15 +12,17 @@ using Microsoft.Scripting.Ast; using System; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// ArgBuilder which always produces null. /// - internal sealed class NullArgBuilder : ArgBuilder { + internal sealed class NullArgBuilder : ArgBuilder + { internal NullArgBuilder() { } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { return Expression.Constant(null); } } diff --git a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs index 065dcce1d..7cddf3a84 100644 --- a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs @@ -12,29 +12,35 @@ using Microsoft.Scripting.Ast; using System; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// SimpleArgBuilder produces the value produced by the user as the argument value. It /// also tracks information about the original parameter and is used to create extended /// methods for params arrays and param dictionary functions. /// - internal class SimpleArgBuilder : ArgBuilder { + internal class SimpleArgBuilder : ArgBuilder + { private readonly Type _parameterType; - internal SimpleArgBuilder(Type parameterType) { + internal SimpleArgBuilder(Type parameterType) + { _parameterType = parameterType; } - internal Type ParameterType { + internal Type ParameterType + { get { return _parameterType; } } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { Debug.Assert(parameter != null); return Helpers.Convert(parameter, _parameterType); } - internal override Expression UnmarshalFromRef(Expression newValue) { + internal override Expression UnmarshalFromRef(Expression newValue) + { Debug.Assert(newValue != null && newValue.Type.IsAssignableFrom(_parameterType)); return base.UnmarshalFromRef(newValue); diff --git a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs index 1b28e7fe8..3a62eb7b5 100644 --- a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs +++ b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs @@ -14,9 +14,10 @@ using System.Runtime.CompilerServices; //using Microsoft.Scripting.Utils; #if !SILVERLIGHT -namespace System.Management.Automation.ComInterop { - - internal sealed class SplatCallSite { +namespace System.Management.Automation.ComInterop +{ + internal sealed class SplatCallSite + { // Stored callable Delegate or IDynamicMetaObjectProvider. internal readonly object _callable; @@ -25,22 +26,26 @@ namespace System.Management.Automation.ComInterop { // delegate that does the splatting. internal CallSite> _site; - internal SplatCallSite(object callable) { + internal SplatCallSite(object callable) + { Debug.Assert(callable != null); _callable = callable; } - internal object Invoke(object[] args) { + internal object Invoke(object[] args) + { Debug.Assert(args != null); // If it is a delegate, just let DynamicInvoke do the binding. var d = _callable as Delegate; - if (d != null) { + if (d != null) + { return d.DynamicInvoke(args); } // Otherwise, create a CallSite and invoke it. - if (_site == null) { + if (_site == null) + { _site = CallSite>.Create(SplatInvokeBinder.Instance); } diff --git a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs index b42e04213..41d7a7353 100644 --- a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs @@ -14,25 +14,28 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { - - internal class StringArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class StringArgBuilder : SimpleArgBuilder + { private readonly bool _isWrapper; internal StringArgBuilder(Type parameterType) - : base(parameterType) { - + : base(parameterType) + { Debug.Assert(parameterType == typeof(string) || parameterType == typeof(BStrWrapper)); _isWrapper = parameterType == typeof(BStrWrapper); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { parameter = base.Marshal(parameter); // parameter.WrappedObject - if (_isWrapper) { + if (_isWrapper) + { parameter = Expression.Property( Helpers.Convert(parameter, typeof(BStrWrapper)), typeof(BStrWrapper).GetProperty("WrappedObject") @@ -42,7 +45,8 @@ namespace System.Management.Automation.ComInterop { return parameter; } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { parameter = Marshal(parameter); @@ -53,7 +57,8 @@ namespace System.Management.Automation.ComInterop { ); } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // value == IntPtr.Zero ? null : Marshal.PtrToStringBSTR(value); Expression unmarshal = Expression.Condition( Expression.Equal(value, Expression.Constant(IntPtr.Zero)), @@ -64,7 +69,8 @@ namespace System.Management.Automation.ComInterop { ) ); - if (_isWrapper) { + if (_isWrapper) + { unmarshal = Expression.New( typeof(BStrWrapper).GetConstructor(new Type[] { typeof(string) }), unmarshal diff --git a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs index 08b485e62..d5bf3f510 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs @@ -16,18 +16,22 @@ using System.Dynamic; //using AstUtils = Microsoft.Scripting.Ast.Utils; using AstUtils = System.Management.Automation.Interpreter.Utils; -namespace System.Management.Automation.ComInterop { - - internal class TypeEnumMetaObject : DynamicMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal class TypeEnumMetaObject : DynamicMetaObject + { private readonly ComTypeEnumDesc _desc; internal TypeEnumMetaObject(ComTypeEnumDesc desc, Expression expression) - : base(expression, BindingRestrictions.Empty, desc) { + : base(expression, BindingRestrictions.Empty, desc) + { _desc = desc; } - public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - if (_desc.HasMember(binder.Name)) { + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { + if (_desc.HasMember(binder.Name)) + { return new DynamicMetaObject( // return (.bound $arg0).GetValue("") Expression.Constant(((ComTypeEnumDesc)Value).GetValue(binder.Name), typeof(object)), @@ -38,11 +42,13 @@ namespace System.Management.Automation.ComInterop { throw new NotImplementedException(); } - public override IEnumerable GetDynamicMemberNames() { + public override IEnumerable GetDynamicMemberNames() + { return _desc.GetMemberNames(); } - private BindingRestrictions EnumRestrictions() { + private BindingRestrictions EnumRestrictions() + { return BindingRestrictions.GetTypeRestriction( Expression, typeof(ComTypeEnumDesc) ).Merge( diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs index 74fcd7c82..8f0a11141 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs @@ -15,26 +15,31 @@ using System.Dynamic; //using AstUtils = Microsoft.Scripting.Ast.Utils; using AstUtils = System.Management.Automation.Interpreter.Utils; -namespace System.Management.Automation.ComInterop { - - internal sealed class TypeLibInfoMetaObject : DynamicMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal sealed class TypeLibInfoMetaObject : DynamicMetaObject + { private readonly ComTypeLibInfo _info; internal TypeLibInfoMetaObject(Expression expression, ComTypeLibInfo info) - : base(expression, BindingRestrictions.Empty, info) { + : base(expression, BindingRestrictions.Empty, info) + { _info = info; } - public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { string name = binder.Name; - if (name == _info.Name) { + if (name == _info.Name) + { name = "TypeLibDesc"; - } else if (name != "Guid" && - name != "Name" && - name != "VersionMajor" && - name != "VersionMinor") { - + } + else if (name != "Guid" && + name != "Name" && + name != "VersionMajor" && + name != "VersionMinor") + { return binder.FallbackGetMember(this); } @@ -50,11 +55,13 @@ namespace System.Management.Automation.ComInterop { ); } - public override IEnumerable GetDynamicMemberNames() { + public override IEnumerable GetDynamicMemberNames() + { return _info.GetMemberNames(); } - private BindingRestrictions ComTypeLibInfoRestrictions(params DynamicMetaObject[] args) { + private BindingRestrictions ComTypeLibInfoRestrictions(params DynamicMetaObject[] args) + { return BindingRestrictions.Combine(args).Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(ComTypeLibInfo))); } } diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs index 0c976abb8..bc02ba463 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs @@ -14,18 +14,22 @@ using System.Dynamic; //using AstUtils = Microsoft.Scripting.Ast.Utils; using AstUtils = System.Management.Automation.Interpreter.Utils; -namespace System.Management.Automation.ComInterop { - - internal class TypeLibMetaObject : DynamicMetaObject { +namespace System.Management.Automation.ComInterop +{ + internal class TypeLibMetaObject : DynamicMetaObject + { private readonly ComTypeLibDesc _lib; internal TypeLibMetaObject(Expression expression, ComTypeLibDesc lib) - : base(expression, BindingRestrictions.Empty, lib) { + : base(expression, BindingRestrictions.Empty, lib) + { _lib = lib; } - private DynamicMetaObject TryBindGetMember(string name) { - if (_lib.HasMember(name)) { + private DynamicMetaObject TryBindGetMember(string name) + { + if (_lib.HasMember(name)) + { BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction( Expression, typeof(ComTypeLibDesc) @@ -54,20 +58,24 @@ namespace System.Management.Automation.ComInterop { return null; } - public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { return TryBindGetMember(binder.Name) ?? base.BindGetMember(binder); } - public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { + public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) + { var result = TryBindGetMember(binder.Name); - if (result != null) { + if (result != null) + { return binder.FallbackInvoke(result, args, null); } return base.BindInvokeMember(binder, args); } - public override IEnumerable GetDynamicMemberNames() { + public override IEnumerable GetDynamicMemberNames() + { return _lib.GetMemberNames(); } } diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index 374c48dd9..a86bfe33d 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -13,93 +13,113 @@ using System.Collections.Generic; using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.ComInterop { - - internal static class TypeUtils { +namespace System.Management.Automation.ComInterop +{ + internal static class TypeUtils + { private const BindingFlags AnyStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static; //CONFORMING - internal static Type GetNonNullableType(Type type) { - if (IsNullableType(type)) { + internal static Type GetNonNullableType(Type type) + { + if (IsNullableType(type)) + { return type.GetGenericArguments()[0]; } return type; } //CONFORMING - internal static bool IsNullableType(this Type type) { + internal static bool IsNullableType(this Type type) + { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } //CONFORMING - internal static bool AreReferenceAssignable(Type dest, Type src) { + internal static bool AreReferenceAssignable(Type dest, Type src) + { // WARNING: This actually implements "Is this identity assignable and/or reference assignable?" - if (dest == src) { + if (dest == src) + { return true; } - if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { + if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) + { return true; } return false; } //CONFORMING - internal static bool AreAssignable(Type dest, Type src) { - if (dest == src) { + internal static bool AreAssignable(Type dest, Type src) + { + if (dest == src) + { return true; } - if (dest.IsAssignableFrom(src)) { + if (dest.IsAssignableFrom(src)) + { return true; } - if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { + if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) + { return true; } if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) - && dest.GetGenericArguments()[0] == src.GetElementType()) { + && dest.GetGenericArguments()[0] == src.GetElementType()) + { return true; } return false; } //CONFORMING - internal static bool IsImplicitlyConvertible(Type source, Type destination) { + internal static bool IsImplicitlyConvertible(Type source, Type destination) + { return IsIdentityConversion(source, destination) || IsImplicitNumericConversion(source, destination) || IsImplicitReferenceConversion(source, destination) || IsImplicitBoxingConversion(source, destination); } - internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) { + internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) + { return IsImplicitlyConvertible(source, destination) || (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) != null); } //CONFORMING - internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) { + internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) + { // check for implicit coercions first Type nnExprType = TypeUtils.GetNonNullableType(convertFrom); Type nnConvType = TypeUtils.GetNonNullableType(convertToType); // try exact match on types MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly); - if (method != null) { + if (method != null) + { return method; } MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); - if (method != null) { + if (method != null) + { return method; } // try lifted conversion - if (nnExprType != convertFrom || nnConvType != convertToType) { + if (nnExprType != convertFrom || nnConvType != convertToType) + { method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly); - if (method == null) { + if (method == null) + { method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); } - if (method != null) { + if (method != null) + { return method; } } @@ -107,8 +127,10 @@ namespace System.Management.Automation.ComInterop { } //CONFORMING - internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) { - foreach (MethodInfo mi in methods) { + internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) + { + foreach (MethodInfo mi in methods) + { if (mi.Name != "op_Implicit" && (implicitOnly || mi.Name != "op_Explicit")) continue; if (mi.ReturnType != typeTo) @@ -123,19 +145,23 @@ namespace System.Management.Automation.ComInterop { //CONFORMING - private static bool IsIdentityConversion(Type source, Type destination) { + private static bool IsIdentityConversion(Type source, Type destination) + { return source == destination; } //CONFORMING [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - private static bool IsImplicitNumericConversion(Type source, Type destination) { + private static bool IsImplicitNumericConversion(Type source, Type destination) + { TypeCode tcSource = Type.GetTypeCode(source); TypeCode tcDest = Type.GetTypeCode(destination); - switch (tcSource) { + switch (tcSource) + { case TypeCode.SByte: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: @@ -146,7 +172,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.Byte: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: @@ -160,7 +187,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.Int16: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: @@ -170,7 +198,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.UInt16: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: @@ -182,7 +211,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.Int32: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: @@ -191,7 +221,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.UInt32: - switch (tcDest) { + switch (tcDest) + { case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: @@ -202,7 +233,8 @@ namespace System.Management.Automation.ComInterop { return false; case TypeCode.Int64: case TypeCode.UInt64: - switch (tcDest) { + switch (tcDest) + { case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: @@ -210,7 +242,8 @@ namespace System.Management.Automation.ComInterop { } return false; case TypeCode.Char: - switch (tcDest) { + switch (tcDest) + { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: @@ -229,12 +262,14 @@ namespace System.Management.Automation.ComInterop { } //CONFORMING - private static bool IsImplicitReferenceConversion(Type source, Type destination) { + private static bool IsImplicitReferenceConversion(Type source, Type destination) + { return AreAssignable(destination, source); } //CONFORMING - private static bool IsImplicitBoxingConversion(Type source, Type destination) { + private static bool IsImplicitBoxingConversion(Type source, Type destination) + { if (source.IsValueType && (destination == typeof(object) || destination == typeof(System.ValueType))) return true; if (source.IsEnum && destination == typeof(System.Enum)) diff --git a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs index 6b429462f..93cd81858 100644 --- a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs @@ -15,21 +15,25 @@ using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; -namespace System.Management.Automation.ComInterop { - internal class UnknownArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class UnknownArgBuilder : SimpleArgBuilder + { private readonly bool _isWrapper; internal UnknownArgBuilder(Type parameterType) - : base(parameterType) { - + : base(parameterType) + { _isWrapper = parameterType == typeof(UnknownWrapper); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { parameter = base.Marshal(parameter); // parameter.WrappedObject - if (_isWrapper) { + if (_isWrapper) + { parameter = Expression.Property( Helpers.Convert(parameter, typeof(UnknownWrapper)), typeof(UnknownWrapper).GetProperty("WrappedObject") @@ -39,7 +43,8 @@ namespace System.Management.Automation.ComInterop { return Helpers.Convert(parameter, typeof(object)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { parameter = Marshal(parameter); // parameter == null ? IntPtr.Zero : Marshal.GetIUnknownForObject(parameter); @@ -54,7 +59,8 @@ namespace System.Management.Automation.ComInterop { } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // value == IntPtr.Zero ? null : Marshal.GetObjectForIUnknown(value); Expression unmarshal = Expression.Condition( Expression.Equal(value, Expression.Constant(IntPtr.Zero)), @@ -65,7 +71,8 @@ namespace System.Management.Automation.ComInterop { ) ); - if (_isWrapper) { + if (_isWrapper) + { unmarshal = Expression.New( typeof(UnknownWrapper).GetConstructor(new Type[] { typeof(object) }), unmarshal diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index 9f727d4a0..a9f7046a3 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -11,7 +11,8 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Management.Automation.ComInterop; -namespace System.Management.Automation.ComInterop { +namespace System.Management.Automation.ComInterop +{ /// /// If a managed user type (as opposed to a primitive type or a COM object) is passed as an argument to a COM call, we need /// to determine the VarEnum type we will marshal it as. We have the following options: @@ -26,22 +27,27 @@ namespace System.Management.Automation.ComInterop { /// /// VarEnumSelector implements option # 3 /// - internal class VarEnumSelector { + internal class VarEnumSelector + { private readonly VariantBuilder[] _variantBuilders; - private static readonly Dictionary _ComToManagedPrimitiveTypes = CreateComToManagedPrimitiveTypes(); - private static readonly IList> _ComPrimitiveTypeFamilies = CreateComPrimitiveTypeFamilies(); + private static readonly Dictionary s_comToManagedPrimitiveTypes = CreateComToManagedPrimitiveTypes(); + private static readonly IList> s_comPrimitiveTypeFamilies = CreateComPrimitiveTypeFamilies(); - internal VarEnumSelector(Type[] explicitArgTypes) { + internal VarEnumSelector(Type[] explicitArgTypes) + { _variantBuilders = new VariantBuilder[explicitArgTypes.Length]; - for (int i = 0; i < explicitArgTypes.Length; i++) { + for (int i = 0; i < explicitArgTypes.Length; i++) + { _variantBuilders[i] = GetVariantBuilder(explicitArgTypes[i]); } } - internal VariantBuilder[] VariantBuilders { - get { + internal VariantBuilder[] VariantBuilders + { + get + { return _variantBuilders; } } @@ -112,18 +118,22 @@ namespace System.Management.Automation.ComInterop { /// 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too /// general. /// - internal static Type GetManagedMarshalType(VarEnum varEnum) { + internal static Type GetManagedMarshalType(VarEnum varEnum) + { Debug.Assert((varEnum & VarEnum.VT_BYREF) == 0); - if (varEnum == VarEnum.VT_CY) { + if (varEnum == VarEnum.VT_CY) + { return typeof(CurrencyWrapper); } - if (Variant.IsPrimitiveType(varEnum)) { - return _ComToManagedPrimitiveTypes[varEnum]; + if (Variant.IsPrimitiveType(varEnum)) + { + return s_comToManagedPrimitiveTypes[varEnum]; } - switch (varEnum) { + switch (varEnum) + { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: case VarEnum.VT_UNKNOWN: @@ -139,7 +149,8 @@ namespace System.Management.Automation.ComInterop { } } - private static Dictionary CreateComToManagedPrimitiveTypes() { + private static Dictionary CreateComToManagedPrimitiveTypes() + { Dictionary dict = new Dictionary(); #region Generated Outer ComToManagedPrimitiveTypes @@ -182,7 +193,8 @@ namespace System.Management.Automation.ComInterop { /// Creates a family of COM types such that within each family, there is a completely non-lossy /// conversion from a type to an earlier type in the family. /// - private static IList> CreateComPrimitiveTypeFamilies() { + private static IList> CreateComPrimitiveTypeFamilies() + { VarEnum[][] typeFamilies = new VarEnum[][] { new VarEnum[] { VarEnum.VT_I8, VarEnum.VT_I4, VarEnum.VT_I2, VarEnum.VT_I1 }, new VarEnum[] { VarEnum.VT_UI8, VarEnum.VT_UI4, VarEnum.VT_UI2, VarEnum.VT_UI1 }, @@ -205,13 +217,17 @@ namespace System.Management.Automation.ComInterop { /// /// Get the (one representative type for each) primitive type families that the argument can be converted to /// - private static List GetConversionsToComPrimitiveTypeFamilies(Type argumentType) { + private static List GetConversionsToComPrimitiveTypeFamilies(Type argumentType) + { List compatibleComTypes = new List(); - foreach (IList typeFamily in _ComPrimitiveTypeFamilies) { - foreach (VarEnum candidateType in typeFamily) { - Type candidateManagedType = _ComToManagedPrimitiveTypes[candidateType]; - if (TypeUtils.IsImplicitlyConvertible(argumentType, candidateManagedType, true)) { + foreach (IList typeFamily in s_comPrimitiveTypeFamilies) + { + foreach (VarEnum candidateType in typeFamily) + { + Type candidateManagedType = s_comToManagedPrimitiveTypes[candidateType]; + if (TypeUtils.IsImplicitlyConvertible(argumentType, candidateManagedType, true)) + { compatibleComTypes.Add(candidateType); // Move on to the next type family. We need atmost one type from each family break; @@ -225,17 +241,23 @@ namespace System.Management.Automation.ComInterop { /// If there is more than one type family that the argument can be converted to, we will throw a /// AmbiguousMatchException instead of randomly picking a winner. /// - private static void CheckForAmbiguousMatch(Type argumentType, List compatibleComTypes) { - if (compatibleComTypes.Count <= 1) { + private static void CheckForAmbiguousMatch(Type argumentType, List compatibleComTypes) + { + if (compatibleComTypes.Count <= 1) + { return; } String typeNames = ""; - for (int i = 0; i < compatibleComTypes.Count; i++) { - string typeName = _ComToManagedPrimitiveTypes[compatibleComTypes[i]].Name; - if (i == (compatibleComTypes.Count - 1)) { + for (int i = 0; i < compatibleComTypes.Count; i++) + { + string typeName = s_comToManagedPrimitiveTypes[compatibleComTypes[i]].Name; + if (i == (compatibleComTypes.Count - 1)) + { typeNames += " and "; - } else if (i != 0) { + } + else if (i != 0) + { typeNames += ", "; } typeNames += typeName; @@ -245,14 +267,15 @@ namespace System.Management.Automation.ComInterop { throw Error.AmbiguousConversion(argumentType.Name, typeNames); } - private static bool TryGetPrimitiveComType(Type argumentType, out VarEnum primitiveVarEnum) { - + private static bool TryGetPrimitiveComType(Type argumentType, out VarEnum primitiveVarEnum) + { #region Generated Outer Managed To COM Primitive Type Map // *** BEGIN GENERATED CODE *** // generated by function: gen_ManagedToComPrimitiveTypes from: generate_comdispatch.py - switch (Type.GetTypeCode(argumentType)) { + switch (Type.GetTypeCode(argumentType)) + { case TypeCode.Boolean: primitiveVarEnum = VarEnum.VT_BOOL; return true; @@ -300,22 +323,26 @@ namespace System.Management.Automation.ComInterop { return true; } - if (argumentType == typeof(CurrencyWrapper)) { + if (argumentType == typeof(CurrencyWrapper)) + { primitiveVarEnum = VarEnum.VT_CY; return true; } - if (argumentType == typeof(ErrorWrapper)) { + if (argumentType == typeof(ErrorWrapper)) + { primitiveVarEnum = VarEnum.VT_ERROR; return true; } - if (argumentType == typeof(IntPtr)) { + if (argumentType == typeof(IntPtr)) + { primitiveVarEnum = VarEnum.VT_PTR; return true; } - if (argumentType == typeof(UIntPtr)) { + if (argumentType == typeof(UIntPtr)) + { primitiveVarEnum = VarEnum.VT_PTR; return true; } @@ -331,11 +358,13 @@ namespace System.Management.Automation.ComInterop { /// /// Is there a unique primitive type that has the best conversion for the argument /// - private static bool TryGetPrimitiveComTypeViaConversion(Type argumentType, out VarEnum primitiveVarEnum) { + private static bool TryGetPrimitiveComTypeViaConversion(Type argumentType, out VarEnum primitiveVarEnum) + { // Look for a unique type family that the argument can be converted to. List compatibleComTypes = GetConversionsToComPrimitiveTypeFamilies(argumentType); CheckForAmbiguousMatch(argumentType, compatibleComTypes); - if (compatibleComTypes.Count == 1) { + if (compatibleComTypes.Count == 1) + { primitiveVarEnum = compatibleComTypes[0]; return true; } @@ -349,55 +378,73 @@ namespace System.Management.Automation.ComInterop { // Type.InvokeMember tries to marshal objects as VT_DISPATCH, and falls back to VT_UNKNOWN // VT_RECORD here just indicates that we have user defined type. // We will try VT_DISPATCH and then call GetNativeVariantForObject. - const VarEnum VT_DEFAULT = VarEnum.VT_RECORD; + private const VarEnum VT_DEFAULT = VarEnum.VT_RECORD; - private VarEnum GetComType(ref Type argumentType) { - if (argumentType == typeof(Missing)) { + private VarEnum GetComType(ref Type argumentType) + { + if (argumentType == typeof(Missing)) + { //actual variant type will be VT_ERROR | E_PARAMNOTFOUND return VarEnum.VT_RECORD; } - if (argumentType.IsArray) { + if (argumentType.IsArray) + { //actual variant type will be VT_ARRAY | VT_ return VarEnum.VT_ARRAY; } - if (argumentType == typeof(UnknownWrapper)) { + if (argumentType == typeof(UnknownWrapper)) + { return VarEnum.VT_UNKNOWN; - } else if (argumentType == typeof(DispatchWrapper)) { + } + else if (argumentType == typeof(DispatchWrapper)) + { return VarEnum.VT_DISPATCH; - } else if (argumentType == typeof(VariantWrapper)) { + } + else if (argumentType == typeof(VariantWrapper)) + { return VarEnum.VT_VARIANT; - } else if (argumentType == typeof(BStrWrapper)) { + } + else if (argumentType == typeof(BStrWrapper)) + { return VarEnum.VT_BSTR; - } else if (argumentType == typeof(ErrorWrapper)) { + } + else if (argumentType == typeof(ErrorWrapper)) + { return VarEnum.VT_ERROR; - } else if (argumentType == typeof(CurrencyWrapper)) { + } + else if (argumentType == typeof(CurrencyWrapper)) + { return VarEnum.VT_CY; } // Many languages require an explicit cast for an enum to be used as the underlying type. // However, we want to allow this conversion for COM without requiring an explicit cast // so that enums from interop assemblies can be used as arguments. - if (argumentType.IsEnum) { + if (argumentType.IsEnum) + { argumentType = Enum.GetUnderlyingType(argumentType); return GetComType(ref argumentType); } // COM cannot express valuetype nulls so we will convert to underlying type // it will throw if there is no value - if (TypeUtils.IsNullableType(argumentType)) { + if (TypeUtils.IsNullableType(argumentType)) + { argumentType = TypeUtils.GetNonNullableType(argumentType); return GetComType(ref argumentType); } //generic types cannot be exposed to COM so they do not implement COM interfaces. - if (argumentType.IsGenericType) { + if (argumentType.IsGenericType) + { return VarEnum.VT_UNKNOWN; } VarEnum primitiveVarEnum; - if (TryGetPrimitiveComType(argumentType, out primitiveVarEnum)) { + if (TryGetPrimitiveComType(argumentType, out primitiveVarEnum)) + { return primitiveVarEnum; } @@ -408,29 +455,36 @@ namespace System.Management.Automation.ComInterop { /// /// Get the COM Variant type that argument should be marshaled as for a call to COM /// - private VariantBuilder GetVariantBuilder(Type argumentType) { + private VariantBuilder GetVariantBuilder(Type argumentType) + { //argumentType is coming from MarshalType, null means the dynamic object holds //a null value and not byref - if (argumentType == null) { + if (argumentType == null) + { return new VariantBuilder(VarEnum.VT_EMPTY, new NullArgBuilder()); } - if (argumentType == typeof(DBNull)) { + if (argumentType == typeof(DBNull)) + { return new VariantBuilder(VarEnum.VT_NULL, new NullArgBuilder()); } ArgBuilder argBuilder; - if (argumentType.IsByRef) { + if (argumentType.IsByRef) + { Type elementType = argumentType.GetElementType(); VarEnum elementVarEnum; - if (elementType == typeof(object) || elementType == typeof(DBNull)) { + if (elementType == typeof(object) || elementType == typeof(DBNull)) + { //no meaningful value to pass ByRef. //perhaps the calee will replace it with something. //need to pass as a variant reference elementVarEnum = VarEnum.VT_VARIANT; - } else { + } + else + { elementVarEnum = GetComType(ref elementType); } @@ -448,19 +502,23 @@ namespace System.Management.Automation.ComInterop { // This helper is called when we are looking for a ByVal marhsalling // In a ByVal case we can take into account conversions or IConvertible if all other // attempts to find marshalling type failed - private static ArgBuilder GetByValArgBuilder(Type elementType, ref VarEnum elementVarEnum) { + private static ArgBuilder GetByValArgBuilder(Type elementType, ref VarEnum elementVarEnum) + { // if VT indicates that marshalling type is unknown - if (elementVarEnum == VT_DEFAULT) { + if (elementVarEnum == VT_DEFAULT) + { //trying to find a conversion. VarEnum convertibleTo; - if (TryGetPrimitiveComTypeViaConversion(elementType, out convertibleTo)) { + if (TryGetPrimitiveComTypeViaConversion(elementType, out convertibleTo)) + { elementVarEnum = convertibleTo; Type marshalType = GetManagedMarshalType(elementVarEnum); return new ConversionArgBuilder(elementType, GetSimpleArgBuilder(marshalType, elementVarEnum)); } //checking for IConvertible. - if (typeof(IConvertible).IsAssignableFrom(elementType)) { + if (typeof(IConvertible).IsAssignableFrom(elementType)) + { return new ConvertibleArgBuilder(); } } @@ -468,10 +526,12 @@ namespace System.Management.Automation.ComInterop { } // This helper can produce a builder for types that are directly supported by Variant. - private static SimpleArgBuilder GetSimpleArgBuilder(Type elementType, VarEnum elementVarEnum) { + private static SimpleArgBuilder GetSimpleArgBuilder(Type elementType, VarEnum elementVarEnum) + { SimpleArgBuilder argBuilder; - switch (elementVarEnum) { + switch (elementVarEnum) + { case VarEnum.VT_BSTR: argBuilder = new StringArgBuilder(elementType); break; @@ -500,9 +560,12 @@ namespace System.Management.Automation.ComInterop { break; default: var marshalType = GetManagedMarshalType(elementVarEnum); - if (elementType == marshalType) { + if (elementType == marshalType) + { argBuilder = new SimpleArgBuilder(elementType); - } else { + } + else + { argBuilder = new ConvertArgBuilder(elementType, marshalType); } break; diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.cs b/src/System.Management.Automation/engine/ComInterop/Variant.cs index 586bdfc3e..7f20f090e 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.cs @@ -17,26 +17,30 @@ using System.Reflection; using System.Reflection.Emit; using Assert = System.Management.Automation.Interpreter.Assert; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// Variant is the basic COM type for late-binding. It can contain any other COM data type. /// This type definition precisely matches the unmanaged data layout so that the struct can be passed /// to and from COM calls. /// [StructLayout(LayoutKind.Explicit)] - internal struct Variant { - + internal struct Variant + { #if DEBUG [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2207:InitializeValueTypeStaticFieldsInline")] - static Variant() { + static Variant() + { // Variant size is the size of 4 pointers (16 bytes) on a 32-bit processor, // and 3 pointers (24 bytes) on a 64-bit processor. int intPtrSize = Marshal.SizeOf(typeof(IntPtr)); int variantSize = Marshal.SizeOf(typeof(Variant)); - if (intPtrSize == 4) { + if (intPtrSize == 4) + { Debug.Assert(variantSize == (4 * intPtrSize)); - } else { + } + else + { Debug.Assert(intPtrSize == 8); Debug.Assert(variantSize == (3 * intPtrSize)); } @@ -54,7 +58,8 @@ namespace System.Management.Automation.ComInterop { private Decimal _decimal; [StructLayout(LayoutKind.Sequential)] - private struct TypeUnion { + private struct TypeUnion + { internal ushort _vt; internal ushort _wReserved1; internal ushort _wReserved2; @@ -64,43 +69,64 @@ namespace System.Management.Automation.ComInterop { } [StructLayout(LayoutKind.Sequential)] - private struct Record { + private struct Record + { private IntPtr _record; private IntPtr _recordInfo; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] [StructLayout(LayoutKind.Explicit)] - private struct UnionTypes { + private struct UnionTypes + { #region Generated Outer Variant union types // *** BEGIN GENERATED CODE *** // generated by function: gen_UnionTypes from: generate_comdispatch.py - [FieldOffset(0)] internal SByte _i1; - [FieldOffset(0)] internal Int16 _i2; - [FieldOffset(0)] internal Int32 _i4; - [FieldOffset(0)] internal Int64 _i8; - [FieldOffset(0)] internal Byte _ui1; - [FieldOffset(0)] internal UInt16 _ui2; - [FieldOffset(0)] internal UInt32 _ui4; - [FieldOffset(0)] internal UInt64 _ui8; + [FieldOffset(0)] + internal SByte _i1; + [FieldOffset(0)] + internal Int16 _i2; + [FieldOffset(0)] + internal Int32 _i4; + [FieldOffset(0)] + internal Int64 _i8; + [FieldOffset(0)] + internal Byte _ui1; + [FieldOffset(0)] + internal UInt16 _ui2; + [FieldOffset(0)] + internal UInt32 _ui4; + [FieldOffset(0)] + internal UInt64 _ui8; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - [FieldOffset(0)] internal IntPtr _int; - [FieldOffset(0)] internal UIntPtr _uint; - [FieldOffset(0)] internal Int16 _bool; - [FieldOffset(0)] internal Int32 _error; - [FieldOffset(0)] internal Single _r4; - [FieldOffset(0)] internal Double _r8; - [FieldOffset(0)] internal Int64 _cy; - [FieldOffset(0)] internal Double _date; + [FieldOffset(0)] + internal IntPtr _int; + [FieldOffset(0)] + internal UIntPtr _uint; + [FieldOffset(0)] + internal Int16 _bool; + [FieldOffset(0)] + internal Int32 _error; + [FieldOffset(0)] + internal Single _r4; + [FieldOffset(0)] + internal Double _r8; + [FieldOffset(0)] + internal Int64 _cy; + [FieldOffset(0)] + internal Double _date; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] - [FieldOffset(0)] internal IntPtr _bstr; + [FieldOffset(0)] + internal IntPtr _bstr; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - [FieldOffset(0)] internal IntPtr _unknown; + [FieldOffset(0)] + internal IntPtr _unknown; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - [FieldOffset(0)] internal IntPtr _dispatch; + [FieldOffset(0)] + internal IntPtr _dispatch; // *** END GENERATED CODE *** @@ -114,7 +140,8 @@ namespace System.Management.Automation.ComInterop { internal Record _record; } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.CurrentCulture, "Variant ({0})", VariantType); } @@ -122,8 +149,10 @@ namespace System.Management.Automation.ComInterop { /// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types /// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). /// - internal static bool IsPrimitiveType(VarEnum varEnum) { - switch (varEnum) { + internal static bool IsPrimitiveType(VarEnum varEnum) + { + switch (varEnum) + { #region Generated Outer Variant IsPrimitiveType // *** BEGIN GENERATED CODE *** @@ -148,9 +177,9 @@ namespace System.Management.Automation.ComInterop { case VarEnum.VT_DATE: case VarEnum.VT_BSTR: - // *** END GENERATED CODE *** + // *** END GENERATED CODE *** - #endregion + #endregion return true; } @@ -162,13 +191,16 @@ namespace System.Management.Automation.ComInterop { /// /// [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - public object ToObject() { + public object ToObject() + { // Check the simple case upfront - if (IsEmpty) { + if (IsEmpty) + { return null; } - switch (VariantType) { + switch (VariantType) + { case VarEnum.VT_NULL: return DBNull.Value; #region Generated Outer Variant ToObject @@ -211,7 +243,8 @@ namespace System.Management.Automation.ComInterop { /// Release any unmanaged memory associated with the Variant /// /// - public void Clear() { + public void Clear() + { // We do not need to call OLE32's VariantClear for primitive types or ByRefs // to safe ourselves the cost of interop transition. // ByRef indicates the memory is not owned by the VARIANT itself while @@ -219,50 +252,63 @@ namespace System.Management.Automation.ComInterop { // Hence, only safearrays, BSTRs, interfaces and user types are // handled differently. VarEnum vt = VariantType; - if ((vt & VarEnum.VT_BYREF) != 0) { + if ((vt & VarEnum.VT_BYREF) != 0) + { VariantType = VarEnum.VT_EMPTY; - } else if ( - ((vt & VarEnum.VT_ARRAY) != 0) || - ((vt) == VarEnum.VT_BSTR) || - ((vt) == VarEnum.VT_UNKNOWN) || - ((vt) == VarEnum.VT_DISPATCH) || - ((vt) == VarEnum.VT_RECORD) - ) { + } + else if ( + ((vt & VarEnum.VT_ARRAY) != 0) || + ((vt) == VarEnum.VT_BSTR) || + ((vt) == VarEnum.VT_UNKNOWN) || + ((vt) == VarEnum.VT_DISPATCH) || + ((vt) == VarEnum.VT_RECORD) + ) + { IntPtr variantPtr = UnsafeMethods.ConvertVariantByrefToPtr(ref this); NativeMethods.VariantClear(variantPtr); Debug.Assert(IsEmpty); - } else { + } + else + { VariantType = VarEnum.VT_EMPTY; } } - public VarEnum VariantType { - get { + public VarEnum VariantType + { + get + { return (VarEnum)_typeUnion._vt; } - set { + set + { _typeUnion._vt = (ushort)value; } } - internal bool IsEmpty { - get { + internal bool IsEmpty + { + get + { return _typeUnion._vt == ((ushort)VarEnum.VT_EMPTY); } } - public void SetAsNull() { + public void SetAsNull() + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_NULL; } - public void SetAsIConvertible(IConvertible value) { + public void SetAsIConvertible(IConvertible value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise TypeCode tc = value.GetTypeCode(); CultureInfo ci = CultureInfo.CurrentCulture; - switch (tc) { + switch (tc) + { case TypeCode.Empty: break; case TypeCode.Object: AsUnknown = value; break; case TypeCode.DBNull: SetAsNull(); break; @@ -293,281 +339,340 @@ namespace System.Management.Automation.ComInterop { // generated by function: gen_accessors from: generate_comdispatch.py // VT_I1 - public SByte AsI1 { - get { + public SByte AsI1 + { + get + { Debug.Assert(VariantType == VarEnum.VT_I1); return _typeUnion._unionTypes._i1; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I1; _typeUnion._unionTypes._i1 = value; } } - public void SetAsByrefI1(ref SByte value) { + public void SetAsByrefI1(ref SByte value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_I1 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertSByteByrefToPtr(ref value); } // VT_I2 - public Int16 AsI2 { - get { + public Int16 AsI2 + { + get + { Debug.Assert(VariantType == VarEnum.VT_I2); return _typeUnion._unionTypes._i2; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I2; _typeUnion._unionTypes._i2 = value; } } - public void SetAsByrefI2(ref Int16 value) { + public void SetAsByrefI2(ref Int16 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_I2 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt16ByrefToPtr(ref value); } // VT_I4 - public Int32 AsI4 { - get { + public Int32 AsI4 + { + get + { Debug.Assert(VariantType == VarEnum.VT_I4); return _typeUnion._unionTypes._i4; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I4; _typeUnion._unionTypes._i4 = value; } } - public void SetAsByrefI4(ref Int32 value) { + public void SetAsByrefI4(ref Int32 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_I4 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt32ByrefToPtr(ref value); } // VT_I8 - public Int64 AsI8 { - get { + public Int64 AsI8 + { + get + { Debug.Assert(VariantType == VarEnum.VT_I8); return _typeUnion._unionTypes._i8; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_I8; _typeUnion._unionTypes._i8 = value; } } - public void SetAsByrefI8(ref Int64 value) { + public void SetAsByrefI8(ref Int64 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_I8 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt64ByrefToPtr(ref value); } // VT_UI1 - public Byte AsUi1 { - get { + public Byte AsUi1 + { + get + { Debug.Assert(VariantType == VarEnum.VT_UI1); return _typeUnion._unionTypes._ui1; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI1; _typeUnion._unionTypes._ui1 = value; } } - public void SetAsByrefUi1(ref Byte value) { + public void SetAsByrefUi1(ref Byte value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UI1 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertByteByrefToPtr(ref value); } // VT_UI2 - public UInt16 AsUi2 { - get { + public UInt16 AsUi2 + { + get + { Debug.Assert(VariantType == VarEnum.VT_UI2); return _typeUnion._unionTypes._ui2; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI2; _typeUnion._unionTypes._ui2 = value; } } - public void SetAsByrefUi2(ref UInt16 value) { + public void SetAsByrefUi2(ref UInt16 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UI2 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertUInt16ByrefToPtr(ref value); } // VT_UI4 - public UInt32 AsUi4 { - get { + public UInt32 AsUi4 + { + get + { Debug.Assert(VariantType == VarEnum.VT_UI4); return _typeUnion._unionTypes._ui4; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI4; _typeUnion._unionTypes._ui4 = value; } } - public void SetAsByrefUi4(ref UInt32 value) { + public void SetAsByrefUi4(ref UInt32 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UI4 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertUInt32ByrefToPtr(ref value); } // VT_UI8 - public UInt64 AsUi8 { - get { + public UInt64 AsUi8 + { + get + { Debug.Assert(VariantType == VarEnum.VT_UI8); return _typeUnion._unionTypes._ui8; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UI8; _typeUnion._unionTypes._ui8 = value; } } - public void SetAsByrefUi8(ref UInt64 value) { + public void SetAsByrefUi8(ref UInt64 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UI8 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertUInt64ByrefToPtr(ref value); } // VT_INT - public IntPtr AsInt { - get { + public IntPtr AsInt + { + get + { Debug.Assert(VariantType == VarEnum.VT_INT); return _typeUnion._unionTypes._int; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_INT; _typeUnion._unionTypes._int = value; } } - public void SetAsByrefInt(ref IntPtr value) { + public void SetAsByrefInt(ref IntPtr value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_INT | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertIntPtrByrefToPtr(ref value); } // VT_UINT - public UIntPtr AsUint { - get { + public UIntPtr AsUint + { + get + { Debug.Assert(VariantType == VarEnum.VT_UINT); return _typeUnion._unionTypes._uint; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UINT; _typeUnion._unionTypes._uint = value; } } - public void SetAsByrefUint(ref UIntPtr value) { + public void SetAsByrefUint(ref UIntPtr value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UINT | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertUIntPtrByrefToPtr(ref value); } // VT_BOOL - public Boolean AsBool { - get { + public Boolean AsBool + { + get + { Debug.Assert(VariantType == VarEnum.VT_BOOL); return _typeUnion._unionTypes._bool != 0; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_BOOL; _typeUnion._unionTypes._bool = value ? (Int16)(-1) : (Int16)0; } } - public void SetAsByrefBool(ref Int16 value) { + public void SetAsByrefBool(ref Int16 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_BOOL | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt16ByrefToPtr(ref value); } // VT_ERROR - public Int32 AsError { - get { + public Int32 AsError + { + get + { Debug.Assert(VariantType == VarEnum.VT_ERROR); return _typeUnion._unionTypes._error; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_ERROR; _typeUnion._unionTypes._error = value; } } - public void SetAsByrefError(ref Int32 value) { + public void SetAsByrefError(ref Int32 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_ERROR | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt32ByrefToPtr(ref value); } // VT_R4 - public Single AsR4 { - get { + public Single AsR4 + { + get + { Debug.Assert(VariantType == VarEnum.VT_R4); return _typeUnion._unionTypes._r4; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_R4; _typeUnion._unionTypes._r4 = value; } } - public void SetAsByrefR4(ref Single value) { + public void SetAsByrefR4(ref Single value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_R4 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertSingleByrefToPtr(ref value); } // VT_R8 - public Double AsR8 { - get { + public Double AsR8 + { + get + { Debug.Assert(VariantType == VarEnum.VT_R8); return _typeUnion._unionTypes._r8; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_R8; _typeUnion._unionTypes._r8 = value; } } - public void SetAsByrefR8(ref Double value) { + public void SetAsByrefR8(ref Double value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_R8 | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertDoubleByrefToPtr(ref value); } // VT_DECIMAL - public Decimal AsDecimal { - get { + public Decimal AsDecimal + { + get + { Debug.Assert(VariantType == VarEnum.VT_DECIMAL); // The first byte of Decimal is unused, but usually set to 0 Variant v = this; v._typeUnion._vt = 0; return v._decimal; } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DECIMAL; _decimal = value; @@ -576,120 +681,153 @@ namespace System.Management.Automation.ComInterop { } } - public void SetAsByrefDecimal(ref Decimal value) { + public void SetAsByrefDecimal(ref Decimal value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_DECIMAL | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertDecimalByrefToPtr(ref value); } // VT_CY - public Decimal AsCy { - get { + public Decimal AsCy + { + get + { Debug.Assert(VariantType == VarEnum.VT_CY); return Decimal.FromOACurrency(_typeUnion._unionTypes._cy); } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_CY; _typeUnion._unionTypes._cy = Decimal.ToOACurrency(value); } } - public void SetAsByrefCy(ref Int64 value) { + public void SetAsByrefCy(ref Int64 value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_CY | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertInt64ByrefToPtr(ref value); } // VT_DATE - public DateTime AsDate { - get { + public DateTime AsDate + { + get + { Debug.Assert(VariantType == VarEnum.VT_DATE); return DateTime.FromOADate(_typeUnion._unionTypes._date); } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DATE; _typeUnion._unionTypes._date = value.ToOADate(); } } - public void SetAsByrefDate(ref Double value) { + public void SetAsByrefDate(ref Double value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_DATE | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertDoubleByrefToPtr(ref value); } // VT_BSTR - public String AsBstr { - get { + public String AsBstr + { + get + { Debug.Assert(VariantType == VarEnum.VT_BSTR); - if (_typeUnion._unionTypes._bstr != IntPtr.Zero) { + if (_typeUnion._unionTypes._bstr != IntPtr.Zero) + { return Marshal.PtrToStringBSTR(_typeUnion._unionTypes._bstr); - } else { + } + else + { return null; } } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_BSTR; - if (value != null) { + if (value != null) + { Marshal.GetNativeVariantForObject(value, UnsafeMethods.ConvertVariantByrefToPtr(ref this)); } } } - public void SetAsByrefBstr(ref IntPtr value) { + public void SetAsByrefBstr(ref IntPtr value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_BSTR | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertIntPtrByrefToPtr(ref value); } // VT_UNKNOWN - public Object AsUnknown { - get { + public Object AsUnknown + { + get + { Debug.Assert(VariantType == VarEnum.VT_UNKNOWN); - if (_typeUnion._unionTypes._dispatch != IntPtr.Zero) { + if (_typeUnion._unionTypes._dispatch != IntPtr.Zero) + { return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown); - } else { + } + else + { return null; } } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UNKNOWN; - if (value != null) { + if (value != null) + { _typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value); } } } - public void SetAsByrefUnknown(ref IntPtr value) { + public void SetAsByrefUnknown(ref IntPtr value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_UNKNOWN | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertIntPtrByrefToPtr(ref value); } // VT_DISPATCH - public Object AsDispatch { - get { + public Object AsDispatch + { + get + { Debug.Assert(VariantType == VarEnum.VT_DISPATCH); - if (_typeUnion._unionTypes._dispatch != IntPtr.Zero) { + if (_typeUnion._unionTypes._dispatch != IntPtr.Zero) + { return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch); - } else { + } + else + { return null; } } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DISPATCH; - if (value != null) { + if (value != null) + { _typeUnion._unionTypes._unknown = Marshal.GetIDispatchForObject(value); } } } - public void SetAsByrefDispatch(ref IntPtr value) { + public void SetAsByrefDispatch(ref IntPtr value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_DISPATCH | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertIntPtrByrefToPtr(ref value); @@ -703,31 +841,38 @@ namespace System.Management.Automation.ComInterop { // VT_VARIANT - public Object AsVariant { - get { + public Object AsVariant + { + get + { return Marshal.GetObjectForNativeVariant(UnsafeMethods.ConvertVariantByrefToPtr(ref this)); } - set { + set + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise - if (value != null) { + if (value != null) + { UnsafeMethods.InitVariantForObject(value, ref this); } } } - public void SetAsByrefVariant(ref Variant value) { + public void SetAsByrefVariant(ref Variant value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = (VarEnum.VT_VARIANT | VarEnum.VT_BYREF); _typeUnion._unionTypes._byref = UnsafeMethods.ConvertVariantByrefToPtr(ref value); } // constructs a ByRef variant to pass contents of another variant ByRef. - public void SetAsByrefVariantIndirect(ref Variant value) { + public void SetAsByrefVariantIndirect(ref Variant value) + { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise Debug.Assert((value.VariantType & VarEnum.VT_BYREF) == 0, "double indirection"); - switch (value.VariantType) { + switch (value.VariantType) + { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: // these cannot combine with VT_BYREF. Should try passing as a variant reference @@ -749,9 +894,10 @@ namespace System.Management.Automation.ComInterop { } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - internal static System.Reflection.PropertyInfo GetAccessor(VarEnum varType) { - switch (varType) { - + internal static System.Reflection.PropertyInfo GetAccessor(VarEnum varType) + { + switch (varType) + { #region Generated Outer Variant accessors PropertyInfos // *** BEGIN GENERATED CODE *** @@ -793,9 +939,10 @@ namespace System.Management.Automation.ComInterop { } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - internal static System.Reflection.MethodInfo GetByrefSetter(VarEnum varType) { - switch (varType) { - + internal static System.Reflection.MethodInfo GetByrefSetter(VarEnum varType) + { + switch (varType) + { #region Generated Outer Variant byref setter // *** BEGIN GENERATED CODE *** diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs index 69ab54d8c..e7a789685 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs @@ -15,19 +15,23 @@ using System.Runtime.InteropServices; using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.ComInterop { - internal class VariantArgBuilder : SimpleArgBuilder { +namespace System.Management.Automation.ComInterop +{ + internal class VariantArgBuilder : SimpleArgBuilder + { private readonly bool _isWrapper; internal VariantArgBuilder(Type parameterType) - : base(parameterType) { - + : base(parameterType) + { _isWrapper = parameterType == typeof(VariantWrapper); } - internal override Expression Marshal(Expression parameter) { + internal override Expression Marshal(Expression parameter) + { // parameter.WrappedObject - if (_isWrapper) { + if (_isWrapper) + { parameter = Expression.Property( Helpers.Convert(parameter, typeof(VariantWrapper)), typeof(VariantWrapper).GetProperty("WrappedObject") @@ -37,7 +41,8 @@ namespace System.Management.Automation.ComInterop { return Helpers.Convert(parameter, typeof(object)); } - internal override Expression MarshalToRef(Expression parameter) { + internal override Expression MarshalToRef(Expression parameter) + { parameter = Marshal(parameter); // parameter == UnsafeMethods.GetVariantForObject(parameter); @@ -48,7 +53,8 @@ namespace System.Management.Automation.ComInterop { } - internal override Expression UnmarshalFromRef(Expression value) { + internal override Expression UnmarshalFromRef(Expression value) + { // value == IntPtr.Zero ? null : Marshal.GetObjectForNativeVariant(value); Expression unmarshal = Expression.Call( @@ -56,7 +62,8 @@ namespace System.Management.Automation.ComInterop { value ); - if (_isWrapper) { + if (_isWrapper) + { unmarshal = Expression.New( typeof(VariantWrapper).GetConstructor(new Type[] { typeof(object) }), unmarshal diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index 63e593475..6b4ff5e20 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -17,25 +17,29 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ [StructLayout(LayoutKind.Sequential)] - internal struct VariantArray1 { + internal struct VariantArray1 + { public Variant Element0; } [StructLayout(LayoutKind.Sequential)] - internal struct VariantArray2 { + internal struct VariantArray2 + { public Variant Element0, Element1; } [StructLayout(LayoutKind.Sequential)] - internal struct VariantArray4 { + internal struct VariantArray4 + { public Variant Element0, Element1, Element2, Element3; } [StructLayout(LayoutKind.Sequential)] - internal struct VariantArray8 { + internal struct VariantArray8 + { public Variant Element0, Element1, Element2, Element3, Element4, Element5, Element6, Element7; } @@ -46,16 +50,19 @@ namespace System.Management.Automation.ComInterop { // We use this because we don't have stackalloc or pinning in Expression // Trees, so we can't create an array of Variants directly. // - internal static class VariantArray { + internal static class VariantArray + { // Don't need a dictionary for this, it will have very few elements // (guarenteed less than 28, in practice 0-2) - private static readonly List _generatedTypes = new List(0); + private static readonly List s_generatedTypes = new List(0); - internal static MemberExpression GetStructField(ParameterExpression variantArray, int field) { + internal static MemberExpression GetStructField(ParameterExpression variantArray, int field) + { return Expression.Field(variantArray, "Element" + field); } - internal static Type GetStructType(int args) { + internal static Type GetStructType(int args) + { Debug.Assert(args >= 0); if (args <= 1) return typeof(VariantArray1); if (args <= 2) return typeof(VariantArray2); @@ -63,31 +70,37 @@ namespace System.Management.Automation.ComInterop { if (args <= 8) return typeof(VariantArray8); int size = 1; - while (args > size) { + while (args > size) + { size *= 2; } - lock (_generatedTypes) { + lock (s_generatedTypes) + { // See if we can find an existing type - foreach (Type t in _generatedTypes) { + foreach (Type t in s_generatedTypes) + { int arity = int.Parse(t.Name.Substring("VariantArray".Length), CultureInfo.InvariantCulture); - if (size == arity) { + if (size == arity) + { return t; } } // Else generate a new type - Type type = CreateCustomType(size).MakeGenericType(new Type[]{typeof(Variant)}); - _generatedTypes.Add(type); + Type type = CreateCustomType(size).MakeGenericType(new Type[] { typeof(Variant) }); + s_generatedTypes.Add(type); return type; } } - private static Type CreateCustomType(int size) { + private static Type CreateCustomType(int size) + { var attrs = TypeAttributes.NotPublic | TypeAttributes.SequentialLayout; TypeBuilder type = UnsafeMethods.DynamicModule.DefineType("VariantArray" + size, attrs, typeof(ValueType)); var T = type.DefineGenericParameters(new string[] { "T" })[0]; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { type.DefineField("Element" + i, T, FieldAttributes.Public); } return type.CreateType(); diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index 9a5cadef1..b3828ca89 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -14,40 +14,44 @@ using System; using System.Diagnostics; using System.Runtime.InteropServices; -namespace System.Management.Automation.ComInterop { - +namespace System.Management.Automation.ComInterop +{ /// /// VariantBuilder handles packaging of arguments into a Variant for a call to IDispatch.Invoke /// - internal class VariantBuilder { - + internal class VariantBuilder + { private MemberExpression _variant; private readonly ArgBuilder _argBuilder; private readonly VarEnum _targetComType; internal ParameterExpression TempVariable { get; private set; } - internal VariantBuilder(VarEnum targetComType, ArgBuilder builder) { + internal VariantBuilder(VarEnum targetComType, ArgBuilder builder) + { _targetComType = targetComType; _argBuilder = builder; } - internal bool IsByRef { + internal bool IsByRef + { get { return (_targetComType & VarEnum.VT_BYREF) != 0; } } - internal Expression InitializeArgumentVariant(MemberExpression variant, Expression parameter) { + internal Expression InitializeArgumentVariant(MemberExpression variant, Expression parameter) + { //NOTE: we must remember our variant //the reason is that argument order does not map exactly to the order of variants for invoke //and when we are doing clean-up we must be sure we are cleaning the variant we have initialized. _variant = variant; - if (IsByRef) { + if (IsByRef) + { // temp = argument // paramVariants._elementN.SetAsByrefT(ref temp) Debug.Assert(TempVariable == null); var argExpr = _argBuilder.MarshalToRef(parameter); - + TempVariable = Expression.Variable(argExpr.Type, null); return Expression.Block( Expression.Assign(TempVariable, argExpr), @@ -63,7 +67,8 @@ namespace System.Management.Automation.ComInterop { // we are forced to special case ConvertibleArgBuilder since it does not have // a corresponding _targetComType. - if (_argBuilder is ConvertibleArgBuilder) { + if (_argBuilder is ConvertibleArgBuilder) + { return Expression.Call( variant, typeof(Variant).GetMethod("SetAsIConvertible"), @@ -76,7 +81,8 @@ namespace System.Management.Automation.ComInterop { (_targetComType == VarEnum.VT_UNKNOWN) || (_targetComType == VarEnum.VT_VARIANT) || (_targetComType == VarEnum.VT_RECORD) || - (_targetComType == VarEnum.VT_ARRAY)){ + (_targetComType == VarEnum.VT_ARRAY)) + { // paramVariants._elementN.AsT = (cast)argN return Expression.Assign( Expression.Property( @@ -87,7 +93,8 @@ namespace System.Management.Automation.ComInterop { ); } - switch (_targetComType) { + switch (_targetComType) + { case VarEnum.VT_EMPTY: return null; @@ -101,22 +108,32 @@ namespace System.Management.Automation.ComInterop { } } - private static Expression Release(Expression pUnk) { + private static Expression Release(Expression pUnk) + { return Expression.Call(typeof(UnsafeMethods).GetMethod("IUnknownReleaseNotZero"), pUnk); } - internal Expression Clear() { - if (IsByRef) { - if (_argBuilder is StringArgBuilder) { + internal Expression Clear() + { + if (IsByRef) + { + if (_argBuilder is StringArgBuilder) + { Debug.Assert(TempVariable != null); return Expression.Call(typeof(Marshal).GetMethod("FreeBSTR"), TempVariable); - } else if (_argBuilder is DispatchArgBuilder) { + } + else if (_argBuilder is DispatchArgBuilder) + { Debug.Assert(TempVariable != null); return Release(TempVariable); - } else if (_argBuilder is UnknownArgBuilder) { + } + else if (_argBuilder is UnknownArgBuilder) + { Debug.Assert(TempVariable != null); return Release(TempVariable); - } else if (_argBuilder is VariantArgBuilder) { + } + else if (_argBuilder is VariantArgBuilder) + { Debug.Assert(TempVariable != null); return Expression.Call(TempVariable, typeof(Variant).GetMethod("Clear")); } @@ -124,7 +141,8 @@ namespace System.Management.Automation.ComInterop { } - switch (_targetComType) { + switch (_targetComType) + { case VarEnum.VT_EMPTY: case VarEnum.VT_NULL: return null; @@ -144,8 +162,10 @@ namespace System.Management.Automation.ComInterop { } } - internal Expression UpdateFromReturn(Expression parameter) { - if (TempVariable == null) { + internal Expression UpdateFromReturn(Expression parameter) + { + if (TempVariable == null) + { return null; } return Expression.Assign( diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 1db650e9a..b8080df77 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -18,7 +18,7 @@ using System.Threading; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Runspaces; - + namespace System.Management.Automation.Internal { /// @@ -54,7 +54,7 @@ namespace System.Management.Automation.Internal #endregion private_members #region ctor - + /// /// Initializes the new instance of Cmdlet class. /// @@ -62,7 +62,7 @@ namespace System.Management.Automation.Internal /// The only constructor is internal, so outside users cannot create /// an instance of this class. /// - internal InternalCommand () + internal InternalCommand() { this.CommandInfo = null; } @@ -77,7 +77,7 @@ namespace System.Management.Automation.Internal /// internal IScriptExtent InvocationExtent { get; set; } - private InvocationInfo myInvocation = null; + private InvocationInfo _myInvocation = null; /// /// Return the invocation data object for this command. /// @@ -86,12 +86,12 @@ namespace System.Management.Automation.Internal { get { - if (myInvocation == null) + if (_myInvocation == null) { - myInvocation = new InvocationInfo (this); + _myInvocation = new InvocationInfo(this); } - return myInvocation; + return _myInvocation; } } @@ -106,7 +106,8 @@ namespace System.Management.Automation.Internal internal PSObject CurrentPipelineObject { get { return currentObjectInPipeline; } - set { + set + { currentObjectInPipeline = value; } } @@ -116,9 +117,9 @@ namespace System.Management.Automation.Internal /// internal PSHost PSHostInternal { - get { return CBhost; } + get { return _CBhost; } } - private PSHost CBhost; + private PSHost _CBhost; /// /// Internal helper to get to SessionState @@ -126,16 +127,17 @@ namespace System.Management.Automation.Internal /// internal SessionState InternalState { - get { return state; } + get { return _state; } } - private SessionState state; + private SessionState _state; /// /// Internal helper. Indicates whether stop has been requested on this command. /// internal bool IsStopping { - get { + get + { MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime; return (mcr != null && mcr.IsStopping); } @@ -144,14 +146,14 @@ namespace System.Management.Automation.Internal /// /// The information about the command. /// - private CommandInfo commandInfo; + private CommandInfo _commandInfo; /// /// Gets or sets the command information for the command. /// internal CommandInfo CommandInfo { - get { return commandInfo; } - set { commandInfo = value; } + get { return _commandInfo; } + set { _commandInfo = value; } } #endregion internal_members @@ -166,23 +168,23 @@ namespace System.Management.Automation.Internal /// internal ExecutionContext Context { - get { return context; } + get { return _context; } set { if (value == null) { throw PSTraceSource.NewArgumentNullException("Context"); } - context = value; - Diagnostics.Assert (context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost"); - CBhost = (InternalHost)context.EngineHostInterface; + _context = value; + Diagnostics.Assert(_context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost"); + _CBhost = (InternalHost)_context.EngineHostInterface; // Construct the session state API set from the new context - state = new SessionState (context.EngineSessionState); + _state = new SessionState(_context.EngineSessionState); } } - private ExecutionContext context; + private ExecutionContext _context; /// /// This property tells you if you were being invoked inside the runspace or @@ -197,13 +199,13 @@ namespace System.Management.Automation.Internal #endregion public_properties #region Override - + /// /// When overridden in the derived class, performs initialization /// of command execution. /// Default implementation in the base class just returns. /// - internal virtual void DoBeginProcessing () + internal virtual void DoBeginProcessing() { } @@ -211,7 +213,7 @@ namespace System.Management.Automation.Internal /// When overridden in the derived class, performs execution /// of the command. /// - internal virtual void DoProcessRecord () + internal virtual void DoProcessRecord() { } @@ -220,7 +222,7 @@ namespace System.Management.Automation.Internal /// after the command execution. /// Default implementation in the base class just returns. /// - internal virtual void DoEndProcessing () + internal virtual void DoEndProcessing() { } @@ -230,7 +232,7 @@ namespace System.Management.Automation.Internal /// ProcessRecord, and EndProcessing. /// Default implementation in the base class just returns. /// - internal virtual void DoStopProcessing () + internal virtual void DoStopProcessing() { } @@ -262,10 +264,10 @@ namespace System.Management.Automation.Internal /// internal void InternalDispose(bool isDisposing) { - myInvocation = null; - state = null; - commandInfo = null; - context = null; + _myInvocation = null; + _state = null; + _commandInfo = null; + _context = null; } #endregion @@ -297,7 +299,6 @@ namespace System.Management.Automation Ignore, /// Suspend the command for further diagnosis. Supported only for workflows. Suspend, - } // enum ActionPreference #endregion ActionPreference @@ -358,8 +359,8 @@ namespace System.Management.Automation public abstract partial class PSCmdlet : Cmdlet { #region private_members - - private ProviderIntrinsics invokeProvider = null; + + private ProviderIntrinsics _invokeProvider = null; #endregion private_members @@ -455,11 +456,11 @@ namespace System.Management.Automation { using (PSTransactionManager.GetEngineProtectionScope()) { - if (invokeProvider == null) + if (_invokeProvider == null) { - invokeProvider = new ProviderIntrinsics(this); + _invokeProvider = new ProviderIntrinsics(this); } - return invokeProvider; + return _invokeProvider; } } } // InvokeProvider @@ -471,7 +472,6 @@ namespace System.Management.Automation { using (PSTransactionManager.GetEngineProtectionScope()) { - if (providerId == null) { throw PSTraceSource.NewArgumentNullException("providerId"); @@ -505,7 +505,7 @@ namespace System.Management.Automation #endregion internal_members #region ctor - + /// /// Initializes the new instance of PSCmdlet class. /// diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 8b5153d7e..d2c5f9d96 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -56,7 +56,7 @@ namespace System.Management.Automation public Collection CompletionMatches { get; set; } internal static readonly IList EmptyCompletionResult = Utils.EmptyArray(); - private static readonly CommandCompletion EmptyCommandCompletion = new CommandCompletion( + private static readonly CommandCompletion s_emptyCommandCompletion = new CommandCompletion( new Collection(EmptyCompletionResult), -1, -1, -1); #endregion Fields and Properties @@ -96,7 +96,7 @@ namespace System.Management.Automation { if (input == null) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } var parsedInput = MapStringInputToParsedInput(input, cursorIndex); @@ -145,7 +145,7 @@ namespace System.Management.Automation { if (input == null) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } if (cursorIndex > input.Length) @@ -172,7 +172,7 @@ namespace System.Management.Automation // supported on remote runspaces. if (powershell.IsNested || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } // If it's in the nested prompt, the powershell instance is created by "PowerShell.Create(RunspaceMode.CurrentRunspace);". @@ -251,7 +251,7 @@ namespace System.Management.Automation // supported on remote runspaces. if (powershell.IsNested || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } if (!powershell.IsChild) @@ -332,7 +332,7 @@ namespace System.Management.Automation { if (input == null) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } if (cursorIndex > input.Length) @@ -420,7 +420,7 @@ namespace System.Management.Automation } } - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } #endregion @@ -454,7 +454,7 @@ namespace System.Management.Automation var results = powershell.Invoke(); if (results == null) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } if (results.Count == 1) @@ -476,7 +476,7 @@ namespace System.Management.Automation powershell.Commands.Clear(); } - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } private static CommandCompletion CallScriptWithAstParameterSet(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, PowerShell powershell) @@ -492,7 +492,7 @@ namespace System.Management.Automation var results = powershell.Invoke(); if (results == null) { - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } if (results.Count == 1) @@ -514,7 +514,7 @@ namespace System.Management.Automation powershell.Commands.Clear(); } - return EmptyCommandCompletion; + return s_emptyCommandCompletion; } // This is the start of the real implementation of autocomplete/intellisense/tab completion @@ -528,7 +528,7 @@ namespace System.Management.Automation var context = LocalPipeline.GetExecutionContextFromTLS(); bool cleanupModuleAnalysisAppDomain = context.TakeResponsibilityForModuleAnalysisAppDomain(); - + try { // First, check if a V1/V2 implementation of TabExpansion exists. If so, the user had overridden @@ -577,8 +577,8 @@ namespace System.Management.Automation try { */ - var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); - results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); + var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); + results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); /* } finally @@ -627,7 +627,7 @@ namespace System.Management.Automation var functionInfo = executionContext.EngineSessionState.GetFunction("TabExpansion"); if (functionInfo != null) return true; - + var aliasInfo = executionContext.EngineSessionState.GetAlias("TabExpansion"); if (aliasInfo != null) return true; @@ -700,8 +700,8 @@ namespace System.Management.Automation /// private static class PSv2CompletionCompleter { - private static readonly Regex CmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); - private static readonly char[] CharsRequiringQuotedString = "`&@'#{}()$,;|<> \t".ToCharArray(); + private static readonly Regex s_cmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); + private static readonly char[] s_charsRequiringQuotedString = "`&@'#{}()$,;|<> \t".ToCharArray(); #region "Handle Command" @@ -718,14 +718,14 @@ namespace System.Management.Automation string[] cmdletParts = lastWord.Split(Utils.Separators.Backslash); if (cmdletParts.Length == 1) { - return CmdletTabRegex.IsMatch(lastWord); + return s_cmdletTabRegex.IsMatch(lastWord); } if (cmdletParts.Length == 2) { isSnapinSpecified = PSSnapInInfo.IsPSSnapinIdValid(cmdletParts[0]); if (isSnapinSpecified) { - return CmdletTabRegex.IsMatch(cmdletParts[1]); + return s_cmdletTabRegex.IsMatch(cmdletParts[1]); } } return false; @@ -850,7 +850,6 @@ namespace System.Management.Automation nextCommandAndName.CommandName.ShortName, StringComparison.OrdinalIgnoreCase) == 0) { - AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results); previousMatched = true; } @@ -946,7 +945,7 @@ namespace System.Management.Automation private static string AddQuoteIfNecessary(string completionText, string quote, bool completingAtStartOfLine) { - if (completionText.IndexOfAny(CharsRequiringQuotedString) != -1) + if (completionText.IndexOfAny(s_charsRequiringQuotedString) != -1) { bool needAmpersand = quote.Length == 0 && completingAtStartOfLine; string quoteInUse = quote.Length == 0 ? "'" : quote; @@ -1127,7 +1126,7 @@ namespace System.Management.Automation return null; } - result.Sort(delegate(PathItemAndConvertedPath x, PathItemAndConvertedPath y) + result.Sort(delegate (PathItemAndConvertedPath x, PathItemAndConvertedPath y) { Diagnostics.Assert(x.Path != null && y.Path != null, "SafeToString always returns a non-null string"); return string.Compare(x.Path, y.Path, StringComparison.CurrentCultureIgnoreCase); @@ -1152,9 +1151,9 @@ namespace System.Management.Automation private LastWordFinder(string sentence) { - replacementIndex = 0; + _replacementIndex = 0; Diagnostics.Assert(sentence != null, "need to provide an instance"); - this.sentence = sentence; + _sentence = sentence; } /// @@ -1179,7 +1178,7 @@ namespace System.Management.Automation ReplacementIndex = 0; - for (sentenceIndex = 0; sentenceIndex < sentence.Length; ++sentenceIndex) + for (_sentenceIndex = 0; _sentenceIndex < _sentence.Length; ++_sentenceIndex) { Diagnostics.Assert( (inSingleQuote && !inDoubleQuote) @@ -1187,7 +1186,7 @@ namespace System.Management.Automation || (!inSingleQuote && !inDoubleQuote), "Can't be in both single and double quotes"); - char c = sentence[sentenceIndex]; + char c = _sentence[_sentenceIndex]; // there are 3 possibilities: // 1) a new sequence is starting, @@ -1205,18 +1204,18 @@ namespace System.Management.Automation else if (c == '`') { Consume(c); - if (++sentenceIndex < sentence.Length) + if (++_sentenceIndex < _sentence.Length) { - Consume(sentence[sentenceIndex]); + Consume(_sentence[_sentenceIndex]); } } else if (IsWhitespace(c)) { - if (sequenceDueToEnd) + if (_sequenceDueToEnd) { // we skipped a quote earlier, now end that sequence - sequenceDueToEnd = false; + _sequenceDueToEnd = false; if (inSingleQuote) { inSingleQuote = false; @@ -1227,7 +1226,7 @@ namespace System.Management.Automation inDoubleQuote = false; } - ReplacementIndex = sentenceIndex + 1; + ReplacementIndex = _sentenceIndex + 1; } else if (inSingleQuote || inDoubleQuote) { @@ -1239,7 +1238,7 @@ namespace System.Management.Automation { // no sequence is started, so ignore c - ReplacementIndex = sentenceIndex + 1; + ReplacementIndex = _sentenceIndex + 1; } } else @@ -1250,7 +1249,7 @@ namespace System.Management.Automation } } - string result = new string(wordBuffer, 0, wordBufferIndex); + string result = new string(_wordBuffer, 0, _wordBufferIndex); closingQuote = inSingleQuote ? '\'' : inDoubleQuote ? '"' : '\0'; replacementIndexOut = ReplacementIndex; @@ -1268,43 +1267,43 @@ namespace System.Management.Automation if (inQuote) { - if (sequenceDueToEnd) + if (_sequenceDueToEnd) { // I've ended a sequence and am starting another; don't consume c, update replacementIndex - ReplacementIndex = sentenceIndex + 1; + ReplacementIndex = _sentenceIndex + 1; } - sequenceDueToEnd = !sequenceDueToEnd; + _sequenceDueToEnd = !_sequenceDueToEnd; } else { // I'm starting a sequence; don't consume c, update replacementIndex inQuote = true; - ReplacementIndex = sentenceIndex; + ReplacementIndex = _sentenceIndex; } } private void Consume(char c) { - Diagnostics.Assert(wordBuffer != null, "wordBuffer is not initialized"); - Diagnostics.Assert(wordBufferIndex < wordBuffer.Length, "wordBufferIndex is out of range"); + Diagnostics.Assert(_wordBuffer != null, "wordBuffer is not initialized"); + Diagnostics.Assert(_wordBufferIndex < _wordBuffer.Length, "wordBufferIndex is out of range"); - wordBuffer[wordBufferIndex++] = c; + _wordBuffer[_wordBufferIndex++] = c; } private int ReplacementIndex { - get { return replacementIndex; } + get { return _replacementIndex; } set { - Diagnostics.Assert(value >= 0 && value < sentence.Length + 1, "value out of range"); + Diagnostics.Assert(value >= 0 && value < _sentence.Length + 1, "value out of range"); // when we set the replacement index, that means we're also resetting our word buffer. we know wordBuffer // will never be longer than sentence. - wordBuffer = new char[sentence.Length]; - wordBufferIndex = 0; - replacementIndex = value; + _wordBuffer = new char[_sentence.Length]; + _wordBufferIndex = 0; + _replacementIndex = value; } } @@ -1313,12 +1312,12 @@ namespace System.Management.Automation return (c == ' ') || (c == '\x0009'); } - private readonly string sentence; - private char[] wordBuffer; - private int wordBufferIndex; - private int replacementIndex; - private int sentenceIndex; - private bool sequenceDueToEnd; + private readonly string _sentence; + private char[] _wordBuffer; + private int _wordBufferIndex; + private int _replacementIndex; + private int _sentenceIndex; + private bool _sequenceDueToEnd; } #endregion private methods diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 581e02489..04284b1e9 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -26,8 +26,8 @@ namespace System.Management.Automation internal CompletionExecutionHelper Helper { get; set; } internal Hashtable Options { get; set; } - internal Dictionary CustomArgumentCompleters { get; set; } - internal Dictionary NativeArgumentCompleters { get; set; } + internal Dictionary CustomArgumentCompleters { get; set; } + internal Dictionary NativeArgumentCompleters { get; set; } internal string WordToComplete { get; set; } internal int ReplacementIndex { get; set; } internal int ReplacementLength { get; set; } @@ -55,43 +55,43 @@ namespace System.Management.Automation internal CompletionAnalysis(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options) { - this._ast = ast; - this._tokens = tokens; - this._cursorPosition = cursorPosition; - this._options = options; + _ast = ast; + _tokens = tokens; + _cursorPosition = cursorPosition; + _options = options; } - static bool IsInterestingToken(Token token) + private static bool IsInterestingToken(Token token) { return token.Kind != TokenKind.NewLine && token.Kind != TokenKind.EndOfInput; } - static bool IsCursorWithinOrJustAfterExtent(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorWithinOrJustAfterExtent(IScriptPosition cursor, IScriptExtent extent) { return cursor.Offset > extent.StartOffset && cursor.Offset <= extent.EndOffset; } - static bool IsCursorRightAfterExtent(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorRightAfterExtent(IScriptPosition cursor, IScriptExtent extent) { return cursor.Offset == extent.EndOffset; } - static bool IsCursorAfterExtentAndInTheSameLine(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorAfterExtentAndInTheSameLine(IScriptPosition cursor, IScriptExtent extent) { return cursor.Offset >= extent.EndOffset && extent.EndLineNumber == cursor.LineNumber; } - static bool IsCursorBeforeExtent(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorBeforeExtent(IScriptPosition cursor, IScriptExtent extent) { return cursor.Offset < extent.StartOffset; } - static bool IsCursorAfterExtent(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorAfterExtent(IScriptPosition cursor, IScriptExtent extent) { return extent.EndOffset < cursor.Offset; } - static bool IsCursorOutsideOfExtent(IScriptPosition cursor, IScriptExtent extent) + private static bool IsCursorOutsideOfExtent(IScriptPosition cursor, IScriptExtent extent) { return cursor.Offset < extent.StartOffset || cursor.Offset > extent.EndOffset; } @@ -178,7 +178,7 @@ namespace System.Management.Automation return false; } - return (errorStatement.Kind.Kind.Equals(TokenKind.Switch) && + return (errorStatement.Kind.Kind.Equals(TokenKind.Switch) && errorStatement.Flags.TryGetValue("file", out fileConditionTuple) && fileConditionTuple.Item2 == pipeline); } @@ -396,7 +396,7 @@ namespace System.Management.Automation case TokenKind.RBracket: if (lastAst is TypeExpressionAst) { - var targetExpr = (TypeExpressionAst) lastAst; + var targetExpr = (TypeExpressionAst)lastAst; var memberResult = new List(); CompletionCompleters.CompleteMemberHelper( @@ -404,7 +404,7 @@ namespace System.Management.Automation "*", targetExpr, completionContext, memberResult); - + if (memberResult.Count > 0) { replacementIndex++; @@ -415,10 +415,10 @@ namespace System.Management.Automation } } break; - + case TokenKind.Comma: // Hanlde array elements such as dir .\cd, || dir -Path: .\cd, - if (lastAst is ErrorExpressionAst && + if (lastAst is ErrorExpressionAst && (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst)) { replacementIndex += replacementLength; @@ -445,9 +445,9 @@ namespace System.Management.Automation case TokenKind.Number: // Handle scenarios such as Get-Process -Id 5 || Get-Process -Id 5210, 3 || Get-Process -Id: 5210, 3 - if (lastAst is ConstantExpressionAst && - (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst || - (lastAst.Parent is ArrayLiteralAst && + if (lastAst is ConstantExpressionAst && + (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst || + (lastAst.Parent is ArrayLiteralAst && (lastAst.Parent.Parent is CommandAst || lastAst.Parent.Parent is CommandParameterAst)))) { completionContext.WordToComplete = tokenAtCursor.Text; @@ -500,34 +500,33 @@ namespace System.Management.Automation case TokenKind.Equals: case TokenKind.AtParen: case TokenKind.LParen: - { - if (lastAst is AttributeAst) { - completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length; - completionContext.ReplacementLength = replacementLength = 0; - result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + if (lastAst is AttributeAst) + { + completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length; + completionContext.ReplacementLength = replacementLength = 0; + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + } + else + { + // + // Handle auto completion for enum/dependson property of DSC resource, + // cursor is right after '=', '(' or '@(' + // + // Configuration config + // { + // User test + // { + // DependsOn=| + // DependsOn=@(|) + // DependsOn=(| + // + bool unused; + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, + ref replacementIndex, ref replacementLength, out unused); + } + break; } - else - { - // - // Handle auto completion for enum/dependson property of DSC resource, - // cursor is right after '=', '(' or '@(' - // - // Configuration config - // { - // User test - // { - // DependsOn=| - // DependsOn=@(|) - // DependsOn=(| - // - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, - ref replacementIndex, ref replacementLength, out unused); - - } - break; - } default: if ((tokenAtCursor.TokenFlags & TokenFlags.Keyword) != 0) { @@ -580,7 +579,7 @@ namespace System.Management.Automation (lastAst is CommandParameterAst || lastAst is CommandAst || (lastAstIsExpressionAst && lastAst.Parent is CommandAst) || (lastAstIsExpressionAst && lastAst.Parent is CommandParameterAst) || - (lastAstIsExpressionAst && lastAst.Parent is ArrayLiteralAst && + (lastAstIsExpressionAst && lastAst.Parent is ArrayLiteralAst && (lastAst.Parent.Parent is CommandAst || lastAst.Parent.Parent is CommandParameterAst)))) { completionContext.WordToComplete = string.Empty; @@ -673,23 +672,23 @@ namespace System.Management.Automation case TokenKind.Equals: case TokenKind.Comma: case TokenKind.AtParen: - { - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); - break; - } + { + bool unused; + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); + break; + } case TokenKind.LParen: - if (lastAst is AttributeAst) - { - completionContext.ReplacementLength = replacementLength = 0; - result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); - } - else - { - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, - ref replacementIndex, ref replacementLength, out unused); - } + if (lastAst is AttributeAst) + { + completionContext.ReplacementLength = replacementLength = 0; + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + } + else + { + bool unused; + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, + ref replacementIndex, ref replacementLength, out unused); + } break; default: break; @@ -769,7 +768,7 @@ namespace System.Management.Automation { replacementIndex = completionContext.RelatedAsts[0].Extent.StartScriptPosition.Offset; replacementLength = completionContext.RelatedAsts[0].Extent.EndScriptPosition.Offset - replacementIndex; - + completionContext.WordToComplete = input; result = CompleteFileNameAsCommand(completionContext); } @@ -885,14 +884,14 @@ namespace System.Management.Automation { return FindTypeNameToComplete(arrayTypeName.ElementType, cursor) ?? null; } - + return null; } private static string GetFirstLineSubString(string stringToComplete, out bool hasNewLine) { hasNewLine = false; - if(!String.IsNullOrEmpty(stringToComplete)) + if (!String.IsNullOrEmpty(stringToComplete)) { var index = stringToComplete.IndexOfAny(Utils.Separators.CrLf); if (index >= 0) @@ -1044,7 +1043,7 @@ namespace System.Management.Automation Diagnostics.Assert(isCursorInString || (!hasNewLine), "hasNoQuote and hasNewLine cannot be true at the same time"); if (property.ValueMap != null && property.ValueMap.Count > 0) { - IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(x => x).Where(v=>!existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); + IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(x => x).Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v)); if (matchedResults == null || !matchedResults.Any()) { @@ -1290,10 +1289,10 @@ namespace System.Management.Automation matched = false; #if CORECLR // Microsoft.PowerShell.DesiredStateConfiguration is not in CORE CLR - results = new List(); + results = new List(); #else IEnumerable keywords = configureAst.DefinedKeywords.Where( - k=> // Node is special case, legal in both Resource and Meta configuration + k => // Node is special case, legal in both Resource and Meta configuration String.Compare(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) == 0 || ( // Check compatibility between Resource and Configuration Type @@ -1330,7 +1329,7 @@ namespace System.Management.Automation { results = new List(); } - results.Add(new CompletionResult( + results.Add(new CompletionResult( keyword.Keyword, keyword.Keyword, CompletionResultType.DynamicKeyword, @@ -1353,7 +1352,7 @@ namespace System.Management.Automation var strConst = lastAst as StringConstantExpressionAst; if (strConst != null) { - if( strConst.Value.Equals("$", StringComparison.Ordinal)) + if (strConst.Value.Equals("$", StringComparison.Ordinal)) { completionContext.WordToComplete = ""; return CompletionCompleters.CompleteVariable(completionContext); @@ -1373,14 +1372,14 @@ namespace System.Management.Automation case UsingStatementKind.Command: break; case UsingStatementKind.Module: - var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - StringLiterals.PowerShellModuleFileExtension, + var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + StringLiterals.PowerShellModuleFileExtension, StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellNgenAssemblyExtension, - StringLiterals.DependentWorkflowAssemblyExtension, - StringLiterals.PowerShellCmdletizationFileExtension, - StringLiterals.WorkflowFileExtension + StringLiterals.DependentWorkflowAssemblyExtension, + StringLiterals.PowerShellCmdletizationFileExtension, + StringLiterals.WorkflowFileExtension }; result = CompletionCompleters.CompleteFilename(completionContext, false, moduleExtensions).ToList(); if (completionContext.WordToComplete.IndexOfAny(Utils.Separators.DirectoryOrDrive) != -1) @@ -1401,7 +1400,6 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("UsingStatementKind"); } - } } } @@ -1422,7 +1420,7 @@ namespace System.Management.Automation var scriptBlockAst = (ScriptBlockAst)completionContext.RelatedAsts[0]; cursorAst = GetLastAstAtCursor(scriptBlockAst, cursorBeforeCmdName); } - + if (cursorAst != null && cursorAst.Extent.EndLineNumber == tokenAtCursor.Extent.StartLineNumber && cursorAst.Extent.EndColumnNumber == tokenAtCursor.Extent.StartColumnNumber) @@ -1451,14 +1449,14 @@ namespace System.Management.Automation extraText: tokenAtCursor.Text, executionContext: completionContext.ExecutionContext) : null; - + if (fullPath == null) { return result; } - + // Continue trying the filename/commandname completion for scenarios like this: $aa\d completionContext.WordToComplete = fullPath; replacementIndex = cursorAst.Extent.StartScriptPosition.Offset; replacementLength += cursorAst.Extent.Text.Length; - + completionContext.ReplacementIndex = replacementIndex; completionContext.ReplacementLength = replacementLength; } @@ -1483,9 +1481,9 @@ namespace System.Management.Automation string expandedString = null; var expandableStringAst = new ExpandableStringExpressionAst(strConst.Extent, strConst.Value, StringConstantType.BareWord); if (CompletionCompleters.IsPathSafelyExpandable(expandableStringAst: expandableStringAst, - extraText: String.Empty, - executionContext: completionContext.ExecutionContext, - expandedString: out expandedString)) + extraText: String.Empty, + executionContext: completionContext.ExecutionContext, + expandedString: out expandedString)) { completionContext.WordToComplete = expandedString; } @@ -1626,7 +1624,7 @@ namespace System.Management.Automation bool needFileCompletion = false; if (lastAst.Parent is FileRedirectionAst || CompleteAgainstSwitchFile(lastAst, completionContext.TokenBeforeCursor)) { - string wordToComplete = + string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, String.Empty, completionContext); if (wordToComplete != null) { @@ -1667,7 +1665,7 @@ namespace System.Management.Automation } else { - string wordToComplete = + string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, String.Empty, completionContext); if (wordToComplete != null) { @@ -1733,7 +1731,7 @@ namespace System.Management.Automation var addAmpersandIfNecessary = CompletionCompleters.IsAmpersandNeeded(completionContext, true); var result = new List(); var clearLiteralPathsKey = false; - + if (completionContext.Options == null) { completionContext.Options = new Hashtable { { "LiteralPaths", true } }; diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 51cb463a5..32d3be823 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -45,13 +45,13 @@ namespace System.Management.Automation #if CORECLR static void UpdateTypeCacheOnAssemblyLoad(Assembly loadedAssembly) #else - static void UpdateTypeCacheOnAssemblyLoad(object sender, AssemblyLoadEventArgs args) + private static void UpdateTypeCacheOnAssemblyLoad(object sender, AssemblyLoadEventArgs args) #endif { // Just null out the cache - we'll rebuild it the next time someone tries to complete a type. // We could rebuild it now, but we could be loading multiple assemblies (e.g. dependent assemblies) // and there is no sense in rebuilding anything until we're done loading all of the assemblies. - Interlocked.Exchange(ref typeCache, null); + Interlocked.Exchange(ref s_typeCache, null); } #region Command Names @@ -188,7 +188,7 @@ namespace System.Management.Automation Exception exceptionThrown; var commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); - + if (commandInfos != null && commandInfos.Count > 1) { var sortedCommandInfos = commandInfos.OrderBy(a => a, new CommandNameComparer()); @@ -204,7 +204,7 @@ namespace System.Management.Automation return commandResults; } - static private readonly HashSet KeywordsToExcludeFromAddingAmpersand + static private readonly HashSet s_keywordsToExcludeFromAddingAmpersand = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.InlineScript.ToString(), TokenKind.Configuration.ToString() }; static internal CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote) { @@ -247,7 +247,7 @@ namespace System.Management.Automation else { needAmpersand = quote == string.Empty && addAmpersandIfNecessary && - Tokenizer.IsKeyword(name) && !KeywordsToExcludeFromAddingAmpersand.Contains(name); + Tokenizer.IsKeyword(name) && !s_keywordsToExcludeFromAddingAmpersand.Contains(name); name = quote + name + quote; } @@ -315,7 +315,7 @@ namespace System.Management.Automation } else { - list = new List {value, baseObj}; + list = new List { value, baseObj }; commandTable[name] = list; } } @@ -407,7 +407,7 @@ namespace System.Management.Automation /// static internal readonly List PseudoWorkflowCommands = new List { "Checkpoint-Workflow", "Suspend-Workflow", "InlineScript" }; - static private Collection CompleteWorkflowCommand (string command, Ast lastAst, Collection commandInfos) + static private Collection CompleteWorkflowCommand(string command, Ast lastAst, Collection commandInfos) { if (!lastAst.IsInWorkflow()) return commandInfos; @@ -426,7 +426,7 @@ namespace System.Management.Automation return commandInfos; } - class FindFunctionsVisitor : AstVisitor + private class FindFunctionsVisitor : AstVisitor { internal readonly List FunctionDefinitions = new List(); @@ -446,7 +446,7 @@ namespace System.Management.Automation var moduleName = context.WordToComplete ?? string.Empty; var result = new List(); var quote = HandleDoubleAndSingleQuote(ref moduleName); - + if (!moduleName.EndsWith("*", StringComparison.Ordinal)) { moduleName += "*"; @@ -494,7 +494,7 @@ namespace System.Management.Automation #endregion Module Names #region Command Parameters - private static string[] ParameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" }; + private static string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" }; internal static List CompleteCommandParameter(CompletionContext context) { @@ -528,15 +528,15 @@ namespace System.Management.Automation var wordToMatch = context.WordToComplete.Substring(1) + "*"; var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase); var parameterNames = keywordAst.CommandElements.Where(ast => ast is CommandParameterAst).Select(ast => (ast as CommandParameterAst).ParameterName); - foreach (var parameterName in ParameterNamesOfImportDSCResource) + foreach (var parameterName in s_parameterNamesOfImportDSCResource) { if (pattern.IsMatch(parameterName) && !parameterNames.Contains(parameterName, StringComparer.OrdinalIgnoreCase)) { string tooltip = "[String] " + parameterName; - result.Add(new CompletionResult("-"+parameterName, parameterName, CompletionResultType.ParameterName, tooltip)); + result.Add(new CompletionResult("-" + parameterName, parameterName, CompletionResultType.ParameterName, tooltip)); } } - if(result.Count > 0) + if (result.Count > 0) { context.ReplacementLength = context.WordToComplete.Length; context.ReplacementIndex = lastAst.Extent.StartOffset; @@ -561,7 +561,7 @@ namespace System.Management.Automation return result; // Parent must be a command - commandAst = (CommandAst) dashAst.Parent; + commandAst = (CommandAst)dashAst.Parent; partialName = string.Empty; } @@ -633,7 +633,7 @@ namespace System.Management.Automation if (bindingInfo.AmbiguousParameters.Any(pAst => parameterAst.GetHashCode() == pAst.GetHashCode())) { result = GetParameterCompletionResults( - parameterName, + parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.UnboundParameters, withColon); @@ -677,7 +677,7 @@ namespace System.Management.Automation break; case AstParameterArgumentType.Fake: { - FakePair pair = (FakePair) entry.Value; + FakePair pair = (FakePair)entry.Value; if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode()) { matchedParameterName = entry.Key; @@ -686,7 +686,7 @@ namespace System.Management.Automation break; case AstParameterArgumentType.Switch: { - SwitchPair pair = (SwitchPair) entry.Value; + SwitchPair pair = (SwitchPair)entry.Value; if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode()) { matchedParameterName = entry.Key; @@ -704,7 +704,7 @@ namespace System.Management.Automation Diagnostics.Assert(matchedParameterName != null, "we should find matchedParameterName from the BoundArguments"); MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName]; - + WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase); string parameterType = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] "; string colonSuffix = withColon ? ":" : string.Empty; @@ -724,7 +724,7 @@ namespace System.Management.Automation return result; } - + /// /// Get the parameter completion results by using the given valid parameter sets and available parameters /// @@ -949,7 +949,7 @@ namespace System.Management.Automation } else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandAst) { - commandAst = (CommandAst) expressionAst.Parent.Parent; + commandAst = (CommandAst)expressionAst.Parent.Parent; if (commandAst.CommandElements.Count == 1 || context.WordToComplete == string.Empty) { @@ -959,14 +959,14 @@ namespace System.Management.Automation else { // dir -Path a.txt, b.txt c - expressionAst = (ExpressionAst) expressionAst.Parent; + expressionAst = (ExpressionAst)expressionAst.Parent; } } else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandParameterAst) { // Handle scenarios such as // dir -Path: a.txt, || dir -Path: a.txt, b.txt - commandAst = (CommandAst) expressionAst.Parent.Parent.Parent; + commandAst = (CommandAst)expressionAst.Parent.Parent.Parent; if (context.WordToComplete == string.Empty) { // dir -Path: a.txt, b.txt @@ -975,12 +975,12 @@ namespace System.Management.Automation else { // dir -Path: a.txt, b - expressionAst = (ExpressionAst) expressionAst.Parent; + expressionAst = (ExpressionAst)expressionAst.Parent; } } else if (expressionAst.Parent is CommandParameterAst && expressionAst.Parent.Parent is CommandAst) { - commandAst = (CommandAst) expressionAst.Parent.Parent; + commandAst = (CommandAst)expressionAst.Parent.Parent; if (expressionAst is ErrorExpressionAst && expressionAst.Extent.Text.EndsWith(",", StringComparison.Ordinal)) { // dir -Path: a.txt, @@ -1071,7 +1071,7 @@ namespace System.Management.Automation } if (!parsedArgumentsProvidesMatch) - { + { int index = 0; CommandElementAst prevElem = null; if (expressionAst != null) @@ -1140,7 +1140,6 @@ namespace System.Management.Automation } } } - } while (false); // Indicate if the current argument completion falls into those pre-defined cases and @@ -1208,7 +1207,7 @@ namespace System.Management.Automation context.Helper.CurrentPowerShell, out fakeReplacementIndex, out fakeReplacementLength); - + if (ret != null && ret.Count > 0) { var prefix = TokenKind.LParen.Text() + input.Substring(0, fakeReplacementIndex); @@ -1305,7 +1304,7 @@ namespace System.Management.Automation { if (InvokeScriptArgumentCompleter( customCompleter, - new object[] {context.WordToComplete, commandAst, context.CursorPosition.Offset }, + new object[] { context.WordToComplete, commandAst, context.CursorPosition.Offset }, result)) { return result; @@ -1366,10 +1365,10 @@ namespace System.Management.Automation var expandablePathAst = stringAst as ExpandableStringExpressionAst; string fullPath = null; if (expandablePathAst != null && - IsPathSafelyExpandable(expandableStringAst: expandablePathAst, - extraText: partialPath, - executionContext: completionContext.ExecutionContext, - expandedString: out fullPath)) + IsPathSafelyExpandable(expandableStringAst: expandablePathAst, + extraText: partialPath, + executionContext: completionContext.ExecutionContext, + expandedString: out fullPath)) { return fullPath; } @@ -1467,7 +1466,7 @@ namespace System.Management.Automation // positional argument if (!entry.Value.ParameterSpecified) { - var arg = (AstPair) entry.Value; + var arg = (AstPair)entry.Value; if (arg.Argument.GetHashCode() == lastPositionalArg.Argument.GetHashCode()) { lastPositionalGetBound = true; @@ -1477,7 +1476,7 @@ namespace System.Management.Automation else if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray)) { // check if the positional argument would be bound to a "ValueFromRemainingArgument" parameter - var arg = (AstArrayPair) entry.Value; + var arg = (AstArrayPair)entry.Value; if (arg.Argument.Any(exp => exp.GetHashCode() == lastPositionalArg.Argument.GetHashCode())) { parameterNames.Add(entry.Key); @@ -1507,7 +1506,7 @@ namespace System.Management.Automation bindingInfo.CommandName, commandAst, context, - result, + result, bindingInfo.UnboundParameters, bindingInfo.DefaultParameterSetFlag, bindingInfo.ValidParameterSetsFlags, @@ -1528,8 +1527,8 @@ namespace System.Management.Automation if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray) && !argLocation.Argument.ParameterSpecified) { - var arrayArg = (AstArrayPair) entry.Value; - var target = (AstPair) argLocation.Argument; + var arrayArg = (AstArrayPair)entry.Value; + var target = (AstPair)argLocation.Argument; if (arrayArg.Argument.Any(exp => exp.GetHashCode() == target.Argument.GetHashCode())) { parameterNames.Add(entry.Key); @@ -1630,7 +1629,7 @@ namespace System.Management.Automation ProcessParameter(commandName, commandAst, context, result, positionalParam, boundArguments); } - if (! isProcessedAsPositional) + if (!isProcessedAsPositional) { foreach (MergedCompiledCommandParameter param in parameters) { @@ -1671,13 +1670,13 @@ namespace System.Management.Automation string commandName, CommandAst commandAst, CompletionContext context, - List result, + List result, MergedCompiledCommandParameter parameter, Dictionary boundArguments = null) { CompletionResult fullMatch = null; Type parameterType = GetEffectiveParameterType(parameter.Parameter.Type); - + if (parameterType.IsArray) { parameterType = parameterType.GetElementType(); @@ -1689,7 +1688,7 @@ namespace System.Management.Automation string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(parameterType); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(new string[] {separator}, StringSplitOptions.RemoveEmptyEntries); + string[] enumArray = enumString.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries); string wordToComplete = context.WordToComplete; string quote = HandleDoubleAndSingleQuote(ref wordToComplete); @@ -1705,7 +1704,7 @@ namespace System.Management.Automation fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value); continue; } - + if (pattern.IsMatch(value)) { enumList.Add(value); @@ -1773,7 +1772,7 @@ namespace System.Management.Automation { result.Add(fullMatch); } - + setList.Sort(); foreach (string entry in setList) { @@ -1795,7 +1794,7 @@ namespace System.Management.Automation } completionText = quote + realEntry + quote; } - + result.Add(new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); } result.Add(CompletionResult.Null); @@ -1828,7 +1827,7 @@ namespace System.Management.Automation { case AstParameterArgumentType.AstPair: { - AstPair astPair = (AstPair) astParameterArgumentPair; + AstPair astPair = (AstPair)astParameterArgumentPair; argumentAst = astPair.Argument; } break; @@ -1880,7 +1879,7 @@ namespace System.Management.Automation IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue); if (enumerable == null) { - enumerable = new object[] {argumentValue}; + enumerable = new object[] { argumentValue }; } foreach (var element in enumerable) { @@ -1933,12 +1932,12 @@ namespace System.Management.Automation var value = (AstPair)argumentValue; if (value.Argument is StringConstantExpressionAst) { - var argument = (StringConstantExpressionAst) value.Argument; + var argument = (StringConstantExpressionAst)value.Argument; result.Add(argument.Value); } else if (value.Argument is ArrayLiteralAst) { - var argument = (ArrayLiteralAst) value.Argument; + var argument = (ArrayLiteralAst)value.Argument; foreach (ExpressionAst entry in argument.Elements) { var entryAsString = entry as StringConstantExpressionAst; @@ -1984,9 +1983,9 @@ namespace System.Management.Automation } private static void NativeCommandArgumentCompletion( - string commandName, - CompiledCommandParameter parameter, - List result, + string commandName, + CompiledCommandParameter parameter, + List result, CommandAst commandAst, CompletionContext context, Dictionary boundArguments = null) @@ -1999,7 +1998,7 @@ namespace System.Management.Automation var parameterName = parameter.Name; var customCompleter = GetCustomArgumentCompleter( "CustomArgumentCompleters", - new [] { commandName + ":" + parameterName, parameterName}, + new[] { commandName + ":" + parameterName, parameterName }, context); if (customCompleter != null) { @@ -2290,7 +2289,7 @@ namespace System.Management.Automation default: { NativeCompletionPathArgument(context.WordToComplete, parameterName, result, context); - break; + break; } } } @@ -2389,7 +2388,7 @@ namespace System.Management.Automation { bool result = InvokeScriptArgumentCompleter( scriptBlock, - new object[] {commandName, parameterName, wordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)}, + new object[] { commandName, parameterName, wordToComplete, commandAst, GetBoundArgumentsAsHashtable(context) }, resultList); if (result) { @@ -2467,7 +2466,7 @@ namespace System.Management.Automation return false; } - if (!match.Groups["NetTypeName"].Value.Equals(typeof (CimInstance).FullName, StringComparison.OrdinalIgnoreCase)) + if (!match.Groups["NetTypeName"].Value.Equals(typeof(CimInstance).FullName, StringComparison.OrdinalIgnoreCase)) { return false; } @@ -2480,7 +2479,7 @@ namespace System.Management.Automation private static void NativeCompletionCimCommands( string parameter, Dictionary boundArguments, - List result, + List result, CommandAst commandAst, CompletionContext context) { @@ -2554,7 +2553,7 @@ namespace System.Management.Automation } } - private static ConcurrentDictionary> cimNamespaceAndClassNameToAssociationResultClassNames = + private static ConcurrentDictionary> s_cimNamespaceAndClassNameToAssociationResultClassNames = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); private static IEnumerable NativeCompletionCimAssociationResultClassName_GetResultClassNames( @@ -2580,7 +2579,7 @@ namespace System.Management.Automation CultureInfo.InvariantCulture, "associators of {{{0}}} WHERE SchemaOnly", cimClass.CimSystemProperties.ClassName); - + resultClassNames.AddRange( cimSession.QueryInstances(cimNamespaceOfSource ?? "root/cimv2", "WQL", query) .Select(associationInstance => associationInstance.CimSystemProperties.ClassName)); @@ -2604,10 +2603,10 @@ namespace System.Management.Automation return; } - IEnumerable resultClassNames = cimNamespaceAndClassNameToAssociationResultClassNames.GetOrAdd( + IEnumerable resultClassNames = s_cimNamespaceAndClassNameToAssociationResultClassNames.GetOrAdd( (pseudoboundNamespace ?? "root/cimv2") + ":" + pseudoboundClassName, _ => NativeCompletionCimAssociationResultClassName_GetResultClassNames(pseudoboundNamespace, pseudoboundClassName)); - + WildcardPattern resultClassNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); result.AddRange(resultClassNames .Where(resultClassNamePattern.IsMatch) @@ -2618,7 +2617,7 @@ namespace System.Management.Automation string pseudoboundNamespace, string pseudoboundClassName, bool staticMethod, - List result, + List result, CompletionContext context) { if (string.IsNullOrWhiteSpace(pseudoboundClassName)) @@ -2685,7 +2684,7 @@ namespace System.Management.Automation result.AddRange(localResults.OrderBy(x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); } - private static ConcurrentDictionary> cimNamespaceToClassNames = + private static ConcurrentDictionary> s_cimNamespaceToClassNames = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); private static IEnumerable NativeCompletionCimClassName_GetClassNames(string targetNamespace) @@ -2693,20 +2692,20 @@ namespace System.Management.Automation List result = new List(); using (CimSession cimSession = CimSession.Create(null)) { - using (var operationOptions = new CimOperationOptions {ClassNamesOnly = true}) - foreach (CimClass cimClass in cimSession.EnumerateClasses(targetNamespace, null, operationOptions)) - using (cimClass) - { - string className = cimClass.CimSystemProperties.ClassName; - result.Add(className); - } + using (var operationOptions = new CimOperationOptions { ClassNamesOnly = true }) + foreach (CimClass cimClass in cimSession.EnumerateClasses(targetNamespace, null, operationOptions)) + using (cimClass) + { + string className = cimClass.CimSystemProperties.ClassName; + result.Add(className); + } } return result; } private static void NativeCompletionCimClassName( string pseudoBoundNamespace, - List result, + List result, CompletionContext context) { string targetNamespace = pseudoBoundNamespace ?? "root/cimv2"; @@ -2714,7 +2713,7 @@ namespace System.Management.Automation List regularClasses = new List(); List systemClasses = new List(); - IEnumerable allClasses = cimNamespaceToClassNames.GetOrAdd( + IEnumerable allClasses = s_cimNamespaceToClassNames.GetOrAdd( targetNamespace, NativeCompletionCimClassName_GetClassNames); WildcardPattern classNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); @@ -2749,7 +2748,7 @@ namespace System.Management.Automation } private static void NativeCompletionCimNamespace( - List result, + List result, CompletionContext context) { string containerNamespace = "root"; @@ -2769,36 +2768,36 @@ namespace System.Management.Automation using (CimSession cimSession = CimSession.Create(null)) { foreach (CimInstance namespaceInstance in cimSession.EnumerateInstances(containerNamespace, "__Namespace")) - using (namespaceInstance) - { - if (context.Helper.CancelTabCompletion) + using (namespaceInstance) { - break; - } + if (context.Helper.CancelTabCompletion) + { + break; + } - CimProperty namespaceNameProperty = namespaceInstance.CimInstanceProperties["Name"]; - if (namespaceNameProperty == null) - { - continue; - } + CimProperty namespaceNameProperty = namespaceInstance.CimInstanceProperties["Name"]; + if (namespaceNameProperty == null) + { + continue; + } - string childNamespace = namespaceNameProperty.Value as string; - if (childNamespace == null) - { - continue; - } + string childNamespace = namespaceNameProperty.Value as string; + if (childNamespace == null) + { + continue; + } - if (!childNamespacePattern.IsMatch(childNamespace)) - { - continue; - } + if (!childNamespacePattern.IsMatch(childNamespace)) + { + continue; + } - namespaceResults.Add(new CompletionResult( - containerNamespace + "/" + childNamespace, - childNamespace, - CompletionResultType.Namespace, - containerNamespace + "/" + childNamespace)); - } + namespaceResults.Add(new CompletionResult( + containerNamespace + "/" + childNamespace, + childNamespace, + CompletionResultType.Namespace, + containerNamespace + "/" + childNamespace)); + } } result.AddRange(namespaceResults.OrderBy(x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); @@ -3122,14 +3121,14 @@ namespace System.Management.Automation if (isImportModule) { - var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { StringLiterals.PowerShellScriptFileExtension, - StringLiterals.PowerShellModuleFileExtension, + var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) + { StringLiterals.PowerShellScriptFileExtension, + StringLiterals.PowerShellModuleFileExtension, StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellNgenAssemblyExtension, StringLiterals.DependentWorkflowAssemblyExtension, - StringLiterals.PowerShellCmdletizationFileExtension, - StringLiterals.WorkflowFileExtension + StringLiterals.PowerShellCmdletizationFileExtension, + StringLiterals.WorkflowFileExtension }; var moduleFilesResults = new List(CompleteFilename(new CompletionContext { WordToComplete = assemblyOrModuleName, Helper = context.Helper }, false, moduleExtensions)); if (moduleFilesResults.Count > 0) @@ -3174,7 +3173,7 @@ namespace System.Management.Automation { wordToComplete += "*"; } - + if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { AddCommandWithPreferenceSetting(powershell, "Microsoft.PowerShell.Management\\Get-Process"); @@ -3232,7 +3231,7 @@ namespace System.Management.Automation { completionText = quote + completionText + quote; } - + result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3475,8 +3474,8 @@ namespace System.Management.Automation private static void NativeCompletionAliasCommands(string commandName, string paramName, List result, CompletionContext context) { - if (string.IsNullOrEmpty(paramName) || - (!paramName.Equals("Definition", StringComparison.OrdinalIgnoreCase) && + if (string.IsNullOrEmpty(paramName) || + (!paramName.Equals("Definition", StringComparison.OrdinalIgnoreCase) && !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))) { return; @@ -3642,7 +3641,7 @@ namespace System.Management.Automation ProviderInfo provider; executionContext.LocationGlobber.GetProviderPath(providedPath, out provider); - var isFileSystem = provider != null && + var isFileSystem = provider != null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); //AutoComplete only if filesystem provider. @@ -3695,7 +3694,7 @@ namespace System.Management.Automation { return; } - + if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) || paramName.Equals("Path", StringComparison.OrdinalIgnoreCase)) { NativeCompletionPathArgument(pathName, paramName, result, context); @@ -3726,7 +3725,7 @@ namespace System.Management.Automation private static void NativeCompletionPathArgument(string pathName, string paramName, List result, CompletionContext context) { - if (string.IsNullOrEmpty(paramName) || + if (string.IsNullOrEmpty(paramName) || (!paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) && (!paramName.Equals("Path", StringComparison.OrdinalIgnoreCase)) && (!paramName.Equals("FilePath", StringComparison.OrdinalIgnoreCase)))) @@ -3888,7 +3887,7 @@ namespace System.Management.Automation else if (!pair.ParameterSpecified) { index++; - lastPositionalArgument = (AstPair) pair; + lastPositionalArgument = (AstPair)pair; } } @@ -3909,7 +3908,7 @@ namespace System.Management.Automation { case AstParameterArgumentType.AstPair: { - var arg = (AstPair) pair; + var arg = (AstPair)pair; if (arg.ParameterSpecified) { // Named argument @@ -3922,7 +3921,7 @@ namespace System.Management.Automation if (!arg.ParameterContainsArgument && arg.Argument.Extent.StartOffset > token.Extent.StartOffset) { // case: Get-Cmdlet -Param abc - return new ArgumentLocation() {Argument = arg, IsPositional = false, Position = -1}; + return new ArgumentLocation() { Argument = arg, IsPositional = false, Position = -1 }; } } else @@ -3970,7 +3969,7 @@ namespace System.Management.Automation // Tab is typed before the first argument if (prev == null) { - return new ArgumentLocation() {Argument = null, IsPositional = true, Position = 0}; + return new ArgumentLocation() { Argument = null, IsPositional = true, Position = 0 }; } switch (prev.ParameterArgumentType) @@ -3980,17 +3979,17 @@ namespace System.Management.Automation if (!prev.ParameterSpecified) return new ArgumentLocation() { Argument = null, IsPositional = true, Position = position }; - return prev.Parameter.Extent.Text.EndsWith(":", StringComparison.Ordinal) - ? new ArgumentLocation() {Argument = prev, IsPositional = false, Position = -1} - : new ArgumentLocation() {Argument = null, IsPositional = true, Position = position}; + return prev.Parameter.Extent.Text.EndsWith(":", StringComparison.Ordinal) + ? new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 } + : new ArgumentLocation() { Argument = null, IsPositional = true, Position = position }; case AstParameterArgumentType.Fake: - return new ArgumentLocation() {Argument = prev, IsPositional = false, Position = -1}; + return new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 }; default: Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject"); return null; } } - + /// /// Find the location where 'tab' is typed based on the expressionAst. /// @@ -4007,20 +4006,20 @@ namespace System.Management.Automation { case AstParameterArgumentType.AstPair: { - AstPair arg = (AstPair) pair; + AstPair arg = (AstPair)pair; if (arg.ArgumentIsCommandParameterAst) continue; if (arg.ParameterContainsArgument && arg.Argument == expAst) { - return new ArgumentLocation() {IsPositional = false, Position = -1, Argument = arg}; + return new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg }; } if (arg.Argument.GetHashCode() == expAst.GetHashCode()) { - return arg.ParameterSpecified ? - new ArgumentLocation() {IsPositional = false, Position = -1, Argument = arg} : - new ArgumentLocation() {IsPositional = true, Position = position, Argument = arg}; + return arg.ParameterSpecified ? + new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg } : + new ArgumentLocation() { IsPositional = true, Position = position, Argument = arg }; } if (!arg.ParameterSpecified) @@ -4071,7 +4070,7 @@ namespace System.Management.Automation } var helper = new CompletionExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace)); - return CompleteFilename(new CompletionContext {WordToComplete = fileName, Helper = helper}); + return CompleteFilename(new CompletionContext { WordToComplete = fileName, Helper = helper }); } internal static IEnumerable CompleteFilename(CompletionContext context) @@ -4145,7 +4144,7 @@ namespace System.Management.Automation { var isFileSystem = false; var wordContainsProviderId = ProviderSpecified(wordToComplete); - + if (psobjs.Count > 0) { dynamic firstObj = psobjs[0]; @@ -4180,11 +4179,11 @@ namespace System.Management.Automation if (isFileSystem) { bool hiddenFilesAreHandled = false; - + if (psobjs.Count > 0 && !LocationGlobber.StringContainsGlobCharacters(wordToComplete)) { string leaf = null; - string pathWithoutProvider = wordContainsProviderId + string pathWithoutProvider = wordContainsProviderId ? wordToComplete.Substring(wordToComplete.IndexOf(':') + 2) : wordToComplete; @@ -4192,7 +4191,7 @@ namespace System.Management.Automation { leaf = Path.GetFileName(pathWithoutProvider); } - catch(Exception e) + catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } @@ -4372,7 +4371,6 @@ namespace System.Management.Automation } else { - completionText = completionText.Replace("[", "``["); completionText = completionText.Replace("]", "``]"); } @@ -4445,18 +4443,18 @@ namespace System.Management.Automation } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - struct SHARE_INFO_1 + private struct SHARE_INFO_1 { public string netname; public int type; public string remark; } - const int MAX_PREFERRED_LENGTH = -1; - const int NERR_Success = 0; - const int ERROR_MORE_DATA = 234; - const int STYPE_DISKTREE = 0; - const int STYPE_MASK = 0x000000FF; + private const int MAX_PREFERRED_LENGTH = -1; + private const int NERR_Success = 0; + private const int ERROR_MORE_DATA = 234; + private const int STYPE_DISKTREE = 0; + private const int STYPE_MASK = 0x000000FF; [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] private static extern int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, @@ -4482,7 +4480,7 @@ namespace System.Management.Automation { IntPtr curInfoPtr = (IntPtr)((long)shBuf + (ClrFacade.SizeOf() * i)); SHARE_INFO_1 shareInfo = ClrFacade.PtrToStructure(curInfoPtr); - + if ((shareInfo.type & STYPE_MASK) != STYPE_DISKTREE) continue; @@ -4526,8 +4524,8 @@ namespace System.Management.Automation return CompleteVariable(new CompletionContext { WordToComplete = variableName, Helper = helper }); } - private static readonly string[] VariableScopes = new string[] {"Global:", "Local:", "Script:", "Private:"}; - private static readonly char[] CharactersRequiringQuotes = new char[] { + private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:" }; + private static readonly char[] s_charactersRequiringQuotes = new char[] { '-', '`', '&', '@', '\'', '"', '#', '{', '}', '(', ')', '$', ',', ';', '|', '<', '>', ' ', '.', '\\', '/', '\t', '^', }; @@ -4553,7 +4551,7 @@ namespace System.Management.Automation if (lastAst != null) { Ast parent = lastAst.Parent; - var findVariablesVisitor = new FindVariablesVisitor {CompletionVariableAst = lastAst}; + var findVariablesVisitor = new FindVariablesVisitor { CompletionVariableAst = lastAst }; while (parent != null) { if (parent is IParameterMetadataProvider) @@ -4592,7 +4590,7 @@ namespace System.Management.Automation if (wildcardPattern.IsMatch(userPath)) { - var completedName = (userPath.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (userPath.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + userPath : prefix + "{" + userPath + "}"; var tooltip = userPath; @@ -4650,7 +4648,7 @@ namespace System.Management.Automation else { provider = wordToComplete.Substring(0, colon + 1); - if (VariableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) + if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) { pattern = "variable:" + wordToComplete.Substring(colon + 1) + "*"; } @@ -4686,7 +4684,7 @@ namespace System.Management.Automation } } - var completedName = (name.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + provider + name : prefix + "{" + provider + name + "}"; AddUniqueVariable(hashedResults, results, completedName, name, tooltip); @@ -4709,7 +4707,7 @@ namespace System.Management.Automation if (!string.IsNullOrEmpty(name)) { name = "env:" + name; - var completedName = (name.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + name : prefix + "{" + name + "}"; AddUniqueVariable(hashedResults, results, completedName, name, "[string]" + name); @@ -4720,11 +4718,11 @@ namespace System.Management.Automation // Return variables already in session state first, because we can sometimes give better information, // like the variables type. - foreach (var specialVariable in _specialVariablesCache.Value) + foreach (var specialVariable in s_specialVariablesCache.Value) { if (wildcardPattern.IsMatch(specialVariable)) { - var completedName = (specialVariable.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (specialVariable.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + specialVariable : prefix + "{" + specialVariable + "}"; @@ -4749,7 +4747,7 @@ namespace System.Management.Automation var name = driveInfo.Name; if (name != null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) { - var completedName = (name.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + name + ":" : prefix + "{" + name + ":}"; @@ -4761,11 +4759,11 @@ namespace System.Management.Automation } var scopePattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - foreach (var scope in VariableScopes) + foreach (var scope in s_variableScopes) { if (scopePattern.IsMatch(scope)) { - var completedName = (scope.IndexOfAny(CharactersRequiringQuotes) == -1) + var completedName = (scope.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + scope : prefix + "{" + scope + "}"; AddUniqueVariable(hashedResults, results, completedName, scope, scope); @@ -4785,7 +4783,7 @@ namespace System.Management.Automation } } - class FindVariablesVisitor : AstVisitor + private class FindVariablesVisitor : AstVisitor { internal Ast Top; internal Ast CompletionVariableAst; @@ -4845,9 +4843,9 @@ namespace System.Management.Automation } } - private static readonly Lazy> _specialVariablesCache = new Lazy>(BuildSpecialVariablesCache); + private static readonly Lazy> s_specialVariablesCache = new Lazy>(BuildSpecialVariablesCache); - static SortedSet BuildSpecialVariablesCache() + private static SortedSet BuildSpecialVariablesCache() { var result = new SortedSet(); foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static)) @@ -4882,7 +4880,7 @@ namespace System.Management.Automation { AddCommandWithPreferenceSetting(powershell, "Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId); psobjs = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); - + if (psobjs != null && psobjs.Count == 1) { var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; @@ -4909,10 +4907,10 @@ namespace System.Management.Automation psobjs = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); - + if (psobjs != null) { - for (int index = psobjs.Count - 1; index >= 0; index --) + for (int index = psobjs.Count - 1; index >= 0; index--) { var psobj = psobjs[index]; var historyInfo = PSObject.Base(psobj) as HistoryInfo; @@ -4939,14 +4937,14 @@ namespace System.Management.Automation #region Members // List of extension methods - static private readonly List> ExtensionMethods = + static private readonly List> s_extensionMethods = new List> { new Tuple("Where", "Where({ expression } [, mode [, numberToReturn]])"), new Tuple("ForEach", "ForEach(expression [, arguments...])") }; // List of DSC collection-value variables - static private readonly HashSet DscCollectionVariables = + static private readonly HashSet s_dscCollectionVariables = new HashSet(StringComparer.OrdinalIgnoreCase) { "SelectedNodes", "AllNodes" }; internal static List CompleteMember(CompletionContext context, bool @static) @@ -5035,13 +5033,13 @@ namespace System.Management.Automation } else if (lastAst.Parent is BinaryExpressionAst && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) { - var memberExprAst = ((BinaryExpressionAst) lastAst.Parent).Left as MemberExpressionAst; + var memberExprAst = ((BinaryExpressionAst)lastAst.Parent).Left as MemberExpressionAst; if (memberExprAst != null) { targetExpr = memberExprAst.Expression; if (memberExprAst.Member is StringConstantExpressionAst) { - memberName = ((StringConstantExpressionAst) memberExprAst.Member).Value + "*"; + memberName = ((StringConstantExpressionAst)memberExprAst.Member).Value + "*"; } } } @@ -5069,7 +5067,7 @@ namespace System.Management.Automation var typeExpr = targetExpr as TypeExpressionAst; if (typeExpr != null) { - inferredTypes = new[] {new PSTypeName(typeExpr.TypeName) }; + inferredTypes = new[] { new PSTypeName(typeExpr.TypeName) }; } } else @@ -5096,7 +5094,7 @@ namespace System.Management.Automation { // Handle $SelectedNodes and $AllNodes var variablePath = variableAst.VariablePath; - if (variablePath.IsVariable && DscCollectionVariables.Contains(variablePath.UserPath) && IsInDscContext(variableAst)) + if (variablePath.IsVariable && s_dscCollectionVariables.Contains(variablePath.UserPath) && IsInDscContext(variableAst)) { shouldAddExtensionMethods = true; } @@ -5150,7 +5148,7 @@ namespace System.Management.Automation /// private static void CompleteExtensionMethods(WildcardPattern pattern, List results) { - results.AddRange(from member in ExtensionMethods + results.AddRange(from member in s_extensionMethods where pattern.IsMatch(member.Item1) select new CompletionResult(member.Item1 + "(", member.Item1, @@ -5166,7 +5164,7 @@ namespace System.Management.Automation if (variableExpr != null) { var varPath = variableExpr.VariablePath; - if (varPath.IsVariable && + if (varPath.IsVariable && varPath.UserPath.Equals("ConfigurationData", StringComparison.OrdinalIgnoreCase)) { return true; @@ -5184,7 +5182,7 @@ namespace System.Management.Automation return Ast.GetAncestorAst(expression) != null; } - private static void CompleteMemberByInferredType(CompletionContext context, IEnumerable inferredTypes, List results, string memberName, Func filter , bool isStatic) + private static void CompleteMemberByInferredType(CompletionContext context, IEnumerable inferredTypes, List results, string memberName, Func filter, bool isStatic) { bool extensionMethodsAdded = false; HashSet typeNameUsed = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -5292,32 +5290,32 @@ namespace System.Management.Automation string type; switch (cimProperty.CimType) { - case Microsoft.Management.Infrastructure.CimType.DateTime: - case Microsoft.Management.Infrastructure.CimType.Instance: - case Microsoft.Management.Infrastructure.CimType.Reference: - case Microsoft.Management.Infrastructure.CimType.DateTimeArray: - case Microsoft.Management.Infrastructure.CimType.InstanceArray: - case Microsoft.Management.Infrastructure.CimType.ReferenceArray: - type = "CimInstance#" + cimProperty.CimType.ToString(); - break; + case Microsoft.Management.Infrastructure.CimType.DateTime: + case Microsoft.Management.Infrastructure.CimType.Instance: + case Microsoft.Management.Infrastructure.CimType.Reference: + case Microsoft.Management.Infrastructure.CimType.DateTimeArray: + case Microsoft.Management.Infrastructure.CimType.InstanceArray: + case Microsoft.Management.Infrastructure.CimType.ReferenceArray: + type = "CimInstance#" + cimProperty.CimType.ToString(); + break; - default: - type = ToStringCodeMethods.Type(CimConverter.GetDotNetType(cimProperty.CimType)); - break; + default: + type = ToStringCodeMethods.Type(CimConverter.GetDotNetType(cimProperty.CimType)); + break; } bool isReadOnly = (CimFlags.ReadOnly == (cimProperty.Flags & CimFlags.ReadOnly)); return type + " " + cimProperty.Name + " { get; " + (isReadOnly ? "}" : "set; }"); } - static bool IsWriteablePropertyMember(object member) + private static bool IsWriteablePropertyMember(object member) { var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { return propertyInfo.CanWrite; } - + var psPropertyInfo = member as PSPropertyInfo; if (psPropertyInfo != null) { @@ -5327,7 +5325,7 @@ namespace System.Management.Automation return false; } - static bool IsPropertyMember(object member) + private static bool IsPropertyMember(object member) { return member is PropertyInfo || member is FieldInfo @@ -5336,7 +5334,7 @@ namespace System.Management.Automation || member is PropertyMemberAst; } - static bool IsMemberHidden(object member) + private static bool IsMemberHidden(object member) { var psMemberInfo = member as PSMemberInfo; if (psMemberInfo != null) @@ -5357,12 +5355,11 @@ namespace System.Management.Automation return false; } - static bool IsConstructor(object member) + private static bool IsConstructor(object member) { var psMethod = member as PSMethod; if (psMethod != null) { - var methodCacheEntry = psMethod.adapterData as DotNetAdapter.MethodCacheEntry; if (methodCacheEntry != null) { @@ -5390,7 +5387,7 @@ namespace System.Management.Automation IEnumerable elementTypes; if (typename.Type.IsArray) { - elementTypes = new [] {typename.Type.GetElementType()}; + elementTypes = new[] { typename.Type.GetElementType() }; } else { @@ -5498,7 +5495,7 @@ namespace System.Management.Automation // Look in the type table first. if (!@static) { - var consolidatedString = new ConsolidatedString(new string[] {typename.Name}); + var consolidatedString = new ConsolidatedString(new string[] { typename.Name }); results.AddRange(context.ExecutionContext.TypeTable.GetMembers(consolidatedString)); } @@ -5517,7 +5514,7 @@ namespace System.Management.Automation } } } - + return results; } @@ -5525,11 +5522,11 @@ namespace System.Management.Automation #region Types - abstract class TypeCompletionBase + private abstract class TypeCompletionBase { internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix); internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove); - + internal static string RemoveBackTick(string typeName) { var backtick = typeName.LastIndexOf('`'); @@ -5544,7 +5541,7 @@ namespace System.Management.Automation /// This type represents a non-generic type for type name completion. It only contains information that can be /// inferred from the full type name. /// - class TypeCompletionInStringFormat : TypeCompletionBase + private class TypeCompletionInStringFormat : TypeCompletionBase { /// /// Get the full type name of the type represented by this instance. @@ -5558,18 +5555,18 @@ namespace System.Management.Automation { get { - if (shortTypeName == null) + if (_shortTypeName == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); int lastPlusIndex = FullTypeName.LastIndexOf('+'); - shortTypeName = lastPlusIndex != -1 + _shortTypeName = lastPlusIndex != -1 ? FullTypeName.Substring(lastPlusIndex + 1) : FullTypeName.Substring(lastDotIndex + 1); } - return shortTypeName; + return _shortTypeName; } } - private string shortTypeName; + private string _shortTypeName; /// /// Get the namespace of the type represented by this instance. @@ -5578,15 +5575,15 @@ namespace System.Management.Automation { get { - if (@namespace == null) + if (_namespace == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); - @namespace = FullTypeName.Substring(0, lastDotIndex); + _namespace = FullTypeName.Substring(0, lastDotIndex); } - return @namespace; + return _namespace; } } - private string @namespace; + private string _namespace; /// /// Construct the CompletionResult based on the information of this instance @@ -5619,7 +5616,7 @@ namespace System.Management.Automation /// This type represents a generic type for type name completion. It only contains information that can be /// inferred from the full type name. /// - class GenericTypeCompletionInStringFormat : TypeCompletionInStringFormat + private class GenericTypeCompletionInStringFormat : TypeCompletionInStringFormat { /// /// Get the number of generic type arguments required by the type represented by this instance. @@ -5628,16 +5625,16 @@ namespace System.Management.Automation { get { - if (genericArgumentCount == 0) + if (_genericArgumentCount == 0) { var backtick = FullTypeName.LastIndexOf('`'); var argCount = FullTypeName.Substring(backtick + 1); - genericArgumentCount = LanguagePrimitives.ConvertTo(argCount); + _genericArgumentCount = LanguagePrimitives.ConvertTo(argCount); } - return genericArgumentCount; + return _genericArgumentCount; } } - private int genericArgumentCount = 0; + private int _genericArgumentCount = 0; /// /// Construct the CompletionResult based on the information of this instance @@ -5680,7 +5677,7 @@ namespace System.Management.Automation /// /// This type represents a non-generic type for type name completion. It contains the actual type instance. /// - class TypeCompletion : TypeCompletionBase + private class TypeCompletion : TypeCompletionBase { internal Type Type; @@ -5735,7 +5732,7 @@ namespace System.Management.Automation /// /// This type represents a generic type for type name completion. It contains the actual type instance. /// - class GenericTypeCompletion : TypeCompletion + private class GenericTypeCompletion : TypeCompletion { internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { @@ -5748,7 +5745,7 @@ namespace System.Management.Automation string completion = string.IsNullOrEmpty(namespaceToRemove) ? fullNameWithoutBacktip : fullNameWithoutBacktip.Substring(namespaceToRemove.Length + 1); - + string typeName = RemoveBackTick(Type.Name); var listItem = typeName + "<>"; @@ -5771,7 +5768,7 @@ namespace System.Management.Automation /// /// This type represents a namespace for namespace completion. /// - class NamespaceCompletion : TypeCompletionBase + private class NamespaceCompletion : TypeCompletionBase { internal string Namespace; @@ -5792,14 +5789,14 @@ namespace System.Management.Automation } } - class TypeCompletionMapping + private class TypeCompletionMapping { // The Key is the string we'll be searching on. It could complete to various things. internal string Key; internal List Completions = new List(); } - private static TypeCompletionMapping[][] typeCache; + private static TypeCompletionMapping[][] s_typeCache; private static TypeCompletionMapping[][] InitializeTypeCache() { #region Process_TypeAccelerators @@ -5809,7 +5806,7 @@ namespace System.Management.Automation { TypeCompletionMapping entry; var typeCompletionInstance = new TypeCompletion { Type = type.Value }; - + if (entries.TryGetValue(type.Key, out entry)) { // Check if this accelerator type is already included in the mapping entry referenced by the same key. @@ -5860,12 +5857,12 @@ namespace System.Management.Automation } #endregion Process_TypeAccelerators - + #region Process_LoadedAssemblies var assembliesExludingPSGenerated = ClrFacade.GetAssemblies(); var allPublicTypes = assembliesExludingPSGenerated.SelectMany(assembly => assembly.GetTypes().Where(TypeResolver.IsPublic)); - + foreach (var type in allPublicTypes) { HandleNamespace(entries, type.Namespace); @@ -5894,7 +5891,7 @@ namespace System.Management.Automation localTypeCache[group.Key] = group.ToArray(); } - Interlocked.Exchange(ref typeCache, localTypeCache); + Interlocked.Exchange(ref s_typeCache, localTypeCache); return localTypeCache; } @@ -5998,7 +5995,7 @@ namespace System.Management.Automation internal static List CompleteNamespace(CompletionContext context, string prefix = "", string suffix = "") { - var localTypeCache = typeCache ?? InitializeTypeCache(); + var localTypeCache = s_typeCache ?? InitializeTypeCache(); var results = new List(); var wordToComplete = context.WordToComplete; var dots = wordToComplete.Count(c => c == '.'); @@ -6038,7 +6035,7 @@ namespace System.Management.Automation internal static List CompleteType(CompletionContext context, string prefix = "", string suffix = "") { - var localTypeCache = typeCache ?? InitializeTypeCache(); + var localTypeCache = s_typeCache ?? InitializeTypeCache(); var results = new List(); var completionTextSet = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -6069,7 +6066,7 @@ namespace System.Management.Automation } } } - + //this is a temparary fix. Only the type defined in the same script get complete. Need to use using Module when that is available. var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; var typeAsts = scriptBlockAst.FindAll(ast => ast is TypeDefinitionAst, false).Cast(); @@ -6086,24 +6083,24 @@ namespace System.Management.Automation results.Add(new CompletionResult(prefix + typeAst.Name + suffix, typeAst.Name, CompletionResultType.Type, toolTipPrefix + typeAst.Name)); } - results.Sort((c1,c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); + results.Sort((c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } - static string GetNamespaceToRemove(CompletionContext context, TypeCompletionBase completion) + private static string GetNamespaceToRemove(CompletionContext context, TypeCompletionBase completion) { if (completion is NamespaceCompletion) { return null; } var typeCompletion = completion as TypeCompletion; - string typeNameSpace = typeCompletion != null - ? typeCompletion.Type.Namespace + string typeNameSpace = typeCompletion != null + ? typeCompletion.Type.Namespace : ((TypeCompletionInStringFormat)completion).Namespace; var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; - var matchingNsStates= scriptBlockAst.UsingStatements.Where(s => - s.UsingStatementKind == UsingStatementKind.Namespace - && typeNameSpace != null - && typeNameSpace.StartsWith(s.Name.Value, StringComparison.OrdinalIgnoreCase)); + var matchingNsStates = scriptBlockAst.UsingStatements.Where(s => + s.UsingStatementKind == UsingStatementKind.Namespace + && typeNameSpace != null + && typeNameSpace.StartsWith(s.Name.Value, StringComparison.OrdinalIgnoreCase)); string ns = String.Empty; foreach (var nsState in matchingNsStates) @@ -6128,7 +6125,7 @@ namespace System.Management.Automation var wordToComplete = context.WordToComplete + "*"; var topicPattern = WildcardPattern.Get("about_*.help.txt", WildcardOptions.IgnoreCase); string[] files = null; - + try { files = Directory.GetFiles(dirPath, wordToComplete); @@ -6185,7 +6182,7 @@ namespace System.Management.Automation string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SwitchFlags)); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(new string[] {separator}, StringSplitOptions.RemoveEmptyEntries); + string[] enumArray = enumString.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List(); @@ -6202,13 +6199,13 @@ namespace System.Management.Automation fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterName, value); continue; } - + if (pattern.IsMatch(value)) { enumList.Add(value); } } - + if (fullMatch != null) { result.Add(fullMatch); @@ -6477,7 +6474,6 @@ namespace System.Management.Automation else { powershell.AddCommand(command); - } powershell .AddParameter("ErrorAction", ActionPreference.Ignore) @@ -6519,7 +6515,7 @@ namespace System.Management.Automation var formattedString = String.Format(CultureInfo.InvariantCulture, expandableStringAst.FormatExpression, varValues.ToArray()); string quote = (constType == StringConstantType.DoubleQuoted) ? "\"" : String.Empty; - + expandedString = quote + formattedString + extraText + quote; return true; } @@ -6612,7 +6608,7 @@ namespace System.Management.Automation if (targetExpr is ArrayExpressionAst && !(value is object[])) { // When the array contains only one element, the evaluation result would be that element. We wrap it into an array - value = new[] {value}; + value = new[] { value }; } var powershell = context.Helper.CurrentPowerShell; @@ -6653,7 +6649,7 @@ namespace System.Management.Automation var completionText = memberInfo.Name; // Handle scenarios like this: $aa | add-member 'a b' 23; $aa.a - if (completionText.IndexOfAny(CharactersRequiringQuotes) != -1) + if (completionText.IndexOfAny(s_charactersRequiringQuotes) != -1) { completionText = completionText.Replace("'", "''"); completionText = "'" + completionText + "'"; @@ -6700,7 +6696,7 @@ namespace System.Management.Automation if (pattern.IsMatch(key)) { // Handle scenarios like this: $hashtable["abc#d"] = 100; $hashtable.ab - if (key.IndexOfAny(CharactersRequiringQuotes) != -1) + if (key.IndexOfAny(s_charactersRequiringQuotes) != -1) { key = key.Replace("'", "''"); key = "'" + key + "'"; @@ -6725,7 +6721,7 @@ namespace System.Management.Automation private static bool IsValueEnumerable(object value) { object baseValue = PSObject.Base(value); - + if (baseValue == null || baseValue is string || baseValue is PSObject || baseValue is IDictionary || baseValue is System.Xml.XmlNode) { @@ -6767,12 +6763,12 @@ namespace System.Management.Automation ParseError[] errors; Language.Parser.ParseInput(completion, out tokens, out errors); - char[] charToCheck = escape ? new[] { '$', '[', ']', '`' } : new[] {'$', '`'}; + char[] charToCheck = escape ? new[] { '$', '[', ']', '`' } : new[] { '$', '`' }; // Expect no errors and 2 tokens (1 is for our completion, the other is eof) // Or if the completion is a keyword, we ignore the errors bool requireQuote = !(errors.Length == 0 && tokens.Length == 2); - if ((!requireQuote && tokens[0] is StringToken) || + if ((!requireQuote && tokens[0] is StringToken) || (tokens.Length == 2 && (tokens[0].TokenFlags & TokenFlags.Keyword) != 0)) { requireQuote = false; @@ -6835,7 +6831,7 @@ namespace System.Management.Automation var lastAst = context.RelatedAsts.Last(); var parent = lastAst.Parent as CommandAst; - if (parent != null && parent.CommandElements.Count == 1 && + if (parent != null && parent.CommandElements.Count == 1 && ((!defaultChoice && parent.InvocationOperator == TokenKind.Unknown) || (defaultChoice && parent.InvocationOperator != TokenKind.Unknown))) { @@ -6916,7 +6912,7 @@ namespace System.Management.Automation /// use is for intellisense where you don't want to run arbitrary code, but you do want to know the values /// of various expressions so you can get the members. /// - class SafeExprEvaluator : ICustomAstVisitor2 + internal class SafeExprEvaluator : ICustomAstVisitor2 { internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionContext, out object value) { @@ -6929,9 +6925,9 @@ namespace System.Management.Automation try { // ConstrainedLanguage has already been applied as necessary when we construct CompletionContext - Diagnostics.Assert(!(ExecutionContext.HasEverUsedConstrainedLanguage && executionContext.LanguageMode != PSLanguageMode.ConstrainedLanguage), + Diagnostics.Assert(!(ExecutionContext.HasEverUsedConstrainedLanguage && executionContext.LanguageMode != PSLanguageMode.ConstrainedLanguage), "If the runspace has ever used constrained language mode, then the current language mode should already be set to contrained language"); - + // We're passing 'true' here for isTrustedInput, because SafeExprEvaluator ensures that the AST // has no dangerous side-effects such as arbitrary expression evaluation. It does require variable // access and a few other minor things, which staples of tab completion: diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionExecutionHelper.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionExecutionHelper.cs index a75478b61..2e688af22 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionExecutionHelper.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionExecutionHelper.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation /// Auxilliary class to the execution of commands as needed by /// CommandCompletion /// - class CompletionExecutionHelper + internal class CompletionExecutionHelper { #region Constructors diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 1da7f7d86..0cf0892c2 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -1,5 +1,4 @@ //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // // @@ -53,7 +52,7 @@ namespace System.Management.Automation /// A type name Type = 11, - + /// A keyword Keyword = 12, @@ -68,32 +67,32 @@ namespace System.Management.Automation /// /// Class used to store a tab completion or Intellisense result /// - public class CompletionResult - { + public class CompletionResult + { /// /// Text to be used as the auto completion result /// - private string completionText; + private string _completionText; /// /// Text to be displayed in a list /// - private string listItemText; + private string _listItemText; /// /// The text for the tooltip with details to be displayed about the object /// - private string toolTip; + private string _toolTip; /// /// Type of completion result /// - private CompletionResultType resultType; + private CompletionResultType _resultType; /// /// Private member for null instance /// - private static readonly CompletionResult NullInstance = new CompletionResult(); + private static readonly CompletionResult s_nullInstance = new CompletionResult(); /// /// Gets the text to be used as the auto completion result @@ -102,11 +101,11 @@ namespace System.Management.Automation { get { - if (this == NullInstance) + if (this == s_nullInstance) { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } - return this.completionText; + return _completionText; } } @@ -117,11 +116,11 @@ namespace System.Management.Automation { get { - if (this == NullInstance) + if (this == s_nullInstance) { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } - return this.listItemText; + return _listItemText; } } @@ -132,11 +131,11 @@ namespace System.Management.Automation { get { - if (this == NullInstance) + if (this == s_nullInstance) { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } - return this.resultType; + return _resultType; } } @@ -147,11 +146,11 @@ namespace System.Management.Automation { get { - if (this == NullInstance) + if (this == s_nullInstance) { throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.NoAccessToProperties); } - return this.toolTip; + return _toolTip; } } @@ -160,7 +159,7 @@ namespace System.Management.Automation /// internal static CompletionResult Null { - get { return NullInstance; } + get { return s_nullInstance; } } /// @@ -192,10 +191,10 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("toolTip"); } - this.completionText = completionText; - this.listItemText = listItemText; - this.toolTip = toolTip; - this.resultType = resultType; + _completionText = completionText; + _listItemText = listItemText; + _toolTip = toolTip; + _resultType = resultType; } @@ -216,6 +215,6 @@ namespace System.Management.Automation /// This can be used in argument completion, to indicate that the completion attempt has gone through the /// native command argument completion methods. /// - private CompletionResult() {} + private CompletionResult() { } } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 231625fbd..56219ba0f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -93,15 +93,15 @@ namespace System.Management.Automation /// /// /// - [Parameter(ParameterSetName="NativeSet", Mandatory = true)] - [Parameter(ParameterSetName="PowerShellSet")] + [Parameter(ParameterSetName = "NativeSet", Mandatory = true)] + [Parameter(ParameterSetName = "PowerShellSet")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CommandName { get; set; } /// /// /// - [Parameter(ParameterSetName="PowerShellSet", Mandatory = true)] + [Parameter(ParameterSetName = "PowerShellSet", Mandatory = true)] public string ParameterName { get; set; } /// @@ -114,7 +114,7 @@ namespace System.Management.Automation /// /// /// - [Parameter(ParameterSetName="NativeSet")] + [Parameter(ParameterSetName = "NativeSet")] public SwitchParameter Native { get; set; } /// @@ -136,7 +136,7 @@ namespace System.Management.Automation if (CommandName == null || CommandName.Length == 0) { - CommandName = new[] {""}; + CommandName = new[] { "" }; } for (int i = 0; i < CommandName.Length; i++) diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 2308265db..84f95db1f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -354,7 +354,7 @@ namespace System.Management.Automation.Language if ((desiredParameters != null) && (desiredParameters.Length > 0)) { bool possiblyHadDesiredParameter = false; - foreach(CommandParameterAst commandParameter in commandAst.CommandElements.OfType()) + foreach (CommandParameterAst commandParameter in commandAst.CommandElements.OfType()) { string actualParameterName = commandParameter.ParameterName; @@ -388,20 +388,20 @@ namespace System.Management.Automation.Language PseudoBindingInfo pseudoBinding = null; if (Runspace.DefaultRunspace == null) { - lock (bindCommandlLock) + lock (s_bindCommandlLock) { - if (bindCommandPowerShell == null) + if (s_bindCommandPowerShell == null) { // Create a mini runspace by remove the types and formats InitialSessionState minimalState = InitialSessionState.CreateDefault2(); minimalState.Types.Clear(); minimalState.Formats.Clear(); - bindCommandPowerShell = PowerShell.Create(minimalState); + s_bindCommandPowerShell = PowerShell.Create(minimalState); } // Handle static binding from a non-PowerShell / C# application - Runspace.DefaultRunspace = bindCommandPowerShell.Runspace; + Runspace.DefaultRunspace = s_bindCommandPowerShell.Runspace; // Static binding always does argument binding (not argument or parameter completion). pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentBinding); Runspace.DefaultRunspace = null; @@ -415,8 +415,8 @@ namespace System.Management.Automation.Language return new StaticBindingResult(commandAst, pseudoBinding); } - static Object bindCommandlLock = new Object(); - static PowerShell bindCommandPowerShell = null; + private static Object s_bindCommandlLock = new Object(); + private static PowerShell s_bindCommandPowerShell = null; } /// @@ -426,8 +426,8 @@ namespace System.Management.Automation.Language { internal StaticBindingResult(CommandAst commandAst, PseudoBindingInfo bindingInfo) { - boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - bindingExceptions = new Dictionary(StringComparer.OrdinalIgnoreCase); + _boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); + _bindingExceptions = new Dictionary(StringComparer.OrdinalIgnoreCase); if (bindingInfo == null) { @@ -441,7 +441,7 @@ namespace System.Management.Automation.Language private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoBindingInfo bindingInfo) { - this.bindingInfo = bindingInfo; + _bindingInfo = bindingInfo; // Check if there is exactly one parameter set valid. In that case, // ValidParameterSetFlags is exactly a power of two. Otherwise, @@ -459,9 +459,9 @@ namespace System.Management.Automation.Language (bindingInfo.ValidParameterSetsFlags & (bindingInfo.ValidParameterSetsFlags - 1)) == 0; - if(parameterSetSpecified && - (! remainingParameterSetIncludesDefault) && - (! onlyOneRemainingParameterSet)) + if (parameterSetSpecified && + (!remainingParameterSetIncludesDefault) && + (!onlyOneRemainingParameterSet)) { ParameterBindingException bindingException = new ParameterBindingException( @@ -473,7 +473,7 @@ namespace System.Management.Automation.Language null, ParameterBinderStrings.AmbiguousParameterSet, "AmbiguousParameterSet"); - bindingExceptions.Add(commandAst.CommandElements[0].Extent.Text, + _bindingExceptions.Add(commandAst.CommandElements[0].Extent.Text, new StaticBindingError(commandAst.CommandElements[0], bindingException)); } @@ -501,7 +501,7 @@ namespace System.Management.Automation.Language null, ParameterBinderStrings.NamedParameterNotFound, "NamedParameterNotFound"); - bindingExceptions.Add(parameterNotFound.ParameterName, new StaticBindingError(parameterNotFound, bindingException)); + _bindingExceptions.Add(parameterNotFound.ParameterName, new StaticBindingError(parameterNotFound, bindingException)); } } @@ -511,7 +511,7 @@ namespace System.Management.Automation.Language foreach (CommandParameterAst ambiguousParameter in bindingInfo.AmbiguousParameters) { ParameterBindingException bindingException = bindingInfo.BindingExceptions[ambiguousParameter]; - bindingExceptions.Add(ambiguousParameter.ParameterName, new StaticBindingError(ambiguousParameter, bindingException)); + _bindingExceptions.Add(ambiguousParameter.ParameterName, new StaticBindingError(ambiguousParameter, bindingException)); } } @@ -532,7 +532,7 @@ namespace System.Management.Automation.Language null, ParameterBinderStrings.PositionalParameterNotFound, "PositionalParameterNotFound"); - bindingExceptions.Add(argument.Argument.Extent.Text, new StaticBindingError(argument.Argument, bindingException)); + _bindingExceptions.Add(argument.Argument.Extent.Text, new StaticBindingError(argument.Argument, bindingException)); } } @@ -558,7 +558,7 @@ namespace System.Management.Automation.Language if (argumentAstArrayPair != null) { List arguments = new List(); - foreach(ExpressionAst expression in argumentAstArrayPair.Argument) + foreach (ExpressionAst expression in argumentAstArrayPair.Argument) { ArrayLiteralAst expressionArray = expression as ArrayLiteralAst; if (expressionArray != null) @@ -595,7 +595,7 @@ namespace System.Management.Automation.Language // We got a parameter and a value if ((value != null) || (constantValue != null)) { - boundParameters.Add(item.Key, new ParameterBindingResult(parameter, value, constantValue)); + _boundParameters.Add(item.Key, new ParameterBindingResult(parameter, value, constantValue)); } else { @@ -623,7 +623,7 @@ namespace System.Management.Automation.Language ParameterBinderStrings.MissingArgument, "MissingArgument"); - bindingExceptions.Add(commandAst.CommandElements[0].Extent.Text, + _bindingExceptions.Add(commandAst.CommandElements[0].Extent.Text, new StaticBindingError(commandAst.CommandElements[0], bindingException)); } } @@ -649,12 +649,12 @@ namespace System.Management.Automation.Language ParameterBinderStrings.ParameterAlreadyBound, "ParameterAlreadyBound"); // if the duplicated Parameter Name appears more than twice, we will ignore as we already have similar bindingException. - if (!bindingExceptions.ContainsKey(duplicateParameter.ParameterName)) + if (!_bindingExceptions.ContainsKey(duplicateParameter.ParameterName)) { - bindingExceptions.Add(duplicateParameter.ParameterName, new StaticBindingError(duplicateParameter, bindingException)); + _bindingExceptions.Add(duplicateParameter.ParameterName, new StaticBindingError(duplicateParameter, bindingException)); } } - PseudoBindingInfo bindingInfo = null; + private PseudoBindingInfo _bindingInfo = null; private void CreateBindingResultForSyntacticBind(CommandAst commandAst) { @@ -732,13 +732,13 @@ namespace System.Management.Automation.Language private void AddBoundParameter(CommandParameterAst parameter, string parameterName, ParameterBindingResult bindingResult) { - if (boundParameters.ContainsKey(parameterName)) + if (_boundParameters.ContainsKey(parameterName)) { AddDuplicateParameterBindingException(parameter); } else { - boundParameters.Add(parameterName, bindingResult); + _boundParameters.Add(parameterName, bindingResult); } } @@ -759,18 +759,18 @@ namespace System.Management.Automation.Language /// public Dictionary BoundParameters { - get { return boundParameters; } + get { return _boundParameters; } } - private Dictionary boundParameters; + private Dictionary _boundParameters; /// /// /// public Dictionary BindingExceptions { - get { return bindingExceptions; } + get { return _bindingExceptions; } } - private Dictionary bindingExceptions; + private Dictionary _bindingExceptions; } /// @@ -799,26 +799,26 @@ namespace System.Management.Automation.Language /// public Object ConstantValue { - get { return constantValue; } + get { return _constantValue; } internal set { if (value != null) { - this.constantValue = value; + _constantValue = value; } } } - private object constantValue; + private object _constantValue; /// /// /// public CommandElementAst Value { - get { return this.value; } + get { return _value; } internal set { - this.value = value; + _value = value; ConstantExpressionAst constantValueAst = value as ConstantExpressionAst; if (constantValueAst != null) @@ -827,7 +827,7 @@ namespace System.Management.Automation.Language } } } - private CommandElementAst value; + private CommandElementAst _value; } /// @@ -914,20 +914,20 @@ namespace System.Management.Automation.Language Collection duplicateParameters, Collection unboundArguments) { - this._commandInfo = commandInfo; - this._infoType = PseudoBindingInfoType.PseudoBindingSucceed; - this._validParameterSetsFlags = validParameterSetsFlags; - this._defaultParameterSetFlag = defaultParameterSetFalg; - this._boundParameters = boundParameters; - this._unboundParameters = unboundParameters; - this._boundArguments = boundArguments; - this._boundPositionalParameter = boundPositionalParameter; - this._allParsedArguments = allParsedArguments; - this._parametersNotFound = parametersNotFound; - this._ambiguousParameters = ambiguousParameters; - this._bindingExceptions = bindingExceptions; - this._duplicateParameters = duplicateParameters; - this._unboundArguments = unboundArguments; + _commandInfo = commandInfo; + _infoType = PseudoBindingInfoType.PseudoBindingSucceed; + _validParameterSetsFlags = validParameterSetsFlags; + _defaultParameterSetFlag = defaultParameterSetFalg; + _boundParameters = boundParameters; + _unboundParameters = unboundParameters; + _boundArguments = boundArguments; + _boundPositionalParameter = boundPositionalParameter; + _allParsedArguments = allParsedArguments; + _parametersNotFound = parametersNotFound; + _ambiguousParameters = ambiguousParameters; + _bindingExceptions = bindingExceptions; + _duplicateParameters = duplicateParameters; + _unboundArguments = unboundArguments; } /// @@ -943,11 +943,11 @@ namespace System.Management.Automation.Language Collection allParsedArguments, List unboundParameters) { - this._commandInfo = commandInfo; - this._infoType = PseudoBindingInfoType.PseudoBindingFail; - this._defaultParameterSetFlag = defaultParameterSetFlag; - this._allParsedArguments = allParsedArguments; - this._unboundParameters = unboundParameters; + _commandInfo = commandInfo; + _infoType = PseudoBindingInfoType.PseudoBindingFail; + _defaultParameterSetFlag = defaultParameterSetFlag; + _allParsedArguments = allParsedArguments; + _unboundParameters = unboundParameters; } internal string CommandName @@ -1061,7 +1061,7 @@ namespace System.Management.Automation.Language /// ParameterCompletion } - + /// /// Get the parameter binding metadata /// @@ -1262,7 +1262,7 @@ namespace System.Management.Automation.Language private Dictionary _bindingExceptions; // A corresponding list is also kept in WorkflowJobConverter.cs. - List ignoredWorkflowParameters = null; + private List _ignoredWorkflowParameters = null; /// /// Initialize collection/dictionary members when it's necessary @@ -1270,8 +1270,8 @@ namespace System.Management.Automation.Language private void InitializeMembers() { List supportedCommonParameters = new List() { "Verbose", "Debug", "ErrorAction", "WarningAction", "InformationAction" }; - ignoredWorkflowParameters = new List(Cmdlet.CommonParameters.Concat(Cmdlet.OptionalCommonParameters)); - ignoredWorkflowParameters.RemoveAll(item => supportedCommonParameters.Contains(item, StringComparer.OrdinalIgnoreCase)); + _ignoredWorkflowParameters = new List(Cmdlet.CommonParameters.Concat(Cmdlet.OptionalCommonParameters)); + _ignoredWorkflowParameters.RemoveAll(item => supportedCommonParameters.Contains(item, StringComparer.OrdinalIgnoreCase)); // Initializing binding realted members _function = false; @@ -1343,7 +1343,7 @@ namespace System.Management.Automation.Language var scriptProcessor = processor as ScriptCommandProcessorBase; bool implementsDynamicParameters = commandProcessor != null && commandProcessor.CommandInfo.ImplementsDynamicParameters; - + var argumentsToGetDynamicParameters = implementsDynamicParameters ? new List(_commandElements.Count) : null; @@ -1481,7 +1481,7 @@ namespace System.Management.Automation.Language { Type parameterType = GetActualActivityParameterType(pair.Value); var runtimeDefinedParameter = new RuntimeDefinedParameter(pair.Key, parameterType, attrCollection); - var compiledCommandParameter = new CompiledCommandParameter(runtimeDefinedParameter, false) {IsInAllSets = true}; + var compiledCommandParameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; var mergedCompiledCommandParameter = new MergedCompiledCommandParameter(compiledCommandParameter, ParameterBinderAssociation.DeclaredFormalParameters); parametersToAdd.Add(mergedCompiledCommandParameter); } @@ -1503,7 +1503,7 @@ namespace System.Management.Automation.Language // Remove common parameters that are supported by all commands, but not // by workflows bool fixedReadOnly = false; - foreach (var ignored in ignoredWorkflowParameters) + foreach (var ignored in _ignoredWorkflowParameters) { if (_bindableParameters.BindableParameters.ContainsKey(ignored)) { @@ -1797,7 +1797,7 @@ namespace System.Management.Automation.Language // Otherwise, skip the next argument index++; _parametersNotFound.Add(argument.Parameter); - continue; + continue; } } } diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index c69a72358..3a3a91b65 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Tracing; @@ -30,24 +31,24 @@ namespace System.Management.Automation /// The execution context for this command internal CommandLookupEventArgs(string commandName, CommandOrigin commandOrigin, ExecutionContext context) { - this.commandName = commandName; - this.commandOrigin = commandOrigin; - this.context = context; + _commandName = commandName; + _commandOrigin = commandOrigin; + _context = context; } - ExecutionContext context; + private ExecutionContext _context; /// /// The name of the command we're looking for /// - public string CommandName { get { return this.commandName; } } - string commandName; + public string CommandName { get { return _commandName; } } + private string _commandName; /// /// The origin of the command internal or runspace (external) /// - public CommandOrigin CommandOrigin { get { return this.commandOrigin; } } - CommandOrigin commandOrigin; + public CommandOrigin CommandOrigin { get { return _commandOrigin; } } + private CommandOrigin _commandOrigin; /// /// If true on return from event handler, the search is stopped. @@ -65,15 +66,15 @@ namespace System.Management.Automation /// public ScriptBlock CommandScriptBlock { - get { return scriptBlock; } + get { return _scriptBlock; } set { - scriptBlock = value; - if (scriptBlock != null) + _scriptBlock = value; + if (_scriptBlock != null) { - string dynamicName = "LookupHandlerReplacementFor<<" + commandName + ">>"; - Command = new FunctionInfo(dynamicName, scriptBlock, context); + string dynamicName = "LookupHandlerReplacementFor<<" + _commandName + ">>"; + Command = new FunctionInfo(dynamicName, _scriptBlock, _context); StopSearch = true; } else @@ -83,7 +84,7 @@ namespace System.Management.Automation } } } - ScriptBlock scriptBlock; + private ScriptBlock _scriptBlock; } /// @@ -142,7 +143,7 @@ namespace System.Management.Automation // Cache the ScriptInfo for the scripts defined in the RunspaceConfiguration - cachedScriptInfo = + _cachedScriptInfo = new Dictionary(StringComparer.OrdinalIgnoreCase); LoadScriptInfo(); @@ -283,7 +284,7 @@ namespace System.Management.Automation { try { - cachedScriptInfo.Add(entry.Name, new ScriptInfo(entry.Name, ScriptBlock.Create(_context, entry.Definition), _context)); + _cachedScriptInfo.Add(entry.Name, new ScriptInfo(entry.Name, ScriptBlock.Create(_context, entry.Definition), _context)); } catch (ArgumentException) { @@ -450,7 +451,7 @@ namespace System.Management.Automation return result; } - CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState) + private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState) { VerifyScriptRequirements(scriptInfo, Context); @@ -719,8 +720,8 @@ namespace System.Management.Automation HashSet processedAliases = new HashSet(StringComparer.OrdinalIgnoreCase); - while(commandInfo.CommandType == CommandTypes.Alias && - (! processedAliases.Contains(commandInfo.Name)) && + while (commandInfo.CommandType == CommandTypes.Alias && + (!processedAliases.Contains(commandInfo.Name)) && (commandOrigin == CommandOrigin.Internal || commandInfo.Visibility == SessionStateEntryVisibility.Public)) { processedAliases.Add(commandInfo.Name); @@ -731,7 +732,7 @@ namespace System.Management.Automation // If we didn't have the alias target already resolved, see if it can be loaded. if (commandInfo == null) { - commandInfo = LookupCommandInfo(aliasCommandInfo.Definition, commandOrigin, this._context); + commandInfo = LookupCommandInfo(aliasCommandInfo.Definition, commandOrigin, _context); } if (commandInfo == null) @@ -1037,7 +1038,7 @@ namespace System.Management.Automation } // If we resolved a command, give the PostCommandLookup a chance to change it - if(result != null) + if (result != null) { System.EventHandler postAction = context.EngineIntrinsics.InvokeCommand.PostCommandLookupAction; if (postAction != null) @@ -1097,12 +1098,12 @@ namespace System.Management.Automation if (moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) { CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); - if ((commandOrigin == CommandOrigin.Internal) || + if ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) { foreach (var module in System.Management.Automation.ExecutionContext.ModulesWithJobSourceAdapters) { - List existingModule = context.Modules.GetModules(new string[] {module}, false); + List existingModule = context.Modules.GetModules(new string[] { module }, false); if (existingModule == null || existingModule.Count == 0) { Exception unUsedException = null; @@ -1147,7 +1148,7 @@ namespace System.Management.Automation //Call-out to user code, catch-all OK CommandProcessorBase.CheckForSevereException(e); } - + return matchingModules; } @@ -1456,10 +1457,10 @@ namespace System.Management.Automation HashSet currentActionSet = null; switch (currentAction) { - case "ActivePreLookup": currentActionSet = activePreLookup; break; - case "ActiveModuleSearch": currentActionSet = activeModuleSearch; break; - case "ActiveCommandNotFound": currentActionSet = activeCommandNotFound; break; - case "ActivePostCommand": currentActionSet = activePostCommand; break; + case "ActivePreLookup": currentActionSet = _activePreLookup; break; + case "ActiveModuleSearch": currentActionSet = _activeModuleSearch; break; + case "ActiveCommandNotFound": currentActionSet = _activeCommandNotFound; break; + case "ActivePostCommand": currentActionSet = _activePostCommand; break; } if (currentActionSet.Contains(command)) @@ -1473,20 +1474,20 @@ namespace System.Management.Automation HashSet currentActionSet = null; switch (currentAction) { - case "ActivePreLookup": currentActionSet = activePreLookup; break; - case "ActiveModuleSearch": currentActionSet = activeModuleSearch; break; - case "ActiveCommandNotFound": currentActionSet = activeCommandNotFound; break; - case "ActivePostCommand": currentActionSet = activePostCommand; break; + case "ActivePreLookup": currentActionSet = _activePreLookup; break; + case "ActiveModuleSearch": currentActionSet = _activeModuleSearch; break; + case "ActiveCommandNotFound": currentActionSet = _activeCommandNotFound; break; + case "ActivePostCommand": currentActionSet = _activePostCommand; break; } if (currentActionSet.Contains(command)) currentActionSet.Remove(command); } - HashSet activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); - HashSet activeModuleSearch = new HashSet(StringComparer.OrdinalIgnoreCase); - HashSet activeCommandNotFound = new HashSet(StringComparer.OrdinalIgnoreCase); - HashSet activePostCommand = new HashSet(StringComparer.OrdinalIgnoreCase); + private HashSet _activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); + private HashSet _activeModuleSearch = new HashSet(StringComparer.OrdinalIgnoreCase); + private HashSet _activeCommandNotFound = new HashSet(StringComparer.OrdinalIgnoreCase); + private HashSet _activePostCommand = new HashSet(StringComparer.OrdinalIgnoreCase); /// @@ -1537,61 +1538,61 @@ namespace System.Management.Automation bool isPathCacheValid = path != null && - String.Equals(pathCacheKey, path, StringComparison.OrdinalIgnoreCase) && - cachedPath != null; + String.Equals(_pathCacheKey, path, StringComparison.OrdinalIgnoreCase) && + _cachedPath != null; if (!isPathCacheValid) { // Reset the cached lookup paths - cachedLookupPaths = null; + _cachedLookupPaths = null; // Tokenize the path and cache it - pathCacheKey = path; + _pathCacheKey = path; - if (pathCacheKey != null) + if (_pathCacheKey != null) { - string[] tokenizedPath = pathCacheKey.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); - cachedPath = new Collection(); + string[] tokenizedPath = _pathCacheKey.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + _cachedPath = new Collection(); foreach (string directory in tokenizedPath) { string tempDir = directory.TrimStart(); - cachedPath.Add(tempDir); + _cachedPath.Add(tempDir); result.Add(tempDir); } } } else { - result.AddRange(cachedPath); + result.AddRange(_cachedPath); } // Cache the new lookup paths - if (cachedLookupPaths == null) + if (_cachedLookupPaths == null) { - cachedLookupPaths = result; + _cachedLookupPaths = result; } - return cachedLookupPaths; + return _cachedLookupPaths; } // GetLookupDirectoryPaths /// /// The cached list of lookup paths. It can be invalidated by /// the PATH changing. /// - private LookupPathCollection cachedLookupPaths; + private LookupPathCollection _cachedLookupPaths; /// /// The key that determines if the cached PATH can be used. /// - private string pathCacheKey; + private string _pathCacheKey; /// /// The cache of the tokenized PATH directories /// - private Collection cachedPath; + private Collection _cachedPath; #endregion internal members @@ -1607,13 +1608,13 @@ namespace System.Management.Automation { var pathExt = Environment.GetEnvironmentVariable("PATHEXT"); - if (!string.Equals(pathExt, pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || - cachedPathExtCollection == null) + if (!string.Equals(pathExt, s_pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || + s_cachedPathExtCollection == null) { InitPathExtCache(pathExt); } - return cachedPathExtCollectionWithPs1; + return s_cachedPathExtCollectionWithPs1; } // get } // PathExtensions @@ -1627,28 +1628,28 @@ namespace System.Management.Automation { var pathExt = Environment.GetEnvironmentVariable("PATHEXT"); - if (!string.Equals(pathExt, pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || - cachedPathExtCollection == null) + if (!string.Equals(pathExt, s_pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || + s_cachedPathExtCollection == null) { InitPathExtCache(pathExt); } - return cachedPathExtCollection; + return s_cachedPathExtCollection; } // get } // PathExtensions private static void InitPathExtCache(string pathExt) { - lock (lockObject) + lock (s_lockObject) { - cachedPathExtCollection = pathExt != null + s_cachedPathExtCollection = pathExt != null ? pathExt.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries) : Utils.EmptyArray(); - cachedPathExtCollectionWithPs1 = new string[cachedPathExtCollection.Length + 1]; - cachedPathExtCollectionWithPs1[0] = StringLiterals.PowerShellScriptFileExtension; - Array.Copy(cachedPathExtCollection, 0, cachedPathExtCollectionWithPs1, 1, cachedPathExtCollection.Length); + s_cachedPathExtCollectionWithPs1 = new string[s_cachedPathExtCollection.Length + 1]; + s_cachedPathExtCollectionWithPs1[0] = StringLiterals.PowerShellScriptFileExtension; + Array.Copy(s_cachedPathExtCollection, 0, s_cachedPathExtCollectionWithPs1, 1, s_cachedPathExtCollection.Length); - pathExtCacheKey = pathExt; + s_pathExtCacheKey = pathExt; } } @@ -1656,10 +1657,10 @@ namespace System.Management.Automation #region private members - private static object lockObject = new object(); - private static string pathExtCacheKey; - private static string[] cachedPathExtCollection; - private static string[] cachedPathExtCollectionWithPs1; + private static object s_lockObject = new object(); + private static string s_pathExtCacheKey; + private static string[] s_cachedPathExtCollection; + private static string[] s_cachedPathExtCollectionWithPs1; /// @@ -1860,7 +1861,7 @@ namespace System.Management.Automation "The caller should verify the name"); ScriptInfo result; - cachedScriptInfo.TryGetValue(name, out result); + _cachedScriptInfo.TryGetValue(name, out result); return result; } // GetScriptInfo @@ -1870,14 +1871,14 @@ namespace System.Management.Automation /// internal Dictionary ScriptCache { - get { return cachedScriptInfo; } + get { return _cachedScriptInfo; } } /// /// The cache for the ScriptInfo. /// /// - private Dictionary cachedScriptInfo; + private Dictionary _cachedScriptInfo; internal ExecutionContext Context { @@ -1956,7 +1957,7 @@ namespace System.Management.Automation { if (result != null) { - return LanguagePrimitives.ConvertTo(result); + return LanguagePrimitives.ConvertTo(result); } // check the environment variable @@ -2146,7 +2147,7 @@ namespace System.Management.Automation internal class CommandDiscoveryEventSource : EventSource { internal static CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); - + public void CommandLookupStart(string CommandName) { WriteEvent(1, CommandName); } public void CommandLookupStop(string CommandName) { WriteEvent(2, CommandName); } public void ModuleAutoLoadingStart(string CommandName) { WriteEvent(3, CommandName); } diff --git a/src/System.Management.Automation/engine/CommandFactory.cs b/src/System.Management.Automation/engine/CommandFactory.cs index 43499be9a..b3f4f0684 100644 --- a/src/System.Management.Automation/engine/CommandFactory.cs +++ b/src/System.Management.Automation/engine/CommandFactory.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text.RegularExpressions; using System.Management.Automation; @@ -14,7 +15,7 @@ namespace System.Management.Automation { #region private_members - private ExecutionContext context; + private ExecutionContext _context; #endregion private_members @@ -25,8 +26,8 @@ namespace System.Management.Automation /// internal ExecutionContext Context { - get {return context;} - set {context = value;} + get { return _context; } + set { _context = value; } } #endregion public_properties @@ -108,13 +109,13 @@ namespace System.Management.Automation private CommandProcessorBase _CreateCommand(string commandName, CommandOrigin commandOrigin, bool? useLocalScope) { - if (context == null) + if (_context == null) { throw PSTraceSource.NewInvalidOperationException(DiscoveryExceptions.ExecutionContextNotSet); } // Look for a cmdlet... - CommandDiscovery discovery = this.context.CommandDiscovery; + CommandDiscovery discovery = _context.CommandDiscovery; if (discovery == null) { diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 9cb71a51c..f76a7a682 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -26,7 +27,7 @@ namespace System.Management.Automation /// /// Aliases are only persisted within the execution of a single engine. /// - Alias = 0x0001, + Alias = 0x0001, /// /// Script functions that are defined by a script block @@ -35,7 +36,7 @@ namespace System.Management.Automation /// /// Functions are only persisted within the execution of a single engine. /// - Function = 0x0002, + Function = 0x0002, /// /// Script filters that are defined by a script block. @@ -44,17 +45,17 @@ namespace System.Management.Automation /// /// Filters are only persisted within the execution of a single engine. /// - Filter = 0x0004, + Filter = 0x0004, /// /// A cmdlet. /// - Cmdlet = 0x0008, + Cmdlet = 0x0008, /// /// An MSH script (*.ps1 file) /// - ExternalScript = 0x0010, + ExternalScript = 0x0010, /// /// Any existing application (can be console or GUI). @@ -82,7 +83,7 @@ namespace System.Management.Automation /// Configuration = 0x0100, - /// + /// /// All possible command types. /// /// @@ -127,8 +128,8 @@ namespace System.Management.Automation throw new ArgumentNullException("name"); } - this._name = name; - this._type = type; + _name = name; + _type = type; } // CommandInfo ctor /// @@ -167,22 +168,22 @@ namespace System.Management.Automation //this._moduleName = other._moduleName; //this.parameterSets = other.parameterSets; this.Module = other.Module; - this._visibility = other._visibility; - this._arguments = other._arguments; + _visibility = other._visibility; + _arguments = other._arguments; this.Context = other.Context; - this._name = other._name; - this._type = other._type; - this._copiedCommand = other; + _name = other._name; + _type = other._type; + _copiedCommand = other; this.DefiningLanguageMode = other.DefiningLanguageMode; } - /// + /// /// This is a copy constructor, used primarily for get-command. /// internal CommandInfo(string name, CommandInfo other) : this(other) { - this._name = name; + _name = name; } #endregion ctor @@ -214,7 +215,7 @@ namespace System.Management.Automation /// /// Gets the source of the command (shown by default in Get-Command) /// - public virtual string Source { get { return this.ModuleName; } } + public virtual string Source { get { return this.ModuleName; } } /// /// Gets the source version (shown by default in Get-Command) @@ -275,7 +276,7 @@ namespace System.Management.Automation internal virtual HelpCategory HelpCategory { - get { return HelpCategory.None; } + get { return HelpCategory.None; } } internal CommandInfo CopiedCommand @@ -328,7 +329,7 @@ namespace System.Management.Automation throw new ArgumentNullException("newName"); } - this._name = newName; + _name = newName; } /// @@ -472,28 +473,28 @@ namespace System.Management.Automation // One of the things we do here is change the current scope in execution context, // that can mess up the runspace our CommandInfo object came from. - var runspace = (RunspaceBase) _context.CurrentRunspace; + var runspace = (RunspaceBase)_context.CurrentRunspace; if (!runspace.RunActionIfNoRunningPipelinesWithThreadCheck( () => GetMergedCommandParameterMetadata(out result))) { _context.Events.SubscribeEvent( - source: null, - eventName: PSEngineEvent.GetCommandInfoParameterMetadata, - sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, - data: null, - handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler), - supportEvent: true, - forwardEvent: false, + source: null, + eventName: PSEngineEvent.GetCommandInfoParameterMetadata, + sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, + data: null, + handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler), + supportEvent: true, + forwardEvent: false, shouldQueueAndProcessInExecutionThread: true, - maxTriggerCount: 1); + maxTriggerCount: 1); var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs(); _context.Events.GenerateEvent( - sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, - sender: null, - args: new [] { eventArgs }, - extraData: null, + sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, + sender: null, + args: new[] { eventArgs }, + extraData: null, processInCurrentThread: true, waitForCompletionInCurrentThread: true); @@ -551,7 +552,7 @@ namespace System.Management.Automation if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this) { // Accessing the parameters within the invocation of the same cmdlet/advanced function. - processor = (CommandProcessor) Context.CurrentCommandProcessor; + processor = (CommandProcessor)Context.CurrentCommandProcessor; } else { @@ -625,7 +626,7 @@ namespace System.Management.Automation return _externalCommandMetadata; } - set { _externalCommandMetadata = value; } + set { _externalCommandMetadata = value; } } private CommandMetadata _externalCommandMetadata; @@ -804,7 +805,6 @@ namespace System.Management.Automation isDefaultParameterSet, currentFlagPosition, parameterMetadata)); - } } } @@ -895,7 +895,7 @@ namespace System.Management.Automation { get { return _name; } } - readonly string _name; + private readonly string _name; /// /// Return the type with metadata, or null if the type is not loaded. @@ -936,13 +936,13 @@ namespace System.Management.Automation return _type; } } - Type _type; + private Type _type; /// /// When a type is defined by PowerShell, the ast for that type. /// public TypeDefinitionAst TypeDefinitionAst { get; private set; } - bool _typeWasCalculated; + private bool _typeWasCalculated; /// /// Returns a String that represents the current PSTypeName. diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 27749dad1..67e34e6c6 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -172,48 +173,48 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("other"); } - this._commandName = other._commandName; - this._confirmImpact = other._confirmImpact; - this._defaultParameterSetFlag = other._defaultParameterSetFlag; - this._defaultParameterSetName = other._defaultParameterSetName; - this._implementsDynamicParameters = other._implementsDynamicParameters; - this._supportsShouldProcess = other._supportsShouldProcess; - this._supportsPaging = other._supportsPaging; - this._supportsTransactions = other._supportsTransactions; + _commandName = other._commandName; + _confirmImpact = other._confirmImpact; + _defaultParameterSetFlag = other._defaultParameterSetFlag; + _defaultParameterSetName = other._defaultParameterSetName; + _implementsDynamicParameters = other._implementsDynamicParameters; + _supportsShouldProcess = other._supportsShouldProcess; + _supportsPaging = other._supportsPaging; + _supportsTransactions = other._supportsTransactions; this.CommandType = other.CommandType; - this._wrappedAnyCmdlet = other._wrappedAnyCmdlet; - this._wrappedCommand = other._wrappedCommand; - this._wrappedCommandType = other._wrappedCommandType; + _wrappedAnyCmdlet = other._wrappedAnyCmdlet; + _wrappedCommand = other._wrappedCommand; + _wrappedCommandType = other._wrappedCommandType; + + _parameters = new Dictionary(other.Parameters.Count, StringComparer.OrdinalIgnoreCase); - this._parameters = new Dictionary(other.Parameters.Count, StringComparer.OrdinalIgnoreCase); - // deep copy if (other.Parameters != null) { foreach (KeyValuePair entry in other.Parameters) { - this._parameters.Add(entry.Key, new ParameterMetadata(entry.Value)); + _parameters.Add(entry.Key, new ParameterMetadata(entry.Value)); } } // deep copy of the collection, collection items (Attributes) copied by reference if (other._otherAttributes == null) { - this._otherAttributes = null; + _otherAttributes = null; } else { - this._otherAttributes = new Collection(new List(other._otherAttributes.Count)); + _otherAttributes = new Collection(new List(other._otherAttributes.Count)); foreach (Attribute attribute in other._otherAttributes) { - this._otherAttributes.Add(attribute); + _otherAttributes.Add(attribute); } } // not copying those fields/members as they are untouched (and left set to null) // by public constructors, so we can't rely on those fields/members to be set // when CommandMetadata comes from a user - this.staticCommandParameterMetadata = null; + _staticCommandParameterMetadata = null; } /// @@ -231,36 +232,36 @@ namespace System.Management.Automation bool positionalBinding, Dictionary parameters) { - this._commandName = this._wrappedCommand = name; - this._wrappedCommandType = commandType; - this._wrappedAnyCmdlet = isProxyForCmdlet; - this._defaultParameterSetName = defaultParameterSetName; - this._supportsShouldProcess = supportsShouldProcess; - this._supportsPaging = supportsPaging; - this._confirmImpact = confirmImpact; - this._supportsTransactions = supportsTransactions; - this._positionalBinding = positionalBinding; + _commandName = _wrappedCommand = name; + _wrappedCommandType = commandType; + _wrappedAnyCmdlet = isProxyForCmdlet; + _defaultParameterSetName = defaultParameterSetName; + _supportsShouldProcess = supportsShouldProcess; + _supportsPaging = supportsPaging; + _confirmImpact = confirmImpact; + _supportsTransactions = supportsTransactions; + _positionalBinding = positionalBinding; this.Parameters = parameters; } - void Init(string name, string fullyQualifiedName, Type commandType, bool shouldGenerateCommonParameters) + private void Init(string name, string fullyQualifiedName, Type commandType, bool shouldGenerateCommonParameters) { - this._commandName = name; + _commandName = name; this.CommandType = commandType; if (commandType != null) { ConstructCmdletMetadataUsingReflection(); - this._shouldGenerateCommonParameters = shouldGenerateCommonParameters; + _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } // Use fully qualified name if available. _wrappedCommand = !string.IsNullOrEmpty(fullyQualifiedName) ? fullyQualifiedName : _commandName; _wrappedCommandType = CommandTypes.Cmdlet; - _wrappedAnyCmdlet = true; + _wrappedAnyCmdlet = true; } - void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommonParameters) + private void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommonParameters) { if (scriptBlock.UsesCmdletBinding) { @@ -285,7 +286,7 @@ namespace System.Management.Automation _obsolete = scriptBlock.ObsoleteAttribute; _scriptBlock = scriptBlock; _wrappedCommand = _commandName = name; - this._shouldGenerateCommonParameters = shouldGenerateCommonParameters; + _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } #endregion @@ -338,21 +339,21 @@ namespace System.Management.Automation } CommandMetadata result = null; - + if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; - CommandMetadataCache.TryGetValue(cmdletTypeName, out result); + s_commandMetadataCache.TryGetValue(cmdletTypeName, out result); } - if(result == null) + if (result == null) { result = new CommandMetadata(commandName, cmdletType, context); if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; - CommandMetadataCache.TryAdd(cmdletTypeName, result); + s_commandMetadataCache.TryAdd(cmdletTypeName, result); } } @@ -398,16 +399,16 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("commandName"); } - this._commandName = commandName; + _commandName = commandName; this.CommandType = cmdletType; if (cmdletType != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false); ConstructCmdletMetadataUsingReflection(); - this.staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, true); - this._defaultParameterSetFlag = this.staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); - this.staticCommandParameterMetadata.MakeReadOnly(); + _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, true); + _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); + _staticCommandParameterMetadata.MakeReadOnly(); } } @@ -453,20 +454,20 @@ namespace System.Management.Automation _defaultParameterSetName = null; } - this._obsolete = scriptblock.ObsoleteAttribute; - this._commandName = commandName; + _obsolete = scriptblock.ObsoleteAttribute; + _commandName = commandName; this.CommandType = typeof(PSScriptCmdlet); if (scriptblock.HasDynamicParameters) { - this._implementsDynamicParameters = true; + _implementsDynamicParameters = true; } InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(scriptblock.RuntimeDefinedParameters, false, scriptblock.UsesCmdletBinding); - this.staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding); - this._defaultParameterSetFlag = this.staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); - this.staticCommandParameterMetadata.MakeReadOnly(); + _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding); + _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); + _staticCommandParameterMetadata.MakeReadOnly(); } #endregion ctor @@ -573,7 +574,6 @@ namespace System.Management.Automation { get { return _helpUri; } set { _helpUri = value; } - } private string _helpUri = String.Empty; @@ -595,7 +595,6 @@ namespace System.Management.Automation return _remotingCapability; } set { _remotingCapability = value; } - } private RemotingCapability _remotingCapability = RemotingCapability.PowerShell; @@ -623,7 +622,7 @@ namespace System.Management.Automation if (_parameters == null) { // Return parameters for a script block - if (this._scriptBlock != null) + if (_scriptBlock != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(_scriptBlock.RuntimeDefinedParameters, false, _scriptBlock.UsesCmdletBinding); @@ -679,10 +678,10 @@ namespace System.Management.Automation { get { - return staticCommandParameterMetadata; + return _staticCommandParameterMetadata; } } - private readonly MergedCommandParameterMetadata staticCommandParameterMetadata; + private readonly MergedCommandParameterMetadata _staticCommandParameterMetadata; /// /// True if the cmdlet implements dynamic parameters, or false otherwise @@ -727,7 +726,7 @@ namespace System.Management.Automation { get { - return this._wrappedCommandType; + return _wrappedCommandType; } } @@ -921,7 +920,7 @@ namespace System.Management.Automation .ForwardHelpTargetName {0} .ForwardHelpCategory {1} ", - this._wrappedCommand, this._wrappedCommandType); + _wrappedCommand, _wrappedCommandType); } string dynamicParamblock = String.Empty; @@ -1254,12 +1253,12 @@ end ParameterMetadata showCommandInfo = new ParameterMetadata("ShowCommandInfo", typeof(SwitchParameter)); return GetRestrictedCmdlet( - "Get-Command", + "Get-Command", null, // defaultParameterSet "http://go.microsoft.com/fwlink/?LinkID=113309", // helpUri - nameParameter, - moduleParameter, - argumentListParameter, + nameParameter, + moduleParameter, + argumentListParameter, commandTypeParameter, listImportedParameter, showCommandInfo); @@ -1586,7 +1585,7 @@ end CommandMetadata removeJob = GetRestrictedCmdlet("Remove-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=113377", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, forceParameter); - + restrictedJobCommands.Add(removeJob); // Suspend-Job cmdlet @@ -1612,7 +1611,7 @@ end /// The command metadata cache. This is separate from the parameterMetadata cache /// because it is specific to cmdlets. /// - private static System.Collections.Concurrent.ConcurrentDictionary CommandMetadataCache = + private static System.Collections.Concurrent.ConcurrentDictionary s_commandMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); #endregion diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index b1f6bccae..90d311ca2 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Diagnostics; using System.Management.Automation.Language; @@ -13,13 +14,13 @@ namespace System.Management.Automation [DebuggerDisplay("{ParameterName}")] internal sealed class CommandParameterInternal { - class Parameter + private class Parameter { internal IScriptExtent extent; internal string parameterName; internal string parameterText; } - class Argument + private class Argument { internal IScriptExtent extent; internal object value; @@ -31,7 +32,7 @@ namespace System.Management.Automation private Argument _argument; private bool _spaceAfterParameter; - internal bool SpaceAfterParameter { get { return _spaceAfterParameter; } } + internal bool SpaceAfterParameter { get { return _spaceAfterParameter; } } internal bool ParameterNameSpecified { get { return _parameter != null; } } internal bool ArgumentSpecified { get { return _argument != null; } } internal bool ParameterAndArgumentSpecified { get { return ParameterNameSpecified && ArgumentSpecified; } } @@ -78,7 +79,7 @@ namespace System.Management.Automation /// internal IScriptExtent ArgumentExtent { - get { return _argument != null ? _argument.extent : PositionUtilities.EmptyExtent; } + get { return _argument != null ? _argument.extent : PositionUtilities.EmptyExtent; } } /// @@ -151,10 +152,10 @@ namespace System.Management.Automation { Diagnostics.Assert(extent != null, "Caller to verify extent argument"); return new CommandParameterInternal - { - _parameter = + { + _parameter = new Parameter { extent = extent, parameterName = parameterName, parameterText = parameterText } - }; + }; } /// @@ -172,15 +173,15 @@ namespace System.Management.Automation { Diagnostics.Assert(extent != null, "Caller to verify extent argument"); return new CommandParameterInternal - { - _argument = new Argument - { - extent = extent, - value = value, - splatted = splatted, - arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand - } - }; + { + _argument = new Argument + { + extent = extent, + value = value, + splatted = splatted, + arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand + } + }; } /// @@ -216,9 +217,9 @@ namespace System.Management.Automation _parameter = new Parameter { extent = parameterExtent, parameterName = parameterName, parameterText = parameterText }, _argument = new Argument { extent = argumentExtent, value = value, arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand }, _spaceAfterParameter = spaceAfterParameter - }; + }; } - + #endregion ctor internal bool IsDashQuestion() diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index d05ecc283..005c6fd01 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -7,7 +7,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { @@ -17,8 +17,8 @@ namespace System.Management.Automation /// internal class CommandPathSearch : IEnumerable, IEnumerator { - [TraceSource("CommandSearch","CommandSearch")] - private static PSTraceSource tracer = PSTraceSource.GetTracer ("CommandSearch", "CommandSearch"); + [TraceSource("CommandSearch", "CommandSearch")] + private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch"); /// /// Constructs a command searching enumerator that resolves the location @@ -58,36 +58,36 @@ namespace System.Management.Automation // The old code would enumerate the file system many more times, once per possible extension. if (Platform.IsWindows) { - commandPatterns = new [] { commandName + ".*" }; + commandPatterns = new[] { commandName + ".*" }; } else { // Porting note: on non-Windows platforms, we want to always allow just 'commandName' // as an acceptable command name. However, we also want to allow commands to be // called with the .ps1 extension, so that 'script.ps1' can be called by 'script'. - commandPatterns = new [] { commandName + ".ps1", commandName }; + commandPatterns = new[] { commandName + ".ps1", commandName }; } - this.postProcessEnumeratedFiles = CheckAgainstAcceptableCommandNames; - this.acceptableCommandNames = acceptableCommandNames; + _postProcessEnumeratedFiles = CheckAgainstAcceptableCommandNames; + _acceptableCommandNames = acceptableCommandNames; } else { - commandPatterns = new [] { commandName }; - postProcessEnumeratedFiles = JustCheckExtensions; + commandPatterns = new[] { commandName }; + _postProcessEnumeratedFiles = JustCheckExtensions; } Init(commandPatterns, lookupPaths, context); - this.orderedPathExt = CommandDiscovery.PathExtensionsWithPs1Prepended; + _orderedPathExt = CommandDiscovery.PathExtensionsWithPs1Prepended; } private void Init(IEnumerable commandPatterns, IEnumerable searchPath, ExecutionContext context) { // Note, discovery must be set before resolving the current directory - this._context = context; - this.patterns = commandPatterns; + _context = context; + _patterns = commandPatterns; - this.lookupPaths = new LookupPathCollection(searchPath); + _lookupPaths = new LookupPathCollection(searchPath); ResolveCurrentDirectoryInLookupPaths(); this.Reset(); @@ -119,14 +119,14 @@ namespace System.Management.Automation // Loop through the relative paths and resolve them - foreach (int index in this.lookupPaths.IndexOfRelativePath()) + foreach (int index in _lookupPaths.IndexOfRelativePath()) { string resolvedDirectory = null; string resolvedPath = null; CommandDiscovery.discoveryTracer.WriteLine( "Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...", - lookupPaths[index]); + _lookupPaths[index]); if (isCurrentDriveValid) { @@ -135,21 +135,21 @@ namespace System.Management.Automation ProviderInfo provider; resolvedPath = pathResolver.GetProviderPath( - lookupPaths[index], + _lookupPaths[index], out provider); } catch (ProviderInvocationException providerInvocationException) { CommandDiscovery.discoveryTracer.WriteLine( "The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'", - lookupPaths[index], + _lookupPaths[index], providerInvocationException.Message); } catch (InvalidOperationException) { CommandDiscovery.discoveryTracer.WriteLine( "The relative path '{0}', could not resolve a home directory for the provider", - lookupPaths[index]); + _lookupPaths[index]); } @@ -167,7 +167,7 @@ namespace System.Management.Automation { CommandDiscovery.discoveryTracer.WriteLine( "The relative path was not a file system path. {0}", - lookupPaths[index]); + _lookupPaths[index]); } } else @@ -184,7 +184,7 @@ namespace System.Management.Automation if (resolvedDirectory != null) { - int existingIndex = lookupPaths.IndexOf(resolvedDirectory); + int existingIndex = _lookupPaths.IndexOf(resolvedDirectory); if (existingIndex != -1) { @@ -194,7 +194,7 @@ namespace System.Management.Automation // so remove the explicit path. indexesToRemove.Add(removalListCount++, existingIndex); - lookupPaths[index] = resolvedDirectory; + _lookupPaths[index] = resolvedDirectory; } else { @@ -208,7 +208,7 @@ namespace System.Management.Automation { // Change the relative path to the resolved path. - lookupPaths[index] = resolvedDirectory; + _lookupPaths[index] = resolvedDirectory; } } else @@ -227,7 +227,7 @@ namespace System.Management.Automation for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex) { int indexToRemove = indexesToRemove[removeIndex - 1]; - lookupPaths.RemoveAt(indexToRemove); + _lookupPaths.RemoveAt(indexToRemove); } } // ResolveCurrentDirectoryInLookupPaths @@ -269,23 +269,23 @@ namespace System.Management.Automation { bool result = false; - if (justReset) + if (_justReset) { - justReset = false; + _justReset = false; - if (!patternEnumerator.MoveNext()) + if (!_patternEnumerator.MoveNext()) { - tracer.TraceError("No patterns were specified"); + s_tracer.TraceError("No patterns were specified"); return false; } - if (!lookupPathsEnumerator.MoveNext()) + if (!_lookupPathsEnumerator.MoveNext()) { - tracer.TraceError("No lookup paths were specified"); + s_tracer.TraceError("No lookup paths were specified"); return false; } - GetNewDirectoryResults(patternEnumerator.Current, lookupPathsEnumerator.Current); + GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } do // while lookupPathsEnumerator is valid @@ -294,26 +294,26 @@ namespace System.Management.Automation { // Try moving to the next path in the current results - if (!currentDirectoryResultsEnumerator.MoveNext()) + if (!_currentDirectoryResultsEnumerator.MoveNext()) { - tracer.WriteLine("Current directory results are invalid"); + s_tracer.WriteLine("Current directory results are invalid"); // Since a path was not found in the current result, // advance the pattern and try again - if (!patternEnumerator.MoveNext()) + if (!_patternEnumerator.MoveNext()) { - tracer.WriteLine("Current patterns exhausted in current directory: {0}", lookupPathsEnumerator.Current); + s_tracer.WriteLine("Current patterns exhausted in current directory: {0}", _lookupPathsEnumerator.Current); break; } // Get the results of the next pattern - GetNewDirectoryResults(patternEnumerator.Current, lookupPathsEnumerator.Current); + GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } else { - tracer.WriteLine("Next path found: {0}", currentDirectoryResultsEnumerator.Current); + s_tracer.WriteLine("Next path found: {0}", _currentDirectoryResultsEnumerator.Current); result = true; break; } @@ -329,24 +329,23 @@ namespace System.Management.Automation // Since the path was not found in the current results, and all patterns were exhausted, // advance the path and continue - if (!lookupPathsEnumerator.MoveNext()) + if (!_lookupPathsEnumerator.MoveNext()) { - tracer.WriteLine("All lookup paths exhausted, no more matches can be found"); + s_tracer.WriteLine("All lookup paths exhausted, no more matches can be found"); break; } // Reset the pattern enumerator and get new results using the new lookup path - patternEnumerator = patterns.GetEnumerator(); + _patternEnumerator = _patterns.GetEnumerator(); - if (!patternEnumerator.MoveNext()) + if (!_patternEnumerator.MoveNext()) { - tracer.WriteLine("All patterns exhausted, no more matches can be found"); + s_tracer.WriteLine("All patterns exhausted, no more matches can be found"); break; } - GetNewDirectoryResults(patternEnumerator.Current, lookupPathsEnumerator.Current); - + GetNewDirectoryResults(_patternEnumerator.Current, _lookupPathsEnumerator.Current); } while (true); return result; @@ -357,11 +356,11 @@ namespace System.Management.Automation /// public void Reset() { - lookupPathsEnumerator = lookupPaths.GetEnumerator(); - patternEnumerator = patterns.GetEnumerator(); - currentDirectoryResults = Utils.EmptyArray(); - currentDirectoryResultsEnumerator = currentDirectoryResults.GetEnumerator(); - justReset = true; + _lookupPathsEnumerator = _lookupPaths.GetEnumerator(); + _patternEnumerator = _patterns.GetEnumerator(); + _currentDirectoryResults = Utils.EmptyArray(); + _currentDirectoryResultsEnumerator = _currentDirectoryResults.GetEnumerator(); + _justReset = true; } // Reset /// @@ -376,14 +375,14 @@ namespace System.Management.Automation /// string IEnumerator.Current { - get - { - if (currentDirectoryResults == null) + get + { + if (_currentDirectoryResults == null) { throw PSTraceSource.NewInvalidOperationException(); } - return currentDirectoryResultsEnumerator.Current; + return _currentDirectoryResultsEnumerator.Current; } } // Current @@ -391,7 +390,7 @@ namespace System.Management.Automation { get { - return ((IEnumerator) this).Current; + return ((IEnumerator)this).Current; } } @@ -439,8 +438,8 @@ namespace System.Management.Automation { var matchingFiles = Directory.EnumerateFiles(directory, pattern); - result = this.postProcessEnumeratedFiles != null - ? this.postProcessEnumeratedFiles(matchingFiles.ToArray()) + result = _postProcessEnumeratedFiles != null + ? _postProcessEnumeratedFiles(matchingFiles.ToArray()) : matchingFiles; } } @@ -465,8 +464,8 @@ namespace System.Management.Automation // accessible } - currentDirectoryResults = result ?? Utils.EmptyArray(); - currentDirectoryResultsEnumerator = currentDirectoryResults.GetEnumerator(); + _currentDirectoryResults = result ?? Utils.EmptyArray(); + _currentDirectoryResultsEnumerator = _currentDirectoryResults.GetEnumerator(); } // GetMatchingPathsInDirectory private IEnumerable CheckAgainstAcceptableCommandNames(string[] fileNames) @@ -481,7 +480,7 @@ namespace System.Management.Automation Collection result = null; if (baseNames.Length > 0) { - foreach (var name in acceptableCommandNames) + foreach (var name in _acceptableCommandNames) { for (int i = 0; i < baseNames.Length; i++) { @@ -508,7 +507,7 @@ namespace System.Management.Automation // Porting note: allow files with executable bit on non-Windows platforms Collection result = null; - foreach (var allowedExt in orderedPathExt) + foreach (var allowedExt in _orderedPathExt) { foreach (var fileName in fileNames) { @@ -529,33 +528,33 @@ namespace System.Management.Automation /// The directory paths in which to look for commands. /// This is derived from the PATH environment variable /// - private LookupPathCollection lookupPaths; + private LookupPathCollection _lookupPaths; /// /// The enumerator for the lookup paths /// - private IEnumerator lookupPathsEnumerator; + private IEnumerator _lookupPathsEnumerator; /// /// The list of results matching the pattern in the current /// path lookup directory. Resets to null. /// - private IEnumerable currentDirectoryResults; + private IEnumerable _currentDirectoryResults; /// /// The enumerator for the list of results /// - private IEnumerator currentDirectoryResultsEnumerator; + private IEnumerator _currentDirectoryResultsEnumerator; /// /// The command name to search for /// - private IEnumerable patterns; + private IEnumerable _patterns; /// /// The enumerator for the patterns /// - private IEnumerator patternEnumerator; + private IEnumerator _patternEnumerator; /// /// A reference to the execution context for this runspace @@ -566,18 +565,17 @@ namespace System.Management.Automation /// When reset is called, this gets set to true. Once MoveNext /// is called, this gets set to false. /// - private bool justReset; + private bool _justReset; /// /// If not null, called with the enumerated files for futher processing /// - private Func> postProcessEnumeratedFiles; + private Func> _postProcessEnumeratedFiles; - private string[] orderedPathExt; - private Collection acceptableCommandNames; + private string[] _orderedPathExt; + private Collection _acceptableCommandNames; #endregion private members - } // CommandSearch } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 7874f7a8d..896459acc 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Concurrent; @@ -20,29 +21,29 @@ namespace System.Management.Automation /// Class definition of CommandProcessor - This class provides interface to create /// and execute commands written in CLS compliant languages. /// - internal class CommandProcessor: CommandProcessorBase + internal class CommandProcessor : CommandProcessorBase { #region ctor static CommandProcessor() { - ConstructInstanceCache = new ConcurrentDictionary>(); + s_constructInstanceCache = new ConcurrentDictionary>(); // Avoid jitting constructors some of the more commonly used cmdlets in SMA.dll - not meant to be // exhaustive b/c many cmdlets aren't called at all, so we'd never even need an entry in the cache. - ConstructInstanceCache.GetOrAdd(typeof(ForEachObjectCommand), () => new ForEachObjectCommand()); - ConstructInstanceCache.GetOrAdd(typeof(WhereObjectCommand), () => new WhereObjectCommand()); - ConstructInstanceCache.GetOrAdd(typeof(ImportModuleCommand), () => new ImportModuleCommand()); - ConstructInstanceCache.GetOrAdd(typeof(GetModuleCommand), () => new GetModuleCommand()); - ConstructInstanceCache.GetOrAdd(typeof(GetHelpCommand), () => new GetHelpCommand()); - ConstructInstanceCache.GetOrAdd(typeof(InvokeCommandCommand), () => new InvokeCommandCommand()); - ConstructInstanceCache.GetOrAdd(typeof(GetCommandCommand), () => new GetCommandCommand()); - ConstructInstanceCache.GetOrAdd(typeof(OutDefaultCommand), () => new OutDefaultCommand()); - ConstructInstanceCache.GetOrAdd(typeof(OutHostCommand), () => new OutHostCommand()); - ConstructInstanceCache.GetOrAdd(typeof(OutNullCommand), () => new OutNullCommand()); - ConstructInstanceCache.GetOrAdd(typeof(SetStrictModeCommand), () => new SetStrictModeCommand()); - ConstructInstanceCache.GetOrAdd(typeof(FormatDefaultCommand), () => new FormatDefaultCommand()); - ConstructInstanceCache.GetOrAdd(typeof(OutLineOutputCommand), () => new OutLineOutputCommand()); + s_constructInstanceCache.GetOrAdd(typeof(ForEachObjectCommand), () => new ForEachObjectCommand()); + s_constructInstanceCache.GetOrAdd(typeof(WhereObjectCommand), () => new WhereObjectCommand()); + s_constructInstanceCache.GetOrAdd(typeof(ImportModuleCommand), () => new ImportModuleCommand()); + s_constructInstanceCache.GetOrAdd(typeof(GetModuleCommand), () => new GetModuleCommand()); + s_constructInstanceCache.GetOrAdd(typeof(GetHelpCommand), () => new GetHelpCommand()); + s_constructInstanceCache.GetOrAdd(typeof(InvokeCommandCommand), () => new InvokeCommandCommand()); + s_constructInstanceCache.GetOrAdd(typeof(GetCommandCommand), () => new GetCommandCommand()); + s_constructInstanceCache.GetOrAdd(typeof(OutDefaultCommand), () => new OutDefaultCommand()); + s_constructInstanceCache.GetOrAdd(typeof(OutHostCommand), () => new OutHostCommand()); + s_constructInstanceCache.GetOrAdd(typeof(OutNullCommand), () => new OutNullCommand()); + s_constructInstanceCache.GetOrAdd(typeof(SetStrictModeCommand), () => new SetStrictModeCommand()); + s_constructInstanceCache.GetOrAdd(typeof(FormatDefaultCommand), () => new FormatDefaultCommand()); + s_constructInstanceCache.GetOrAdd(typeof(OutLineOutputCommand), () => new OutLineOutputCommand()); } /// @@ -382,7 +383,7 @@ namespace System.Management.Automation #endregion public_methods #region helper_methods - + /// /// Tells whether it is the first call to Read /// @@ -442,7 +443,7 @@ namespace System.Management.Automation // ProcessRecord() until the incoming pipe is empty. We need to // stop this loop if a downstream cmdlet broke guidelines and // "swallowed" a PipelineStoppedException. - Command.ThrowIfStopping (); + Command.ThrowIfStopping(); // Prepare the default value parameter list if this is the first call to Read if (_firstCallToRead) @@ -464,7 +465,7 @@ namespace System.Management.Automation // the final binding stage in before executing the cmdlet. bool mandatoryParametersSpecified = false; - + while (!mandatoryParametersSpecified) { // Retrieve the object from the input pipeline @@ -514,7 +515,7 @@ namespace System.Management.Automation Collection missingMandatoryParameters; - using (ParameterBinderBase.bindingTracer.TraceScope ( + using (ParameterBinderBase.bindingTracer.TraceScope( "MANDATORY PARAMETER CHECK on cmdlet [{0}]", this.CommandInfo.Name)) { @@ -535,7 +536,7 @@ namespace System.Management.Automation WriteInputObjectError( inputObject, ParameterBinderStrings.InputObjectMissingMandatory, - "InputObjectMissingMandatory", + "InputObjectMissingMandatory", missingParameters); } } @@ -632,15 +633,15 @@ namespace System.Management.Automation return this.CmdletParameterBinderController.BindPipelineParameters(inputToOperateOn); } - private static readonly ConcurrentDictionary> ConstructInstanceCache; - static Cmdlet ConstructInstance(Type type) + private static readonly ConcurrentDictionary> s_constructInstanceCache; + private static Cmdlet ConstructInstance(Type type) { // Call the default constructor if type derives from Cmdlet. // Return null (and the caller will generate an appropriate error) if // type does not derive from Cmdlet. We do it this way so the expensive type check // is performed just once per type. - return ConstructInstanceCache.GetOrAdd(type, + return s_constructInstanceCache.GetOrAdd(type, t => Expression.Lambda>( typeof(Cmdlet).IsAssignableFrom(t) ? (Expression)Expression.New(t) @@ -739,7 +740,7 @@ namespace System.Management.Automation private void Init(IScriptCommandInfo scriptCommandInfo) { - InternalCommand scriptCmdlet = + InternalCommand scriptCmdlet = new PSScriptCmdlet(scriptCommandInfo.ScriptBlock, _useLocalScope, FromScriptFile, _context); this.Command = scriptCmdlet; @@ -762,7 +763,7 @@ namespace System.Management.Automation this.Command.CommandInfo = this.CommandInfo; // set the ObsoleteAttribute of the current command - this._obsoleteAttribute = this.CommandInfo.CommandMetadata.Obsolete; + _obsoleteAttribute = this.CommandInfo.CommandMetadata.Obsolete; // set the execution context this.Command.Context = this._context; @@ -838,7 +839,6 @@ namespace System.Management.Automation #endregion helper_methods } - } diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index a92cff451..3f2fc766f 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -29,7 +29,7 @@ namespace System.Management.Automation internal CommandProcessorBase() { } - + /// /// Initializes the base command processor class with the command metadata /// @@ -39,21 +39,21 @@ namespace System.Management.Automation /// /// internal CommandProcessorBase( - CommandInfo commandInfo) + CommandInfo commandInfo) { if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException("commandInfo"); } - this.commandInfo = commandInfo; + _commandInfo = commandInfo; } - + #endregion ctor #region properties - private InternalCommand command; + private InternalCommand _command; // marker of whether BeginProcessing() has already run, // also used by CommandProcessor @@ -75,10 +75,10 @@ namespace System.Management.Automation /// internal CommandInfo CommandInfo { - get { return commandInfo; } - set { commandInfo = value; } + get { return _commandInfo; } + set { _commandInfo = value; } } - private CommandInfo commandInfo; + private CommandInfo _commandInfo; /// /// This indicates whether this command processor is created from @@ -109,8 +109,8 @@ namespace System.Management.Automation /// internal bool RedirectShellErrorOutputPipe { - get { return this._redirectShellErrorOutputPipe; } - set { this._redirectShellErrorOutputPipe = value; } + get { return _redirectShellErrorOutputPipe; } + set { _redirectShellErrorOutputPipe = value; } } private bool _redirectShellErrorOutputPipe = false; @@ -119,23 +119,23 @@ namespace System.Management.Automation /// internal InternalCommand Command { - get{ return command;} - set + get { return _command; } + set { // The command runtime needs to be set up... if (value != null) { value.commandRuntime = this.commandRuntime; - if (command != null) - value.CommandInfo = command.CommandInfo; + if (_command != null) + value.CommandInfo = _command.CommandInfo; // Set the execution context for the command it's currently // null and our context has already been set up. if (value.Context == null && _context != null) value.Context = _context; } - command = value; - } + _command = value; + } } /// @@ -207,7 +207,8 @@ namespace System.Management.Automation /// The execution context used by the system. /// protected ExecutionContext _context; - internal ExecutionContext Context { + internal ExecutionContext Context + { get { return _context; } set { _context = value; } } @@ -252,7 +253,7 @@ namespace System.Management.Automation /// help category /// command processor for "get-help [helpTarget]" static internal CommandProcessorBase CreateGetHelpCommandProcessor( - ExecutionContext context, + ExecutionContext context, string helpTarget, HelpCategory helpCategory) { @@ -387,7 +388,7 @@ namespace System.Management.Automation Diagnostics.Assert(parameter != null, "Caller to verify parameter argument"); arguments.Add(parameter); } // AddParameter - + /// /// Prepares the command for execution. /// This should be called once before ProcessRecord(). @@ -401,10 +402,10 @@ namespace System.Management.Automation private void HandleObsoleteCommand(ObsoleteAttribute obsoleteAttr) { string commandName = - String.IsNullOrEmpty(this.commandInfo.Name) + String.IsNullOrEmpty(_commandInfo.Name) ? "script block" : String.Format(System.Globalization.CultureInfo.InvariantCulture, - CommandBaseStrings.ObsoleteCommand, this.commandInfo.Name); + CommandBaseStrings.ObsoleteCommand, _commandInfo.Name); string warningMsg = String.Format( System.Globalization.CultureInfo.InvariantCulture, @@ -667,15 +668,15 @@ namespace System.Management.Automation /// public override string ToString() { - if (null != commandInfo) - return commandInfo.ToString(); + if (null != _commandInfo) + return _commandInfo.ToString(); return ""; // does not require localization } /// /// True if Read() has not be called, false otherwise. /// - private bool firstCallToRead = true; + private bool _firstCallToRead = true; /// /// Entry point used by the engine to reads the input pipeline object @@ -693,9 +694,9 @@ namespace System.Management.Automation internal virtual bool Read() { // Prepare the default value parameter list if this is the first call to Read - if (firstCallToRead) + if (_firstCallToRead) { - firstCallToRead = false; + _firstCallToRead = false; } // Retrieve the object from the input pipeline @@ -707,7 +708,7 @@ namespace System.Management.Automation } // If we are reading input for the first command in the pipeline increment PipelineIterationInfo[0], which is the number of items read from the input - if (this.Command.MyInvocation.PipelinePosition == 1) + if (this.Command.MyInvocation.PipelinePosition == 1) { this.Command.MyInvocation.PipelineIterationInfo[0]++; } @@ -819,7 +820,7 @@ namespace System.Management.Automation /// stopped by CTRL-C etc, in which case we choose not to /// re-wrap the exception as with CmdletInvocationException. /// - internal PipelineStoppedException ManageInvocationException (Exception e) + internal PipelineStoppedException ManageInvocationException(Exception e) { try { @@ -905,8 +906,8 @@ namespace System.Management.Automation // Rollback the transaction in the case of errors. if ( - _context.TransactionManager.HasTransaction - && + _context.TransactionManager.HasTransaction + && _context.TransactionManager.RollbackPreference != RollbackSeverity.Never ) { @@ -915,7 +916,6 @@ namespace System.Management.Automation } return (PipelineStoppedException)this.commandRuntime.ManageException(e); - } // Upstream cmdlets see only that execution stopped @@ -978,7 +978,7 @@ namespace System.Management.Automation // 2004/03/05-JonN BrucePay has suggested that the IDispose // implementations in PipelineProcessor and CommandProcessor can be // removed. - private bool disposed; + private bool _disposed; /// /// IDisposable implementation @@ -987,15 +987,15 @@ namespace System.Management.Automation /// without waiting for garbage collection /// /// We use the standard IDispose pattern - public void Dispose () + public void Dispose() { - Dispose (true); - GC.SuppressFinalize (this); + Dispose(true); + GC.SuppressFinalize(this); } - private void Dispose (bool disposing) + private void Dispose(bool disposing) { - if (disposed) + if (_disposed) return; if (disposing) @@ -1006,19 +1006,19 @@ namespace System.Management.Automation IDisposable id = Command as IDisposable; if (null != id) { - id.Dispose (); + id.Dispose(); } } - disposed = true; + _disposed = true; } /// /// Finalizer for class CommandProcessorBase /// - ~CommandProcessorBase () + ~CommandProcessorBase() { - Dispose (false); + Dispose(false); } #endregion IDispose diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 5f46c22a1..01ae5f872 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -54,15 +54,15 @@ namespace System.Management.Automation Diagnostics.Assert(context != null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid"); - this.commandName = commandName; - this._context = context; - this.commandResolutionOptions = options; - this.commandTypes = commandTypes; + _commandName = commandName; + _context = context; + _commandResolutionOptions = options; + _commandTypes = commandTypes; // Initialize the enumerators this.Reset(); } - + /// /// Gets an instance of a command enumerator /// @@ -93,7 +93,7 @@ namespace System.Management.Automation { _currentMatch = null; - if (currentState == SearchState.SearchingAliases) + if (_currentState == SearchState.SearchingAliases) { _currentMatch = SearchForAliases(); @@ -107,10 +107,10 @@ namespace System.Management.Automation _currentMatch = null; // Advance the state - currentState = SearchState.SearchingFunctions; + _currentState = SearchState.SearchingFunctions; } - if (currentState == SearchState.SearchingFunctions) + if (_currentState == SearchState.SearchingFunctions) { _currentMatch = SearchForFunctions(); // Return the alias info only if it is visible. If not, then skip to the next @@ -121,10 +121,10 @@ namespace System.Management.Automation } // Advance the state - currentState = SearchState.SearchingCmdlets; + _currentState = SearchState.SearchingCmdlets; } - if (currentState == SearchState.SearchingCmdlets) + if (_currentState == SearchState.SearchingCmdlets) { _currentMatch = SearchForCmdlets(); if (_currentMatch != null) @@ -133,10 +133,10 @@ namespace System.Management.Automation } // Advance the state - currentState = SearchState.SearchingBuiltinScripts; + _currentState = SearchState.SearchingBuiltinScripts; } - if (currentState == SearchState.SearchingBuiltinScripts) + if (_currentState == SearchState.SearchingBuiltinScripts) { _currentMatch = SearchForBuiltinScripts(); if (_currentMatch != null) @@ -145,12 +145,12 @@ namespace System.Management.Automation } // Advance the state - currentState = SearchState.StartSearchingForExternalCommands; + _currentState = SearchState.StartSearchingForExternalCommands; } - if (currentState == SearchState.StartSearchingForExternalCommands) + if (_currentState == SearchState.StartSearchingForExternalCommands) { - if ((commandTypes & (CommandTypes.Application | CommandTypes.ExternalScript)) == 0) + if ((_commandTypes & (CommandTypes.Application | CommandTypes.ExternalScript)) == 0) { // Since we are not requiring any path lookup in this search, just return false now // because all the remaining searches do path lookup. @@ -159,7 +159,7 @@ namespace System.Management.Automation // For security reasons, if the command is coming from outside the runspace and it looks like a path, // we want to pre-check that path before doing any probing of the network or drives - if (_commandOrigin == CommandOrigin.Runspace && commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) >= 0) + if (_commandOrigin == CommandOrigin.Runspace && _commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) >= 0) { bool allowed = false; @@ -180,7 +180,7 @@ namespace System.Management.Automation // Ok see it it's in the applications list foreach (string path in _context.EngineSessionState.Applications) { - if (checkPath(path, commandName)) + if (checkPath(path, _commandName)) { allowed = true; break; @@ -192,7 +192,7 @@ namespace System.Management.Automation { foreach (string path in _context.EngineSessionState.Scripts) { - if (checkPath(path, commandName)) + if (checkPath(path, _commandName)) { allowed = true; break; @@ -209,7 +209,7 @@ namespace System.Management.Automation // Advance the state - currentState = SearchState.PowerShellPathResolution; + _currentState = SearchState.PowerShellPathResolution; _currentMatch = ProcessBuiltinScriptState(); @@ -219,14 +219,14 @@ namespace System.Management.Automation // we want to skip the qualified file system path search // in the case where we found a PowerShell qualified path. - currentState = SearchState.QualifiedFileSystemPath; + _currentState = SearchState.QualifiedFileSystemPath; return true; } } // SearchState.Reset - if (currentState == SearchState.PowerShellPathResolution) + if (_currentState == SearchState.PowerShellPathResolution) { - currentState = SearchState.QualifiedFileSystemPath; + _currentState = SearchState.QualifiedFileSystemPath; _currentMatch = ProcessPathResolutionState(); @@ -238,8 +238,8 @@ namespace System.Management.Automation // Search using CommandPathSearch - if (currentState == SearchState.QualifiedFileSystemPath || - currentState == SearchState.PathSearch) + if (_currentState == SearchState.QualifiedFileSystemPath || + _currentState == SearchState.PathSearch) { _currentMatch = ProcessQualifiedFileSystemState(); @@ -249,9 +249,9 @@ namespace System.Management.Automation } } // SearchState.QualifiedFileSystemPath || SearchState.PathSearch - if (currentState == SearchState.PathSearch) + if (_currentState == SearchState.PathSearch) { - currentState = SearchState.PowerShellRelativePath; + _currentState = SearchState.PowerShellRelativePath; _currentMatch = ProcessPathSearchState(); @@ -269,7 +269,7 @@ namespace System.Management.Automation CommandInfo currentMatch = null; if (_context.EngineSessionState != null && - (commandTypes & CommandTypes.Alias) != 0) + (_commandTypes & CommandTypes.Alias) != 0) { currentMatch = GetNextAlias(); } @@ -281,7 +281,7 @@ namespace System.Management.Automation CommandInfo currentMatch = null; if (_context.EngineSessionState != null && - (commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Workflow | CommandTypes.Configuration)) != 0) + (_commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Workflow | CommandTypes.Configuration)) != 0) { currentMatch = GetNextFunction(); } @@ -293,7 +293,7 @@ namespace System.Management.Automation { CommandInfo currentMatch = null; - if ((commandTypes & CommandTypes.Cmdlet) != 0) + if ((_commandTypes & CommandTypes.Cmdlet) != 0) { currentMatch = GetNextCmdlet(); } @@ -305,7 +305,7 @@ namespace System.Management.Automation { CommandInfo currentMatch = null; - if ((commandTypes & CommandTypes.Script) != 0) + if ((_commandTypes & CommandTypes.Script) != 0) { currentMatch = GetNextBuiltinScript(); } @@ -321,7 +321,7 @@ namespace System.Management.Automation if (_context.EngineSessionState != null && _context.EngineSessionState.ProviderCount > 0 && - IsQualifiedPSPath(commandName)) + IsQualifiedPSPath(_commandName)) { currentMatch = GetNextFromPath(); } @@ -337,13 +337,12 @@ namespace System.Management.Automation { // Check to see if the path is a file system path that // is rooted. If so that is the next match - if (Path.IsPathRooted(commandName) && - File.Exists(commandName)) + if (Path.IsPathRooted(_commandName) && + File.Exists(_commandName)) { try { - currentMatch = GetInfoFromPath(commandName); - + currentMatch = GetInfoFromPath(_commandName); } catch (FileLoadException) { @@ -380,25 +379,24 @@ namespace System.Management.Automation } catch (ArgumentException) { - currentState = SearchState.NoMoreMatches; + _currentState = SearchState.NoMoreMatches; throw; } catch (PathTooLongException) { - currentState = SearchState.NoMoreMatches; + _currentState = SearchState.NoMoreMatches; throw; } CommandInfo currentMatch = null; - currentState = SearchState.PathSearch; - if (canDoPathLookup) + _currentState = SearchState.PathSearch; + if (_canDoPathLookup) { - try { - while (currentMatch == null && this.pathSearcher.MoveNext()) + while (currentMatch == null && _pathSearcher.MoveNext()) { - currentMatch = GetInfoFromPath(((IEnumerator)pathSearcher).Current); + currentMatch = GetInfoFromPath(((IEnumerator)_pathSearcher).Current); } } catch (InvalidOperationException) @@ -437,8 +435,8 @@ namespace System.Management.Automation { get { - if ((currentState == SearchState.SearchingAliases && _currentMatch == null) || - currentState == SearchState.NoMoreMatches || + if ((_currentState == SearchState.SearchingAliases && _currentMatch == null) || + _currentState == SearchState.NoMoreMatches || _currentMatch == null) { throw PSTraceSource.NewInvalidOperationException(); @@ -463,10 +461,10 @@ namespace System.Management.Automation /// public void Dispose() { - if (pathSearcher != null) + if (_pathSearcher != null) { - pathSearcher.Dispose(); - pathSearcher = null; + _pathSearcher.Dispose(); + _pathSearcher = null; } Reset(); @@ -491,7 +489,7 @@ namespace System.Management.Automation { CommandDiscovery.discoveryTracer.WriteLine( "The name appears to be a qualified path: {0}", - commandName); + _commandName); CommandDiscovery.discoveryTracer.WriteLine( "Trying to resolve the path as an PSPath"); @@ -505,44 +503,44 @@ namespace System.Management.Automation Provider.CmdletProvider providerInstance; ProviderInfo provider; resolvedPaths = - _context.LocationGlobber.GetGlobbedProviderPathsFromMonadPath(commandName, false, out provider, out providerInstance); + _context.LocationGlobber.GetGlobbedProviderPathsFromMonadPath(_commandName, false, out provider, out providerInstance); } catch (ItemNotFoundException) { CommandDiscovery.discoveryTracer.TraceError( "The path could not be found: {0}", - commandName); + _commandName); } catch (DriveNotFoundException) { CommandDiscovery.discoveryTracer.TraceError( "A drive could not be found for the path: {0}", - commandName); + _commandName); } catch (ProviderNotFoundException) { CommandDiscovery.discoveryTracer.TraceError( "A provider could not be found for the path: {0}", - commandName); + _commandName); } catch (InvalidOperationException) { CommandDiscovery.discoveryTracer.TraceError( "The path specified a home directory, but the provider home directory was not set. {0}", - commandName); + _commandName); } catch (ProviderInvocationException providerException) { CommandDiscovery.discoveryTracer.TraceError( "The provider associated with the path '{0}' encountered an error: {1}", - commandName, + _commandName, providerException.Message); } catch (PSNotSupportedException) { CommandDiscovery.discoveryTracer.TraceError( "The provider associated with the path '{0}' does not implement ContainerCmdletProvider", - commandName); + _commandName); } if (resolvedPaths.Count > 1) @@ -639,7 +637,7 @@ namespace System.Management.Automation if (String.Equals(extension, StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase)) { - if ((this.commandTypes & CommandTypes.ExternalScript) != 0) + if ((_commandTypes & CommandTypes.ExternalScript) != 0) { string scriptName = Path.GetFileName(path); @@ -657,7 +655,7 @@ namespace System.Management.Automation } - if ((this.commandTypes & CommandTypes.Application) != 0) + if ((_commandTypes & CommandTypes.Application) != 0) { // Anything else is treated like an application @@ -671,11 +669,10 @@ namespace System.Management.Automation result = new ApplicationInfo(appName, path, _context); break; } - } while (false); // Verify that this script is not untrusted, if we aren't constrained. - if(ShouldSkipCommandResolutionForConstrainedLanguage(result, this._context)) + if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context)) { result = null; } @@ -695,9 +692,9 @@ namespace System.Management.Automation { CommandInfo result = null; - if ((commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0) + if ((_commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0) { - if (matchingAlias == null) + if (_matchingAlias == null) { // Generate the enumerator of matching alias names @@ -705,7 +702,7 @@ namespace System.Management.Automation WildcardPattern aliasMatcher = WildcardPattern.Get( - commandName, + _commandName, WildcardOptions.IgnoreCase); foreach (KeyValuePair aliasEntry in _context.EngineSessionState.GetAliasTable()) @@ -717,38 +714,38 @@ namespace System.Management.Automation } // Process alias from modules - AliasInfo c = GetAliasFromModules(commandName); + AliasInfo c = GetAliasFromModules(_commandName); if (c != null) { matchingAliases.Add(c); } - matchingAlias = matchingAliases.GetEnumerator(); + _matchingAlias = matchingAliases.GetEnumerator(); } - if (!matchingAlias.MoveNext()) + if (!_matchingAlias.MoveNext()) { // Advance the state - currentState = SearchState.SearchingFunctions; + _currentState = SearchState.SearchingFunctions; - matchingAlias = null; + _matchingAlias = null; } else { - result = matchingAlias.Current; + result = _matchingAlias.Current; } } else { // Advance the state - currentState = SearchState.SearchingFunctions; + _currentState = SearchState.SearchingFunctions; - result = _context.EngineSessionState.GetAlias(commandName) ?? GetAliasFromModules(commandName); + result = _context.EngineSessionState.GetAlias(_commandName) ?? GetAliasFromModules(_commandName); } // Verify that this alias was not created by an untrusted constrained language, // if we aren't constrained. - if(ShouldSkipCommandResolutionForConstrainedLanguage(result, this._context)) + if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context)) { result = null; } @@ -775,17 +772,17 @@ namespace System.Management.Automation { CommandInfo result = null; - if ((commandResolutionOptions & SearchResolutionOptions.ResolveFunctionPatterns) != 0) + if ((_commandResolutionOptions & SearchResolutionOptions.ResolveFunctionPatterns) != 0) { - if (matchingFunctionEnumerator == null) + if (_matchingFunctionEnumerator == null) { Collection matchingFunction = new Collection(); // Generate the enumerator of matching function names WildcardPattern functionMatcher = - WildcardPattern.Get( - commandName, - WildcardOptions.IgnoreCase); + WildcardPattern.Get( + _commandName, + WildcardOptions.IgnoreCase); foreach (DictionaryEntry functionEntry in _context.EngineSessionState.GetFunctionTable()) { @@ -796,38 +793,38 @@ namespace System.Management.Automation } // Process functions from modules - CommandInfo c = GetFunctionFromModules(commandName); + CommandInfo c = GetFunctionFromModules(_commandName); if (c != null) { matchingFunction.Add(c); } - matchingFunctionEnumerator = matchingFunction.GetEnumerator(); + _matchingFunctionEnumerator = matchingFunction.GetEnumerator(); } - if (!matchingFunctionEnumerator.MoveNext()) + if (!_matchingFunctionEnumerator.MoveNext()) { // Advance the state - currentState = SearchState.SearchingCmdlets; + _currentState = SearchState.SearchingCmdlets; - matchingFunctionEnumerator = null; + _matchingFunctionEnumerator = null; } else { - result = matchingFunctionEnumerator.Current; + result = _matchingFunctionEnumerator.Current; } } else { // Advance the state - currentState = SearchState.SearchingCmdlets; + _currentState = SearchState.SearchingCmdlets; - result = GetFunction(commandName); + result = GetFunction(_commandName); } // Verify that this function was not created by an untrusted constrained language, // if we aren't constrained. - if(ShouldSkipCommandResolutionForConstrainedLanguage(result, this._context)) + if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context)) { result = null; } @@ -840,13 +837,13 @@ namespace System.Management.Automation // - Debug prompts calling internal functions that are likely to have code injection private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo result, ExecutionContext executionContext) { - if(result == null) + if (result == null) { return false; } // Don't return untrusted commands to trusted functions - if((result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage) && + if ((result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage) && (executionContext.LanguageMode == PSLanguageMode.FullLanguage)) { return true; @@ -857,12 +854,12 @@ namespace System.Management.Automation // susceptible to injection attacks. However, we do allow execution // of functions defined in the global scope (i.e.: "more",) as those // are intended to be exposed explicitly to users. - if((result is FunctionInfo) && + if ((result is FunctionInfo) && (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (result.DefiningLanguageMode == PSLanguageMode.FullLanguage) && (executionContext.Debugger != null) && (executionContext.Debugger.InBreakpoint) && - (! (executionContext.TopLevelSessionState.GetFunctionTableAtScope("GLOBAL").ContainsKey(result.Name)))) + (!(executionContext.TopLevelSessionState.GetFunctionTableAtScope("GLOBAL").ContainsKey(result.Name)))) { return true; } @@ -873,7 +870,7 @@ namespace System.Management.Automation private AliasInfo GetAliasFromModules(string command) { AliasInfo result = null; - + if (command.IndexOf('\\') > 0) { // See if it's a module qualified alias... @@ -902,7 +899,7 @@ namespace System.Management.Automation if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) { PSModuleInfo module = GetImportedModuleByName(qualifiedName.PSSnapInName); - + if (module != null) { module.ExportedFunctions.TryGetValue(qualifiedName.ShortName, out result); @@ -974,7 +971,7 @@ namespace System.Management.Automation function); } } - else + else { result = GetFunctionFromModules(function); } @@ -996,14 +993,14 @@ namespace System.Management.Automation { CmdletInfo result = null; - if (matchingCmdlet == null) + if (_matchingCmdlet == null) { - if ((commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) + if ((_commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) { Collection matchingCmdletInfo = new Collection(); PSSnapinQualifiedName PSSnapinQualifiedCommandName = - PSSnapinQualifiedName.GetInstance(commandName); + PSSnapinQualifiedName.GetInstance(_commandName); if (PSSnapinQualifiedCommandName == null) { @@ -1034,30 +1031,30 @@ namespace System.Management.Automation } } - matchingCmdlet = matchingCmdletInfo.GetEnumerator(); + _matchingCmdlet = matchingCmdletInfo.GetEnumerator(); } else { - matchingCmdlet = _context.CommandDiscovery.GetCmdletInfo(commandName, - (commandResolutionOptions & SearchResolutionOptions.SearchAllScopes) != 0); + _matchingCmdlet = _context.CommandDiscovery.GetCmdletInfo(_commandName, + (_commandResolutionOptions & SearchResolutionOptions.SearchAllScopes) != 0); } } - if (!matchingCmdlet.MoveNext()) + if (!_matchingCmdlet.MoveNext()) { // Advance the state - currentState = SearchState.SearchingBuiltinScripts; + _currentState = SearchState.SearchingBuiltinScripts; - matchingCmdlet = null; + _matchingCmdlet = null; } else { - result = matchingCmdlet.Current; + result = _matchingCmdlet.Current; } return traceResult(result); } - private IEnumerator matchingCmdlet; + private IEnumerator _matchingCmdlet; private static CmdletInfo traceResult(CmdletInfo result) { @@ -1086,9 +1083,9 @@ namespace System.Management.Automation { ScriptInfo result = null; - if ((commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) + if ((_commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) { - if (matchingScript == null) + if (_matchingScript == null) { // Generate the enumerator of matching script names @@ -1097,12 +1094,12 @@ namespace System.Management.Automation WildcardPattern scriptMatcher = WildcardPattern.Get( - commandName, + _commandName, WildcardOptions.IgnoreCase); WildcardPattern scriptExtensionMatcher = WildcardPattern.Get( - commandName + StringLiterals.PowerShellScriptFileExtension, + _commandName + StringLiterals.PowerShellScriptFileExtension, WildcardOptions.IgnoreCase); // Get the script cache enumerator. This acquires the cache lock, @@ -1116,28 +1113,28 @@ namespace System.Management.Automation matchingScripts.Add(scriptName); } } - matchingScript = matchingScripts.GetEnumerator(); + _matchingScript = matchingScripts.GetEnumerator(); } - if (!matchingScript.MoveNext()) + if (!_matchingScript.MoveNext()) { // Advance the state - currentState = SearchState.StartSearchingForExternalCommands; + _currentState = SearchState.StartSearchingForExternalCommands; - matchingScript = null; + _matchingScript = null; } else { - result = _context.CommandDiscovery.GetScriptInfo(matchingScript.Current); + result = _context.CommandDiscovery.GetScriptInfo(_matchingScript.Current); } } else { // Advance the state - currentState = SearchState.StartSearchingForExternalCommands; + _currentState = SearchState.StartSearchingForExternalCommands; - result = _context.CommandDiscovery.GetScriptInfo(commandName) ?? - _context.CommandDiscovery.GetScriptInfo(commandName + StringLiterals.PowerShellScriptFileExtension); + result = _context.CommandDiscovery.GetScriptInfo(_commandName) ?? + _context.CommandDiscovery.GetScriptInfo(_commandName + StringLiterals.PowerShellScriptFileExtension); } if (result != null) @@ -1148,7 +1145,7 @@ namespace System.Management.Automation } return result; } - private IEnumerator matchingScript; + private IEnumerator _matchingScript; private string DoPowerShellRelativePathLookup() @@ -1168,13 +1165,13 @@ namespace System.Management.Automation // Relative Path: ".\command.exe" // Home Path: "~\command.exe" // Drive Relative Path: "\Users\User\AppData\Local\Temp\command.exe" - if (commandName[0] == '.' || commandName[0] == '~' || commandName[0] == '\\') + if (_commandName[0] == '.' || _commandName[0] == '~' || _commandName[0] == '\\') { using (CommandDiscovery.discoveryTracer.TraceScope( "{0} appears to be a relative path. Trying to resolve relative path", - commandName)) + _commandName)) { - result = ResolvePSPath(commandName); + result = ResolvePSPath(_commandName); } } } @@ -1330,7 +1327,7 @@ namespace System.Management.Automation } // Add the extensions for script, module and data files in that order... - if ((commandTypes & CommandTypes.ExternalScript) != 0) + if ((_commandTypes & CommandTypes.ExternalScript) != 0) { result.Add(name + StringLiterals.PowerShellScriptFileExtension); if (!commandDiscovery) @@ -1341,7 +1338,7 @@ namespace System.Management.Automation } } - if ((commandTypes & CommandTypes.Application) != 0) + if ((_commandTypes & CommandTypes.Application) != 0) { // Now add each extension from the PATHEXT environment variable @@ -1467,23 +1464,23 @@ namespace System.Management.Automation /// /// The command name to search for /// - private string commandName; + private string _commandName; /// /// Determines which command types will be globbed. /// - private SearchResolutionOptions commandResolutionOptions; + private SearchResolutionOptions _commandResolutionOptions; /// /// Determines which types of commands to look for. /// - private CommandTypes commandTypes = CommandTypes.All; + private CommandTypes _commandTypes = CommandTypes.All; /// /// The enumerator that uses the Path to /// search for commands. /// - private CommandPathSearch pathSearcher; + private CommandPathSearch _pathSearcher; /// /// Thge execution context instance for the current engine... @@ -1503,7 +1500,7 @@ namespace System.Management.Automation private void setupPathSearcher() { // If it's already set up, just return... - if (pathSearcher != null) + if (_pathSearcher != null) { return; } @@ -1512,51 +1509,51 @@ namespace System.Management.Automation // Even though file types like .DOC, .LOG,.TXT, etc. can be opened / invoked, users think of these as files, not applications. // So I don't think we should show applications with the additional extensions at all. // Applications should only include files whose extensions are in the PATHEXT list and these would only be returned with the All parameter. - - if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) - { - canDoPathLookup = true; - canDoPathLookupResult = CanDoPathLookupResult.Yes; - pathSearcher = + if ((_commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0) + { + _canDoPathLookup = true; + _canDoPathLookupResult = CanDoPathLookupResult.Yes; + + _pathSearcher = new CommandPathSearch( - commandName, + _commandName, _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, acceptableCommandNames: null); } else { - canDoPathLookupResult = CanDoPathLookup(commandName); - if (canDoPathLookupResult == CanDoPathLookupResult.Yes) + _canDoPathLookupResult = CanDoPathLookup(_commandName); + if (_canDoPathLookupResult == CanDoPathLookupResult.Yes) { - canDoPathLookup = true; - commandName = commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd); + _canDoPathLookup = true; + _commandName = _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd); - pathSearcher = + _pathSearcher = new CommandPathSearch( - commandName, + _commandName, _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, - ConstructSearchPatternsFromName(commandName, commandDiscovery: true)); + ConstructSearchPatternsFromName(_commandName, commandDiscovery: true)); } - else if (canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted) + else if (_canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted) { - canDoPathLookup = true; + _canDoPathLookup = true; - string directory = Path.GetDirectoryName(commandName); - var directoryCollection = new [] { directory }; + string directory = Path.GetDirectoryName(_commandName); + var directoryCollection = new[] { directory }; CommandDiscovery.discoveryTracer.WriteLine( "The path is rooted, so only doing the lookup in the specified directory: {0}", directory); - string fileName = Path.GetFileName(commandName); + string fileName = Path.GetFileName(_commandName); if (!String.IsNullOrEmpty(fileName)) { fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd); - pathSearcher = + _pathSearcher = new CommandPathSearch( fileName, directoryCollection, @@ -1565,17 +1562,17 @@ namespace System.Management.Automation } else { - canDoPathLookup = false; + _canDoPathLookup = false; } } - else if (canDoPathLookupResult == CanDoPathLookupResult.DirectorySeparator) + else if (_canDoPathLookupResult == CanDoPathLookupResult.DirectorySeparator) { - canDoPathLookup = true; + _canDoPathLookup = true; // We must try to resolve the path as an PSPath or else we can't do // path lookup for relative paths. - string directory = Path.GetDirectoryName(commandName); + string directory = Path.GetDirectoryName(_commandName); directory = ResolvePSPath(directory); CommandDiscovery.discoveryTracer.WriteLine( @@ -1584,18 +1581,18 @@ namespace System.Management.Automation if (directory == null) { - canDoPathLookup = false; + _canDoPathLookup = false; } else { var directoryCollection = new[] { directory }; - string fileName = Path.GetFileName(commandName); + string fileName = Path.GetFileName(_commandName); if (!String.IsNullOrEmpty(fileName)) { fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd); - pathSearcher = + _pathSearcher = new CommandPathSearch( fileName, directoryCollection, @@ -1604,7 +1601,7 @@ namespace System.Management.Automation } else { - canDoPathLookup = false; + _canDoPathLookup = false; } } } @@ -1622,20 +1619,20 @@ namespace System.Management.Automation if (_commandOrigin == CommandOrigin.Runspace) { if (_context.EngineSessionState.Applications.Count == 0) - this.commandTypes &= ~CommandTypes.Application; + _commandTypes &= ~CommandTypes.Application; if (_context.EngineSessionState.Scripts.Count == 0) - this.commandTypes &= ~CommandTypes.ExternalScript; + _commandTypes &= ~CommandTypes.ExternalScript; } - if (pathSearcher != null) + if (_pathSearcher != null) { - pathSearcher.Reset(); + _pathSearcher.Reset(); } _currentMatch = null; - currentState = SearchState.SearchingAliases; - matchingAlias = null; - matchingCmdlet = null; - matchingScript = null; + _currentState = SearchState.SearchingAliases; + _matchingAlias = null; + _matchingCmdlet = null; + _matchingScript = null; } // Reset internal CommandOrigin CommandOrigin @@ -1643,32 +1640,32 @@ namespace System.Management.Automation get { return _commandOrigin; } set { _commandOrigin = value; } } - CommandOrigin _commandOrigin = CommandOrigin.Internal; + private CommandOrigin _commandOrigin = CommandOrigin.Internal; /// /// An enumerator of the matching aliases /// - private IEnumerator matchingAlias; + private IEnumerator _matchingAlias; /// /// An enumerator of the matching functions /// - private IEnumerator matchingFunctionEnumerator; + private IEnumerator _matchingFunctionEnumerator; /// /// The CommandInfo that references the command that matches the pattern. /// private CommandInfo _currentMatch; - private bool canDoPathLookup; - private CanDoPathLookupResult canDoPathLookupResult = CanDoPathLookupResult.Yes; + private bool _canDoPathLookup; + private CanDoPathLookupResult _canDoPathLookupResult = CanDoPathLookupResult.Yes; /// /// The current state of the enumerator /// - private SearchState currentState = SearchState.SearchingAliases; + private SearchState _currentState = SearchState.SearchingAliases; - enum SearchState + private enum SearchState { // the searcher has been reset or has not been advanced since being created. SearchingAliases, @@ -1708,7 +1705,6 @@ namespace System.Management.Automation } // SearchState #endregion private members - } // CommandSearcher /// diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 3cce1975b..a841c11c1 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Management.Automation; @@ -29,13 +30,13 @@ namespace System.Management.Automation.Internal /// If is null. /// /// - internal CommonParameters (MshCommandRuntime commandRuntime) + internal CommonParameters(MshCommandRuntime commandRuntime) { if (commandRuntime == null) { throw PSTraceSource.NewArgumentNullException("commandRuntime"); } - this.commandRuntime = commandRuntime; + _commandRuntime = commandRuntime; } // ctor #endregion ctor @@ -86,8 +87,8 @@ namespace System.Management.Automation.Internal [Alias("vb")] public SwitchParameter Verbose { - get { return commandRuntime.Verbose; } - set { commandRuntime.Verbose = value; } + get { return _commandRuntime.Verbose; } + set { _commandRuntime.Verbose = value; } } //Verbose /// @@ -103,8 +104,8 @@ namespace System.Management.Automation.Internal [Alias("db")] public SwitchParameter Debug { - get { return commandRuntime.Debug; } - set { commandRuntime.Debug = value; } + get { return _commandRuntime.Debug; } + set { _commandRuntime.Debug = value; } } //Debug /// @@ -118,8 +119,8 @@ namespace System.Management.Automation.Internal [Alias("ea")] public ActionPreference ErrorAction { - get { return commandRuntime.ErrorAction; } - set { commandRuntime.ErrorAction = value; } + get { return _commandRuntime.ErrorAction; } + set { _commandRuntime.ErrorAction = value; } } //ErrorAction /// @@ -134,8 +135,8 @@ namespace System.Management.Automation.Internal [Alias("wa")] public ActionPreference WarningAction { - get { return commandRuntime.WarningPreference; } - set { commandRuntime.WarningPreference = value; } + get { return _commandRuntime.WarningPreference; } + set { _commandRuntime.WarningPreference = value; } } //WarningAction /// @@ -149,8 +150,8 @@ namespace System.Management.Automation.Internal [Alias("infa")] public ActionPreference InformationAction { - get { return commandRuntime.InformationPreference; } - set { commandRuntime.InformationPreference = value; } + get { return _commandRuntime.InformationPreference; } + set { _commandRuntime.InformationPreference = value; } } //InformationAction /// @@ -171,8 +172,8 @@ namespace System.Management.Automation.Internal [ValidateVariableName] public string ErrorVariable { - get { return commandRuntime.ErrorVariable; } - set { commandRuntime.ErrorVariable = value; } + get { return _commandRuntime.ErrorVariable; } + set { _commandRuntime.ErrorVariable = value; } }//ErrorVariable /// @@ -188,8 +189,8 @@ namespace System.Management.Automation.Internal [ValidateVariableName] public string WarningVariable { - get { return commandRuntime.WarningVariable; } - set { commandRuntime.WarningVariable = value; } + get { return _commandRuntime.WarningVariable; } + set { _commandRuntime.WarningVariable = value; } }//WarningVariable /// @@ -205,8 +206,8 @@ namespace System.Management.Automation.Internal [ValidateVariableName] public string InformationVariable { - get { return commandRuntime.InformationVariable; } - set { commandRuntime.InformationVariable = value; } + get { return _commandRuntime.InformationVariable; } + set { _commandRuntime.InformationVariable = value; } } /// @@ -220,12 +221,12 @@ namespace System.Management.Automation.Internal /// but it should be MUCH faster as there is no binding that takes place /// [Parameter] - [Alias ("ov")] + [Alias("ov")] [ValidateVariableName] public string OutVariable { - get { return commandRuntime.OutVariable; } - set { commandRuntime.OutVariable = value; } + get { return _commandRuntime.OutVariable; } + set { _commandRuntime.OutVariable = value; } } //OutVariable /// @@ -240,8 +241,8 @@ namespace System.Management.Automation.Internal [Alias("ob")] public int OutBuffer { - get { return commandRuntime.OutBuffer; } - set { commandRuntime.OutBuffer = value; } + get { return _commandRuntime.OutBuffer; } + set { _commandRuntime.OutBuffer = value; } } //OutBuffer /// @@ -259,13 +260,13 @@ namespace System.Management.Automation.Internal [ValidateVariableName] public string PipelineVariable { - get { return commandRuntime.PipelineVariable; } - set { commandRuntime.PipelineVariable = value; } + get { return _commandRuntime.PipelineVariable; } + set { _commandRuntime.PipelineVariable = value; } } //PipelineVariable #endregion parameters - private MshCommandRuntime commandRuntime; + private MshCommandRuntime _commandRuntime; internal class ValidateVariableName : ValidateArgumentsAttribute { @@ -290,6 +291,5 @@ namespace System.Management.Automation.Internal } } } // class UserFeedbackParameters - } diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index d973df684..1f5f0e416 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -45,7 +46,7 @@ namespace System.Management.Automation { if (runtimeDefinedParameter == null) { - throw PSTraceSource.NewArgumentNullException ("runtimeDefinedParameter"); + throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); } this.Name = runtimeDefinedParameter.Name; @@ -54,7 +55,7 @@ namespace System.Management.Automation this.CollectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType); - this.CompiledAttributes = new Collection (); + this.CompiledAttributes = new Collection(); this.ParameterSetData = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -65,7 +66,7 @@ namespace System.Management.Automation // First, process attributes that aren't type conversions foreach (Attribute attribute in runtimeDefinedParameter.Attributes) { - if (! (attribute is ArgumentTypeConverterAttribute)) + if (!(attribute is ArgumentTypeConverterAttribute)) { ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases); } @@ -688,7 +689,6 @@ namespace System.Management.Automation // elementType remains null return; } - } // ctor /// diff --git a/src/System.Management.Automation/engine/ConfigurationInfo.cs b/src/System.Management.Automation/engine/ConfigurationInfo.cs index 2f1639e1d..98c2ff7e7 100644 --- a/src/System.Management.Automation/engine/ConfigurationInfo.cs +++ b/src/System.Management.Automation/engine/ConfigurationInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Text; @@ -37,7 +38,7 @@ namespace System.Management.Automation /// internal ConfigurationInfo(string name, ScriptBlock configuration, ExecutionContext context) : this(name, configuration, context, null) { - } + } /// /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock @@ -67,7 +68,7 @@ namespace System.Management.Automation : base(name, configuration, context, helpFile) { SetCommandType(CommandTypes.Configuration); - } + } /// /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock @@ -132,7 +133,7 @@ namespace System.Management.Automation { SetCommandType(CommandTypes.Configuration); IsMetaConfiguration = isMetaConfig; - } + } /// /// Creates an instance of the ConfigurationInfo class with the specified name and ScriptBlock @@ -165,7 +166,7 @@ namespace System.Management.Automation internal ConfigurationInfo(string name, ScriptBlock configuration, ScopedItemOptions options, ExecutionContext context, string helpFile) : this(name, configuration, options, context, helpFile, false) { - } + } /// /// This is a copy constructor, used primarily for get-command. @@ -197,7 +198,7 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { - get { return HelpCategory.Configuration; } + get { return HelpCategory.Configuration; } } /// @@ -205,5 +206,5 @@ namespace System.Management.Automation /// public bool IsMetaConfiguration { get; internal set; } - } -} + } +} diff --git a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs index 815f9c554..e84462f0a 100644 --- a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -46,8 +47,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.sessionState = cmdlet.Context.EngineSessionState; + _cmdlet = cmdlet; + _sessionState = cmdlet.Context.EngineSessionState; } // ContentCmdletProviderIntrinsics internal /// @@ -69,9 +70,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // ContentCmdletProviderIntrinsics internal - + #endregion Constructors #region Public methods @@ -118,12 +119,12 @@ namespace System.Management.Automation public Collection GetReader(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentReader(new string[] { path }, false, false); + return _sessionState.GetContentReader(new string[] { path }, false, false); } // GetContentReader /// @@ -174,14 +175,14 @@ namespace System.Management.Automation public Collection GetReader(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentReader(path, force, literalPath); + return _sessionState.GetContentReader(path, force, literalPath); } - + /// /// /// @@ -220,18 +221,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal Collection GetReader( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentReader(new string[] { path }, context); + return _sessionState.GetContentReader(new string[] { path }, context); } // GetContentReader - + /// /// Gets the dynamic parameters for the get-content cmdlet. /// @@ -271,16 +272,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object GetContentReaderDynamicParameters( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentReaderDynamicParameters(path, context); + return _sessionState.GetContentReaderDynamicParameters(path, context); } // GetContentReaderDynamicParameters #endregion GetContentReader @@ -327,12 +328,12 @@ namespace System.Management.Automation public Collection GetWriter(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentWriter(new string[] { path }, false, false); + return _sessionState.GetContentWriter(new string[] { path }, false, false); } // GetContentWriter /// @@ -383,14 +384,14 @@ namespace System.Management.Automation public Collection GetWriter(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentWriter(path, force, literalPath); + return _sessionState.GetContentWriter(path, force, literalPath); } // GetContentWriter - + /// /// /// @@ -429,18 +430,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal Collection GetWriter( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentWriter(new string[] { path }, context); + return _sessionState.GetContentWriter(new string[] { path }, context); } // GetContentWriter - + /// /// Gets the dynamic parameters for the set-content and add-content cmdlet. /// @@ -480,16 +481,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object GetContentWriterDynamicParameters( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetContentWriterDynamicParameters(path, context); + return _sessionState.GetContentWriterDynamicParameters(path, context); } // GetContentWriterDynamicParameters #endregion GetContentWriter @@ -532,12 +533,12 @@ namespace System.Management.Automation public void Clear(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearContent(new string[] { path }, false, false); + _sessionState.ClearContent(new string[] { path }, false, false); } // ClearContent /// @@ -584,14 +585,14 @@ namespace System.Management.Automation public void Clear(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearContent(path, force, literalPath); + _sessionState.ClearContent(path, force, literalPath); } - + /// /// Clears the content from the specified item(s) /// @@ -632,14 +633,14 @@ namespace System.Management.Automation internal void Clear(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearContent(new string[] { path }, context); + _sessionState.ClearContent(new string[] { path }, context); } // ClearContent - + /// /// Gets the dynamic parameters for the clear-content cmdlet. /// @@ -681,12 +682,12 @@ namespace System.Management.Automation internal object ClearContentDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ClearContentDynamicParameters(path, context); + return _sessionState.ClearContentDynamicParameters(path, context); } // ClearContentDynamicParameters #endregion ClearContent @@ -695,8 +696,8 @@ namespace System.Management.Automation #region private data - private Cmdlet cmdlet; - private SessionStateInternal sessionState; + private Cmdlet _cmdlet; + private SessionStateInternal _sessionState; #endregion private data } // ContentCmdletProviderIntrinsics diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 94dde0c1c..d2db2b0e6 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -101,7 +101,7 @@ namespace System.Management.Automation /// /// object to get all the member information from /// all members in obj - protected abstract PSMemberInfoInternalCollection GetMembers(object obj) where T: PSMemberInfo; + protected abstract PSMemberInfoInternalCollection GetMembers(object obj) where T : PSMemberInfo; #endregion member @@ -204,7 +204,7 @@ namespace System.Management.Automation returnValue.Append(definitions[i]); returnValue.Append(", "); } - + returnValue.Remove(returnValue.Length - 2, 2); return returnValue.ToString(); } @@ -319,17 +319,17 @@ namespace System.Management.Automation } #endregion parameterized property - + #endregion virtual #region base #region private - private static Exception NewException(Exception e, string errorId, + private static Exception NewException(Exception e, string errorId, string targetErrorId, string resourceString, params object[] parameters) { - object[] newParameters = new object[parameters.Length+1]; + object[] newParameters = new object[parameters.Length + 1]; for (int i = 0; i < parameters.Length; i++) { newParameters[i + 1] = parameters[i]; @@ -369,7 +369,7 @@ namespace System.Management.Automation } } - internal T BaseGetMember(object obj, string memberName) where T:PSMemberInfo + internal T BaseGetMember(object obj, string memberName) where T : PSMemberInfo { try { @@ -916,7 +916,7 @@ namespace System.Management.Automation { return 1; } - else if(candidate1.parameters.Length > candidate2.parameters.Length) + else if (candidate1.parameters.Length > candidate2.parameters.Length) { return -1; } @@ -1252,9 +1252,9 @@ namespace System.Management.Automation // } // // If we have such information in invocationConstraints then we should call method on the baseClass. - if (invocationConstraints != null && - invocationConstraints.MethodTargetType != null && - methodInfo.method != null && + if (invocationConstraints != null && + invocationConstraints.MethodTargetType != null && + methodInfo.method != null && methodInfo.method.DeclaringType != null) { Type targetType = methodInfo.method.DeclaringType; @@ -1272,7 +1272,7 @@ namespace System.Management.Automation } return methodInfo; } - + private static MethodInformation FindBestMethodImpl( MethodInformation[] methods, PSMethodInvocationConstraints invocationConstraints, @@ -1281,7 +1281,6 @@ namespace System.Management.Automation ref string errorMsg, out bool expandParamsOnBest) { - expandParamsOnBest = false; // Small optimization so we don't calculate type distances when there is only one method @@ -1345,7 +1344,7 @@ namespace System.Management.Automation if (arguments.Length != parameters.Length) { // Skip methods w/ an incorrect # of arguments. - + if (arguments.Length > parameters.Length) { // If too many args,it's only OK if the method is varargs. @@ -1370,7 +1369,8 @@ namespace System.Management.Automation int optionals = 0; for (int j = 0; j < parameters.Length; j++) { - if (parameters[j].isOptional) { + if (parameters[j].isOptional) + { optionals += 1; } } @@ -1411,7 +1411,7 @@ namespace System.Management.Automation if (candidate.conversionRanks[j] == ConversionRank.None) { candidate = null; - } + } } else { @@ -1471,8 +1471,8 @@ namespace System.Management.Automation return null; } } - - OverloadCandidate bestCandidate = candidates.Count == 1 + + OverloadCandidate bestCandidate = candidates.Count == 1 ? candidates[0] : FindBestCandidate(candidates, arguments, invocationConstraints); if (bestCandidate != null) @@ -1554,7 +1554,7 @@ namespace System.Management.Automation } internal static MethodInformation GetBestMethodAndArguments( - string methodName, + string methodName, MethodInformation[] methods, object[] arguments, out object[] newArguments) @@ -1563,7 +1563,7 @@ namespace System.Management.Automation } internal static MethodInformation GetBestMethodAndArguments( - string methodName, + string methodName, MethodInformation[] methods, PSMethodInvocationConstraints invocationConstraints, object[] arguments, @@ -1586,8 +1586,8 @@ namespace System.Management.Automation /// Called in GetBestMethodAndArguments after a call to FindBestMethod to perform the /// type conversion, copying(varArg) and optional value setting of the final arguments. /// - internal static object[] GetMethodArgumentsBase(string methodName, - ParameterInformation[] parameters, object[] arguments, + internal static object[] GetMethodArgumentsBase(string methodName, + ParameterInformation[] parameters, object[] arguments, bool expandParamsOnBest) { int parametersLength = parameters.Length; @@ -1677,14 +1677,14 @@ namespace System.Management.Automation /// the complete array of new arguments /// the parameter to use /// the index in newArguments to set - internal static void SetNewArgument(string methodName, object[] arguments, + internal static void SetNewArgument(string methodName, object[] arguments, object[] newArguments, ParameterInformation parameter, int index) { if (arguments.Length > index) { try { - newArguments[index] = MethodArgumentConvertTo(arguments[index], parameter.isByRef, index, + newArguments[index] = MethodArgumentConvertTo(arguments[index], parameter.isByRef, index, parameter.parameterType, CultureInfo.InvariantCulture); } catch (InvalidCastException e) @@ -1704,7 +1704,7 @@ namespace System.Management.Automation } } - internal static object MethodArgumentConvertTo(object valueToConvert, + internal static object MethodArgumentConvertTo(object valueToConvert, bool isParameterByRef, int parameterIndex, Type resultType, IFormatProvider formatProvider) { @@ -1755,8 +1755,8 @@ namespace System.Management.Automation } return obj; } - - internal static object PropertySetAndMethodArgumentConvertTo(object valueToConvert, + + internal static object PropertySetAndMethodArgumentConvertTo(object valueToConvert, Type resultType, IFormatProvider formatProvider) { using (PSObject.memberResolution.TraceScope("Converting parameter \"{0}\" to \"{1}\".", valueToConvert, resultType)) @@ -1794,14 +1794,14 @@ namespace System.Management.Automation typeInfo = type.GetTypeInfo(); if (typeInfo.IsPrimitive) { - if (type == typeof(byte)) { generator.Emit(OpCodes.Ldind_U1); } + if (type == typeof(byte)) { generator.Emit(OpCodes.Ldind_U1); } else if (type == typeof(ushort)) { generator.Emit(OpCodes.Ldind_U2); } - else if (type == typeof(uint)) { generator.Emit(OpCodes.Ldind_U4); } - else if (type == typeof(sbyte)) { generator.Emit(OpCodes.Ldind_I8); } - else if (type == typeof(short)) { generator.Emit(OpCodes.Ldind_I2); } - else if (type == typeof(int)) { generator.Emit(OpCodes.Ldind_I4); } - else if (type == typeof(long)) { generator.Emit(OpCodes.Ldind_I8); } - else if (type == typeof(float)) { generator.Emit(OpCodes.Ldind_R4); } + else if (type == typeof(uint)) { generator.Emit(OpCodes.Ldind_U4); } + else if (type == typeof(sbyte)) { generator.Emit(OpCodes.Ldind_I8); } + else if (type == typeof(short)) { generator.Emit(OpCodes.Ldind_I2); } + else if (type == typeof(int)) { generator.Emit(OpCodes.Ldind_I4); } + else if (type == typeof(long)) { generator.Emit(OpCodes.Ldind_I8); } + else if (type == typeof(float)) { generator.Emit(OpCodes.Ldind_R4); } else if (type == typeof(double)) { generator.Emit(OpCodes.Ldind_R8); } } else if (typeInfo.IsValueType) @@ -1843,15 +1843,15 @@ namespace System.Management.Automation internal class CacheTable { internal Collection memberCollection; - private Dictionary indexes; + private Dictionary _indexes; internal CacheTable() { memberCollection = new Collection(); - indexes = new Dictionary(StringComparer.OrdinalIgnoreCase); + _indexes = new Dictionary(StringComparer.OrdinalIgnoreCase); } internal void Add(string name, object member) { - indexes[name] = memberCollection.Count; + _indexes[name] = memberCollection.Count; memberCollection.Add(member); } internal object this[string name] @@ -1859,7 +1859,7 @@ namespace System.Management.Automation get { int indexObj; - if (!indexes.TryGetValue(name, out indexObj)) + if (!_indexes.TryGetValue(name, out indexObj)) { return null; } @@ -1898,9 +1898,9 @@ namespace System.Management.Automation internal bool hasOptional; internal bool isGeneric; - private bool useReflection; + private bool _useReflection; private delegate object MethodInvoker(object target, object[] arguments); - private MethodInvoker methodInvoker; + private MethodInvoker _methodInvoker; /// /// This constructor supports .net methods @@ -1964,37 +1964,37 @@ namespace System.Management.Automation } } - if (!useReflection) + if (!_useReflection) { - if (methodInvoker == null) + if (_methodInvoker == null) { if (!(method is MethodInfo)) { - useReflection = true; + _useReflection = true; } else { - methodInvoker = GetMethodInvoker((MethodInfo) method); + _methodInvoker = GetMethodInvoker((MethodInfo)method); } } - if (methodInvoker != null) + if (_methodInvoker != null) { - return methodInvoker(target, arguments); + return _methodInvoker(target, arguments); } } return method.Invoke(target, arguments); } - private static OpCode[] _ldc = new OpCode[] { + private static OpCode[] s_ldc = new OpCode[] { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 }; private static void EmitLdc(ILGenerator emitter, int c) { - if (c < _ldc.Length) + if (c < s_ldc.Length) { - emitter.Emit(_ldc[c]); + emitter.Emit(s_ldc[c]); } else { @@ -2028,7 +2028,7 @@ namespace System.Management.Automation methodToCall = null; Type valuetype = method.DeclaringType; - + Diagnostics.Assert(valuetype.GetTypeInfo().IsValueType, "This code only works with valuetypes"); Type[] interfaces = valuetype.GetInterfaces(); @@ -2048,7 +2048,7 @@ namespace System.Management.Automation return null; } - [SuppressMessage("NullPtr", "#pw26500", Justification="This is a false positive. Original warning was on the deference of 'locals' on line 1863: emitter.Emit(OpCodes.Ldloca, locals[cLocal])")] + [SuppressMessage("NullPtr", "#pw26500", Justification = "This is a false positive. Original warning was on the deference of 'locals' on line 1863: emitter.Emit(OpCodes.Ldloca, locals[cLocal])")] private MethodInvoker GetMethodInvoker(MethodInfo method) { Type type; @@ -2161,7 +2161,7 @@ namespace System.Management.Automation type = FindInterfaceForMethod(method, out methodToCall); if (type == null) { - useReflection = true; + _useReflection = true; return null; } emitter.Emit(OpCodes.Ldarg_0); @@ -2323,51 +2323,51 @@ namespace System.Management.Automation BindingFlags.IgnoreCase | BindingFlags.Instance); private const BindingFlags staticBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Static); - private bool isStatic; + private bool _isStatic; internal DotNetAdapter() { } internal DotNetAdapter(bool isStatic) { - this.isStatic = isStatic; + _isStatic = isStatic; } // This static is thread safe based on the lock in GetInstancePropertyReflectionTable /// /// CLR reflection property cache for instance properties /// - private static Dictionary instancePropertyCacheTable = new Dictionary(); + private static Dictionary s_instancePropertyCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetStaticPropertyReflectionTable /// /// CLR reflection property cache for static properties /// - private static Dictionary staticPropertyCacheTable = new Dictionary(); + private static Dictionary s_staticPropertyCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetInstanceMethodReflectionTable /// /// CLR reflection method cache for instance methods /// - private static Dictionary instanceMethodCacheTable = new Dictionary(); + private static Dictionary s_instanceMethodCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetStaticMethodReflectionTable /// /// CLR reflection method cache for static methods /// - private static Dictionary staticMethodCacheTable = new Dictionary(); + private static Dictionary s_staticMethodCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetInstanceMethodReflectionTable /// /// CLR reflection method cache for instance events /// - private static readonly Dictionary> instanceEventCacheTable + private static readonly Dictionary> s_instanceEventCacheTable = new Dictionary>(); // This static is thread safe based on the lock in GetStaticMethodReflectionTable /// /// CLR reflection method cache for static events /// - private static readonly Dictionary> staticEventCacheTable + private static readonly Dictionary> s_staticEventCacheTable = new Dictionary>(); internal class MethodCacheEntry @@ -2493,7 +2493,7 @@ namespace System.Management.Automation propertyTypeInfo.IsGenericType || declaringTypeInfo.IsGenericType || property.DeclaringType.IsComObject() || - property.PropertyType.IsComObject() ) + property.PropertyType.IsComObject()) { this.readOnly = property.GetSetMethod() == null; this.writeOnly = property.GetGetMethod() == null; @@ -2540,7 +2540,7 @@ namespace System.Management.Automation } } - void InitGetter() + private void InitGetter() { if (writeOnly || useReflection) return; @@ -2570,11 +2570,11 @@ namespace System.Management.Automation } Expression getterExpr; - if (declaringTypeInfo.IsGenericTypeDefinition) + if (declaringTypeInfo.IsGenericTypeDefinition) { Expression innerException = Expression.New(CachedReflectionInfo.GetValueException_ctor, Expression.Constant("PropertyGetException"), - Expression.Constant(null, typeof(Exception)), + Expression.Constant(null, typeof(Exception)), Expression.Constant(ParserStrings.PropertyInGenericType), Expression.NewArrayInit(typeof(object), Expression.Constant(field.Name))); getterExpr = Compiler.ThrowRuntimeErrorWithInnerException("PropertyGetException", @@ -2583,10 +2583,10 @@ namespace System.Management.Automation } else { - getterExpr = Expression.Field(instance, field).Cast(typeof(object)); + getterExpr = Expression.Field(instance, field).Cast(typeof(object)); } - this._getterDelegate = Expression.Lambda(getterExpr, parameter).Compile(); + _getterDelegate = Expression.Lambda(getterExpr, parameter).Compile(); return; } @@ -2594,11 +2594,11 @@ namespace System.Management.Automation var propertyGetter = property.GetGetMethod(true); instance = this.isStatic ? null : parameter.Cast(propertyGetter.DeclaringType); - this._getterDelegate = Expression.Lambda( + _getterDelegate = Expression.Lambda( Expression.Property(instance, property).Cast(typeof(object)), parameter).Compile(); } - void InitSetter() + private void InitSetter() { if (readOnly || useReflection) return; @@ -2642,7 +2642,7 @@ namespace System.Management.Automation else if (readOnly) { errMessage = ParserStrings.PropertyIsReadOnly; - } + } if (errMessage != null) { @@ -2659,15 +2659,15 @@ namespace System.Management.Automation { setterExpr = Expression.Assign(Expression.Field(instance, field), Expression.Convert(value, field.FieldType)); } - this._setterDelegate = Expression.Lambda(setterExpr, parameter, value).Compile(); + _setterDelegate = Expression.Lambda(setterExpr, parameter, value).Compile(); return; } - var property = (PropertyInfo) member; + var property = (PropertyInfo)member; MethodInfo propertySetter = property.GetSetMethod(true); instance = this.isStatic ? null : parameter.Cast(propertySetter.DeclaringType); - this._setterDelegate = + _setterDelegate = Expression.Lambda( Expression.Assign(Expression.Property(instance, property), Expression.Convert(value, property.PropertyType)), parameter, value).Compile(); @@ -2697,7 +2697,7 @@ namespace System.Management.Automation { InitSetter(); } - + return _setterDelegate; } } @@ -2709,18 +2709,18 @@ namespace System.Management.Automation internal bool isStatic; internal Type propertyType; - private AttributeCollection attributes; + private AttributeCollection _attributes; internal AttributeCollection Attributes { get { - if (this.attributes == null) + if (_attributes == null) { // Since AttributeCollection can only be constructed with an Attribute[], one is built. var objAttributes = this.member.GetCustomAttributes(true); - attributes = new AttributeCollection(objAttributes.Cast().ToArray()); + _attributes = new AttributeCollection(objAttributes.Cast().ToArray()); } - return this.attributes; + return _attributes; } } } @@ -3125,7 +3125,7 @@ namespace System.Management.Automation /// /// The dictionary cache about if an assembly supports reflection execution on its internal types. /// - private static readonly ConcurrentDictionary DisallowReflectionCache = + private static readonly ConcurrentDictionary s_disallowReflectionCache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); /// @@ -3136,7 +3136,7 @@ namespace System.Management.Automation { bool disallowReflection = false; Assembly assembly = typeInfo.Assembly; - if (DisallowReflectionCache.TryGetValue(assembly.FullName, out disallowReflection)) + if (s_disallowReflectionCache.TryGetValue(assembly.FullName, out disallowReflection)) { return disallowReflection; } @@ -3153,7 +3153,7 @@ namespace System.Management.Automation disallowReflection = disablePrivateReflectionAttribute != null; } - DisallowReflectionCache.TryAdd(assembly.FullName, disallowReflection); + s_disallowReflectionCache.TryAdd(assembly.FullName, disallowReflection); return disallowReflection; } @@ -3188,17 +3188,17 @@ namespace System.Management.Automation /// type to load properties for private static CacheTable GetStaticPropertyReflectionTable(Type type) { - lock (staticPropertyCacheTable) + lock (s_staticPropertyCacheTable) { CacheTable typeTable = null; - if (staticPropertyCacheTable.TryGetValue(type, out typeTable)) + if (s_staticPropertyCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new CacheTable(); PopulatePropertyReflectionTable(type, typeTable, staticBindingFlags); - staticPropertyCacheTable[type] = typeTable; + s_staticPropertyCacheTable[type] = typeTable; return typeTable; } } @@ -3209,17 +3209,17 @@ namespace System.Management.Automation /// type to load methods for private static CacheTable GetStaticMethodReflectionTable(Type type) { - lock (staticMethodCacheTable) + lock (s_staticMethodCacheTable) { CacheTable typeTable = null; - if (staticMethodCacheTable.TryGetValue(type, out typeTable)) + if (s_staticMethodCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new CacheTable(); PopulateMethodReflectionTable(type, typeTable, staticBindingFlags); - staticMethodCacheTable[type] = typeTable; + s_staticMethodCacheTable[type] = typeTable; return typeTable; } } @@ -3230,16 +3230,16 @@ namespace System.Management.Automation /// type containing properties to load in typeTable private static Dictionary GetStaticEventReflectionTable(Type type) { - lock (staticEventCacheTable) + lock (s_staticEventCacheTable) { Dictionary typeTable; - if (staticEventCacheTable.TryGetValue(type, out typeTable)) + if (s_staticEventCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new Dictionary(); PopulateEventReflectionTable(type, typeTable, staticBindingFlags); - staticEventCacheTable[type] = typeTable; + s_staticEventCacheTable[type] = typeTable; return typeTable; } } @@ -3252,16 +3252,16 @@ namespace System.Management.Automation /// type with properties to load in typeTable private static CacheTable GetInstancePropertyReflectionTable(Type type) { - lock (instancePropertyCacheTable) + lock (s_instancePropertyCacheTable) { CacheTable typeTable = null; - if (instancePropertyCacheTable.TryGetValue(type, out typeTable)) + if (s_instancePropertyCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new CacheTable(); PopulatePropertyReflectionTable(type, typeTable, instanceBindingFlags); - instancePropertyCacheTable[type] = typeTable; + s_instancePropertyCacheTable[type] = typeTable; return typeTable; } } @@ -3272,16 +3272,16 @@ namespace System.Management.Automation /// type with methods to load in typeTable private static CacheTable GetInstanceMethodReflectionTable(Type type) { - lock (instanceMethodCacheTable) + lock (s_instanceMethodCacheTable) { CacheTable typeTable = null; - if (instanceMethodCacheTable.TryGetValue(type, out typeTable)) + if (s_instanceMethodCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new CacheTable(); PopulateMethodReflectionTable(type, typeTable, instanceBindingFlags); - instanceMethodCacheTable[type] = typeTable; + s_instanceMethodCacheTable[type] = typeTable; return typeTable; } } @@ -3317,16 +3317,16 @@ namespace System.Management.Automation /// type containing methods to load in typeTable private static Dictionary GetInstanceEventReflectionTable(Type type) { - lock (instanceEventCacheTable) + lock (s_instanceEventCacheTable) { Dictionary typeTable; - if (instanceEventCacheTable.TryGetValue(type, out typeTable)) + if (s_instanceEventCacheTable.TryGetValue(type, out typeTable)) { return typeTable; } typeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); PopulateEventReflectionTable(type, typeTable, instanceBindingFlags); - instanceEventCacheTable[type] = typeTable; + s_instanceEventCacheTable[type] = typeTable; return typeTable; } } @@ -3356,7 +3356,7 @@ namespace System.Management.Automation return null; } - CacheTable typeTable = this.isStatic + CacheTable typeTable = _isStatic ? GetStaticPropertyReflectionTable((Type)obj) : GetInstancePropertyReflectionTable(obj.GetType()); @@ -3392,7 +3392,7 @@ namespace System.Management.Automation return null; } - CacheTable typeTable = this.isStatic + CacheTable typeTable = _isStatic ? GetStaticMethodReflectionTable((Type)obj) : GetInstanceMethodReflectionTable(obj.GetType()); @@ -3415,7 +3415,7 @@ namespace System.Management.Automation return new PSMethod(methods[0].method.Name, this, obj, methods, isSpecial, isHidden) as T; } - internal void AddAllProperties(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T: PSMemberInfo + internal void AddAllProperties(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo { bool lookingForProperties = typeof(T).IsAssignableFrom(typeof(PSProperty)); bool lookingForParameterizedProperties = IsTypeParameterizedProperty(typeof(T)); @@ -3424,7 +3424,7 @@ namespace System.Management.Automation return; } - CacheTable table = this.isStatic + CacheTable table = _isStatic ? GetStaticPropertyReflectionTable((Type)obj) : GetInstancePropertyReflectionTable(obj.GetType()); @@ -3439,7 +3439,8 @@ namespace System.Management.Automation { var isHidden = propertyEntry.member.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); members.Add(new PSProperty(propertyEntry.member.Name, this, - obj, propertyEntry) { IsHidden = isHidden } as T); + obj, propertyEntry) + { IsHidden = isHidden } as T); } } } @@ -3458,14 +3459,14 @@ namespace System.Management.Automation } } - internal void AddAllMethods(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T: PSMemberInfo + internal void AddAllMethods(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo { if (!typeof(T).IsAssignableFrom(typeof(PSMethod))) { return; } - CacheTable table = this.isStatic + CacheTable table = _isStatic ? GetStaticMethodReflectionTable((Type)obj) : GetInstanceMethodReflectionTable(obj.GetType()); @@ -3499,7 +3500,7 @@ namespace System.Management.Automation return; } - var table = this.isStatic + var table = _isStatic ? GetStaticEventReflectionTable((Type)obj) : GetInstanceEventReflectionTable(obj.GetType()); @@ -3548,12 +3549,12 @@ namespace System.Management.Automation internal override bool SiteBinderCanOptimize { get { return true; } } - private static ConcurrentDictionary typeToTypeNameDictionary = + private static ConcurrentDictionary s_typeToTypeNameDictionary = new ConcurrentDictionary(); internal static ConsolidatedString GetInternedTypeNameHierarchy(Type type) { - return typeToTypeNameDictionary.GetOrAdd(type, + return s_typeToTypeNameDictionary.GetOrAdd(type, t => new ConsolidatedString(GetDotNetTypeNameHierarchy(t), interned: true)); } @@ -3669,7 +3670,6 @@ namespace System.Management.Automation { return adapterData.getterDelegate(property.baseObject); } - } FieldInfo field = adapterData.member as FieldInfo; @@ -3692,7 +3692,7 @@ namespace System.Management.Automation protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { PropertyCacheEntry adapterData = (PropertyCacheEntry)property.adapterData; - + if (adapterData.readOnly) { throw new SetValueException("ReadOnlyProperty", @@ -3703,7 +3703,7 @@ namespace System.Management.Automation PropertyInfo propertyInfo = adapterData.member as PropertyInfo; if (propertyInfo != null) - { + { if (convertIfPossible) { setValue = PropertySetAndMethodArgumentConvertTo(setValue, propertyInfo.PropertyType, CultureInfo.InvariantCulture); @@ -3857,7 +3857,7 @@ namespace System.Management.Automation // a TargetInvocationException only when the invocation uses reflection so we need to bubble them up here as well. // catch (ParameterBindingException) { throw; } - catch (FlowControlException) { throw; } + catch (FlowControlException) { throw; } catch (ScriptCallDepthException) { throw; } catch (PipelineStoppedException) { throw; } catch (Exception e) @@ -3917,9 +3917,9 @@ namespace System.Management.Automation /// if the method throws an exception /// if we could not find a method for the given arguments internal static object MethodInvokeDotNet( - string methodName, - object target, - MethodInformation[] methodInformation, + string methodName, + object target, + MethodInformation[] methodInformation, PSMethodInvocationConstraints invocationConstraints, object[] arguments) { @@ -4040,7 +4040,7 @@ namespace System.Management.Automation if (methodEntry.IsGenericMethodDefinition) { builder.Append("["); - + Type[] genericArgs = methodEntry.GetGenericArguments(); for (int i = 0; i < genericArgs.Length; i++) { @@ -4114,9 +4114,9 @@ namespace System.Management.Automation { MethodCacheEntry methodEntry = (MethodCacheEntry)method.adapterData; return DotNetAdapter.MethodInvokeDotNet( - method.Name, + method.Name, method.baseObject, - methodEntry.methodInformationStructures, + methodEntry.methodInformationStructures, invocationConstraints, arguments); } @@ -4302,7 +4302,7 @@ namespace System.Management.Automation return parameterizedProperty as T; } } - return null; + return null; } } @@ -4313,10 +4313,10 @@ namespace System.Management.Automation /// internal class DotNetAdapterWithComTypeName : DotNetAdapter { - private ComTypeInfo comTypeInfo; + private ComTypeInfo _comTypeInfo; internal DotNetAdapterWithComTypeName(ComTypeInfo comTypeInfo) { - this.comTypeInfo = comTypeInfo; + _comTypeInfo = comTypeInfo; } protected override IEnumerable GetTypeNameHierarchy(object obj) @@ -4325,7 +4325,7 @@ namespace System.Management.Automation { if (type.FullName.Equals("System.__ComObject")) { - yield return ComAdapter.GetComTypeName(comTypeInfo.Clsid); + yield return ComAdapter.GetComTypeName(_comTypeInfo.Clsid); } yield return type.FullName; } @@ -4456,7 +4456,7 @@ namespace System.Management.Automation } #endregion method specific - + #endregion virtual } /// @@ -4615,7 +4615,7 @@ namespace System.Management.Automation { PSProperty property = DoGetProperty(obj, memberName); - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property!=null) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) { return property as T; } @@ -4689,7 +4689,6 @@ namespace System.Management.Automation /// internal class XmlNodeAdapter : PropertyOnlyAdapter { - #region virtual /// /// Returns the TypeNameHierarchy out of an object @@ -5041,7 +5040,7 @@ namespace System.Management.Automation internal class TypeInference { [TraceSource("ETS", "Extended Type System")] - private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); internal static MethodInformation Infer(MethodInformation genericMethod, Type[] argumentTypes) { @@ -5084,7 +5083,7 @@ namespace System.Management.Automation // we can try to infer for this signature instead // M)(T1, T2, ..., T3, T3, T3, T3) // where T3 is repeated appropriate number of times depending on the number of actual method arguments. - if (inferredMethod == null && + if (inferredMethod == null && hasVarArgs && typesOfMethodArguments.Length >= (typesOfMethodParameters.Length - 1)) { @@ -5110,11 +5109,11 @@ namespace System.Management.Automation Dbg.Assert(typesOfMethodParameters != null, "Caller should verify that typesOfMethodParameters != null"); Dbg.Assert(typesOfMethodArguments != null, "Caller should verify that typesOfMethodArguments != null"); - using (tracer.TraceScope("Inferring type parameters for the following method: {0}", genericMethod)) + using (s_tracer.TraceScope("Inferring type parameters for the following method: {0}", genericMethod)) { - if (PSTraceSourceOptions.WriteLine == (tracer.Options & PSTraceSourceOptions.WriteLine)) + if (PSTraceSourceOptions.WriteLine == (s_tracer.Options & PSTraceSourceOptions.WriteLine)) { - tracer.WriteLine( + s_tracer.WriteLine( "Types of method arguments: {0}", string.Join(", ", typesOfMethodArguments.Select(t => t.ToString()).ToArray())); } @@ -5134,22 +5133,22 @@ namespace System.Management.Automation try { MethodInfo instantiatedMethod = genericMethod.MakeGenericMethod(inferredTypeParameters.ToArray()); - tracer.WriteLine("Inference succesful: {0}", instantiatedMethod); + s_tracer.WriteLine("Inference succesful: {0}", instantiatedMethod); return instantiatedMethod; } catch (ArgumentException e) { // Inference failure - most likely due to generic constraints being violated (i.e. where T: IEnumerable) - tracer.WriteLine("Inference failure: {0}", e.Message); + s_tracer.WriteLine("Inference failure: {0}", e.Message); return null; } } } - private readonly HashSet[] typeParameterIndexToSetOfInferenceCandidates; + private readonly HashSet[] _typeParameterIndexToSetOfInferenceCandidates; #if DEBUG - private readonly HashSet typeParametersOfTheMethod; + private readonly HashSet _typeParametersOfTheMethod; #endif internal TypeInference(ICollection typeParameters) @@ -5160,24 +5159,24 @@ namespace System.Management.Automation typeParameters.All(t => t.IsGenericParameter), "Caller should verify that typeParameters are really generic type parameters"); #endif - this.typeParameterIndexToSetOfInferenceCandidates = new HashSet[typeParameters.Count]; + _typeParameterIndexToSetOfInferenceCandidates = new HashSet[typeParameters.Count]; #if DEBUG List listOfTypeParameterPositions = typeParameters.Select(t => t.GenericParameterPosition).ToList(); listOfTypeParameterPositions.Sort(); Dbg.Assert( - listOfTypeParameterPositions.Count == listOfTypeParameterPositions.Distinct().Count(), + listOfTypeParameterPositions.Count == listOfTypeParameterPositions.Distinct().Count(), "No type parameters should occupy the same position"); Dbg.Assert( - listOfTypeParameterPositions.All(p => p >= 0), + listOfTypeParameterPositions.All(p => p >= 0), "Type parameter positions should be between 0 and #ofParams"); Dbg.Assert( - listOfTypeParameterPositions.All(p => p < this.typeParameterIndexToSetOfInferenceCandidates.Length), + listOfTypeParameterPositions.All(p => p < _typeParameterIndexToSetOfInferenceCandidates.Length), "Type parameter positions should be between 0 and #ofParams"); - this.typeParametersOfTheMethod = new HashSet(); + _typeParametersOfTheMethod = new HashSet(); foreach (Type t in typeParameters) { - this.typeParametersOfTheMethod.Add(t); + _typeParametersOfTheMethod.Add(t); } #endif } @@ -5187,21 +5186,21 @@ namespace System.Management.Automation #if DEBUG Dbg.Assert(typeParameter != null, "Caller should verify typeParameter != null"); Dbg.Assert( - this.typeParametersOfTheMethod.Contains(typeParameter), + _typeParametersOfTheMethod.Contains(typeParameter), "Caller should verify that typeParameter is actuall a generic type parameter of the method"); #endif ICollection inferenceCandidates = - this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition]; + _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition]; if ((inferenceCandidates != null) && (inferenceCandidates.Any(t => t == typeof(LanguagePrimitives.Null)))) { Type firstValueType = inferenceCandidates.FirstOrDefault(t => t.GetTypeInfo().IsValueType); if (firstValueType != null) { - tracer.WriteLine("Cannot reconcile null and {0} (a value type)", firstValueType); + s_tracer.WriteLine("Cannot reconcile null and {0} (a value type)", firstValueType); inferenceCandidates = null; - this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; + _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } else { @@ -5209,7 +5208,7 @@ namespace System.Management.Automation if (inferenceCandidates.Count == 0) { inferenceCandidates = null; - this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; + _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } } } @@ -5218,7 +5217,7 @@ namespace System.Management.Automation { // "base class" assignability-wise (to account for interfaces) Type commonBaseClass = inferenceCandidates.FirstOrDefault( - potentiallyCommonBaseClass => + potentiallyCommonBaseClass => inferenceCandidates.All( otherCandidate => otherCandidate == potentiallyCommonBaseClass || @@ -5231,15 +5230,15 @@ namespace System.Management.Automation } else { - tracer.WriteLine("Multiple unreconcilable inferences for type parameter {0}", typeParameter); + s_tracer.WriteLine("Multiple unreconcilable inferences for type parameter {0}", typeParameter); inferenceCandidates = null; - this.typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; + _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition] = null; } } if (inferenceCandidates == null) { - tracer.WriteLine("Couldn't infer type parameter {0}", typeParameter); + s_tracer.WriteLine("Couldn't infer type parameter {0}", typeParameter); return null; } else @@ -5256,7 +5255,7 @@ namespace System.Management.Automation if (leftList.Count != rightList.Count) { - tracer.WriteLine("Mismatch in number of parameters and arguments"); + s_tracer.WriteLine("Mismatch in number of parameters and arguments"); return false; } @@ -5264,7 +5263,7 @@ namespace System.Management.Automation { if (!this.Unify(leftList[i], rightList[i])) { - tracer.WriteLine("Couldn't unify {0} with {1}", leftList[i], rightList[i]); + s_tracer.WriteLine("Couldn't unify {0} with {1}", leftList[i], rightList[i]); return false; } } @@ -5284,18 +5283,18 @@ namespace System.Management.Automation { #if DEBUG Dbg.Assert( - this.typeParametersOfTheMethod.Contains(parameterType), + _typeParametersOfTheMethod.Contains(parameterType), "Only uninstantinated generic type parameters encountered in real life, should be the ones coming from the method"); #endif - HashSet inferenceCandidates = this.typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition]; + HashSet inferenceCandidates = _typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition]; if (inferenceCandidates == null) { inferenceCandidates = new HashSet(); - this.typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition] = inferenceCandidates; + _typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition] = inferenceCandidates; } inferenceCandidates.Add(argumentType); - tracer.WriteLine("Inferred {0} => {1}", parameterType, argumentType); + s_tracer.WriteLine("Inferred {0} => {1}", parameterType, argumentType); return true; } @@ -5311,7 +5310,7 @@ namespace System.Management.Automation return this.Unify(parameterType.GetElementType(), argumentType.GetElementType()); } - tracer.WriteLine("Couldn't unify array {0} with {1}", parameterType, argumentType); + s_tracer.WriteLine("Couldn't unify array {0} with {1}", parameterType, argumentType); return false; } @@ -5333,7 +5332,7 @@ namespace System.Management.Automation } else { - tracer.WriteLine("Couldn't unify reference type {0} with {1}", parameterType, argumentType); + s_tracer.WriteLine("Couldn't unify reference type {0} with {1}", parameterType, argumentType); return false; } } @@ -5359,7 +5358,7 @@ namespace System.Management.Automation } Dbg.Assert(false, "Unrecognized kind of type"); - tracer.WriteLine("Unrecognized kind of type: {0}", parameterType); + s_tracer.WriteLine("Unrecognized kind of type: {0}", parameterType); return false; } @@ -5393,7 +5392,7 @@ namespace System.Management.Automation baseType = baseType.GetTypeInfo().BaseType; } - tracer.WriteLine("Attempt to unify different constructed types: {0} and {1}", parameterType, argumentType); + s_tracer.WriteLine("Attempt to unify different constructed types: {0} and {1}", parameterType, argumentType); return false; } diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 3a6b07a77..5d60968c0 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -7,7 +7,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System.Diagnostics.CodeAnalysis; using System.Net; using System.Security; -using SafeString=System.String; +using SafeString = System.String; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -44,7 +44,7 @@ namespace System.Management.Automation /// Default = Generic | Domain } - + /// /// Defines the options available when prompting for credentials. Used /// by PromptForCredential calls. @@ -56,12 +56,12 @@ namespace System.Management.Automation /// Validates the username, but not its existence /// or correctness. /// - Default = ValidateUserNameSyntax, + Default = ValidateUserNameSyntax, /// /// Performs no validation. /// - None = 0, + None = 0, /// /// Validates the username, but not its existence. @@ -88,7 +88,7 @@ namespace System.Management.Automation /// symmetric encryption initialization vector. /// public delegate bool GetSymmetricEncryptionKey(StreamingContext context, out byte[] key, out byte[] iv); - + /// /// Offers a centralized way to manage usernames, passwords, and /// credentials. @@ -103,14 +103,14 @@ namespace System.Management.Automation { get { - return _delegate; + return s_delegate; } set { - _delegate = value; + s_delegate = value; } } - private static GetSymmetricEncryptionKey _delegate = null; + private static GetSymmetricEncryptionKey s_delegate = null; /// /// GetObjectData @@ -129,7 +129,7 @@ namespace System.Management.Automation { byte[] key; byte[] iv; - if (_delegate != null && _delegate(context, out key, out iv)) + if (s_delegate != null && s_delegate(context, out key, out iv)) { safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData; } @@ -161,7 +161,7 @@ namespace System.Management.Automation return; _userName = (string)info.GetValue("UserName", typeof(string)); - + // deserialize to secure string SafeString safePassword = (SafeString)info.GetValue("Password", typeof(SafeString)); if (safePassword == SafeString.Empty) @@ -172,7 +172,7 @@ namespace System.Management.Automation { byte[] key; byte[] iv; - if (_delegate != null && _delegate(context, out key, out iv)) + if (s_delegate != null && s_delegate(context, out key, out iv)) { _password = SecureStringHelper.Decrypt(safePassword, key, iv); } @@ -315,16 +315,16 @@ namespace System.Management.Automation /// public static explicit operator NetworkCredential(PSCredential credential) { - #pragma warning disable 56506 +#pragma warning disable 56506 - if(credential == null) + if (credential == null) { throw PSTraceSource.NewArgumentNullException("credential"); } - return credential.GetNetworkCredential(); + return credential.GetNetworkCredential(); - #pragma warning restore 56506 +#pragma warning restore 56506 } /// @@ -335,11 +335,11 @@ namespace System.Management.Automation { get { - return empty; + return s_empty; } } - private static readonly PSCredential empty = new PSCredential(); + private static readonly PSCredential s_empty = new PSCredential(); /// /// Parse a string that represents a fully qualified username @@ -368,7 +368,7 @@ namespace System.Management.Automation //See bug NTRAID#Windows OS Bugs-1106386-2005/03/25-hiteshr throw PSTraceSource.NewArgumentException("UserName", Credential.InvalidUserNameFormat); } - + return true; } @@ -395,7 +395,7 @@ namespace System.Management.Automation if ((i = input.IndexOf('\\')) >= 0) { - user = input.Substring(i+1); + user = input.Substring(i + 1); domain = input.Substring(0, i); return; } @@ -412,7 +412,7 @@ namespace System.Management.Automation // Username = foo@bar.com, Domain = bar.com // // We need to keep the behaviour in this case. - + i = input.LastIndexOf('@'); if ( @@ -423,12 +423,12 @@ namespace System.Management.Automation ) ) { - domain = input.Substring(i+1); - user = input.Substring(0, i); + domain = input.Substring(i + 1); + user = input.Substring(0, i); } else { - user = input; + user = input; domain = ""; } } diff --git a/src/System.Management.Automation/engine/CultureVariable.cs b/src/System.Management.Automation/engine/CultureVariable.cs index 646226b91..761838057 100644 --- a/src/System.Management.Automation/engine/CultureVariable.cs +++ b/src/System.Management.Automation/engine/CultureVariable.cs @@ -61,5 +61,5 @@ namespace System.Management.Automation return System.Globalization.CultureInfo.CurrentUICulture.Name; } } - } + } } diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index e6f926e2c..6ad0a6c85 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -7,7 +7,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Runtime.InteropServices; using System.Threading; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -23,7 +23,7 @@ namespace System.Management.Automation /// a member of their derived class and use it when /// the provider is invoked. /// - public class PSDriveInfo : IComparable + public class PSDriveInfo : IComparable { /// /// An instance of the PSTraceSource class used for trace output @@ -31,10 +31,10 @@ namespace System.Management.Automation /// This is the same category as the SessionState tracer class. /// [Dbg.TraceSourceAttribute( - "PSDriveInfo", + "PSDriveInfo", "The namespace navigation tracer")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("PSDriveInfo", + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("PSDriveInfo", "The namespace navigation tracer"); /// @@ -44,11 +44,11 @@ namespace System.Management.Automation { get { - return currentWorkingDirectory; + return _currentWorkingDirectory; } set { - currentWorkingDirectory = value; + _currentWorkingDirectory = value; } } // CurrentLocation @@ -57,7 +57,7 @@ namespace System.Management.Automation /// The current working directory for the virtual drive /// as a relative path from Root /// - private string currentWorkingDirectory; + private string _currentWorkingDirectory; /// /// Gets the name of the drive @@ -66,14 +66,14 @@ namespace System.Management.Automation { get { - return name; + return _name; } } /// /// The name of the virtual drive /// - private string name; + private string _name; /// /// Gets the name of the provider that root path @@ -83,7 +83,7 @@ namespace System.Management.Automation { get { - return provider; + return _provider; } } @@ -91,7 +91,7 @@ namespace System.Management.Automation /// The provider information for the provider that implements /// the functionality for the drive. /// - private ProviderInfo provider; + private ProviderInfo _provider; /// /// Gets the root path of the drive. @@ -100,11 +100,11 @@ namespace System.Management.Automation { get { - return root; + return _root; } internal set { - root = value; + _root = value; } } @@ -138,21 +138,20 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("path"); } - if (!driveBeingCreated) + if (!_driveBeingCreated) { NotSupportedException e = PSTraceSource.NewNotSupportedException(); throw e; - } - this.root = path; + _root = path; } // SetRoot /// /// The root of the virtual drive /// - private string root; + private string _root; /// /// Gets or sets the description for the drive. @@ -161,19 +160,19 @@ namespace System.Management.Automation { get { - return description; + return _description; } set { - description = value; + _description = value; } } /// /// The description for this virtual drive /// - private string description; + private string _description; /// /// When supported by provider this specifies a maximum drive size. @@ -191,14 +190,14 @@ namespace System.Management.Automation { get { - return credentials; + return _credentials; } } /// /// The user name to use with this drive. /// - private PSCredential credentials = PSCredential.Empty; + private PSCredential _credentials = PSCredential.Empty; /// /// Determines if the root of the drive can @@ -216,7 +215,7 @@ namespace System.Management.Automation { set { - driveBeingCreated = value; + _driveBeingCreated = value; } // set } // DriveBeingCreated @@ -225,7 +224,7 @@ namespace System.Management.Automation /// the drive root to be changed through the SetRoot /// method. /// - private bool driveBeingCreated; + private bool _driveBeingCreated; /// @@ -237,15 +236,15 @@ namespace System.Management.Automation { get { - return isAutoMounted; + return _isAutoMounted; } set { - isAutoMounted = value; + _isAutoMounted = value; } } - private bool isAutoMounted; + private bool _isAutoMounted; /// /// True if the drive was automounted by the system, @@ -256,15 +255,15 @@ namespace System.Management.Automation { get { - return isAutoMountedManuallyRemoved; + return _isAutoMountedManuallyRemoved; } set { - isAutoMountedManuallyRemoved = value; + _isAutoMountedManuallyRemoved = value; } } - private bool isAutoMountedManuallyRemoved; + private bool _isAutoMountedManuallyRemoved; /// /// Gets or sets the Persist Switch parameter. @@ -273,19 +272,19 @@ namespace System.Management.Automation /// internal bool Persist { - get { return persist; } + get { return _persist; } } - private bool persist = false; + private bool _persist = false; /// /// Get or sets the value indicating if the created drive is a network drive. /// internal bool IsNetworkDrive { - get { return isNetworkDrive; } - set { isNetworkDrive = value; } + get { return _isNetworkDrive; } + set { _isNetworkDrive = value; } } - private bool isNetworkDrive = false; + private bool _isNetworkDrive = false; /// /// Gets or sets the UNC path of the drive. This property would be populated only @@ -294,10 +293,10 @@ namespace System.Management.Automation /// public string DisplayRoot { - get { return displayRoot; } - internal set { displayRoot = value; } + get { return _displayRoot; } + internal set { _displayRoot = value; } } - private string displayRoot = null; + private string _displayRoot = null; /// /// Gets or sets if the drive-root relative paths on this drive are separated by a @@ -376,20 +375,20 @@ namespace System.Management.Automation { if (driveInfo == null) { - throw PSTraceSource.NewArgumentNullException ("driveInfo"); + throw PSTraceSource.NewArgumentNullException("driveInfo"); } - this.name = driveInfo.Name; - this.provider = driveInfo.Provider; - this.credentials = driveInfo.Credential; - this.currentWorkingDirectory = driveInfo.CurrentLocation; - this.description = driveInfo.Description; + _name = driveInfo.Name; + _provider = driveInfo.Provider; + _credentials = driveInfo.Credential; + _currentWorkingDirectory = driveInfo.CurrentLocation; + _description = driveInfo.Description; this.MaximumSize = driveInfo.MaximumSize; - this.driveBeingCreated = driveInfo.driveBeingCreated; - this.hidden = driveInfo.hidden; - this.isAutoMounted = driveInfo.isAutoMounted; - this.root = driveInfo.root; - this.persist = driveInfo.Persist; + _driveBeingCreated = driveInfo._driveBeingCreated; + _hidden = driveInfo._hidden; + _isAutoMounted = driveInfo._isAutoMounted; + _root = driveInfo._root; + _persist = driveInfo.Persist; this.Trace(); } @@ -452,23 +451,23 @@ namespace System.Management.Automation // Copy the parameters to the local members - this.name = name; - this.provider = provider; - this.root = root; - this.description = description; + _name = name; + _provider = provider; + _root = root; + _description = description; if (credential != null) { - this.credentials = credential; + _credentials = credential; } // Set the current working directory to the empty // string since it is relative to the root. - this.currentWorkingDirectory = String.Empty; + _currentWorkingDirectory = String.Empty; Dbg.Diagnostics.Assert( - this.currentWorkingDirectory != null, + _currentWorkingDirectory != null, "The currentWorkingDirectory cannot be null"); // Trace out the fields @@ -521,7 +520,7 @@ namespace System.Management.Automation PSCredential credential, string displayRoot) : this(name, provider, root, description, credential) { - this.displayRoot = displayRoot; + _displayRoot = displayRoot; } /// @@ -570,7 +569,7 @@ namespace System.Management.Automation bool persist) : this(name, provider, root, description, credential) { - this.persist = persist; + _persist = persist; } #endregion ctor @@ -601,19 +600,19 @@ namespace System.Management.Automation { get { - return hidden; + return _hidden; } //get set { - hidden = value; + _hidden = value; } // set } // Hidden /// /// Determines if the drive should be hidden from the user. /// - private bool hidden; + private bool _hidden; /// /// Sets the name of the drive to a new name. @@ -641,7 +640,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("newName"); } - name = newName; + _name = newName; } // SetName /// @@ -671,7 +670,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("newProvider"); } - provider = newProvider; + _provider = newProvider; } // SetProvider /// @@ -679,40 +678,40 @@ namespace System.Management.Automation /// internal void Trace() { - tracer.WriteLine( + s_tracer.WriteLine( "A drive was found:"); if (Name != null) { - tracer.WriteLine( - "\tName: {0}", + s_tracer.WriteLine( + "\tName: {0}", Name); } if (Provider != null) { - tracer.WriteLine( - "\tProvider: {0}", + s_tracer.WriteLine( + "\tProvider: {0}", Provider); } if (Root != null) { - tracer.WriteLine( + s_tracer.WriteLine( "\tRoot: {0}", Root); } if (CurrentLocation != null) { - tracer.WriteLine( + s_tracer.WriteLine( "\tCWD: {0}", CurrentLocation); } if (Description != null) { - tracer.WriteLine( + s_tracer.WriteLine( "\tDescription: {0}", Description); } @@ -734,16 +733,16 @@ namespace System.Management.Automation /// public int CompareTo(PSDriveInfo drive) { - #pragma warning disable 56506 +#pragma warning disable 56506 - if(drive == null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } return String.Compare(Name, drive.Name, StringComparison.CurrentCultureIgnoreCase); - #pragma warning restore 56506 +#pragma warning restore 56506 } /// @@ -768,7 +767,7 @@ namespace System.Management.Automation if (drive == null) { - ArgumentException e = + ArgumentException e = PSTraceSource.NewArgumentException( "obj", SessionStateStrings.OnlyAbleToComparePSDriveInfo); @@ -982,9 +981,9 @@ namespace System.Management.Automation /// The result of base.GetHashCode() /// - public override int GetHashCode () + public override int GetHashCode() { - return base.GetHashCode (); + return base.GetHashCode(); } private PSNoteProperty _noteProperty; diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index a8f5c30ab..131e12584 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -7,7 +7,7 @@ using System.Management.Automation.Provider; using System.Reflection; using System.Linq; using System.Threading; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections.Generic; namespace System.Management.Automation @@ -20,7 +20,7 @@ namespace System.Management.Automation /// A cmdlet provider may want to derive from this class to provide their /// own public members to expose to the user or to cache information related to the provider. /// - public class ProviderInfo + public class ProviderInfo { /// /// Gets the System.Type of the class that implements the provider. @@ -29,10 +29,10 @@ namespace System.Management.Automation { get { - return implementingType; + return _implementingType; } } - private Type implementingType; + private Type _implementingType; /// /// Gets the help file path for the provider. @@ -41,15 +41,15 @@ namespace System.Management.Automation { get { - return helpFile; + return _helpFile; } } - private string helpFile = ""; + private string _helpFile = ""; /// /// The instance of session state the provider belongs to. /// - private SessionState sessionState; + private SessionState _sessionState; /// @@ -59,10 +59,10 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private string name; + private string _name; /// /// Gets the full name of the provider including the pssnapin name if available @@ -82,7 +82,7 @@ namespace System.Management.Automation this.PSSnapInName, this.Name); } - + // After converting core snapins to load as modules, the providers will have Module property populated else if (!string.IsNullOrEmpty(this.ModuleName)) { @@ -104,10 +104,10 @@ namespace System.Management.Automation { get { - return pssnapin; + return _pssnapin; } } - private PSSnapInInfo pssnapin; + private PSSnapInInfo _pssnapin; /// /// Gets the pssnapin name that the provider is implemented in. @@ -118,9 +118,9 @@ namespace System.Management.Automation get { string result = null; - if (pssnapin != null) + if (_pssnapin != null) { - result = pssnapin.Name; + result = _pssnapin.Name; } return result; } @@ -150,8 +150,8 @@ namespace System.Management.Automation { get { - if (pssnapin != null) - return pssnapin.Name; + if (_pssnapin != null) + return _pssnapin.Name; if (_module != null) return _module.Name; return String.Empty; @@ -165,12 +165,12 @@ namespace System.Management.Automation { get { return _module; } } - + internal void SetModule(PSModuleInfo module) { _module = module; } - PSModuleInfo _module; + private PSModuleInfo _module; /// /// Gets or sets the description for the provider @@ -179,14 +179,14 @@ namespace System.Management.Automation { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// /// Gets the capabilies that are implemented by the provider. @@ -195,7 +195,7 @@ namespace System.Management.Automation { get { - if (!capabilitiesRead) + if (!_capabilitiesRead) { try { @@ -208,8 +208,8 @@ namespace System.Management.Automation if (cmdletProviderAttributes.Length == 1) { - capabilities = cmdletProviderAttributes[0].ProviderCapabilities; - capabilitiesRead = true; + _capabilities = cmdletProviderAttributes[0].ProviderCapabilities; + _capabilitiesRead = true; } } catch (Exception e) // Catch-all OK, 3rd party callout @@ -218,11 +218,11 @@ namespace System.Management.Automation // Assume no capabilites for now } } - return capabilities; + return _capabilities; } // get } // Capabilities - private ProviderCapabilities capabilities = ProviderCapabilities.None; - private bool capabilitiesRead; + private ProviderCapabilities _capabilities = ProviderCapabilities.None; + private bool _capabilitiesRead; /// /// Gets or sets the home for the provider. @@ -236,15 +236,15 @@ namespace System.Management.Automation { get { - return home; + return _home; } set { - home = value; + _home = value; } } // Home - private string home; + private string _home; /// /// Gets an enumeration of drives that are available for @@ -254,7 +254,7 @@ namespace System.Management.Automation { get { - return sessionState.Drive.GetAllForProvider(FullName); + return _sessionState.Drive.GetAllForProvider(FullName); } // get } // Drives @@ -262,7 +262,7 @@ namespace System.Management.Automation /// A hidden drive for the provider that is used for setting /// the location to a provider-qualified path. /// - private PSDriveInfo hiddenDrive; + private PSDriveInfo _hiddenDrive; /// /// Gets the hidden drive for the provider that is used @@ -273,7 +273,7 @@ namespace System.Management.Automation { get { - return hiddenDrive; + return _hiddenDrive; } // get } // HiddenDrive @@ -310,10 +310,10 @@ namespace System.Management.Automation /// public bool VolumeSeparatedByColon { - get { return volumeSeparatedByColon; } - internal set { volumeSeparatedByColon = value; } + get { return _volumeSeparatedByColon; } + internal set { _volumeSeparatedByColon = value; } } - private bool volumeSeparatedByColon = true; + private bool _volumeSeparatedByColon = true; /// /// Constructs an instance of the class using an existing reference @@ -338,19 +338,19 @@ namespace System.Management.Automation { if (providerInfo == null) { - throw PSTraceSource.NewArgumentNullException ("providerInfo"); + throw PSTraceSource.NewArgumentNullException("providerInfo"); } - this.name = providerInfo.Name; - this.implementingType = providerInfo.ImplementingType; - this.capabilities = providerInfo.capabilities; - this.description = providerInfo.description; - this.hiddenDrive = providerInfo.hiddenDrive; - this.home = providerInfo.home; - this.helpFile = providerInfo.helpFile; - this.pssnapin = providerInfo.pssnapin; - this.sessionState = providerInfo.sessionState; - this.volumeSeparatedByColon = providerInfo.volumeSeparatedByColon; + _name = providerInfo.Name; + _implementingType = providerInfo.ImplementingType; + _capabilities = providerInfo._capabilities; + _description = providerInfo._description; + _hiddenDrive = providerInfo._hiddenDrive; + _home = providerInfo._home; + _helpFile = providerInfo._helpFile; + _pssnapin = providerInfo._pssnapin; + _sessionState = providerInfo._sessionState; + _volumeSeparatedByColon = providerInfo._volumeSeparatedByColon; } /// @@ -391,7 +391,7 @@ namespace System.Management.Automation /// internal ProviderInfo( SessionState sessionState, - Type implementingType, + Type implementingType, string name, string helpFile, PSSnapInInfo psSnapIn) @@ -472,14 +472,14 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - this.sessionState = sessionState; + _sessionState = sessionState; - this.name = name; - this.description = description; - this.home = home; - this.implementingType = implementingType; - this.helpFile = helpFile; - this.pssnapin = psSnapIn; + _name = name; + _description = description; + _home = home; + _implementingType = implementingType; + _helpFile = helpFile; + _pssnapin = psSnapIn; #if SUPPORTS_CMDLETPROVIDER_FILE LoadProviderFromPath(path); @@ -487,7 +487,7 @@ namespace System.Management.Automation // Create the hidden drive. The name doesn't really // matter since we are not adding this drive to a scope. - hiddenDrive = + _hiddenDrive = new PSDriveInfo( this.FullName, this, @@ -495,13 +495,13 @@ namespace System.Management.Automation "", null); - hiddenDrive.Hidden = true; + _hiddenDrive.Hidden = true; // TODO:PSL // this is probably not right here if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows) { - volumeSeparatedByColon = false; + _volumeSeparatedByColon = false; } } @@ -583,7 +583,7 @@ namespace System.Management.Automation if (!String.IsNullOrEmpty(qualifiedProviderName.PSSnapInName)) { // After converting core snapins to load as modules, the providers will have Module property populated - if (!String.Equals(qualifiedProviderName.PSSnapInName, this.PSSnapInName, StringComparison.OrdinalIgnoreCase) && + if (!String.Equals(qualifiedProviderName.PSSnapInName, this.PSSnapInName, StringComparison.OrdinalIgnoreCase) && !String.Equals(qualifiedProviderName.PSSnapInName, this.ModuleName, StringComparison.OrdinalIgnoreCase)) { break; @@ -653,7 +653,7 @@ namespace System.Management.Automation return result; } - + /// /// Creates an instance of the provider /// @@ -763,32 +763,32 @@ namespace System.Management.Automation /// internal void GetOutputTypes(string cmdletname, List listToAppend) { - if (providerOutputType == null) + if (_providerOutputType == null) { - providerOutputType = new Dictionary>(); - foreach (OutputTypeAttribute outputType in implementingType.GetCustomAttributes(false)) + _providerOutputType = new Dictionary>(); + foreach (OutputTypeAttribute outputType in _implementingType.GetCustomAttributes(false)) { if (string.IsNullOrEmpty(outputType.ProviderCmdlet)) { continue; } List l; - if (!providerOutputType.TryGetValue(outputType.ProviderCmdlet, out l)) + if (!_providerOutputType.TryGetValue(outputType.ProviderCmdlet, out l)) { l = new List(); - providerOutputType[outputType.ProviderCmdlet] = l; + _providerOutputType[outputType.ProviderCmdlet] = l; } l.AddRange(outputType.Type); } } List cmdletOutputType = null; - if (providerOutputType.TryGetValue(cmdletname, out cmdletOutputType)) + if (_providerOutputType.TryGetValue(cmdletname, out cmdletOutputType)) { listToAppend.AddRange(cmdletOutputType); } } - private Dictionary> providerOutputType; + private Dictionary> _providerOutputType; private PSNoteProperty _noteProperty; internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) @@ -801,7 +801,6 @@ namespace System.Management.Automation return _noteProperty; } } // class ProviderInfo - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index f84af74c5..fe0712250 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -17,8 +17,7 @@ namespace System.Management.Automation /// internal class DefaultCommandRuntime : ICommandRuntime2 { - - private List output; + private List _output; /// /// Constructs an instance of the default ICommandRuntime object /// that will write objects into the list that was passed. @@ -28,25 +27,25 @@ namespace System.Management.Automation if (outputList == null) throw new System.ArgumentNullException("outputList"); - this.output = outputList; + _output = outputList; } - private PSHost host; + private PSHost _host; /// /// Return the instance of PSHost - null by default. /// public PSHost Host { - set { host = value; } - get { return host; } + set { _host = value; } + get { return _host; } } - #region Write + #region Write /// /// Implementation of WriteDebug - just discards the input. /// /// Text to write - public void WriteDebug(string text) { ; } + public void WriteDebug(string text) {; } /// /// Default implementation of WriteError - if the error record contains @@ -69,7 +68,7 @@ namespace System.Management.Automation /// Object to write public void WriteObject(object sendToPipeline) { - output.Add(sendToPipeline); + _output.Add(sendToPipeline); } /// @@ -87,19 +86,19 @@ namespace System.Management.Automation IEnumerator e = LanguagePrimitives.GetEnumerator(sendToPipeline); if (e == null) { - output.Add(sendToPipeline); + _output.Add(sendToPipeline); } else { while (e.MoveNext()) { - output.Add(e.Current); + _output.Add(e.Current); } } } else { - output.Add(sendToPipeline); + _output.Add(sendToPipeline); } } @@ -107,48 +106,48 @@ namespace System.Management.Automation /// Default implementation - just discards it's arguments /// /// progress record to write. - public void WriteProgress(ProgressRecord progressRecord) { ; } + public void WriteProgress(ProgressRecord progressRecord) {; } /// /// Default implementation - just discards it's arguments /// /// Source ID to write for /// record to write. - public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord) { ; } + public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord) {; } /// /// Default implementation - just discards it's arguments /// /// Text to write. - public void WriteVerbose(string text) { ; } + public void WriteVerbose(string text) {; } /// /// Default implementation - just discards it's arguments /// /// Text to write. - public void WriteWarning(string text) { ; } + public void WriteWarning(string text) {; } /// /// Default implementation - just discards it's arguments /// /// Text to write. - public void WriteCommandDetail(string text) { ; } + public void WriteCommandDetail(string text) {; } /// /// Default implementation - just discards it's arguments /// /// Record to write. - public void WriteInformation(InformationRecord informationRecord) { ; } + public void WriteInformation(InformationRecord informationRecord) {; } - #endregion Write + #endregion Write - #region Should + #region Should /// /// Default implementation - always returns true. /// /// ignored /// true - public bool ShouldProcess( string target ) { return true; } + public bool ShouldProcess(string target) { return true; } /// /// Default implementation - always returns true. @@ -156,7 +155,7 @@ namespace System.Management.Automation /// ignored /// ignored /// true - public bool ShouldProcess( string target, string action ) {return true; } + public bool ShouldProcess(string target, string action) { return true; } /// /// Default implementation - always returns true. @@ -175,7 +174,7 @@ namespace System.Management.Automation /// ignored /// ignored /// true - public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { shouldProcessReason = ShouldProcessReason.None; return true; } + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { shouldProcessReason = ShouldProcessReason.None; return true; } /// /// Default implementation - always returns true. @@ -193,7 +192,7 @@ namespace System.Management.Automation /// ignored /// ignored /// true - public bool ShouldContinue( string query, string caption, ref bool yesToAll, ref bool noToAll ) { return true; } + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) { return true; } /// /// Default implementation - always returns true. @@ -206,33 +205,33 @@ namespace System.Management.Automation /// true public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) { return true; } - #endregion Should + #endregion Should - #region Transaction Support - /// - /// Returns true if a transaction is available and active. - /// - public bool TransactionAvailable() { return false; } + #region Transaction Support + /// + /// Returns true if a transaction is available and active. + /// + public bool TransactionAvailable() { return false; } - /// - /// Gets an object that surfaces the current PowerShell transaction. - /// When this object is disposed, PowerShell resets the active transaction - /// - public PSTransactionContext CurrentPSTransaction - { - get + /// + /// Gets an object that surfaces the current PowerShell transaction. + /// When this object is disposed, PowerShell resets the active transaction + /// + public PSTransactionContext CurrentPSTransaction { - string error = TransactionStrings.CmdletRequiresUseTx; + get + { + string error = TransactionStrings.CmdletRequiresUseTx; - // We want to throw in this situation, and want to use a - // property because it mimics the C# using(TransactionScope ...) syntax - #pragma warning suppress 56503 - throw new InvalidOperationException(error); + // We want to throw in this situation, and want to use a + // property because it mimics the C# using(TransactionScope ...) syntax +#pragma warning suppress 56503 + throw new InvalidOperationException(error); + } } - } - #endregion Transaction Support + #endregion Transaction Support - #region Misc + #region Misc /// /// Implementation of the dummy default ThrowTerminatingError API - it just /// does what the base implementation does anyway - rethrow the exception @@ -250,6 +249,6 @@ namespace System.Management.Automation throw new System.InvalidOperationException(errorRecord.ToString()); } } - #endregion + #endregion } } diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index d092d2c93..3fd0d3e3b 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -1,12 +1,13 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -48,7 +49,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // DriveManagementIntrinsics internal #endregion Constructors @@ -68,10 +69,10 @@ namespace System.Management.Automation get { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.CurrentDrive; + return _sessionState.CurrentDrive; } // get } // Current @@ -124,12 +125,12 @@ namespace System.Management.Automation public PSDriveInfo New(PSDriveInfo drive, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewDrive(drive, scope); + return _sessionState.NewDrive(drive, scope); } // New /// @@ -182,17 +183,17 @@ namespace System.Management.Automation /// /// internal void New( - PSDriveInfo drive, - string scope, + PSDriveInfo drive, + string scope, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.NewDrive(drive, scope, context); + _sessionState.NewDrive(drive, scope, context); } // New /// @@ -222,16 +223,16 @@ namespace System.Management.Automation /// /// internal object NewDriveDynamicParameters( - string providerId, + string providerId, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewDriveDynamicParameters(providerId, context); + return _sessionState.NewDriveDynamicParameters(providerId, context); } // NewDriveDynamicParameters #endregion New @@ -259,12 +260,12 @@ namespace System.Management.Automation public void Remove(string driveName, bool force, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveDrive(driveName, force, scope); + _sessionState.RemoveDrive(driveName, force, scope); } // Remove /// @@ -291,24 +292,24 @@ namespace System.Management.Automation /// /// internal void Remove( - string driveName, + string driveName, bool force, - string scope, + string scope, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveDrive(driveName, force, scope, context); + _sessionState.RemoveDrive(driveName, force, scope, context); } // RemoveDrive #endregion Remove #region Get - + /// /// Gets the drive information for the drive specified by name. /// @@ -331,12 +332,12 @@ namespace System.Management.Automation public PSDriveInfo Get(string driveName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetDrive(driveName); + return _sessionState.GetDrive(driveName); } // GetDrive /// @@ -374,12 +375,12 @@ namespace System.Management.Automation public PSDriveInfo GetAtScope(string driveName, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetDrive(driveName, scope); + return _sessionState.GetDrive(driveName, scope); } // GetAtScope /// @@ -388,12 +389,12 @@ namespace System.Management.Automation public Collection GetAll() { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.Drives(null); + return _sessionState.Drives(null); } // GetAll - + /// /// Retrieves all the drives in the specified scope /// @@ -415,10 +416,10 @@ namespace System.Management.Automation public Collection GetAllAtScope(string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.Drives(scope); + return _sessionState.Drives(scope); } // GetAllAtScope /// @@ -435,12 +436,12 @@ namespace System.Management.Automation public Collection GetAllForProvider(string providerName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetDrivesForProvider(providerName); + return _sessionState.GetDrivesForProvider(providerName); } // GetAllForProvider #endregion GetDrive @@ -450,7 +451,7 @@ namespace System.Management.Automation #region private data // A private reference to the internal session state of the engine. - private SessionStateInternal sessionState; + private SessionStateInternal _sessionState; #endregion private data } // DriveIntrinsics diff --git a/src/System.Management.Automation/engine/DriveNames.cs b/src/System.Management.Automation/engine/DriveNames.cs index f7840f863..b25441387 100644 --- a/src/System.Management.Automation/engine/DriveNames.cs +++ b/src/System.Management.Automation/engine/DriveNames.cs @@ -11,7 +11,7 @@ namespace System.Management.Automation /// default providers /// /// - internal static class DriveNames + internal static class DriveNames { /// /// The default VariableProvider drive name @@ -32,6 +32,5 @@ namespace System.Management.Automation /// The default FunctionProvider drive name /// internal const string FunctionDrive = "Function"; - } } diff --git a/src/System.Management.Automation/engine/DscResourceInfo.cs b/src/System.Management.Automation/engine/DscResourceInfo.cs index 57d0cfa7e..c0adcae8b 100644 --- a/src/System.Management.Automation/engine/DscResourceInfo.cs +++ b/src/System.Management.Automation/engine/DscResourceInfo.cs @@ -1,5 +1,4 @@ //----------------------------------------------------------------------- -// // Copyright (C) 2013 Microsoft Corporation // //----------------------------------------------------------------------- @@ -41,7 +40,7 @@ namespace System.Management.Automation /// /// Contains a DSC resource information /// - public class DscResourceInfo + public class DscResourceInfo { /// /// Initializes a new instance of the DscResourceInfo class @@ -51,15 +50,15 @@ namespace System.Management.Automation /// Path of the DscResource. /// ParentPath of the DscResource. /// The execution context for the DscResource. - internal DscResourceInfo(string name, string friendlyName, string path, string parentPath, ExecutionContext context) + internal DscResourceInfo(string name, string friendlyName, string path, string parentPath, ExecutionContext context) { - this.Name = name; + this.Name = name; this.FriendlyName = friendlyName; this.Path = path; this.ParentPath = parentPath; - this.Properties = new ReadOnlyCollection(new List()); + this.Properties = new ReadOnlyCollection(new List()); } - + /// /// Name of the DSC Resource. /// @@ -110,15 +109,15 @@ namespace System.Management.Automation /// Updated properties public void UpdateProperties(IList properties) { - if(properties != null) + if (properties != null) this.Properties = new ReadOnlyCollection(properties); } /// /// Module in which the DscResource is implemented in. /// - public PSModuleInfo Module { get ; internal set; } - + public PSModuleInfo Module { get; internal set; } + /// /// Gets the help file path for the cmdlet. /// @@ -126,15 +125,14 @@ namespace System.Management.Automation { get { - return helpFilePath; + return _helpFilePath; } internal set { - helpFilePath = value; + _helpFilePath = value; } } // HelpFile - private string helpFilePath = String.Empty; - + private string _helpFilePath = String.Empty; } @@ -173,7 +171,7 @@ namespace System.Management.Automation internal void UpdateValues(IList values) { - if(values != null) + if (values != null) this.Values = new ReadOnlyCollection(values); } } diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index 572cc85e4..822cec98d 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -23,8 +23,8 @@ namespace System.Management.Automation Diagnostics.Assert(context != null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(resourceName), "caller to verify commandName is valid"); - this._resourceName = resourceName; - this._context = context; + _resourceName = resourceName; + _context = context; } #region private properties @@ -32,8 +32,8 @@ namespace System.Management.Automation private string _resourceName = null; private ExecutionContext _context = null; private DscResourceInfo _currentMatch = null; - private IEnumerator matchingResource = null; - private Collection matchingResourceList = null; + private IEnumerator _matchingResource = null; + private Collection _matchingResourceList = null; #endregion @@ -45,7 +45,7 @@ namespace System.Management.Automation public void Reset() { _currentMatch = null; - matchingResource = null; + _matchingResource = null; } /// @@ -128,11 +128,11 @@ namespace System.Management.Automation WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase); - if (matchingResourceList == null) + if (_matchingResourceList == null) { Collection psObjs = ps.Invoke(); - matchingResourceList = new Collection(); + _matchingResourceList = new Collection(); bool matchFound = false; @@ -145,14 +145,14 @@ namespace System.Management.Automation if (resourceMatcher.IsMatch(resourceName)) { DscResourceInfo resourceInfo = new DscResourceInfo(resourceName, - resource.ResourceType, + resource.ResourceType, resource.Path, resource.ParentPath, _context ); - - resourceInfo.FriendlyName = resource.FriendlyName; + + resourceInfo.FriendlyName = resource.FriendlyName; resourceInfo.CompanyName = resource.CompanyName; @@ -160,7 +160,7 @@ namespace System.Management.Automation if (psMod != null) resourceInfo.Module = psMod; - + if (resource.ImplementedAs != null) { ImplementedAsType impType; @@ -186,8 +186,8 @@ namespace System.Management.Automation resourceInfo.UpdateProperties(propertyList); } - - matchingResourceList.Add(resourceInfo); + + _matchingResourceList.Add(resourceInfo); matchFound = true; } //if @@ -195,24 +195,23 @@ namespace System.Management.Automation }// foreach if (matchFound) - matchingResource = matchingResourceList.GetEnumerator(); + _matchingResource = _matchingResourceList.GetEnumerator(); else return returnValue; }//if - if (!matchingResource.MoveNext()) + if (!_matchingResource.MoveNext()) { - matchingResource = null; + _matchingResource = null; } else { - returnValue = matchingResource.Current; + returnValue = _matchingResource.Current; } return returnValue; } #endregion - } } diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index 4f6f7e13d..9157896fe 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Host; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -23,7 +24,7 @@ namespace System.Management.Automation Dbg.Diagnostics.Assert( false, "This constructor should never be called. Only the constructor that takes an instance of ExecutionContext should be called."); - } + } /// /// The internal constructor for this object. It should be the only one that gets called. @@ -44,9 +45,9 @@ namespace System.Management.Automation throw new ArgumentNullException("context"); } - this._context = context; - this._host = context.EngineHostInterface; - } + _context = context; + _host = context.EngineHostInterface; + } #endregion Constructors diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 1d92d3b5a..e624061bc 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -15,7 +15,7 @@ namespace System.Management.Automation /// Takes as input a collection of strings and builds an expression tree from the input. /// At the evaluation stage, it walks down the tree and evaluates the result. /// - public sealed class FlagsExpression where T: struct, IConvertible + public sealed class FlagsExpression where T : struct, IConvertible { #region Constructors @@ -93,7 +93,7 @@ namespace System.Management.Automation Debug.Assert(tokenList.Count > 0, "Input must not all be white characters."); - CheckSyntaxError(tokenList); + CheckSyntaxError(tokenList); _root = ConstructExpressionTree(tokenList); } @@ -336,8 +336,8 @@ namespace System.Management.Automation // allow for negative enum value input (though it's not recommended practice for flags attribute) else { - long valueToCheck = (long) LanguagePrimitives.ConvertTo(val, typeof (long), CultureInfo.InvariantCulture); - long operandValue = (long) LanguagePrimitives.ConvertTo(_operandValue, typeof (long), CultureInfo.InvariantCulture); + long valueToCheck = (long)LanguagePrimitives.ConvertTo(val, typeof(long), CultureInfo.InvariantCulture); + long operandValue = (long)LanguagePrimitives.ConvertTo(_operandValue, typeof(long), CultureInfo.InvariantCulture); satisfy = (operandValue == (valueToCheck & operandValue)); } return satisfy; @@ -411,7 +411,7 @@ namespace System.Management.Automation object val = LanguagePrimitives.ConvertTo(value, _underType, CultureInfo.InvariantCulture); return _root.Eval(val); } - + #endregion #region internal methods @@ -535,11 +535,11 @@ namespace System.Management.Automation string result = sb.ToString().Trim(); // If resulting identifier is enclosed in paired quotes, // remove the only the first pair of quotes from the string - if (result.Length >= 2 && - ((result[0] == '\'' && result[result.Length-1] == '\'') || - (result[0] == '\"' && result[result.Length-1] == '\"'))) + if (result.Length >= 2 && + ((result[0] == '\'' && result[result.Length - 1] == '\'') || + (result[0] == '\"' && result[result.Length - 1] == '\"'))) { - result = result.Substring(1, result.Length-2); + result = result.Substring(1, result.Length - 2); } result = result.Trim(); @@ -548,7 +548,7 @@ namespace System.Management.Automation if (String.IsNullOrWhiteSpace(result)) { throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException), - null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString, + null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString, EnumMinimumDisambiguation.EnumAllValues(typeof(T))); } else if (result[0] == '(') @@ -700,6 +700,5 @@ namespace System.Management.Automation } #endregion - } } diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 19acc2a9d..21a0c8314 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -29,7 +30,7 @@ namespace System.Management.Automation // Add special minimum disambiguation cases here for certain enum types. // The current implementation assumes that special names in each type can be // differentiated by their first letter. - specialDisambiguateCases.Add( + s_specialDisambiguateCases.Add( typeof(System.IO.FileAttributes), new string[] { "Directory", "ReadOnly", "System" }); } @@ -44,7 +45,7 @@ namespace System.Management.Automation { // Get all enum names in the given enum type string[] enumNames = Enum.GetNames(enumType); - + // Get all names that matches the given prefix. List namesWithMatchingPrefix = new List(); foreach (string name in enumNames) @@ -79,7 +80,7 @@ namespace System.Management.Automation } // test for special cases match string[] minDisambiguateNames; - if (specialDisambiguateCases.TryGetValue(enumType, out minDisambiguateNames)) + if (s_specialDisambiguateCases.TryGetValue(enumType, out minDisambiguateNames)) { foreach (string tName in minDisambiguateNames) { @@ -125,6 +126,6 @@ namespace System.Management.Automation return returnValue.ToString(); } - static private Dictionary specialDisambiguateCases = new Dictionary(); + static private Dictionary s_specialDisambiguateCases = new Dictionary(); } } diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index b93356738..343e35e99 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -13,7 +13,7 @@ using System.Text; using System.Resources; using System.Runtime.Serialization; using System.Reflection; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Language; #if CORECLR @@ -220,10 +220,10 @@ namespace System.Management.Automation public class ErrorCategoryInfo { #region ctor - internal ErrorCategoryInfo (ErrorRecord errorRecord) + internal ErrorCategoryInfo(ErrorRecord errorRecord) { if (null == errorRecord) - throw new ArgumentNullException ("errorRecord"); + throw new ArgumentNullException("errorRecord"); _errorRecord = errorRecord; } #endregion ctor @@ -367,7 +367,7 @@ namespace System.Management.Automation _errorRecord._targetTypeOverride = value; } } - + #endregion Properties #region Methods @@ -508,7 +508,7 @@ namespace System.Management.Automation } string first = original.Substring(0, 15); string last = original.Substring(original.Length - 15, 15); - return + return string.Format(uiCultureInfo, ErrorPackage.Ellipsize, first, last); } #endregion Private @@ -531,7 +531,7 @@ namespace System.Management.Automation /// [Serializable] public class ErrorDetails : ISerializable - { + { #region Constructor /// /// Creates an instance of ErrorDetails specifying a Message. @@ -595,7 +595,7 @@ namespace System.Management.Automation string resourceId, params object[] args) { - _message = BuildMessage (cmdlet, baseName, resourceId, args); + _message = BuildMessage(cmdlet, baseName, resourceId, args); } /// /// Creates an instance of ErrorDetails specifying a Message. @@ -648,7 +648,7 @@ namespace System.Management.Automation string resourceId, params object[] args) { - _message = BuildMessage (resourceSupplier, baseName, resourceId, args); + _message = BuildMessage(resourceSupplier, baseName, resourceId, args); } /// /// Creates an instance of ErrorDetails specifying a Message. @@ -689,12 +689,12 @@ namespace System.Management.Automation string resourceId, params object[] args) { - _message = BuildMessage (assembly, baseName, resourceId, args); + _message = BuildMessage(assembly, baseName, resourceId, args); } #endregion UseResourceId // deep-copy constructor - internal ErrorDetails (ErrorDetails errorDetails) + internal ErrorDetails(ErrorDetails errorDetails) { _message = errorDetails._message; _recommendedAction = errorDetails._recommendedAction; @@ -713,8 +713,8 @@ namespace System.Management.Automation protected ErrorDetails(SerializationInfo info, StreamingContext context) { - _message = info.GetString ("ErrorDetails_Message"); - _recommendedAction = info.GetString ( + _message = info.GetString("ErrorDetails_Message"); + _recommendedAction = info.GetString( "ErrorDetails_RecommendedAction"); } @@ -758,7 +758,7 @@ namespace System.Management.Automation /// public string Message { - get { return ErrorRecord.NotNull (_message); } + get { return ErrorRecord.NotNull(_message); } } private string _message = ""; @@ -774,7 +774,7 @@ namespace System.Management.Automation /// public string RecommendedAction { - get { return ErrorRecord.NotNull (_recommendedAction); } + get { return ErrorRecord.NotNull(_recommendedAction); } set { _recommendedAction = value; @@ -967,7 +967,6 @@ namespace System.Management.Automation private ErrorRecord() { - } /// @@ -998,7 +997,7 @@ namespace System.Management.Automation object targetObject) { if (null == exception) - throw PSTraceSource.NewArgumentNullException ("exception"); + throw PSTraceSource.NewArgumentNullException("exception"); if (errorId == null) errorId = ""; @@ -1068,7 +1067,7 @@ namespace System.Management.Automation #endregion Serialization - + #region Remoting /// @@ -1188,21 +1187,21 @@ namespace System.Management.Automation private void ToPSObjectForRemoting(PSObject dest, bool serializeExtInfo) { - RemotingEncoder.AddNoteProperty(dest, "Exception", delegate() { return Exception; }); - RemotingEncoder.AddNoteProperty(dest, "TargetObject", delegate() { return TargetObject; }); - RemotingEncoder.AddNoteProperty(dest, "FullyQualifiedErrorId", delegate() { return FullyQualifiedErrorId; }); - RemotingEncoder.AddNoteProperty(dest, "InvocationInfo", delegate() { return InvocationInfo; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Category", delegate() { return (int)CategoryInfo.Category; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Activity", delegate() { return CategoryInfo.Activity; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Reason", delegate() { return CategoryInfo.Reason; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_TargetName", delegate() { return CategoryInfo.TargetName; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_TargetType", delegate() { return CategoryInfo.TargetType; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Message", delegate() { return CategoryInfo.GetMessage(CultureInfo.CurrentCulture); }); + RemotingEncoder.AddNoteProperty(dest, "Exception", delegate () { return Exception; }); + RemotingEncoder.AddNoteProperty(dest, "TargetObject", delegate () { return TargetObject; }); + RemotingEncoder.AddNoteProperty(dest, "FullyQualifiedErrorId", delegate () { return FullyQualifiedErrorId; }); + RemotingEncoder.AddNoteProperty(dest, "InvocationInfo", delegate () { return InvocationInfo; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Category", delegate () { return (int)CategoryInfo.Category; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Activity", delegate () { return CategoryInfo.Activity; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Reason", delegate () { return CategoryInfo.Reason; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_TargetName", delegate () { return CategoryInfo.TargetName; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_TargetType", delegate () { return CategoryInfo.TargetType; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Message", delegate () { return CategoryInfo.GetMessage(CultureInfo.CurrentCulture); }); if (ErrorDetails != null) { - RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_Message", delegate() { return ErrorDetails.Message; }); - RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_RecommendedAction", delegate() { return ErrorDetails.RecommendedAction; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_Message", delegate () { return ErrorDetails.Message; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_RecommendedAction", delegate () { return ErrorDetails.RecommendedAction; }); } if (!serializeExtInfo || this.InvocationInfo == null) @@ -1213,12 +1212,12 @@ namespace System.Management.Automation { RemotingEncoder.AddNoteProperty(dest, "SerializeExtendedInfo", () => true); this.InvocationInfo.ToPSObjectForRemoting(dest); - RemotingEncoder.AddNoteProperty(dest, "PipelineIterationInfo", delegate() { return PipelineIterationInfo; }); + RemotingEncoder.AddNoteProperty(dest, "PipelineIterationInfo", delegate () { return PipelineIterationInfo; }); } if (!string.IsNullOrEmpty(this.ScriptStackTrace)) { - RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_ScriptStackTrace", delegate() { return this.ScriptStackTrace; }); + RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_ScriptStackTrace", delegate () { return this.ScriptStackTrace; }); } } @@ -1253,7 +1252,7 @@ namespace System.Management.Automation return null; } } - + /// /// Create an ErrorRecord object from serialized ErrorRecord. /// serializedErrorRecord PSObject is in the format returned @@ -1323,8 +1322,8 @@ namespace System.Management.Automation //Get InvocationInfo (optional property) PSObject invocationInfo = Microsoft.PowerShell.DeserializingTypeConverter.GetPropertyValue( - serializedErrorRecord, - "InvocationInfo", + serializedErrorRecord, + "InvocationInfo", Microsoft.PowerShell.DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk); //Get Error Detail (these note properties are optional, so can't right now use RemotingDecoder...) @@ -1360,16 +1359,16 @@ namespace System.Management.Automation // // Get the InvocationInfo // - serializeExtendedInfo = RemotingDecoder.GetPropertyValue(serializedErrorRecord, "SerializeExtendedInfo"); + _serializeExtendedInfo = RemotingDecoder.GetPropertyValue(serializedErrorRecord, "SerializeExtendedInfo"); - if (serializeExtendedInfo) + if (_serializeExtendedInfo) { _invocationInfo = new InvocationInfo(serializedErrorRecord); ArrayList iterationInfo = RemotingDecoder.GetPropertyValue(serializedErrorRecord, "PipelineIterationInfo"); if (null != iterationInfo) { - pipelineIterationInfo = new ReadOnlyCollection((int[])iterationInfo.ToArray(typeof(Int32))); + _pipelineIterationInfo = new ReadOnlyCollection((int[])iterationInfo.ToArray(typeof(Int32))); } } else @@ -1379,7 +1378,7 @@ namespace System.Management.Automation } #endregion Remoting - + /// /// Copy constructor, for use when a new wrapper exception wraps an /// exception which already has an ErrorRecord @@ -1395,7 +1394,7 @@ namespace System.Management.Automation { if (errorRecord == null) { - throw new PSArgumentNullException("errorRecord"); + throw new PSArgumentNullException("errorRecord"); } if (null != replaceParentContainsErrorRecordException @@ -1415,7 +1414,7 @@ namespace System.Management.Automation _targetNameOverride = errorRecord._targetNameOverride; _targetTypeOverride = errorRecord._targetTypeOverride; if (null != errorRecord.ErrorDetails) - _errorDetails = new ErrorDetails (errorRecord.ErrorDetails); + _errorDetails = new ErrorDetails(errorRecord.ErrorDetails); SetInvocationInfo(errorRecord._invocationInfo); _scriptStackTrace = errorRecord._scriptStackTrace; _serializedFullyQualifiedErrorId = errorRecord._serializedFullyQualifiedErrorId; @@ -1451,7 +1450,7 @@ namespace System.Management.Automation { get { - Diagnostics.Assert (null != _error, "_error is null"); + Diagnostics.Assert(null != _error, "_error is null"); return _error; } } @@ -1479,9 +1478,10 @@ namespace System.Management.Automation /// never null public ErrorCategoryInfo CategoryInfo { - get { + get + { if (null == _categoryInfo) - _categoryInfo = new ErrorCategoryInfo (this); + _categoryInfo = new ErrorCategoryInfo(this); return _categoryInfo; } } @@ -1501,16 +1501,16 @@ namespace System.Management.Automation public string FullyQualifiedErrorId { get - { + { if (_serializedFullyQualifiedErrorId != null) return _serializedFullyQualifiedErrorId; - - string typeName = GetInvocationTypeName (); + + string typeName = GetInvocationTypeName(); string delimiter = - ( String.IsNullOrEmpty (typeName) - || String.IsNullOrEmpty (_errorId)) + (String.IsNullOrEmpty(typeName) + || String.IsNullOrEmpty(_errorId)) ? "" : ","; - return NotNull (_errorId) + delimiter + NotNull (typeName); + return NotNull(_errorId) + delimiter + NotNull(typeName); } } @@ -1541,7 +1541,7 @@ namespace System.Management.Automation } private InvocationInfo _invocationInfo /* = null */; - internal void SetInvocationInfo (InvocationInfo invocationInfo) + internal void SetInvocationInfo(InvocationInfo invocationInfo) { // Save the DisplayScriptPosition, if set IScriptExtent savedDisplayScriptPosition = null; @@ -1549,7 +1549,7 @@ namespace System.Management.Automation { savedDisplayScriptPosition = _invocationInfo.DisplayScriptPosition; } - + // Assign the invocationInfo if (invocationInfo != null) { @@ -1568,7 +1568,7 @@ namespace System.Management.Automation { _invocationInfo.DisplayScriptPosition = savedDisplayScriptPosition; } - + LockScriptStackTrace(); // @@ -1578,17 +1578,17 @@ namespace System.Management.Automation { int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone(); - this.pipelineIterationInfo = new ReadOnlyCollection(snapshot); + _pipelineIterationInfo = new ReadOnlyCollection(snapshot); } } // 2005/07/14-913791 "write-error output is confusing and misleading" internal bool PreserveInvocationInfoOnce { - get { return preserveInvocationInfoOnce; } - set { preserveInvocationInfoOnce = value; } + get { return _preserveInvocationInfoOnce; } + set { _preserveInvocationInfoOnce = value; } } - private bool preserveInvocationInfoOnce /* = false */; + private bool _preserveInvocationInfoOnce /* = false */; /// /// The script stack trace for the error. @@ -1633,10 +1633,10 @@ namespace System.Management.Automation { get { - return this.pipelineIterationInfo; + return _pipelineIterationInfo; } } - private ReadOnlyCollection pipelineIterationInfo = Utils.EmptyReadOnlyCollection(); + private ReadOnlyCollection _pipelineIterationInfo = Utils.EmptyReadOnlyCollection(); /// /// Whether to serizalize the InvocationInfo during remote calls @@ -1645,14 +1645,14 @@ namespace System.Management.Automation { get { - return this.serializeExtendedInfo; + return _serializeExtendedInfo; } set { - this.serializeExtendedInfo = value; + _serializeExtendedInfo = value; } } - private bool serializeExtendedInfo = false; + private bool _serializeExtendedInfo = false; #endregion Public Properties @@ -1667,12 +1667,12 @@ namespace System.Management.Automation internal string _targetTypeOverride; #endregion Exposed by ErrorCategoryInfo - internal static string NotNull (string s) + internal static string NotNull(string s) { return (null != s) ? s : ""; } - private string GetInvocationTypeName () + private string GetInvocationTypeName() { InvocationInfo invocationInfo = this.InvocationInfo; if (null == invocationInfo) @@ -1698,20 +1698,20 @@ namespace System.Management.Automation /// developer-readable identifier public override string ToString() { - if ( null != ErrorDetails - && !String.IsNullOrEmpty (ErrorDetails.Message)) + if (null != ErrorDetails + && !String.IsNullOrEmpty(ErrorDetails.Message)) { return ErrorDetails.Message; } if (null != Exception) { - if (!String.IsNullOrEmpty (Exception.Message)) + if (!String.IsNullOrEmpty(Exception.Message)) { return Exception.Message; } return Exception.ToString(); } - return base.ToString (); + return base.ToString(); } #endregion ToString @@ -1835,8 +1835,8 @@ namespace System.Management.Automation /// the base resource name /// the resource id /// the error message template string corresponding to baseName and resourceId - string GetResourceString (string baseName, string resourceId); + string GetResourceString(string baseName, string resourceId); } } // namespace System.Management.Automation - #pragma warning restore 56506 +#pragma warning restore 56506 diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 1412b6d62..615298a48 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -28,14 +28,14 @@ namespace System.Management.Automation public abstract class PSEventManager { /// Sequential event ID - private int nextEventId = 1; + private int _nextEventId = 1; /// /// Returns a sequential event ID /// protected int GetNextEventId() { - return this.nextEventId++; + return _nextEventId++; } /// @@ -43,9 +43,9 @@ namespace System.Management.Automation /// public PSEventArgsCollection ReceivedEvents { - get { return receivedEvents; } + get { return _receivedEvents; } } - private PSEventArgsCollection receivedEvents = new PSEventArgsCollection(); + private PSEventArgsCollection _receivedEvents = new PSEventArgsCollection(); /// /// Gets the list of event subscribers. @@ -114,7 +114,7 @@ namespace System.Management.Automation /// Wait for the event and associated action to be processed and completed. /// /// - public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData, + public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData, bool processInCurrentThread, bool waitForCompletionInCurrentThread) { PSEventArgs newEvent = CreateEvent(sourceIdentifier, sender, args, extraData); @@ -137,7 +137,7 @@ namespace System.Management.Automation /// /// Processes new events (which have either been generated by this instance or forwarded to it) /// - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "InCurrent")] + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "InCurrent")] protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool processInCurrentThread, bool waitForCompletionWhenInCurrentThread) { @@ -212,7 +212,7 @@ namespace System.Management.Automation /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount); - + /// /// Subscribes to an event on an object. /// @@ -320,7 +320,7 @@ namespace System.Management.Automation { return SubscribeEvent(source, eventName, sourceIdentifier, data, handlerDelegate, supportEvent, forwardEvent, maxTriggerCount); } - + /// /// Unsubscribes from an event on an object. @@ -340,34 +340,33 @@ namespace System.Management.Automation /// /// Implementation of the PSEventManager for local runspaces. /// - internal class PSLocalEventManager : PSEventManager, IDisposable + internal class PSLocalEventManager : PSEventManager, IDisposable { - /// /// Creates a new instance of the PSEventManager class. /// internal PSLocalEventManager(ExecutionContext context) { - eventSubscribers = new Dictionary(); - engineEventSubscribers = new Dictionary>(StringComparer.OrdinalIgnoreCase); - actionQueue = new Queue(); - this.context = context; + _eventSubscribers = new Dictionary(); + _engineEventSubscribers = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _actionQueue = new Queue(); + _context = context; } - private Dictionary eventSubscribers; - private Dictionary> engineEventSubscribers; - private Queue actionQueue; - private ExecutionContext context; - private int nextSubscriptionId = 1; - private double throttleLimit = 1; - private int throttleChecks = 0; + private Dictionary _eventSubscribers; + private Dictionary> _engineEventSubscribers; + private Queue _actionQueue; + private ExecutionContext _context; + private int _nextSubscriptionId = 1; + private double _throttleLimit = 1; + private int _throttleChecks = 0; // The assembly and module to hold our event registrations - AssemblyBuilder eventAssembly = null; - ModuleBuilder eventModule = null; - int typeId = 0; + private AssemblyBuilder _eventAssembly = null; + private ModuleBuilder _eventModule = null; + private int _typeId = 0; #if !CORECLR - bool debugMode = false; + private bool debugMode = false; #endif /// @@ -375,18 +374,18 @@ namespace System.Management.Automation /// public override List Subscribers { - get + get { List subscribers = new List(); - lock (eventSubscribers) + lock (_eventSubscribers) { - foreach (PSEventSubscriber currentSubscriber in eventSubscribers.Keys) + foreach (PSEventSubscriber currentSubscriber in _eventSubscribers.Keys) { subscribers.Add(currentSubscriber); } } - + return subscribers; } } @@ -455,7 +454,7 @@ namespace System.Management.Automation public override PSEventSubscriber SubscribeEvent(Object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) { // Record this subscriber. This may just be a registration for engine events. - PSEventSubscriber subscriber = new PSEventSubscriber(context, nextSubscriptionId++, source, eventName, sourceIdentifier, action, supportEvent, forwardEvent, maxTriggerCount); + PSEventSubscriber subscriber = new PSEventSubscriber(_context, _nextSubscriptionId++, source, eventName, sourceIdentifier, action, supportEvent, forwardEvent, maxTriggerCount); ProcessNewSubscriber(subscriber, source, eventName, sourceIdentifier, data, supportEvent, forwardEvent); subscriber.RegisterJob(); @@ -576,7 +575,7 @@ namespace System.Management.Automation public override PSEventSubscriber SubscribeEvent(Object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) { // Record this subscriber. This may just be a registration for engine events. - PSEventSubscriber subscriber = new PSEventSubscriber(context, nextSubscriptionId++, source, eventName, sourceIdentifier, handlerDelegate, supportEvent, forwardEvent, maxTriggerCount); + PSEventSubscriber subscriber = new PSEventSubscriber(_context, _nextSubscriptionId++, source, eventName, sourceIdentifier, handlerDelegate, supportEvent, forwardEvent, maxTriggerCount); ProcessNewSubscriber(subscriber, source, eventName, sourceIdentifier, data, supportEvent, forwardEvent); subscriber.RegisterJob(); @@ -607,7 +606,7 @@ namespace System.Management.Automation /// private void OnElapsedEvent(object source) { - var localRunspace = context.CurrentRunspace as LocalRunspace; + var localRunspace = _context.CurrentRunspace as LocalRunspace; if (localRunspace == null) { @@ -628,10 +627,10 @@ namespace System.Management.Automation if (_consecutiveIdleSamples == 4) { _consecutiveIdleSamples = 0; - lock (engineEventSubscribers) + lock (_engineEventSubscribers) { List subscribers = null; - if (engineEventSubscribers.TryGetValue(PSEngineEvent.OnIdle, out subscribers) && subscribers.Count > 0) + if (_engineEventSubscribers.TryGetValue(PSEngineEvent.OnIdle, out subscribers) && subscribers.Count > 0) { // We send out on-idle event and keep enabling the timer only if there still are subscribers to the on-idle event GenerateEvent(PSEngineEvent.OnIdle, null, new object[] { }, null, false, false); @@ -675,28 +674,28 @@ namespace System.Management.Automation #endregion OnIdleProcessing - static Dictionary GeneratedEventHandlers = new Dictionary(); + private static Dictionary s_generatedEventHandlers = new Dictionary(); private void ProcessNewSubscriber(PSEventSubscriber subscriber, Object source, string eventName, string sourceIdentifier, PSObject data, bool supportEvent, bool forwardEvent) { Delegate handlerDelegate = null; - if (eventAssembly == null) + if (_eventAssembly == null) { #if !CORECLR // Define the assembly that will hold our event handlers StackFrame callStack = new StackFrame(0, true); debugMode = (callStack.GetFileName() != null); #endif - eventAssembly = AssemblyBuilder.DefineDynamicAssembly( + _eventAssembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("PSEventHandler"), AssemblyBuilderAccess.Run); } - if (eventModule == null) + if (_eventModule == null) { #if CORECLR - eventModule = eventAssembly.DefineDynamicModule("PSGenericEventModule"); + _eventModule = _eventAssembly.DefineDynamicModule("PSGenericEventModule"); #else - eventModule = eventAssembly.DefineDynamicModule("PSGenericEventModule", debugMode); + _eventModule = _eventAssembly.DefineDynamicModule("PSGenericEventModule", debugMode); #endif } @@ -769,7 +768,7 @@ namespace System.Management.Automation #endif // Get its invoke method, and register ourselves as a handler MethodInfo invokeMethod = eventInfo.EventHandlerType.GetMethod("Invoke"); - + // We don't support non-void delegates, as the user has no way // to influence the result. In the .NET Framework, the only // events that return values are for extremely advanced scenarios: @@ -784,16 +783,16 @@ namespace System.Management.Automation // Cache generated event handlers (by type and event name) so that they don't bloat our // working set by recompiling event handlers for the same event. - + string eventHandlerKey = source.GetType().FullName + "|" + eventName; Type handlerType; - - lock(GeneratedEventHandlers) + + lock (s_generatedEventHandlers) { - if (!GeneratedEventHandlers.TryGetValue(eventHandlerKey, out handlerType)) + if (!s_generatedEventHandlers.TryGetValue(eventHandlerKey, out handlerType)) { handlerType = GenerateEventHandler(invokeMethod); - GeneratedEventHandlers[eventHandlerKey] = handlerType; + s_generatedEventHandlers[eventHandlerKey] = handlerType; } } @@ -815,15 +814,15 @@ namespace System.Management.Automation } } - lock (eventSubscribers) + lock (_eventSubscribers) { - eventSubscribers[subscriber] = handlerDelegate; + _eventSubscribers[subscriber] = handlerDelegate; if (engineEventSourceIdentifier == null) { return; } - lock (engineEventSubscribers) + lock (_engineEventSubscribers) { if (isOnIdleEvent && !_timerInitialized) { @@ -832,10 +831,10 @@ namespace System.Management.Automation } List subscribers = null; - if (!engineEventSubscribers.TryGetValue(engineEventSourceIdentifier, out subscribers)) + if (!_engineEventSubscribers.TryGetValue(engineEventSourceIdentifier, out subscribers)) { subscribers = new List(); - engineEventSubscribers.Add(engineEventSourceIdentifier, subscribers); + _engineEventSubscribers.Add(engineEventSourceIdentifier, subscribers); } subscribers.Add(subscriber); @@ -862,7 +861,7 @@ namespace System.Management.Automation { UnsubscribeEvent(subscriber, false); } - + /// /// Unsubscribes from an event on an object. @@ -882,9 +881,9 @@ namespace System.Management.Automation } Delegate existingSubscriber = null; - lock(eventSubscribers) + lock (_eventSubscribers) { - if (subscriber.IsBeingUnsubscribed || !eventSubscribers.TryGetValue(subscriber, out existingSubscriber)) + if (subscriber.IsBeingUnsubscribed || !_eventSubscribers.TryGetValue(subscriber, out existingSubscriber)) { // Already unsubscribed by another thread or the subscriber doesn't exist return; @@ -897,16 +896,16 @@ namespace System.Management.Automation // Fire the unregistration handler subscriber.OnPSEventUnsubscribed(subscriber.SourceObject, new PSEventUnsubscribedEventArgs(subscriber)); - + EventInfo eventInfo = null; - + Type sourceType = subscriber.SourceObject as Type; if (sourceType == null) sourceType = subscriber.SourceObject.GetType(); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(subscriber.EventName, bindingFlags); - + if ((eventInfo != null) && (existingSubscriber != null)) { eventInfo.RemoveEventHandler(subscriber.SourceObject, existingSubscriber); @@ -927,14 +926,14 @@ namespace System.Management.Automation subscriber.Action.NotifyJobStopped(); } - lock (eventSubscribers) + lock (_eventSubscribers) { - eventSubscribers.Remove(subscriber); + _eventSubscribers.Remove(subscriber); if (PSEngineEvent.EngineEvents.Contains(subscriber.SourceIdentifier)) { - lock (engineEventSubscribers) + lock (_engineEventSubscribers) { - engineEventSubscribers[subscriber.SourceIdentifier].Remove(subscriber); + _engineEventSubscribers[subscriber.SourceIdentifier].Remove(subscriber); } } } @@ -958,7 +957,7 @@ namespace System.Management.Automation /// protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { - return new PSEventArgs(null, this.context.CurrentRunspace.InstanceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); + return new PSEventArgs(null, _context.CurrentRunspace.InstanceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); } /// @@ -983,7 +982,7 @@ namespace System.Management.Automation /// Processes new events (which have either been generated by this instance or forwarded to it) /// protected internal override void ProcessNewEvent(PSEventArgs newEvent, - bool processInCurrentThread, + bool processInCurrentThread, bool waitForCompletionWhenInCurrentThread) { if (processInCurrentThread) @@ -1014,7 +1013,7 @@ namespace System.Management.Automation else { ThreadPool.QueueUserWorkItem(new WaitCallback( - delegate(object unused) + delegate (object unused) { ProcessNewEventImplementation(newEvent, false); })); @@ -1094,11 +1093,11 @@ namespace System.Management.Automation // This mutex will get set after the event is processed. action.Args.EventProcessed = new ManualResetEventSlim(); } - lock (((System.Collections.ICollection)actionQueue).SyncRoot) + lock (((System.Collections.ICollection)_actionQueue).SyncRoot) { // If the engine isn't active, pulse the pipeline. // When the engine starts up, it will pick up the pending events - actionQueue.Enqueue(action); + _actionQueue.Enqueue(action); } PulseEngine(); @@ -1113,7 +1112,7 @@ namespace System.Management.Automation { try { - ((LocalRunspace)context.CurrentRunspace).Pulse(); + ((LocalRunspace)_context.CurrentRunspace).Pulse(); } catch (ObjectDisposedException) { } @@ -1132,7 +1131,7 @@ namespace System.Management.Automation // We do this check quickly outside of the lock so that the // main-line scenario is as fast as possible. Also, do the real work // in a different method so that this method could be inlined. - if (actionQueue.Count == 0) + if (_actionQueue.Count == 0) return; ProcessPendingActionsImpl(); @@ -1146,29 +1145,29 @@ namespace System.Management.Automation try { - lock (actionProcessingLock) + lock (_actionProcessingLock) { if (IsExecutingEventAction) return; int processed = 0; - throttleChecks++; + _throttleChecks++; EventAction nextAction; - while ((throttleLimit * throttleChecks) >= processed) + while ((_throttleLimit * _throttleChecks) >= processed) { // Now, check for (and process) pending actions. // Lock the collection so that it doesn't change from // beneath us. - lock (((System.Collections.ICollection)actionQueue).SyncRoot) + lock (((System.Collections.ICollection)_actionQueue).SyncRoot) { - int queueCount = actionQueue.Count; + int queueCount = _actionQueue.Count; // Exit if the actions have already been processed if (queueCount == 0) return; - nextAction = actionQueue.Dequeue(); + nextAction = _actionQueue.Dequeue(); } bool addActionBackToActionQueue = false; @@ -1182,12 +1181,12 @@ namespace System.Management.Automation } if (processed > 0) - throttleChecks = 0; + _throttleChecks = 0; } } finally { - if (actionQueue.Count > 0) + if (_actionQueue.Count > 0) { // If we still have work remaining, sleep a bit (to give // other pipelines a chance to interrupt,) and try again. @@ -1196,7 +1195,7 @@ namespace System.Management.Automation // teardown event. That can result in starvation of // foreground threads that also want to use the runspace. ThreadPool.QueueUserWorkItem(new WaitCallback( - delegate(object unused) + delegate (object unused) { System.Threading.Thread.Sleep(100); this.PulseEngine(); @@ -1227,8 +1226,8 @@ namespace System.Management.Automation } } - private object actionProcessingLock = new Object(); - private EventAction processingAction = null; + private object _actionProcessingLock = new Object(); + private EventAction _processingAction = null; /// /// Drain any pending actions for a given subscriber. @@ -1240,16 +1239,16 @@ namespace System.Management.Automation { // We do this check quickly outside of the lock so that the // main-line scenario is as fast as possible. - if (actionQueue.Count == 0) + if (_actionQueue.Count == 0) return; // Now, process pending actions - lock (actionProcessingLock) + lock (_actionProcessingLock) { - lock (((System.Collections.ICollection)actionQueue).SyncRoot) + lock (((System.Collections.ICollection)_actionQueue).SyncRoot) { - int queueCount = actionQueue.Count; - + int queueCount = _actionQueue.Count; + // Exit if the actions have already been processed if (queueCount == 0) return; @@ -1258,14 +1257,14 @@ namespace System.Management.Automation do { - EventAction[] pendingActions = actionQueue.ToArray(); - actionQueue.Clear(); + EventAction[] pendingActions = _actionQueue.ToArray(); + _actionQueue.Clear(); foreach (EventAction pendingAction in pendingActions) { // Make sure an event action can unregister itself. if ((pendingAction.Sender == subscriber) && - (pendingAction != processingAction)) + (pendingAction != _processingAction)) { while (IsExecutingEventAction) System.Threading.Thread.Sleep(100); @@ -1280,10 +1279,9 @@ namespace System.Management.Automation } else { - actionQueue.Enqueue(pendingAction); + _actionQueue.Enqueue(pendingAction); } } - } while (needToScanAgain); } } @@ -1291,26 +1289,26 @@ namespace System.Management.Automation private void InvokeAction(EventAction nextAction, out bool addActionBack) { - lock (actionProcessingLock) + lock (_actionProcessingLock) { - processingAction = nextAction; + _processingAction = nextAction; addActionBack = false; // Invoke the action in its own session state - SessionStateInternal oldSessionState = context.EngineSessionState; + SessionStateInternal oldSessionState = _context.EngineSessionState; if (nextAction.Sender.Action != null) { - context.EngineSessionState = nextAction.Sender.Action.ScriptBlock.SessionStateInternal; + _context.EngineSessionState = nextAction.Sender.Action.ScriptBlock.SessionStateInternal; } Runspace oldDefault = Runspace.DefaultRunspace; - + try { // Set the engine's session state to be // the session state of the action. Also update the default runspace that the // scriptblock will execute under, so that scriptblocks will stay in the same // runspace they were invoked from. - Runspace.DefaultRunspace = context.CurrentRunspace; + Runspace.DefaultRunspace = _context.CurrentRunspace; if (nextAction.Sender.Action != null) { nextAction.Sender.Action.Invoke(nextAction.Sender, nextAction.Args); @@ -1344,8 +1342,8 @@ namespace System.Management.Automation eventProcessed.Set(); } Runspace.DefaultRunspace = oldDefault; - context.EngineSessionState = oldSessionState; - processingAction = null; + _context.EngineSessionState = oldSessionState; + _processingAction = null; } } } @@ -1353,7 +1351,7 @@ namespace System.Management.Automation internal bool IsExecutingEventAction { - get { return (processingAction != null); } + get { return (_processingAction != null); } } /// @@ -1377,9 +1375,9 @@ namespace System.Management.Automation List returnedSubscribers = new List(); List subscribersToBeRemoved = new List(); - lock (eventSubscribers) + lock (_eventSubscribers) { - foreach (PSEventSubscriber currentSubscriber in eventSubscribers.Keys) + foreach (PSEventSubscriber currentSubscriber in _eventSubscribers.Keys) { bool takeActionForEvent = false; if (String.Equals(currentSubscriber.SourceIdentifier, sourceIdentifier, StringComparison.OrdinalIgnoreCase)) @@ -1447,18 +1445,18 @@ namespace System.Management.Automation // Get the filename to associate with the debug symbols ISymbolDocumentWriter doc = null; - if(debugMode) + if (debugMode) { - doc = eventModule.DefineDocument(callStack.GetFileName(), Guid.Empty, Guid.Empty, Guid.Empty); + doc = _eventModule.DefineDocument(callStack.GetFileName(), Guid.Empty, Guid.Empty, Guid.Empty); } #endif // Define the type that will respond to the event. It // derives from PSEventHandler so that complex // functionality can go into its base class. TypeBuilder eventType = - eventModule.DefineType("PSEventHandler_" + typeId, TypeAttributes.Public, typeof(PSEventHandler)); - typeId++; - + _eventModule.DefineType("PSEventHandler_" + _typeId, TypeAttributes.Public, typeof(PSEventHandler)); + _typeId++; + // Retrieve the existing constructor ConstructorInfo existingConstructor = typeof(PSEventHandler).GetConstructor( @@ -1472,17 +1470,17 @@ namespace System.Management.Automation ConstructorInfo debugAttributeCtor = debugAttributeType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) }); CustomAttributeBuilder debugAttributeBuilder = new CustomAttributeBuilder(debugAttributeCtor, - new object[] { - DebuggableAttribute.DebuggingModes.DisableOptimizations | - DebuggableAttribute.DebuggingModes.Default + new object[] { + DebuggableAttribute.DebuggingModes.DisableOptimizations | + DebuggableAttribute.DebuggingModes.Default }); - eventAssembly.SetCustomAttribute(debugAttributeBuilder); + _eventAssembly.SetCustomAttribute(debugAttributeBuilder); } #endif // Define the new constructor // public TestEventHandler(PSEventManager eventManager, Object sender, string sourceIdentifier, PSObject extraData) // : base(eventManager, sender, sourceIdentifier, extraData) - ConstructorBuilder eventConstructor = + ConstructorBuilder eventConstructor = eventType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(PSEventManager), typeof(Object), typeof(string), typeof(PSObject) }); ILGenerator extendedConstructor = eventConstructor.GetILGenerator(); @@ -1497,19 +1495,19 @@ namespace System.Management.Automation // Go through each of the parameters in the event signature, and store their types Type[] parameterTypes = new Type[parameterCount]; int parameterCounter = 0; - foreach(ParameterInfo parameter in invokeSignature.GetParameters()) + foreach (ParameterInfo parameter in invokeSignature.GetParameters()) { parameterTypes[parameterCounter] = parameter.ParameterType; parameterCounter++; } // public void EventDelegate(Object sender, FileSystemEventArgs e) - MethodBuilder eventMethod = eventType.DefineMethod("EventDelegate", + MethodBuilder eventMethod = eventType.DefineMethod("EventDelegate", MethodAttributes.Public, CallingConventions.Standard, invokeSignature.ReturnType, parameterTypes); // Create new parameters that mimic the parameters of the event method parameterCounter = 1; - foreach(ParameterInfo parameter in invokeSignature.GetParameters()) + foreach (ParameterInfo parameter in invokeSignature.GetParameters()) { ParameterBuilder builder = eventMethod.DefineParameter( parameterCounter, parameter.Attributes, parameter.Name); @@ -1550,7 +1548,7 @@ namespace System.Management.Automation methodContents.Emit(OpCodes.Ldloc_0); methodContents.Emit(OpCodes.Ldc_I4, counter - 1); methodContents.Emit(OpCodes.Ldarg, counter); - + // Box the value type if necessary if (parameterTypes[counter - 1].GetTypeInfo().IsValueType) { @@ -1564,19 +1562,19 @@ namespace System.Management.Automation methodContents.Emit(OpCodes.Ldarg_0); // Load the "eventManager" private field, and push it onto the stack - FieldInfo eventManagerField = typeof(PSEventHandler).GetField("eventManager", - BindingFlags.NonPublic | BindingFlags.Instance ); + FieldInfo eventManagerField = typeof(PSEventHandler).GetField("eventManager", + BindingFlags.NonPublic | BindingFlags.Instance); methodContents.Emit(OpCodes.Ldfld, eventManagerField); // Then the "sourceIdentifier" private field methodContents.Emit(OpCodes.Ldarg_0); - FieldInfo identifierField = typeof(PSEventHandler).GetField("sourceIdentifier", + FieldInfo identifierField = typeof(PSEventHandler).GetField("sourceIdentifier", BindingFlags.NonPublic | BindingFlags.Instance); methodContents.Emit(OpCodes.Ldfld, identifierField); // Then the "sender" private field methodContents.Emit(OpCodes.Ldarg_0); - FieldInfo senderField = typeof(PSEventHandler).GetField("sender", + FieldInfo senderField = typeof(PSEventHandler).GetField("sender", BindingFlags.NonPublic | BindingFlags.Instance); methodContents.Emit(OpCodes.Ldfld, senderField); @@ -1658,16 +1656,16 @@ namespace System.Management.Automation /// public void Dispose(bool disposing) { - if(disposing) + if (disposing) { - lock (eventSubscribers) + lock (_eventSubscribers) { if (_timer != null) { _timer.Dispose(); } - foreach (PSEventSubscriber currentSubscriber in eventSubscribers.Keys.ToArray()) + foreach (PSEventSubscriber currentSubscriber in _eventSubscribers.Keys.ToArray()) { UnsubscribeEvent(currentSubscriber); } @@ -1682,10 +1680,10 @@ namespace System.Management.Automation internal class PSRemoteEventManager : PSEventManager { /// Computer on which the event was generated - private string computerName; + private string _computerName; /// Runspace on which the event was generated - private Guid runspaceId; + private Guid _runspaceId; /// /// Creates an event manager for the given runspace @@ -1694,14 +1692,15 @@ namespace System.Management.Automation /// Runspace on which the event was generated internal PSRemoteEventManager(string computerName, Guid runspaceId) { - this.computerName = computerName; - this.runspaceId = runspaceId; + _computerName = computerName; + _runspaceId = runspaceId; } /// /// Gets the list of event subscribers. /// - public override List Subscribers { + public override List Subscribers + { get { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); @@ -1727,7 +1726,7 @@ namespace System.Management.Automation protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { // note that this is a local call, so we use null for the computer name - return new PSEventArgs(null, this.runspaceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); + return new PSEventArgs(null, _runspaceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); } /// @@ -1743,8 +1742,8 @@ namespace System.Management.Automation // want to override this value since we want to preserve the original computer. if (forwardedEvent.ComputerName == null || forwardedEvent.ComputerName.Length == 0) { - forwardedEvent.ComputerName = this.computerName; - forwardedEvent.RunspaceId = this.runspaceId; + forwardedEvent.ComputerName = _computerName; + forwardedEvent.RunspaceId = _runspaceId; } ProcessNewEvent(forwardedEvent, false); @@ -1920,7 +1919,7 @@ namespace System.Management.Automation { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); } - + /// /// Unsubscribes from an event on an object. /// @@ -1990,7 +1989,7 @@ namespace System.Management.Automation /// /// A HashSet that contains all engine event names /// - internal readonly static HashSet EngineEvents = new HashSet(StringComparer.OrdinalIgnoreCase) { Exiting, OnIdle, OnScriptBlockInvoke}; + internal readonly static HashSet EngineEvents = new HashSet(StringComparer.OrdinalIgnoreCase) { Exiting, OnIdle, OnScriptBlockInvoke }; } @@ -2006,14 +2005,14 @@ namespace System.Management.Automation internal PSEventSubscriber(ExecutionContext context, int id, Object source, string eventName, string sourceIdentifier, bool supportEvent, bool forwardEvent, int maxTriggerCount) { - this.context = context; + _context = context; - this.subscriptionId = id; - this.sourceObject = source; - this.eventName = eventName; - this.sourceIdentifier = sourceIdentifier; - this.supportEvent = supportEvent; - this.forwardEvent = forwardEvent; + _subscriptionId = id; + _sourceObject = source; + _eventName = eventName; + _sourceIdentifier = sourceIdentifier; + _supportEvent = supportEvent; + _forwardEvent = forwardEvent; IsBeingUnsubscribed = false; RemainingActionsToProcess = 0; @@ -2039,22 +2038,22 @@ namespace System.Management.Automation this(context, id, source, eventName, sourceIdentifier, supportEvent, forwardEvent, maxTriggerCount) { // Create the bound scriptblock, and job. - if(action != null) + if (action != null) { ScriptBlock newAction = CreateBoundScriptBlock(action); - this.action = new PSEventJob(context.Events, this, newAction, sourceIdentifier); + _action = new PSEventJob(context.Events, this, newAction, sourceIdentifier); } } - + internal void RegisterJob() { // And this event subscriber to the job repository if it's not a support event. - if (!supportEvent) + if (!_supportEvent) { if (this.Action != null) { - JobRepository jobRepository = ((LocalRunspace)context.CurrentRunspace).JobRepository; - jobRepository.Add(this.action); + JobRepository jobRepository = ((LocalRunspace)_context.CurrentRunspace).JobRepository; + jobRepository.Add(_action); } } } @@ -2067,17 +2066,17 @@ namespace System.Management.Automation string eventName, string sourceIdentifier, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) : this(context, id, source, eventName, sourceIdentifier, supportEvent, forwardEvent, maxTriggerCount) { - this.handlerDelegate = handlerDelegate; + _handlerDelegate = handlerDelegate; } - - private ExecutionContext context; + + private ExecutionContext _context; /// /// Create a bound script block /// private ScriptBlock CreateBoundScriptBlock(ScriptBlock scriptAction) { - ScriptBlock newAction = context.Modules.CreateBoundScriptBlock(context, scriptAction, true); + ScriptBlock newAction = _context.Modules.CreateBoundScriptBlock(_context, scriptAction, true); // Create a new Error variable so that it doesn't pollute the global errors. PSVariable errorVariable = new PSVariable("script:Error", new ArrayList(), ScopedItemOptions.Constant); @@ -2095,60 +2094,60 @@ namespace System.Management.Automation { get { - return subscriptionId; + return _subscriptionId; } set { - subscriptionId = value; + _subscriptionId = value; } } - private int subscriptionId; + private int _subscriptionId; /// /// The object to which this event subscription applies /// public Object SourceObject { - get { return sourceObject; } + get { return _sourceObject; } } - private Object sourceObject; + private Object _sourceObject; /// /// The event object to which this event subscription applies /// public string EventName { - get { return eventName; } + get { return _eventName; } } - private string eventName; + private string _eventName; /// /// The identifier that identifies the source of these events /// public string SourceIdentifier { - get { return sourceIdentifier; } + get { return _sourceIdentifier; } } - private string sourceIdentifier; + private string _sourceIdentifier; /// /// The action invoked when this event arrives /// public PSEventJob Action { - get { return action; } + get { return _action; } } - private PSEventJob action; + private PSEventJob _action; /// /// The delegate invoked when this event arrives /// public PSEventReceivedEventHandler HandlerDelegate { - get { return handlerDelegate; } + get { return _handlerDelegate; } } - private PSEventReceivedEventHandler handlerDelegate = null; - + private PSEventReceivedEventHandler _handlerDelegate = null; + /// /// Get the flag that marks this event as a supporting event @@ -2157,35 +2156,35 @@ namespace System.Management.Automation { get { - return supportEvent; + return _supportEvent; } } - private bool supportEvent; + private bool _supportEvent; /// /// Gets whether to forward the event to the PowerShell client during a remote execution /// public bool ForwardEvent { - get { return forwardEvent; } + get { return _forwardEvent; } } - private bool forwardEvent; + private bool _forwardEvent; /// /// Gets whether the event should be processed in the pipeline execution thread. /// internal bool ShouldProcessInExecutionThread { - get { return shouldProcessInExecutionThread; } - set { shouldProcessInExecutionThread = value; } + get { return _shouldProcessInExecutionThread; } + set { _shouldProcessInExecutionThread = value; } } - private bool shouldProcessInExecutionThread; + private bool _shouldProcessInExecutionThread; /// /// Gets whether the event should be unregistered /// internal bool AutoUnregister { get; private set; } - + /// /// Indicate how many new should be added to the action queue. /// e.g. NumberOfTimesToBeInvoked = 3 means that this subscriber only responses to @@ -2210,7 +2209,7 @@ namespace System.Management.Automation /// The event generated when this event subscriber is unregistered /// public event PSEventUnsubscribedEventHandler Unsubscribed; - + #region IComparable Members /// @@ -2221,7 +2220,7 @@ namespace System.Management.Automation /// public bool Equals(PSEventSubscriber other) { - if(other == null) + if (other == null) { return false; } @@ -2319,11 +2318,11 @@ namespace System.Management.Automation /// public class ForwardedEventArgs : EventArgs { - private PSObject serializedRemoteEventArgs; + private PSObject _serializedRemoteEventArgs; internal ForwardedEventArgs(PSObject serializedRemoteEventArgs) { - this.serializedRemoteEventArgs = serializedRemoteEventArgs; + _serializedRemoteEventArgs = serializedRemoteEventArgs; } /// @@ -2333,7 +2332,7 @@ namespace System.Management.Automation { get { - return this.serializedRemoteEventArgs; + return _serializedRemoteEventArgs; } } @@ -2405,27 +2404,27 @@ namespace System.Management.Automation EventArgs sourceEventArgs = argument as EventArgs; if (sourceEventArgs != null) { - this.sourceEventArgs = sourceEventArgs; + _sourceEventArgs = sourceEventArgs; break; } if (ForwardedEventArgs.IsRemoteSourceEventArgs(argument)) { - this.sourceEventArgs = new ForwardedEventArgs((PSObject)argument); + _sourceEventArgs = new ForwardedEventArgs((PSObject)argument); break; } } } - this.computerName = computerName; - this.runspaceId = runspaceId; - this.eventIdentifier = eventIdentifier; - this.sender = sender; - this.sourceArgs = originalArgs; - this.sourceIdentifier = sourceIdentifier; - this.timeGenerated = DateTime.Now; - this.data = additionalData; - this.forwardEvent = false; + _computerName = computerName; + _runspaceId = runspaceId; + _eventIdentifier = eventIdentifier; + _sender = sender; + _sourceArgs = originalArgs; + _sourceIdentifier = sourceIdentifier; + _timeGenerated = DateTime.Now; + _data = additionalData; + _forwardEvent = false; } /// @@ -2433,10 +2432,10 @@ namespace System.Management.Automation /// public string ComputerName { - get { return computerName; } - internal set { computerName = value; } + get { return _computerName; } + internal set { _computerName = value; } } - private string computerName; + private string _computerName; /// /// Gets the unique identifier of this event @@ -2444,29 +2443,29 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public Guid RunspaceId { - get { return runspaceId; } - internal set { runspaceId = value; } + get { return _runspaceId; } + internal set { _runspaceId = value; } } - private Guid runspaceId; + private Guid _runspaceId; /// /// Gets the unique identifier of this event /// public int EventIdentifier { - get { return eventIdentifier; } - internal set { eventIdentifier = value; } + get { return _eventIdentifier; } + internal set { _eventIdentifier = value; } } - private int eventIdentifier; + private int _eventIdentifier; /// /// Gets the object that generated this event /// public Object Sender { - get { return sender; } + get { return _sender; } } - private Object sender; + private Object _sender; /// /// Gets the first argument from the original event source that @@ -2474,9 +2473,9 @@ namespace System.Management.Automation /// public EventArgs SourceEventArgs { - get { return sourceEventArgs; } + get { return _sourceEventArgs; } } - private EventArgs sourceEventArgs; + private EventArgs _sourceEventArgs; /// /// Gets the list of arguments captured by the original event source @@ -2484,57 +2483,57 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Object[] SourceArgs { - get { return sourceArgs; } + get { return _sourceArgs; } } - private Object[] sourceArgs; + private Object[] _sourceArgs; /// /// Gets the identifier associated with the source of this event /// public String SourceIdentifier { - get { return sourceIdentifier; } + get { return _sourceIdentifier; } } - private String sourceIdentifier; + private String _sourceIdentifier; /// /// Gets the time and date that this event was generated /// public DateTime TimeGenerated { - get { return timeGenerated; } - internal set { timeGenerated = value; } // internal setter using during deserialization + get { return _timeGenerated; } + internal set { _timeGenerated = value; } // internal setter using during deserialization } - private DateTime timeGenerated; + private DateTime _timeGenerated; /// /// Gets the additional user data associated with this event /// public PSObject MessageData { - get { return data; } + get { return _data; } } - private PSObject data; + private PSObject _data; /// /// Gets whether to forward the event to the PowerShell client during a remote execution /// - internal bool ForwardEvent + internal bool ForwardEvent { - get { return forwardEvent; } - set { forwardEvent = value; } + get { return _forwardEvent; } + set { _forwardEvent = value; } } - private bool forwardEvent; + private bool _forwardEvent; /// /// When processing synchronous events, this mutex is set so we know when we can safely return. /// internal ManualResetEventSlim EventProcessed { - get { return eventProcessed; } - set { eventProcessed = value; } + get { return _eventProcessed; } + set { _eventProcessed = value; } } - private ManualResetEventSlim eventProcessed; + private ManualResetEventSlim _eventProcessed; } /// @@ -2558,7 +2557,7 @@ namespace System.Management.Automation /// internal PSEventUnsubscribedEventArgs(PSEventSubscriber eventSubscriber) { - this.eventSubscriber = eventSubscriber; + _eventSubscriber = eventSubscriber; } /// @@ -2566,10 +2565,10 @@ namespace System.Management.Automation /// public PSEventSubscriber EventSubscriber { - get { return eventSubscriber; } - internal set { eventSubscriber = value; } + get { return _eventSubscriber; } + internal set { _eventSubscriber = value; } } - private PSEventSubscriber eventSubscriber; + private PSEventSubscriber _eventSubscriber; } /// @@ -2577,7 +2576,7 @@ namespace System.Management.Automation /// public delegate void PSEventUnsubscribedEventHandler(Object sender, PSEventUnsubscribedEventArgs e); - + /// /// This class contains the collection of events received by the /// execution context. @@ -2588,8 +2587,8 @@ namespace System.Management.Automation /// The event generated when a new event is received /// public event PSEventReceivedEventHandler PSEventReceived; - private List eventCollection = new List(); - private object syncRoot = new object(); + private List _eventCollection = new List(); + private object _syncRoot = new object(); /// /// Add add an event to the collection @@ -2601,12 +2600,12 @@ namespace System.Management.Automation /// Don't add events to the collection directly; use the EventManager instead internal void Add(PSEventArgs eventToAdd) { - if(eventToAdd == null) + if (eventToAdd == null) { throw new ArgumentNullException("eventToAdd"); } - eventCollection.Add(eventToAdd); + _eventCollection.Add(eventToAdd); OnPSEventReceived(eventToAdd.Sender, eventToAdd); } @@ -2618,7 +2617,7 @@ namespace System.Management.Automation { get { - return eventCollection.Count; + return _eventCollection.Count; } } @@ -2627,7 +2626,7 @@ namespace System.Management.Automation /// public void RemoveAt(int index) { - eventCollection.RemoveAt(index); + _eventCollection.RemoveAt(index); } /// @@ -2637,7 +2636,7 @@ namespace System.Management.Automation { get { - return eventCollection[index]; + return _eventCollection[index]; } } @@ -2655,7 +2654,7 @@ namespace System.Management.Automation /// public IEnumerator GetEnumerator() { - return eventCollection.GetEnumerator(); + return _eventCollection.GetEnumerator(); } /// @@ -2663,7 +2662,7 @@ namespace System.Management.Automation /// System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { - return eventCollection.GetEnumerator(); + return _eventCollection.GetEnumerator(); } /// @@ -2671,7 +2670,7 @@ namespace System.Management.Automation /// public object SyncRoot { - get { return syncRoot; } + get { return _syncRoot; } } } @@ -2680,12 +2679,12 @@ namespace System.Management.Automation /// This is to support the arguments to script blocks that we invoke automatically /// as a response to some events /// - class EventAction + internal class EventAction { public EventAction(PSEventSubscriber sender, PSEventArgs args) { - this.sender = sender; - this.args = args; + _sender = sender; + _args = args; } /// @@ -2693,18 +2692,18 @@ namespace System.Management.Automation /// public PSEventSubscriber Sender { - get { return sender; } + get { return _sender; } } - private PSEventSubscriber sender; + private PSEventSubscriber _sender; /// /// Get the arguments of this event (the event that was fired) /// public PSEventArgs Args { - get { return args; } + get { return _args; } } - private PSEventArgs args; + private PSEventArgs _args; } /// @@ -2731,27 +2730,27 @@ namespace System.Management.Automation public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) : base(action == null ? null : action.ToString(), name) { - if(eventManager == null) + if (eventManager == null) throw new ArgumentNullException("eventManager"); - if(subscriber == null) + if (subscriber == null) throw new ArgumentNullException("subscriber"); UsesResultsCollection = true; - this.action = action; - this.eventManager = eventManager; - this.subscriber = subscriber; + _action = action; + _eventManager = eventManager; + _subscriber = subscriber; } - PSEventManager eventManager = null; - PSEventSubscriber subscriber = null; - int highestErrorIndex = 0; + private PSEventManager _eventManager = null; + private PSEventSubscriber _subscriber = null; + private int _highestErrorIndex = 0; /// /// Gets dynamic module where the action is invoked /// public PSModuleInfo Module { - get { return action.Module; } + get { return _action.Module; } } /// @@ -2759,7 +2758,7 @@ namespace System.Management.Automation /// public override void StopJob() { - eventManager.UnsubscribeEvent(subscriber); + _eventManager.UnsubscribeEvent(_subscriber); } /// @@ -2769,10 +2768,10 @@ namespace System.Management.Automation { get { - return statusMessage; + return _statusMessage; } } - private string statusMessage = null; + private string _statusMessage = null; /// /// indicates if more data is available @@ -2784,10 +2783,10 @@ namespace System.Management.Automation { get { - return moreData; + return _moreData; } } - private bool moreData = false; + private bool _moreData = false; /// @@ -2795,7 +2794,7 @@ namespace System.Management.Automation /// public override string Location { - get + get { return null; } @@ -2806,9 +2805,9 @@ namespace System.Management.Automation /// internal ScriptBlock ScriptBlock { - get { return action; } + get { return _action; } } - private ScriptBlock action; + private ScriptBlock _action; /// /// Invoke the script block @@ -2828,36 +2827,36 @@ namespace System.Management.Automation SetJobState(JobState.Running); // Prepare the automatic variables - SessionState actionState = action.SessionStateInternal.PublicSessionState; - + SessionState actionState = _action.SessionStateInternal.PublicSessionState; + // $psEventSubscriber = The subscriber // that generated this event actionState.PSVariable.Set("eventSubscriber", eventSubscriber); // $psEvent = The extended event information actionState.PSVariable.Set("event", eventArgs); - + // $sender = $psEvent.Sender actionState.PSVariable.Set("sender", eventArgs.Sender); // $eventArgs = $psEvent.SourceEventArgs actionState.PSVariable.Set("eventArgs", eventArgs.SourceEventArgs); - + List results = new List(); - + // $args = $psEventArgs.SourceArgs (for PARAM statement) try { Pipe outputPipe = new Pipe(results); - action.InvokeWithPipe( - useLocalScope: false, + _action.InvokeWithPipe( + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - outputPipe: outputPipe, - invocationInfo: null, - args: eventArgs.SourceArgs); + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + outputPipe: outputPipe, + invocationInfo: null, + args: eventArgs.SourceArgs); } - catch(Exception e) + catch (Exception e) { // Catch-all OK. This is a third-party call-out. CommandProcessorBase.CheckForSevereException(e); @@ -2875,13 +2874,13 @@ namespace System.Management.Automation */ LogErrorsAndOutput(results, actionState); - moreData = true; + _moreData = true; } internal void NotifyJobStopped() - { + { SetJobState(JobState.Stopped); - moreData = false; + _moreData = false; } private void LogErrorsAndOutput(List results, SessionState actionState) @@ -2900,11 +2899,11 @@ namespace System.Management.Automation for (int i = 0; i < errors.Count; i++) { - var error = (ErrorRecord) errors[i]; - if (currentErrorIndex == highestErrorIndex) + var error = (ErrorRecord)errors[i]; + if (currentErrorIndex == _highestErrorIndex) { this.WriteError(error); - highestErrorIndex++; + _highestErrorIndex++; } currentErrorIndex++; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 5920cad06..0a0a2ffe3 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -36,10 +36,10 @@ namespace System.Management.Automation { get { - return eventManager; + return _eventManager; } } - private PSLocalEventManager eventManager; + private PSLocalEventManager _eventManager; internal HashSet AutoLoadingModuleInProgress { @@ -54,7 +54,7 @@ namespace System.Management.Automation { get { return _debugger; } } - private ScriptDebugger _debugger; + internal ScriptDebugger _debugger; internal int _debuggingMode; @@ -63,16 +63,16 @@ namespace System.Management.Automation /// internal void ResetManagers() { - if (this._debugger != null) + if (_debugger != null) { _debugger.ResetDebugger(); } - if (this.eventManager != null) + if (_eventManager != null) { - this.eventManager.Dispose(); + _eventManager.Dispose(); } - this.eventManager = new PSLocalEventManager(this); + _eventManager = new PSLocalEventManager(this); if (this.transactionManager != null) { this.transactionManager.Dispose(); @@ -88,11 +88,11 @@ namespace System.Management.Automation get { // Pretend that tracing is off if ignoreScriptDebug is true - return ignoreScriptDebug ? 0 : debugTraceLevel; + return _ignoreScriptDebug ? 0 : _debugTraceLevel; } - set { debugTraceLevel = value; } + set { _debugTraceLevel = value; } } - private int debugTraceLevel; + private int _debugTraceLevel; /// /// The step mode for the interpreter. @@ -103,11 +103,11 @@ namespace System.Management.Automation get { // Pretend that tracing is off if ignoreScriptDebug is true - return !ignoreScriptDebug && debugTraceStep; + return !_ignoreScriptDebug && _debugTraceStep; } - set { debugTraceStep = value; } + set { _debugTraceStep = value; } } - private bool debugTraceStep; + private bool _debugTraceStep; // Helper for generated code to handle running w/ no execution context internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) @@ -158,7 +158,7 @@ namespace System.Management.Automation get { // Pretend that tracing is off if ignoreScriptDebug is true - return !ignoreScriptDebug && (debugTraceLevel > 0 || debugTraceStep); + return !_ignoreScriptDebug && (_debugTraceLevel > 0 || _debugTraceStep); } } @@ -171,7 +171,7 @@ namespace System.Management.Automation get { return _scriptCommandProcessorShouldRethrowExit; } set { _scriptCommandProcessorShouldRethrowExit = value; } } - bool _scriptCommandProcessorShouldRethrowExit = false; + private bool _scriptCommandProcessorShouldRethrowExit = false; /// /// If this flag is set to true, script trace output @@ -181,10 +181,10 @@ namespace System.Management.Automation /// The current state of the IgnoreScriptDebug flag. internal bool IgnoreScriptDebug { - set { ignoreScriptDebug = value; } - get { return ignoreScriptDebug; } + set { _ignoreScriptDebug = value; } + get { return _ignoreScriptDebug; } } - private bool ignoreScriptDebug = true; + private bool _ignoreScriptDebug = true; /// /// Gets the automation engine instance. @@ -313,21 +313,21 @@ namespace System.Management.Automation { get { - if (providerNames == null) + if (_providerNames == null) { if (IsSingleShell) { - providerNames = new SingleShellProviderNames(); + _providerNames = new SingleShellProviderNames(); } else { - providerNames = new CustomShellProviderNames(); + _providerNames = new CustomShellProviderNames(); } } - return providerNames; + return _providerNames; } } - private ProviderNames providerNames; + private ProviderNames _providerNames; /// /// The module information for this engine... @@ -474,7 +474,7 @@ namespace System.Management.Automation /// internal bool IsModuleWithJobSourceAdapterLoaded { - get;set; + get; set; } /// @@ -670,20 +670,20 @@ namespace System.Management.Automation { get { - return this._formatInfo; + return _formatInfo; } set { - this._formatInfo = value; + _formatInfo = value; } } private object _formatInfo; #endregion - internal Dictionary CustomArgumentCompleters { get; set; } - internal Dictionary NativeArgumentCompleters { get; set; } + internal Dictionary CustomArgumentCompleters { get; set; } + internal Dictionary NativeArgumentCompleters { get; set; } - private CommandFactory commandFactory; + private CommandFactory _commandFactory; /// /// Routine to create a command(processor) instance using the factory. @@ -693,11 +693,11 @@ namespace System.Management.Automation /// The command processor object internal CommandProcessorBase CreateCommand(string command, bool dotSource) { - if (commandFactory == null) + if (_commandFactory == null) { - commandFactory = new CommandFactory(this); + _commandFactory = new CommandFactory(this); } - CommandProcessorBase commandProcessor = commandFactory.CreateCommand(command, + CommandProcessorBase commandProcessor = _commandFactory.CreateCommand(command, this.EngineSessionState.CurrentScope.ScopeOrigin, !dotSource); // Reset the command origin for script commands... //BUGBUG - dotting can get around command origin checks??? if (commandProcessor != null && commandProcessor is ScriptCommandProcessorBase) @@ -714,14 +714,14 @@ namespace System.Management.Automation { get { - return currentCommandProcessor; + return _currentCommandProcessor; } set { - currentCommandProcessor = value; + _currentCommandProcessor = value; } } - private CommandProcessorBase currentCommandProcessor; + private CommandProcessorBase _currentCommandProcessor; /// @@ -742,11 +742,11 @@ namespace System.Management.Automation /// internal InternalHost EngineHostInterface { - get { return myHostInterface; } + get { return _myHostInterface; } // set not provided: it's not meaningful to change the host post-construction. } - private InternalHost myHostInterface; + private InternalHost _myHostInterface; /// /// Interface to be used for interaction with internal @@ -756,7 +756,7 @@ namespace System.Management.Automation /// internal InternalHost InternalHost { - get { return myHostInterface; } + get { return _myHostInterface; } } @@ -783,10 +783,10 @@ namespace System.Management.Automation { get { - return logContextCache; + return _logContextCache; } } - private LogContextCache logContextCache = new LogContextCache(); + private LogContextCache _logContextCache = new LogContextCache(); #region Output pipes /// @@ -794,10 +794,10 @@ namespace System.Management.Automation /// internal PipelineWriter ExternalSuccessOutput { - get { return externalSuccessOutput; } - set { externalSuccessOutput = value; } + get { return _externalSuccessOutput; } + set { _externalSuccessOutput = value; } } - private PipelineWriter externalSuccessOutput; + private PipelineWriter _externalSuccessOutput; /// /// The PipelineWriter provided by the connection object for error output @@ -821,28 +821,28 @@ namespace System.Management.Automation internal class SavedContextData { - private bool StepScript; - private bool IgnoreScriptDebug; - private int PSDebug; + private bool _stepScript; + private bool _ignoreScriptDebug; + private int _PSDebug; - private Pipe ShellFunctionErrorOutputPipe; + private Pipe _shellFunctionErrorOutputPipe; public SavedContextData(ExecutionContext context) { - this.StepScript = context.PSDebugTraceStep; - this.IgnoreScriptDebug = context.IgnoreScriptDebug; - this.PSDebug = context.PSDebugTraceLevel; + _stepScript = context.PSDebugTraceStep; + _ignoreScriptDebug = context.IgnoreScriptDebug; + _PSDebug = context.PSDebugTraceLevel; - this.ShellFunctionErrorOutputPipe = context.ShellFunctionErrorOutputPipe; + _shellFunctionErrorOutputPipe = context.ShellFunctionErrorOutputPipe; } public void RestoreContextData(ExecutionContext context) { - context.PSDebugTraceStep = this.StepScript; - context.IgnoreScriptDebug = this.IgnoreScriptDebug; - context.PSDebugTraceLevel = this.PSDebug; + context.PSDebugTraceStep = _stepScript; + context.IgnoreScriptDebug = _ignoreScriptDebug; + context.PSDebugTraceLevel = _PSDebug; - context.ShellFunctionErrorOutputPipe = this.ShellFunctionErrorOutputPipe; + context.ShellFunctionErrorOutputPipe = _shellFunctionErrorOutputPipe; } } @@ -857,20 +857,20 @@ namespace System.Management.Automation internal void ResetShellFunctionErrorOutputPipe() { - shellFunctionErrorOutputPipe = null; + _shellFunctionErrorOutputPipe = null; } - private Pipe shellFunctionErrorOutputPipe; + private Pipe _shellFunctionErrorOutputPipe; internal Pipe RedirectErrorPipe(Pipe newPipe) { - Pipe oldPipe = shellFunctionErrorOutputPipe; + Pipe oldPipe = _shellFunctionErrorOutputPipe; ShellFunctionErrorOutputPipe = newPipe; return oldPipe; } internal void RestoreErrorPipe(Pipe pipe) { - shellFunctionErrorOutputPipe = pipe; + _shellFunctionErrorOutputPipe = pipe; } /// @@ -879,7 +879,7 @@ namespace System.Management.Automation /// internal void ResetRedirection() { - shellFunctionErrorOutputPipe = null; + _shellFunctionErrorOutputPipe = null; } /// @@ -890,8 +890,8 @@ namespace System.Management.Automation /// internal Pipe ShellFunctionErrorOutputPipe { - get { return shellFunctionErrorOutputPipe; } - set { shellFunctionErrorOutputPipe = value; } + get { return _shellFunctionErrorOutputPipe; } + set { _shellFunctionErrorOutputPipe = value; } } /// @@ -899,40 +899,40 @@ namespace System.Management.Automation /// internal Pipe ExpressionWarningOutputPipe { - get { return this.expressionWarningOutputPipe; } - set { this.expressionWarningOutputPipe = value; } + get { return _expressionWarningOutputPipe; } + set { _expressionWarningOutputPipe = value; } } - private Pipe expressionWarningOutputPipe; + private Pipe _expressionWarningOutputPipe; /// /// Supports expression Verbose output redirection. /// internal Pipe ExpressionVerboseOutputPipe { - get { return this.expressionVerboseOutputPipe; } - set { this.expressionVerboseOutputPipe = value; } + get { return _expressionVerboseOutputPipe; } + set { _expressionVerboseOutputPipe = value; } } - private Pipe expressionVerboseOutputPipe; + private Pipe _expressionVerboseOutputPipe; /// /// Supports expression Verbose output redirection. /// internal Pipe ExpressionDebugOutputPipe { - get { return this.expressionDebugOutputPipe; } - set { this.expressionDebugOutputPipe = value; } + get { return _expressionDebugOutputPipe; } + set { _expressionDebugOutputPipe = value; } } - private Pipe expressionDebugOutputPipe; + private Pipe _expressionDebugOutputPipe; /// /// Supports expression Information output redirection. /// internal Pipe ExpressionInformationOutputPipe { - get { return this.expressionInformationOutputPipe; } - set { this.expressionInformationOutputPipe = value; } + get { return _expressionInformationOutputPipe; } + set { _expressionInformationOutputPipe = value; } } - private Pipe expressionInformationOutputPipe; + private Pipe _expressionInformationOutputPipe; #endregion Output pipes @@ -1046,15 +1046,15 @@ namespace System.Management.Automation /// /// The current connection object /// - private Runspace currentRunspace; + private Runspace _currentRunspace; //This should be internal, but it need to be friend of remoting dll. /// /// The current connection object /// internal Runspace CurrentRunspace { - get { return currentRunspace; } - set { currentRunspace = value; } + get { return _currentRunspace; } + set { _currentRunspace = value; } } /// @@ -1064,9 +1064,9 @@ namespace System.Management.Automation /// internal void PushPipelineProcessor(PipelineProcessor pp) { - if (currentRunspace == null) + if (_currentRunspace == null) return; - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)currentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) return; lpl.Stopper.Push(pp); @@ -1078,9 +1078,9 @@ namespace System.Management.Automation /// internal void PopPipelineProcessor(bool fromSteppablePipeline) { - if (currentRunspace == null) + if (_currentRunspace == null) return; - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)currentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) return; lpl.Stopper.Pop(fromSteppablePipeline); @@ -1094,9 +1094,9 @@ namespace System.Management.Automation { get { - if (currentRunspace == null) + if (_currentRunspace == null) return false; - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)currentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) return false; return lpl.IsStopping; @@ -1142,7 +1142,7 @@ namespace System.Management.Automation SessionStateScope scope = null; object resultItem = null; - if(! eventManager.IsExecutingEventAction) + if (!_eventManager.IsExecutingEventAction) { resultItem = EngineSessionState.GetVariableValue( SpecialVariables.ErrorVarPath, out context, out scope); @@ -1168,16 +1168,16 @@ namespace System.Management.Automation { bool defaultUsed = false; return this.GetEnumPreference( - SpecialVariables.DebugPreferenceVarPath, - InitialSessionState.defaultDebugPreference, + SpecialVariables.DebugPreferenceVarPath, + InitialSessionState.defaultDebugPreference, out defaultUsed); } set { this.EngineSessionState.SetVariable( - SpecialVariables.DebugPreferenceVarPath, + SpecialVariables.DebugPreferenceVarPath, LanguagePrimitives.ConvertTo(value, typeof(ActionPreference), CultureInfo.InvariantCulture), - true, + true, CommandOrigin.Internal); } } @@ -1188,16 +1188,16 @@ namespace System.Management.Automation { bool defaultUsed = false; return this.GetEnumPreference( - SpecialVariables.VerbosePreferenceVarPath, - InitialSessionState.defaultVerbosePreference, + SpecialVariables.VerbosePreferenceVarPath, + InitialSessionState.defaultVerbosePreference, out defaultUsed); } set { this.EngineSessionState.SetVariable( - SpecialVariables.VerbosePreferenceVarPath, + SpecialVariables.VerbosePreferenceVarPath, LanguagePrimitives.ConvertTo(value, typeof(ActionPreference), CultureInfo.InvariantCulture), - true, + true, CommandOrigin.Internal); } } @@ -1208,16 +1208,16 @@ namespace System.Management.Automation { bool defaultUsed = false; return this.GetEnumPreference( - SpecialVariables.ErrorActionPreferenceVarPath, - InitialSessionState.defaultErrorActionPreference, + SpecialVariables.ErrorActionPreferenceVarPath, + InitialSessionState.defaultErrorActionPreference, out defaultUsed); } set { this.EngineSessionState.SetVariable( - SpecialVariables.ErrorActionPreferenceVarPath, + SpecialVariables.ErrorActionPreferenceVarPath, LanguagePrimitives.ConvertTo(value, typeof(ActionPreference), CultureInfo.InvariantCulture), - true, + true, CommandOrigin.Internal); } } @@ -1270,8 +1270,8 @@ namespace System.Management.Automation SessionStateScope scope = null; object resultItem = this.EngineSessionState.GetVariableValue( - SpecialVariables.WhatIfPreferenceVarPath, - out context, + SpecialVariables.WhatIfPreferenceVarPath, + out context, out scope); return resultItem; @@ -1279,9 +1279,9 @@ namespace System.Management.Automation set { this.EngineSessionState.SetVariable( - SpecialVariables.WhatIfPreferenceVarPath, + SpecialVariables.WhatIfPreferenceVarPath, value, - true, + true, CommandOrigin.Internal); } } @@ -1292,16 +1292,16 @@ namespace System.Management.Automation { bool defaultUsed = false; return this.GetEnumPreference( - SpecialVariables.ConfirmPreferenceVarPath, - InitialSessionState.defaultConfirmPreference, + SpecialVariables.ConfirmPreferenceVarPath, + InitialSessionState.defaultConfirmPreference, out defaultUsed); } set { this.EngineSessionState.SetVariable( - SpecialVariables.ConfirmPreferenceVarPath, + SpecialVariables.ConfirmPreferenceVarPath, LanguagePrimitives.ConvertTo(value, typeof(ConfirmImpact), CultureInfo.InvariantCulture), - true, + true, CommandOrigin.Internal); } } @@ -1315,15 +1315,15 @@ namespace System.Management.Automation EngineSessionState.RunspaceClosingNotification(); - if (this._debugger != null) + if (_debugger != null) { _debugger.Dispose(); } - if (this.eventManager != null) + if (_eventManager != null) { - this.eventManager.Dispose(); + _eventManager.Dispose(); } - this.eventManager = null; + _eventManager = null; if (this.transactionManager != null) { this.transactionManager.Dispose(); @@ -1353,7 +1353,8 @@ namespace System.Management.Automation } // This needs to exist so that RunspaceConfiguration can // push it's shared type table into ExecutionContext - set { + set + { if (this.RunspaceConfiguration != null) throw new NotImplementedException("set_TypeTable()"); _typeTable = value; @@ -1413,7 +1414,8 @@ namespace System.Management.Automation // This needs to exist so that RunspaceConfiguration can // push it's shared format database table into ExecutionContext - set { + set + { if (this.RunspaceConfiguration != null) throw new NotImplementedException("set_FormatDBManager()"); _formatDBManager = value; @@ -1429,7 +1431,7 @@ namespace System.Management.Automation { get { - return transactionManager; + return transactionManager; } } internal PSTransactionManager transactionManager; @@ -1447,10 +1449,8 @@ namespace System.Management.Automation if (this.RunspaceConfiguration != null) { - if (!_assemblyCacheInitialized) { - foreach (AssemblyConfigurationEntry entry in this.RunspaceConfiguration.Assemblies) { Exception error = null; @@ -1509,7 +1509,7 @@ namespace System.Management.Automation if (_assemblyCache.ContainsKey(loadedAssembly.FullName)) { // we should ignore this assembly. - return loadedAssembly; + return loadedAssembly; } // We will cache the assembly by both full name and // file name @@ -1723,8 +1723,8 @@ namespace System.Management.Automation ErrorRecord error = null; var rte = e as RuntimeException; - error = rte != null - ? new ErrorRecord(rte.ErrorRecord, rte) + error = rte != null + ? new ErrorRecord(rte.ErrorRecord, rte) : new ErrorRecord(e, errorId, ErrorCategory.OperationStopped, null); currentRunningModuleCommand.WriteError(error); @@ -1735,7 +1735,7 @@ namespace System.Management.Automation if (null == host) return; PSHostUserInterface ui = host.UI; if (null == ui) return; - ui.WriteErrorLine( e.Message ); + ui.WriteErrorLine(e.Message); } } catch (Exception ex) // swallow all exceptions @@ -1787,7 +1787,7 @@ namespace System.Management.Automation InitialSessionState.CoreModule.Equals(cmdletInfo.ModuleName, StringComparison.OrdinalIgnoreCase)) { result = true; - command = (Cmdlet) this.CurrentCommandProcessor.Command; + command = (Cmdlet)this.CurrentCommandProcessor.Command; errorId = String.Equals(cmdletInfo.Name, "Import-Module", StringComparison.OrdinalIgnoreCase) ? "Module_ImportModuleError" : "Module_RemoveModuleError"; @@ -1841,7 +1841,7 @@ namespace System.Management.Automation private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) { - this._engine = engine; + _engine = engine; #if !CORECLR// System.AppDomain is not in CoreCLR // Set the assembly resolve handler if it isn't already set... if (!_assemblyEventHandlerSet) @@ -1859,13 +1859,13 @@ namespace System.Management.Automation } } #endif - eventManager = new PSLocalEventManager(this); + _eventManager = new PSLocalEventManager(this); transactionManager = new PSTransactionManager(); - this._debugger = new ScriptDebugger(this); + _debugger = new ScriptDebugger(this); - myHostInterface = hostInterface as InternalHost; - if (myHostInterface == null) - myHostInterface = new InternalHost(hostInterface, this); + _myHostInterface = hostInterface as InternalHost; + if (_myHostInterface == null) + _myHostInterface = new InternalHost(hostInterface, this); // Hook up the assembly cache _assemblyCache = new Dictionary(); @@ -1873,7 +1873,7 @@ namespace System.Management.Automation // Initialize the fixed toplevel session state and the current session state _topLevelSessionState = _engineSessionState = new SessionStateInternal(this); - if(_authorizationManager == null) + if (_authorizationManager == null) { // if authorizationmanager==null, this means the configuration // explicitly asked for dummy authorization manager. diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index 840734011..1873a53d3 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Runtime.Serialization; using System.Management.Automation.Internal; @@ -14,13 +15,12 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace System.Management.Automation { - /// /// Defines the exception thrown for all Extended type system related errors /// [Serializable] public class ExtendedTypeSystemException : RuntimeException - { + { #region ctor /// /// Initializes a new instance of ExtendedTypeSystemException with the message set @@ -55,8 +55,8 @@ namespace System.Management.Automation /// Resource string /// Arguments to the resource string internal ExtendedTypeSystemException(string errorId, Exception innerException, string resourceString, - params object[] arguments) : - base(StringUtil.Format(resourceString, arguments),innerException) + params object[] arguments) : + base(StringUtil.Format(resourceString, arguments), innerException) { SetErrorId(errorId); } @@ -75,7 +75,7 @@ namespace System.Management.Automation #endregion Serialization #endregion ctor - + } // ExtendedTypeSystemException @@ -124,8 +124,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal MethodException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal MethodException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -190,8 +190,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal MethodInvocationException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal MethodInvocationException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -254,8 +254,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal GetValueException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal GetValueException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -384,8 +384,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal GetValueInvocationException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal GetValueInvocationException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -446,8 +446,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal SetValueException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal SetValueException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -508,8 +508,8 @@ namespace System.Management.Automation /// The inner exception /// Resource String /// Arguments to the resource string - internal SetValueInvocationException(string errorId, Exception innerException, - string resourceString, params object[] arguments) : + internal SetValueInvocationException(string errorId, Exception innerException, + string resourceString, params object[] arguments) : base(errorId, innerException, resourceString, arguments) { } @@ -554,16 +554,16 @@ namespace System.Management.Automation } base.GetObjectData(info, context); - info.AddValue("ErrorId", this.errorId); + info.AddValue("ErrorId", _errorId); } /// /// Initializes a new instance of PSInvalidCastException with serialization parameters /// /// serialization information /// streaming context - protected PSInvalidCastException(SerializationInfo info, StreamingContext context): base(info,context) + protected PSInvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) { - this.errorId = info.GetString("ErrorId"); + _errorId = info.GetString("ErrorId"); } #endif #endregion Serialization @@ -572,30 +572,34 @@ namespace System.Management.Automation /// Initializes a new instance of PSInvalidCastException with the message set /// to typeof(PSInvalidCastException).FullName /// - public PSInvalidCastException(): base(typeof(PSInvalidCastException).FullName) { + public PSInvalidCastException() : base(typeof(PSInvalidCastException).FullName) + { } /// /// Initializes a new instance of PSInvalidCastException setting the message /// /// the exception's message - public PSInvalidCastException(string message):base(message) { + public PSInvalidCastException(string message) : base(message) + { } /// /// Initializes a new instance of PSInvalidCastException setting the message and innerException /// /// the exception's message /// the exceptions's inner exception - public PSInvalidCastException(string message, Exception innerException):base(message,innerException) { + public PSInvalidCastException(string message, Exception innerException) : base(message, innerException) + { } internal PSInvalidCastException(string errorId, string message, Exception innerException) : base(message, innerException) { - this.errorId = errorId; + _errorId = errorId; } internal PSInvalidCastException(string errorId, Exception innerException, string resourceString, params object[] arguments) - : this(errorId, StringUtil.Format(resourceString, arguments), innerException) { + : this(errorId, StringUtil.Format(resourceString, arguments), innerException) + { } /// @@ -605,21 +609,20 @@ namespace System.Management.Automation { get { - if (null == this.errorRecord) + if (null == _errorRecord) { - this.errorRecord = new ErrorRecord( + _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), - this.errorId, + _errorId, ErrorCategory.InvalidArgument, null); } - return this.errorRecord; + return _errorRecord; } } - private ErrorRecord errorRecord; - private string errorId = "PSInvalidCastException"; + private ErrorRecord _errorRecord; + private string _errorId = "PSInvalidCastException"; } - } diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index ea84414d8..035b8bb44 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -62,7 +62,7 @@ namespace System.Management.Automation Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); // Path might contian short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name - this._path = IO.Path.GetFullPath(path); + _path = IO.Path.GetFullPath(path); CommonInitialization(); } @@ -92,7 +92,7 @@ namespace System.Management.Automation Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); // Path might contian short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name - this._path = IO.Path.GetFullPath(path); + _path = IO.Path.GetFullPath(path); CommonInitialization(); } @@ -102,7 +102,7 @@ namespace System.Management.Automation internal ExternalScriptInfo(ExternalScriptInfo other) : base(other) { - this._path = other._path; + _path = other._path; CommonInitialization(); } @@ -136,7 +136,7 @@ namespace System.Management.Automation /// internal override CommandInfo CreateGetCommandCopy(object[] argumentList) { - ExternalScriptInfo copy = new ExternalScriptInfo(this) {IsGetCommandCopy = true, Arguments = argumentList}; + ExternalScriptInfo copy = new ExternalScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList }; return copy; } @@ -144,8 +144,8 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { - get { return HelpCategory.ExternalScript; } - } + get { return HelpCategory.ExternalScript; } + } /// /// Gets the path to the script file. @@ -200,7 +200,7 @@ namespace System.Management.Automation /// public override SessionStateEntryVisibility Visibility { - get + get { if (Context == null) return SessionStateEntryVisibility.Public; @@ -215,7 +215,7 @@ namespace System.Management.Automation /// public ScriptBlock ScriptBlock { - get + get { if (_scriptBlock == null) { @@ -326,7 +326,7 @@ namespace System.Management.Automation new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } - CommandMetadata _commandMetadata; + private CommandMetadata _commandMetadata; /// /// True if the command has dynamic parameters, false otherwise. @@ -382,7 +382,7 @@ namespace System.Management.Automation return data == null ? null : data.RequiredPSVersion; } } - + internal IEnumerable RequiresPSEditions { get @@ -435,7 +435,7 @@ namespace System.Management.Automation { ReadScriptContents(); } - + return _scriptContents; } } @@ -452,7 +452,7 @@ namespace System.Management.Automation { ReadScriptContents(); } - + return _originalEncoding; } } @@ -471,7 +471,7 @@ namespace System.Management.Automation try { - using(FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) + using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) { Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; @@ -524,7 +524,7 @@ namespace System.Management.Automation ThrowCommandNotFoundException(e); } } - } + } private static void ThrowCommandNotFoundException(Exception innerException) { diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index cf84d41de..443cab499 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -21,7 +21,6 @@ namespace System.Management.Automation /// internal class DataRowAdapter : PropertyOnlyAdapter { - #region virtual /// /// Retrieves all the properties available in the object. @@ -42,7 +41,6 @@ namespace System.Management.Automation } return; - } /// /// Returns null if propertyName is not a property in the adapter or @@ -244,7 +242,7 @@ namespace System.Management.Automation // native adsi object's method, if there is a failure it calls // dotnet method (if one available). // This ensures dotnet methods are available on the adapted object. - private static readonly DotNetAdapter dotNetAdapter = new DotNetAdapter(); + private static readonly DotNetAdapter s_dotNetAdapter = new DotNetAdapter(); #endregion #region member @@ -568,7 +566,7 @@ namespace System.Management.Automation // this code is reached only on exception // check if there is a dotnet method, invoke the dotnet method if available - PSMethod dotNetmethod = dotNetAdapter.GetDotNetMethod(method.baseObject, method.name); + PSMethod dotNetmethod = s_dotNetAdapter.GetDotNetMethod(method.baseObject, method.name); if (null != dotNetmethod) { return dotNetmethod.Invoke(arguments); diff --git a/src/System.Management.Automation/engine/FilterInfo.cs b/src/System.Management.Automation/engine/FilterInfo.cs index 9d403f567..1c48fb18a 100644 --- a/src/System.Management.Automation/engine/FilterInfo.cs +++ b/src/System.Management.Automation/engine/FilterInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Text; @@ -163,8 +164,7 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { - get { return HelpCategory.Filter; } - } - + get { return HelpCategory.Filter; } + } } // FilterInfo } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index 030459993..74a056c91 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Text; using System.Management.Automation.Runspaces; @@ -65,20 +66,19 @@ namespace System.Management.Automation /// If is null. /// /// - internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context, string helpFile): base(name, CommandTypes.Function, context) + internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context, string helpFile) : base(name, CommandTypes.Function, context) { if (function == null) { throw PSTraceSource.NewArgumentNullException("function"); } - this._scriptBlock = function; + _scriptBlock = function; - CmdletInfo.SplitCmdletName(name, out verb, out noun); + CmdletInfo.SplitCmdletName(name, out _verb, out _noun); this.Module = function.Module; - this._helpFile = helpFile; - + _helpFile = helpFile; } // FunctionInfo ctor /// @@ -140,7 +140,7 @@ namespace System.Management.Automation internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context, string helpFile) : this(name, function, context, helpFile) { - this._options = options; + _options = options; } // FunctionInfo ctor /// @@ -154,12 +154,12 @@ namespace System.Management.Automation private void CopyFieldsFromOther(FunctionInfo other) { - this.verb = other.verb; - this.noun = other.noun; - this._scriptBlock = other._scriptBlock; - this._description = other._description; - this._options = other._options; - this._helpFile = other._helpFile; + _verb = other._verb; + _noun = other._noun; + _scriptBlock = other._scriptBlock; + _description = other._description; + _options = other._options; + _helpFile = other._helpFile; } /// @@ -171,7 +171,7 @@ namespace System.Management.Automation CopyFieldsFromOther(other); // Get the verb and noun from the name - CmdletInfo.SplitCmdletName(name, out verb, out noun); + CmdletInfo.SplitCmdletName(name, out _verb, out _noun); } /// @@ -180,7 +180,7 @@ namespace System.Management.Automation /// internal override CommandInfo CreateGetCommandCopy(object[] arguments) { - FunctionInfo copy = new FunctionInfo(this) {IsGetCommandCopy = true, Arguments = arguments}; + FunctionInfo copy = new FunctionInfo(this) { IsGetCommandCopy = true, Arguments = arguments }; return copy; } @@ -188,8 +188,8 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { - get { return HelpCategory.Function; } - } + get { return HelpCategory.Function; } + } /// /// Gets the ScriptBlock which is the implementation of the function @@ -285,10 +285,10 @@ namespace System.Management.Automation throw e; } - this._scriptBlock = newFunction; + _scriptBlock = newFunction; this.Module = newFunction.Module; - this._commandMetadata = null; + _commandMetadata = null; this._parameterSets = null; this.ExternalCommandMetadata = null; @@ -297,7 +297,7 @@ namespace System.Management.Automation this.Options = options; } - this._helpFile = helpFile; + _helpFile = helpFile; } /// @@ -438,10 +438,10 @@ namespace System.Management.Automation { get { - return verb; + return _verb; } } // Verb - private string verb = String.Empty; + private string _verb = String.Empty; /// /// Gets the noun of the function. @@ -450,10 +450,10 @@ namespace System.Management.Automation { get { - return noun; + return _noun; } } // Noun - private string noun = String.Empty; + private string _noun = String.Empty; /// /// Gets the help file path for the function. @@ -508,13 +508,14 @@ namespace System.Management.Automation /// override internal CommandMetadata CommandMetadata { - get { + get + { return _commandMetadata ?? (_commandMetadata = new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } - CommandMetadata _commandMetadata; + private CommandMetadata _commandMetadata; /// /// The output type(s) is specified in the script block @@ -524,5 +525,4 @@ namespace System.Management.Automation get { return ScriptBlock.OutputType; } } } // FunctionInfo - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index a0cd85d6f..b98af63e3 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Globalization; using System.Linq; @@ -45,13 +46,13 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - nameContainsWildcard = false; - names = value; + _nameContainsWildcard = false; + _names = value; if (value != null) { @@ -59,15 +60,15 @@ namespace Microsoft.PowerShell.Commands { if (WildcardPattern.ContainsWildcardCharacters(commandName)) { - nameContainsWildcard = true; + _nameContainsWildcard = true; break; } } } } } // Path - private string[] names; - private bool nameContainsWildcard; + private string[] _names; + private bool _nameContainsWildcard; /// /// Gets or sets the verb parameter to the cmdlet @@ -78,7 +79,7 @@ namespace Microsoft.PowerShell.Commands { get { - return verbs; + return _verbs; } // get set @@ -87,11 +88,11 @@ namespace Microsoft.PowerShell.Commands { value = Utils.EmptyArray(); } - verbs = value; - verbPatterns = null; + _verbs = value; + _verbPatterns = null; } // set } // Verb - private string[] verbs = Utils.EmptyArray(); + private string[] _verbs = Utils.EmptyArray(); /// /// Gets or sets the noun parameter to the cmdlet @@ -103,7 +104,7 @@ namespace Microsoft.PowerShell.Commands { get { - return nouns; + return _nouns; } // get set @@ -112,11 +113,11 @@ namespace Microsoft.PowerShell.Commands { value = Utils.EmptyArray(); } - nouns = value; - nounPatterns = null; + _nouns = value; + _nounPatterns = null; } // set } // Noun - private string[] nouns = Utils.EmptyArray(); + private string[] _nouns = Utils.EmptyArray(); /// /// Gets or sets the PSSnapin/Module parameter to the cmdlet @@ -141,11 +142,11 @@ namespace Microsoft.PowerShell.Commands _modules = value; _modulePatterns = null; - isModuleSpecified = true; + _isModuleSpecified = true; } // set } private string[] _modules = Utils.EmptyArray(); - private bool isModuleSpecified = false; + private bool _isModuleSpecified = false; /// /// Gets or sets the FullyQualifiedModule parameter to the cmdlet @@ -166,11 +167,11 @@ namespace Microsoft.PowerShell.Commands { _moduleSpecifications = value; } - isFullyQualifiedModuleSpecified = true; + _isFullyQualifiedModuleSpecified = true; } } private ModuleSpecification[] _moduleSpecifications = Utils.EmptyArray(); - private bool isFullyQualifiedModuleSpecified = false; + private bool _isFullyQualifiedModuleSpecified = false; /// /// Gets or sets the type of the command to get @@ -182,17 +183,17 @@ namespace Microsoft.PowerShell.Commands { get { - return commandType; + return _commandType; } // get set { - commandType = value; - isCommandTypeSpecified = true; + _commandType = value; + _isCommandTypeSpecified = true; } // set } // Noun - private CommandTypes commandType = CommandTypes.All; - private bool isCommandTypeSpecified = false; + private CommandTypes _commandType = CommandTypes.All; + private bool _isCommandTypeSpecified = false; /// /// The parameter representing the total number of commands that will @@ -205,14 +206,14 @@ namespace Microsoft.PowerShell.Commands { get { - return totalCount; + return _totalCount; } set { - totalCount = value; + _totalCount = value; } } - private int totalCount = -1; + private int _totalCount = -1; /// /// The parameter that determines if the CommandInfo or the string @@ -224,15 +225,15 @@ namespace Microsoft.PowerShell.Commands { get { - return usage; + return _usage; } set { - usage = value; + _usage = value; } } - private bool usage; + private bool _usage; /// /// This parameter causes the output to be packaged into ShowCommandInfo PSObject types @@ -258,14 +259,14 @@ namespace Microsoft.PowerShell.Commands { get { - return commandArgs; + return _commandArgs; } set { - commandArgs = value; + _commandArgs = value; } } - private object[] commandArgs; + private object[] _commandArgs; /// /// The parameter that determines if additional matching commands should be returned. @@ -277,15 +278,15 @@ namespace Microsoft.PowerShell.Commands { get { - return all; + return _all; } set { - all = value; + _all = value; } } - private bool all; + private bool _all; /// /// The parameter that determines if additional matching commands from available modules should be returned. @@ -297,15 +298,15 @@ namespace Microsoft.PowerShell.Commands { get { - return listImported; + return _listImported; } set { - listImported = value; + _listImported = value; } } - private bool listImported; + private bool _listImported; /// /// The parameter that filters commands returned to only include commands that have a parameter with a name that matches one of the ParameterName's arguments @@ -315,7 +316,7 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ParameterName { - get { return this._parameterNames; } + get { return _parameterNames; } set { if (value == null) @@ -323,9 +324,9 @@ namespace Microsoft.PowerShell.Commands throw new ArgumentNullException("value"); } - this._parameterNames = value; - this._parameterNameWildcards = SessionStateUtilities.CreateWildcardsFromStrings( - this._parameterNames, + _parameterNames = value; + _parameterNameWildcards = SessionStateUtilities.CreateWildcardsFromStrings( + _parameterNames, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } @@ -343,7 +344,7 @@ namespace Microsoft.PowerShell.Commands { get { - return this._parameterTypes; + return _parameterTypes; } set { @@ -368,7 +369,7 @@ namespace Microsoft.PowerShell.Commands } filteredParameterTypes.Add(ptn); } - this._parameterTypes = filteredParameterTypes.ToArray(); + _parameterTypes = filteredParameterTypes.ToArray(); } } private PSTypeName[] _parameterTypes; @@ -405,7 +406,7 @@ namespace Microsoft.PowerShell.Commands { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. - if (isModuleSpecified && isFullyQualifiedModuleSpecified) + if (_isModuleSpecified && _isFullyQualifiedModuleSpecified) { string errMsg = String.Format(CultureInfo.InvariantCulture, SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); @@ -444,27 +445,26 @@ namespace Microsoft.PowerShell.Commands { // We do not show the pithy aliases (not of the format Verb-Noun) and applications by default. // We will show them only if the Name, All and totalCount are not specified. - if ((this.Name == null) && (!all) && totalCount == -1) + if ((this.Name == null) && (!_all) && _totalCount == -1) { CommandTypes commandTypesToIgnore = 0; - if (((this.CommandType & CommandTypes.Alias) != CommandTypes.Alias) || (!isCommandTypeSpecified)) + if (((this.CommandType & CommandTypes.Alias) != CommandTypes.Alias) || (!_isCommandTypeSpecified)) { commandTypesToIgnore |= CommandTypes.Alias; } - if (((this.commandType & CommandTypes.Application) != CommandTypes.Application) || - (!isCommandTypeSpecified)) + if (((_commandType & CommandTypes.Application) != CommandTypes.Application) || + (!_isCommandTypeSpecified)) { commandTypesToIgnore |= CommandTypes.Application; } - accumulatedResults = - accumulatedResults.Where( + _accumulatedResults = + _accumulatedResults.Where( commandInfo => (((commandInfo.CommandType & commandTypesToIgnore) == 0) || (commandInfo.Name.IndexOf('-') > 0))).ToList(); - } // report not-found errors for ParameterName and ParameterType if needed @@ -493,13 +493,13 @@ namespace Microsoft.PowerShell.Commands } // Only sort if they didn't fully specify a name) - if ((names == null) || (nameContainsWildcard)) + if ((_names == null) || (_nameContainsWildcard)) { // Use the stable sorting to sort the result list - accumulatedResults = accumulatedResults.OrderBy(a => a, new CommandInfoComparer()).ToList(); + _accumulatedResults = _accumulatedResults.OrderBy(a => a, new CommandInfoComparer()).ToList(); } - OutputResultsHelper(accumulatedResults); + OutputResultsHelper(_accumulatedResults); object pssenderInfo = Context.GetVariableValue(SpecialVariables.PSSenderInfoVarPath); if ((null != pssenderInfo) && (pssenderInfo is System.Management.Automation.Remoting.PSSenderInfo)) @@ -605,7 +605,7 @@ namespace Microsoft.PowerShell.Commands private void AccumulateMatchingCmdlets() { - this.commandType = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Filter | CommandTypes.Alias | CommandTypes.Workflow | CommandTypes.Configuration; + _commandType = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Filter | CommandTypes.Alias | CommandTypes.Workflow | CommandTypes.Configuration; Collection commandNames = new Collection(); commandNames.Add("*"); @@ -618,19 +618,19 @@ namespace Microsoft.PowerShell.Commands do // false loop { - if (verbPatterns == null) + if (_verbPatterns == null) { - verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); + _verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); } - if (nounPatterns == null) + if (_nounPatterns == null) { - nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); + _nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); } if (!string.IsNullOrEmpty(command.ModuleName)) { - if (isFullyQualifiedModuleSpecified) + if (_isFullyQualifiedModuleSpecified) { if (!_moduleSpecifications.Any( moduleSpecification => @@ -668,12 +668,12 @@ namespace Microsoft.PowerShell.Commands break; } - if (!SessionStateUtilities.MatchesAnyWildcardPattern(verb, verbPatterns, true)) + if (!SessionStateUtilities.MatchesAnyWildcardPattern(verb, _verbPatterns, true)) { break; } - if (!SessionStateUtilities.MatchesAnyWildcardPattern(noun, nounPatterns, true)) + if (!SessionStateUtilities.MatchesAnyWildcardPattern(noun, _nounPatterns, true)) { break; } @@ -778,14 +778,14 @@ namespace Microsoft.PowerShell.Commands { if (TotalCount < 0 || count < TotalCount) { - foreach (CommandInfo command in System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands(plainCommandName, this.Context, this.MyInvocation.CommandOrigin, rediscoverImportedModules:true, moduleVersionRequired:isFullyQualifiedModuleSpecified)) + foreach (CommandInfo command in System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands(plainCommandName, this.Context, this.MyInvocation.CommandOrigin, rediscoverImportedModules: true, moduleVersionRequired: _isFullyQualifiedModuleSpecified)) { // Cannot pass in "command" by ref (foreach iteration variable) CommandInfo current = command; if (IsCommandMatch(ref current, out isDuplicate) && (!IsCommandInResult(current)) && IsParameterMatch(current)) { - accumulatedResults.Add(current); + _accumulatedResults.Add(current); // Make sure we don't exceed the TotalCount parameter ++count; @@ -839,7 +839,7 @@ namespace Microsoft.PowerShell.Commands options, this.CommandType, this.Context); - + bool resultFound = false; isDuplicate = false; @@ -919,7 +919,7 @@ namespace Microsoft.PowerShell.Commands break; } - accumulatedResults.Add(current); + _accumulatedResults.Add(current); if (ArgumentList != null) { @@ -931,7 +931,7 @@ namespace Microsoft.PowerShell.Commands // Only for this case, the loop should exit // Get-Command Foo - if (isPattern || All || totalCount != -1 || isCommandTypeSpecified || isModuleSpecified || isFullyQualifiedModuleSpecified) + if (isPattern || All || _totalCount != -1 || _isCommandTypeSpecified || _isModuleSpecified || _isFullyQualifiedModuleSpecified) { continue; } @@ -961,13 +961,13 @@ namespace Microsoft.PowerShell.Commands { break; } - accumulatedResults.Add(c); + _accumulatedResults.Add(c); } // Make sure we don't exceed the TotalCount parameter } } } - + return resultFound; } @@ -1022,13 +1022,13 @@ namespace Microsoft.PowerShell.Commands if (key != null) { - if (commandsWritten.ContainsKey(key)) + if (_commandsWritten.ContainsKey(key)) { result = true; } else { - commandsWritten.Add(key, info); + _commandsWritten.Add(key, info); } } @@ -1042,9 +1042,9 @@ namespace Microsoft.PowerShell.Commands return true; } - if (this._matchedParameterNames == null) + if (_matchedParameterNames == null) { - this._matchedParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); + _matchedParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); } IEnumerable commandParameters = null; @@ -1112,7 +1112,7 @@ namespace Microsoft.PowerShell.Commands // bool typeIsMatching; - if ((this._parameterTypes == null) || (this._parameterTypes.Length == 0)) + if ((_parameterTypes == null) || (_parameterTypes.Length == 0)) { typeIsMatching = true; } @@ -1146,7 +1146,7 @@ namespace Microsoft.PowerShell.Commands // then do the verb/moun check if (current.CommandType == CommandTypes.Cmdlet || - ((verbs.Length > 0 || nouns.Length > 0) && + ((_verbs.Length > 0 || _nouns.Length > 0) && (current.CommandType == CommandTypes.Function || current.CommandType == CommandTypes.Filter || current.CommandType == CommandTypes.Workflow || @@ -1160,7 +1160,7 @@ namespace Microsoft.PowerShell.Commands } else { - if (isFullyQualifiedModuleSpecified) + if (_isFullyQualifiedModuleSpecified) { bool foundModuleMatch = false; foreach (var moduleSpecification in _moduleSpecifications) @@ -1184,7 +1184,6 @@ namespace Microsoft.PowerShell.Commands isCommandMatch = false; } } - } if (isCommandMatch) @@ -1312,12 +1311,12 @@ namespace Microsoft.PowerShell.Commands } else { - bool isModuleMatch = false; - if (!isFullyQualifiedModuleSpecified) + bool isModuleMatch = false; + if (!_isFullyQualifiedModuleSpecified) { isModuleMatch = SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, _modulePatterns, true); } - else if(_moduleSpecifications.Any(moduleSpecification => ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpecification))) + else if (_moduleSpecifications.Any(moduleSpecification => ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpecification))) { isModuleMatch = true; } @@ -1378,12 +1377,12 @@ namespace Microsoft.PowerShell.Commands { bool isPresent = false; bool commandHasModule = command.Module != null; - foreach (CommandInfo commandInfo in accumulatedResults) + foreach (CommandInfo commandInfo in _accumulatedResults) { if ((command.CommandType == commandInfo.CommandType && (String.Compare(command.Name, commandInfo.Name, StringComparison.CurrentCultureIgnoreCase) == 0 || - // If the command has been imported with a prefix, then just checking the names for duplication will not be enough. - // Hence, an additional check is done with the prefix information + // If the command has been imported with a prefix, then just checking the names for duplication will not be enough. + // Hence, an additional check is done with the prefix information String.Compare(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.CurrentCultureIgnoreCase) == 0) ) && commandInfo.Module != null && commandHasModule && ( // We do reference equal comparison if both command are imported. If either one is not imported, we compare the module path @@ -1402,15 +1401,15 @@ namespace Microsoft.PowerShell.Commands #region Members - private Dictionary commandsWritten = + private Dictionary _commandsWritten = new Dictionary(StringComparer.OrdinalIgnoreCase); - private List accumulatedResults = new List(); + private List _accumulatedResults = new List(); // These members are the collection of wildcard patterns for the "CmdletSet" - Collection verbPatterns; - Collection nounPatterns; - Collection _modulePatterns; + private Collection _verbPatterns; + private Collection _nounPatterns; + private Collection _modulePatterns; private Stopwatch _timer = new Stopwatch(); @@ -1489,7 +1488,7 @@ namespace Microsoft.PowerShell.Commands bool hasParameterSet = false; IList validValues = new List(); - var validateSetAttribute = parameter.Attributes.Where(x=>(x is ValidateSetAttribute)).Cast().LastOrDefault(); + var validateSetAttribute = parameter.Attributes.Where(x => (x is ValidateSetAttribute)).Cast().LastOrDefault(); if (validateSetAttribute != null) { hasParameterSet = true; @@ -1545,10 +1544,10 @@ namespace Microsoft.PowerShell.Commands /// public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { - if (fakeBoundParameters == null) - { - throw PSTraceSource.NewArgumentNullException("fakeBoundParameters"); - } + if (fakeBoundParameters == null) + { + throw PSTraceSource.NewArgumentNullException("fakeBoundParameters"); + } var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand)); var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace). diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index e458805c5..d2f3d696b 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -29,8 +29,8 @@ namespace System.Management.Automation /// /// Returns an instance of the PSHost implementation for this environment. /// - PSHost Host { get; } - #region Write + PSHost Host { get; } + #region Write /// /// Display debug information /// @@ -182,9 +182,9 @@ namespace System.Management.Automation /// void WriteCommandDetail(string text); - #endregion Write + #endregion Write - #region Should + #region Should /// /// Called by the cmdlet to confirm the operation with the user. Cmdlets which make changes /// (e.g. delete files, stop services etc.) should call ShouldProcess @@ -222,7 +222,7 @@ namespace System.Management.Automation /// /// /// - bool ShouldProcess( string target ); + bool ShouldProcess(string target); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -268,7 +268,7 @@ namespace System.Management.Automation /// /// /// - bool ShouldProcess( string target, string action ); + bool ShouldProcess(string target, string action); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -322,7 +322,7 @@ namespace System.Management.Automation /// /// /// - bool ShouldProcess( string verboseDescription, string verboseWarning, string caption ); + bool ShouldProcess(string verboseDescription, string verboseWarning, string caption); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -439,7 +439,7 @@ namespace System.Management.Automation /// /// /// - bool ShouldContinue( string query, string caption ); + bool ShouldContinue(string query, string caption); /// /// Called to confirm an operation or grouping of operations with the user. @@ -504,25 +504,25 @@ namespace System.Management.Automation /// /// /// - bool ShouldContinue( string query, string caption, ref bool yesToAll, ref bool noToAll ); + bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll); - #endregion Should + #endregion Should - #region Transaction Support - /// - /// Returns true if a transaction is available and active. - /// + #region Transaction Support + /// + /// Returns true if a transaction is available and active. + /// bool TransactionAvailable(); - /// - /// Gets an object that surfaces the current PowerShell transaction. - /// When this object is disposed, PowerShell resets the active transaction - /// + /// + /// Gets an object that surfaces the current PowerShell transaction. + /// When this object is disposed, PowerShell resets the active transaction + /// PSTransactionContext CurrentPSTransaction { get; } - #endregion Transaction Support + #endregion Transaction Support - #region Misc + #region Misc #region ThrowTerminatingError /// /// This interface will be called to route fatal errors from a cmdlet. @@ -555,7 +555,7 @@ namespace System.Management.Automation /// void ThrowTerminatingError(ErrorRecord errorRecord); #endregion ThrowTerminatingError - #endregion misc + #endregion misc } diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 34546787e..68df207a9 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -48,9 +48,9 @@ namespace System.Management.Automation } // Porting note: PsUtils.GetHostName() already handles platform specifics this.Computer = PsUtils.GetHostName(); - this.ProcessId = (uint) System.Diagnostics.Process.GetCurrentProcess().Id; + this.ProcessId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; this.NativeThreadId = PsUtils.GetNativeThreadId(); - this.ManagedThreadId = (uint) System.Threading.Thread.CurrentThread.ManagedThreadId; + this.ManagedThreadId = (uint)System.Threading.Thread.CurrentThread.ManagedThreadId; } /// @@ -160,11 +160,11 @@ namespace System.Management.Automation informationRecord.Tags = new List(); System.Collections.ArrayList tagsArrayList = RemotingDecoder.GetPropertyValue(inputObject, "Tags"); - foreach(string tag in tagsArrayList) + foreach (string tag in tagsArrayList) { informationRecord.Tags.Add(tag); } - + informationRecord.User = RemotingDecoder.GetPropertyValue(inputObject, "User"); informationRecord.Computer = RemotingDecoder.GetPropertyValue(inputObject, "Computer"); informationRecord.ProcessId = RemotingDecoder.GetPropertyValue(inputObject, "ProcessId"); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index a31e7799c..b50306ef5 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -896,7 +897,8 @@ namespace System.Management.Automation.Runspaces /// /// The script block for this function. /// - internal ScriptBlock ScriptBlock { + internal ScriptBlock ScriptBlock + { get { return _scriptBlock; } set { _scriptBlock = value; } } @@ -1001,7 +1003,8 @@ namespace System.Management.Automation.Runspaces /// /// The script block for this function. /// - internal WorkflowInfo WorkflowInfo { + internal WorkflowInfo WorkflowInfo + { get { return _workflow; } set { _workflow = value; } } @@ -1464,7 +1467,7 @@ namespace System.Management.Automation.Runspaces private Collection _internalCollection; //object to use for locking - object _syncObject = new object(); + private object _syncObject = new object(); } /// @@ -1505,9 +1508,9 @@ namespace System.Management.Automation.Runspaces // Aliases to allowed commands are OK SessionStateAliasEntry aliasEntry = entry as SessionStateAliasEntry; - if(aliasEntry != null) + if (aliasEntry != null) { - if(allowedNames.Exists(allowedName => allowedName.Equals(aliasEntry.Definition, StringComparison.OrdinalIgnoreCase))) + if (allowedNames.Exists(allowedName => allowedName.Equals(aliasEntry.Definition, StringComparison.OrdinalIgnoreCase))) { aliasEntry.Visibility = SessionStateEntryVisibility.Public; continue; @@ -1647,7 +1650,7 @@ namespace System.Management.Automation.Runspaces typeEntry => IO.Path.GetFileName(typeEntry.FileName)); // No providers are visible by default - foreach(SessionStateProviderEntry provider in iss.Providers) + foreach (SessionStateProviderEntry provider in iss.Providers) { provider.Visibility = SessionStateEntryVisibility.Private; } @@ -1677,7 +1680,7 @@ namespace System.Management.Automation.Runspaces } // Porting note: moved to Platform so we have one list to maintain - private static string[] PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); + private static string[] s_PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); private static void IncludePowerShellCoreFormats(InitialSessionState iss) { @@ -1688,7 +1691,7 @@ namespace System.Management.Automation.Runspaces } iss.Formats.Clear(); - foreach (var coreFormat in PSCoreFormatFileNames) + foreach (var coreFormat in s_PSCoreFormatFileNames) { iss.Formats.Add(new SessionStateFormatEntry(Path.Combine(psHome, coreFormat))); } @@ -1751,7 +1754,7 @@ namespace System.Management.Automation.Runspaces // restrict what gets exposed // - List allowedCommands = new List (); + List allowedCommands = new List(); allowedCommands.AddRange(JobCmdlets); allowedCommands.AddRange(ImplicitRemotingCmdlets); allowedCommands.AddRange(MiscCmdlets); @@ -1767,7 +1770,7 @@ namespace System.Management.Automation.Runspaces { if (entry.GetType() == typeof(SessionStateAliasEntry)) { - if(allowedAliases.Contains(entry.Name, StringComparer.OrdinalIgnoreCase)) + if (allowedAliases.Contains(entry.Name, StringComparer.OrdinalIgnoreCase)) { entry.Visibility = SessionStateEntryVisibility.Public; } @@ -1830,7 +1833,7 @@ namespace System.Management.Automation.Runspaces allowedCommands.AddRange(LanguageHelperCmdlets); // Exposing Debug cmdlets in only Full language WF server // because for debugging one needs full language capabilities - allowedCommands.AddRange(DebugCmdlets); + allowedCommands.AddRange(DebugCmdlets); // make all other commands private MakeDisallowedEntriesPrivate( @@ -1871,7 +1874,7 @@ namespace System.Management.Automation.Runspaces iss.Variables.Clear(); // no variables are needed for workflow server - remove all of them // set a preference variable to indicate Get-Command should show // return only loaded public commands - Hashtable parameters = new Hashtable {{"Get-Command:ListImported", true}}; + Hashtable parameters = new Hashtable { { "Get-Command:ListImported", true } }; iss.Variables.Add(new SessionStateVariableEntry("PSDefaultParameterValues", parameters, "Default Get-Command Action")); return iss; } @@ -1978,10 +1981,10 @@ namespace System.Management.Automation.Runspaces /// this cmdlets are exposed due to some bugs. Need to figure out if /// they are still required /// - private static readonly string[] MiscCmdlets = {"Join-Path", "Import-Module"}; + private static readonly string[] MiscCmdlets = { "Join-Path", "Import-Module" }; private static readonly string[] MiscCommands = { "TabExpansion2" }; - private static readonly string[] DefaultTypeFiles = {"types.ps1xml", "typesv3.ps1xml"}; + private static readonly string[] DefaultTypeFiles = { "types.ps1xml", "typesv3.ps1xml" }; #endif #endregion @@ -2148,7 +2151,7 @@ namespace System.Management.Automation.Runspaces ss.Types.Add(this.Types.Clone()); ss.Formats.Add(this.Formats.Clone()); - foreach(string startupScript in this.StartupScripts) + foreach (string startupScript in this.StartupScripts) { ss.StartupScripts.Add(startupScript); } @@ -2176,7 +2179,7 @@ namespace System.Management.Automation.Runspaces ss.UserDriveUserName = this.UserDriveUserName; ss.UserDriveMaximumSize = this.UserDriveMaximumSize; - if (this._wasExecutionPolicySet) + if (_wasExecutionPolicySet) { ss.ExecutionPolicy = this.ExecutionPolicy; } @@ -2187,7 +2190,7 @@ namespace System.Management.Automation.Runspaces #if !CORECLR // No ApartmentState In CoreCLR ss.ApartmentState = this.ApartmentState; #endif - + foreach (ModuleSpecification modSpec in this.ModuleSpecificationsToImport) { ss.ModuleSpecificationsToImport.Add(modSpec); @@ -2363,10 +2366,10 @@ namespace System.Management.Automation.Runspaces /// public PSThreadOptions ThreadOptions { - get { return this.createThreadOptions; } - set { this.createThreadOptions = value; } + get { return _createThreadOptions; } + set { _createThreadOptions = value; } } - private PSThreadOptions createThreadOptions = PSThreadOptions.Default; + private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// /// If this property is set and there was a runspace creation error, then @@ -2375,10 +2378,10 @@ namespace System.Management.Automation.Runspaces /// public bool ThrowOnRunspaceOpenError { - get { return this.throwOnRunspaceOpenError; } - set { this.throwOnRunspaceOpenError = value; } + get { return _throwOnRunspaceOpenError; } + set { _throwOnRunspaceOpenError = value; } } - private bool throwOnRunspaceOpenError = false; + private bool _throwOnRunspaceOpenError = false; /// /// This property will be set only if we are refreshing the Type/Format settings by calling UpdateTypes/UpdateFormats directly. @@ -2474,13 +2477,13 @@ namespace System.Management.Automation.Runspaces _coreModulesToImport.Add(n); } } - + /// /// Imported modules. /// public ReadOnlyCollection Modules { - get { return new ReadOnlyCollection(_moduleSpecificationsToImport);} + get { return new ReadOnlyCollection(_moduleSpecificationsToImport); } } internal Collection ModuleSpecificationsToImport @@ -2489,7 +2492,7 @@ namespace System.Management.Automation.Runspaces } private Collection _moduleSpecificationsToImport = new Collection(); - HashSet _coreModulesToImport = new HashSet(); + private HashSet _coreModulesToImport = new HashSet(); internal Dictionary ImportedSnapins { @@ -2501,7 +2504,7 @@ namespace System.Management.Automation.Runspaces /// /// Gets the dictionary of core modules to import on runspace creation... /// - internal HashSet CoreModulesToImport + internal HashSet CoreModulesToImport { get { return _coreModulesToImport; } } @@ -2661,7 +2664,7 @@ namespace System.Management.Automation.Runspaces } private HashSet _startupScripts = new HashSet(); - Object _syncObject = new Object(); + private Object _syncObject = new Object(); internal void Bind(ExecutionContext context, bool updateOnly) { @@ -2748,7 +2751,7 @@ namespace System.Management.Automation.Runspaces MshLog.EVENT_ID_CONFIGURATION_FAILURE, e, Severity.Warning); - + if (this.ThrowOnRunspaceOpenError) { throw; @@ -2771,7 +2774,7 @@ namespace System.Management.Automation.Runspaces } } - SetSessionStateDrive(context, setLocation:false); + SetSessionStateDrive(context, setLocation: false); } private void Bind_SetVariables(SessionStateInternal ss) @@ -2948,7 +2951,7 @@ namespace System.Management.Automation.Runspaces Path.GetExtension(context.ModuleBeingProcessed) .Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) || - throwOnRunspaceOpenError) + _throwOnRunspaceOpenError) { throw error; } @@ -2990,7 +2993,7 @@ namespace System.Management.Automation.Runspaces SetSessionStateDrive(initializedRunspace.ExecutionContext, true); Exception moduleImportException = ProcessImportModule(initializedRunspace, ModuleSpecificationsToImport, "", publicCommands); - if(moduleImportException != null) + if (moduleImportException != null) { runspaceInitTracer.WriteLine( "Runspace open failed while loading module: First error {1}", moduleImportException); @@ -3031,7 +3034,7 @@ namespace System.Management.Automation.Runspaces } // Start transcribing - if(! String.IsNullOrEmpty(TranscriptDirectory)) + if (!String.IsNullOrEmpty(TranscriptDirectory)) { using (PowerShell psToInvoke = PowerShell.Create()) { @@ -3110,13 +3113,13 @@ namespace System.Management.Automation.Runspaces private void ProcessCommandModifications(Runspace initializedRunspace) { - foreach(var pair in CommandModifications) + foreach (var pair in CommandModifications) { string commandName = pair.Key; Hashtable commandModification = pair.Value; CommandInfo existingCommand = initializedRunspace.SessionStateProxy.InvokeCommand.GetCommand(commandName, CommandTypes.Cmdlet | CommandTypes.Function); - if(existingCommand == null) + if (existingCommand == null) { // Could not find the command - just continue, rather than generating an error. This could just be a missing module // or something similar. @@ -3125,7 +3128,7 @@ namespace System.Management.Automation.Runspaces // If we are wrapping a function, rename it. FunctionInfo commandAsFunction = existingCommand as FunctionInfo; - if(commandAsFunction != null) + if (commandAsFunction != null) { string newCommandName = commandAsFunction.Name + "_" + Guid.NewGuid().ToString("N"); commandAsFunction.Rename(newCommandName); @@ -3142,10 +3145,10 @@ namespace System.Management.Automation.Runspaces } // Visit all parameters of the command we're wrapping - foreach(string existingParameter in metadata.Parameters.Keys.ToArray()) + foreach (string existingParameter in metadata.Parameters.Keys.ToArray()) { // If it's not allowed, remove it - if(! commandModification.ContainsKey(existingParameter)) + if (!commandModification.ContainsKey(existingParameter)) { metadata.Parameters.Remove(existingParameter); } @@ -3184,7 +3187,7 @@ namespace System.Management.Automation.Runspaces private static void ProcessCommandModification(Hashtable commandModification, CommandMetadata metadata, string parameterName) { // If the metadata doesn't actually contain the parameter, then we need to create one. - if(! metadata.Parameters.ContainsKey(parameterName)) + if (!metadata.Parameters.ContainsKey(parameterName)) { metadata.Parameters[parameterName] = new ParameterMetadata(parameterName); } @@ -3243,7 +3246,7 @@ namespace System.Management.Automation.Runspaces return null; } - + private Exception ProcessUserDrive(Runspace initializedRunspace) { if (!UserDriveEnabled) { return null; } @@ -3285,7 +3288,7 @@ namespace System.Management.Automation.Runspaces // Set User drive maximum size. Default maximum size is 50MB userDriveInfo.MaximumSize = (UserDriveMaximumSize > 0) ? UserDriveMaximumSize : 50000000; } - catch (ArgumentNullException e) { ex = e; } + catch (ArgumentNullException e) { ex = e; } catch (ArgumentException e) { ex = e; } catch (NotSupportedException e) { ex = e; } catch (ProviderNotFoundException e) { ex = e; } @@ -3302,7 +3305,7 @@ namespace System.Management.Automation.Runspaces { // Use the user name passsed to initial session state if avaiable, or // otherwise use the current user name. - var userName = (!string.IsNullOrEmpty(this.UserDriveUserName)) ? + var userName = (!string.IsNullOrEmpty(this.UserDriveUserName)) ? this.UserDriveUserName : System.Security.Principal.WindowsIdentity.GetCurrent().Name; @@ -3347,7 +3350,7 @@ namespace System.Management.Automation.Runspaces psToInvoke.Runspace = initializedRunspace; - foreach(Command command in psToInvoke.Commands.Commands) + foreach (Command command in psToInvoke.Commands.Commands) { command.CommandOrigin = CommandOrigin.Internal; } @@ -3369,17 +3372,17 @@ namespace System.Management.Automation.Runspaces finally { // Restore the langauge mode, but not if it was altered by the startup script itself. - if(initializedRunspace.SessionStateProxy.LanguageMode == PSLanguageMode.FullLanguage) + if (initializedRunspace.SessionStateProxy.LanguageMode == PSLanguageMode.FullLanguage) { initializedRunspace.SessionStateProxy.LanguageMode = originalLanguageMode; } } - if(ThrowOnRunspaceOpenError) - { + if (ThrowOnRunspaceOpenError) + { // find out if there are any error records reported. If there is one, report the error.. // this will result in the runspace getting closed/broken. - ArrayList errorList = (ArrayList) initializedRunspace.GetExecutionContext.DollarErrorVariable; + ArrayList errorList = (ArrayList)initializedRunspace.GetExecutionContext.DollarErrorVariable; if (errorList.Count > 0) { ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord; @@ -3444,7 +3447,7 @@ namespace System.Management.Automation.Runspaces version = moduleSpecification.RequiredVersion.ToString(); } else if (moduleSpecification.Version != null) - { + { version = moduleSpecification.Version.ToString(); if (moduleSpecification.MaximumVersion != null) { @@ -3488,7 +3491,7 @@ namespace System.Management.Automation.Runspaces { // Special case for wild card lookups. // "Import-Module" or "ipmo" cannot be visible when exposing commands via VisibleCmdlets, etc. - if ((cmd.Name.Equals("Import-Module", StringComparison.OrdinalIgnoreCase) && + if ((cmd.Name.Equals("Import-Module", StringComparison.OrdinalIgnoreCase) && (!string.IsNullOrEmpty(cmd.ModuleName) && cmd.ModuleName.Equals("Microsoft.PowerShell.Core", StringComparison.OrdinalIgnoreCase)) ) || cmd.Name.Equals("ipmo", StringComparison.OrdinalIgnoreCase) @@ -3529,8 +3532,8 @@ namespace System.Management.Automation.Runspaces /// /// private IEnumerable LookupCommands( - string commandPattern, - string moduleName, + string commandPattern, + string moduleName, ExecutionContext context) { bool isWildCardPattern = WildcardPattern.ContainsWildcardCharacters(commandPattern); @@ -3560,8 +3563,8 @@ namespace System.Management.Automation.Runspaces if (!isWildCardPattern) { break; } } - if (found || (cmdOrigin == CommandOrigin.Internal)) - { + if (found || (cmdOrigin == CommandOrigin.Internal)) + { break; } @@ -3598,14 +3601,14 @@ namespace System.Management.Automation.Runspaces cmd.Parameters.Add("Name", name); } - if (! ThrowOnRunspaceOpenError) + if (!ThrowOnRunspaceOpenError) { cmd.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } pse.AddCommand(cmd); - if (! ThrowOnRunspaceOpenError) + if (!ThrowOnRunspaceOpenError) { c = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, initializedRunspace.ExecutionContext); pse.AddCommand(new Command(c)); @@ -3705,7 +3708,8 @@ namespace System.Management.Automation.Runspaces foreach (SessionStateVariableEntry e in InitialSessionState.BuiltInVariables) { PSVariable v = new PSVariable(e.Name, e.Value, - e.Options, e.Attributes, e.Description) { Visibility = e.Visibility }; + e.Options, e.Attributes, e.Description) + { Visibility = e.Visibility }; ss.GlobalScope.SetVariable(e.Name, v, false, true, ss, fastPath: true); } @@ -3715,7 +3719,8 @@ namespace System.Management.Automation.Runspaces foreach (SessionStateVariableEntry e in Variables) { PSVariable v = new PSVariable(e.Name, e.Value, - e.Options, e.Attributes, e.Description) { Visibility = e.Visibility }; + e.Options, e.Attributes, e.Description) + { Visibility = e.Visibility }; ss.GlobalScope.SetVariable(e.Name, v, false, true, ss, fastPath: true); } @@ -4016,7 +4021,7 @@ namespace System.Management.Automation.Runspaces ConcurrentDictionary filesProcessed = new ConcurrentDictionary(/*concurrencyLevel*/3, /*capacity*/3, StringComparer.OrdinalIgnoreCase); Parallel.ForEach(Types, sste => -// foreach (var sste in Types) + // foreach (var sste in Types) { if (sste.FileName != null) { @@ -4044,7 +4049,7 @@ namespace System.Management.Automation.Runspaces context.TypeTable.Update(sste.TypeData, errors, sste.IsRemove); } }); -// } + // } context.TypeTable.ClearConsolidatedMembers(); @@ -4139,7 +4144,7 @@ namespace System.Management.Automation.Runspaces throw PSTraceSource.NewInvalidOperationException(FormatAndOutXmlLoadingStrings.FormatTableCannotCoExist); } } - else if(ssfe.FormatData != null) + else if (ssfe.FormatData != null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } @@ -4221,7 +4226,7 @@ namespace System.Management.Automation.Runspaces if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString())) { - _PSSnapInTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", name); + s_PSSnapInTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", name); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.AddPSSnapInBadMonadVersion, @@ -4310,18 +4315,18 @@ namespace System.Management.Automation.Runspaces if (reload) { - _PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0}", psSnapInInfo.Name); + s_PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0}", psSnapInInfo.Name); assembly = PSSnapInHelpers.LoadPSSnapInAssembly(psSnapInInfo, out cmdlets, out providers); if (assembly == null) { - _PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", psSnapInInfo.Name); + s_PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", psSnapInInfo.Name); warning = null; return null; //BUGBUG - should add something to the warnings list here instead of quitting... } - _PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0} succeeded", psSnapInInfo.Name); + s_PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0} succeeded", psSnapInInfo.Name); PSSnapInHelpers.AnalyzePSSnapInAssembly(assembly, psSnapInInfo.Name, psSnapInInfo, null, true, out cmdlets, out aliases, out providers, out helpFile); } @@ -4417,7 +4422,7 @@ namespace System.Management.Automation.Runspaces { if (func is SessionStateFunctionEntry) { - ((SessionStateFunctionEntry) func).SetHelpFile(helpFile); + ((SessionStateFunctionEntry)func).SetHelpFile(helpFile); } } } @@ -4475,13 +4480,13 @@ namespace System.Management.Automation.Runspaces Dictionary providers = null; Assembly assembly = null; - _PSSnapInTracer.WriteLine("Loading assembly for mshsnapin {0}", psSnapInInfo.Name); + s_PSSnapInTracer.WriteLine("Loading assembly for mshsnapin {0}", psSnapInInfo.Name); assembly = PSSnapInHelpers.LoadPSSnapInAssembly(psSnapInInfo, out cmdlets, out providers); if (assembly == null) { - _PSSnapInTracer.TraceError("Loading assembly for mshsnapin {0} failed", psSnapInInfo.Name); + s_PSSnapInTracer.TraceError("Loading assembly for mshsnapin {0} failed", psSnapInInfo.Name); return; } @@ -4495,7 +4500,7 @@ namespace System.Management.Automation.Runspaces customPSSnapIn = (CustomPSSnapIn)assembly.CreateInstance(psSnapInInfo.CustomPSSnapInType); } - _PSSnapInTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", psSnapInInfo.Name); + s_PSSnapInTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", psSnapInInfo.Name); } catch (TypeLoadException tle) { @@ -4531,7 +4536,7 @@ namespace System.Management.Automation.Runspaces if (psSnapInInfo == null || customPSSnapIn == null) return; - _PSSnapInTracer.WriteLine("Merging configuration from custom mshsnapin {0}", psSnapInInfo.Name); + s_PSSnapInTracer.WriteLine("Merging configuration from custom mshsnapin {0}", psSnapInInfo.Name); if (customPSSnapIn.Cmdlets != null) { @@ -4586,16 +4591,16 @@ namespace System.Management.Automation.Runspaces [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] internal static Assembly LoadAssemblyFromFile(string fileName) { - _PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0}", fileName); + s_PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0}", fileName); Assembly assembly = ClrFacade.LoadFrom(fileName); if (assembly == null) { - _PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", fileName); + s_PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", fileName); return null; } - _PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0} succeeded", fileName); + s_PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0} succeeded", fileName); return assembly; } @@ -4657,7 +4662,7 @@ namespace System.Management.Automation.Runspaces /// /// This is the default function to use for tab expansion. /// - private static string TabExpansionFunctionText = @" + private static string s_tabExpansionFunctionText = @" <# Options include: RelativeFilePaths - [bool] Always resolve file paths using Resolve-Path -Relative. @@ -4716,7 +4721,7 @@ End /// /// Win8: 320909. Retaining the original definition to ensure backward compatability. /// - private static string ImportSystemModulesText = @""; + private static string s_importSystemModulesText = @""; /// /// This is the default function to use for clear-host. On Windows it rewrites the @@ -5503,8 +5508,8 @@ if($paths) { internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] { // Functions. Only the name and definitions are used - SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText, isProductCode: true), - SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", TabExpansionFunctionText, isProductCode: true), + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText, isProductCode: true), + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", s_tabExpansionFunctionText, isProductCode: true), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", GetClearHostFunctionText(), isProductCode: true), // Porting note: we keep more because the function acts correctly on Linux SessionStateFunctionEntry.GetDelayParsedFunctionEntry("more", DefaultMoreFunctionText, isProductCode: true), @@ -5550,7 +5555,7 @@ if($paths) { SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\", isProductCode: true), // Win8: 320909. Retaining the original definition to ensure backward compatability. - SessionStateFunctionEntry.GetDelayParsedFunctionEntry("ImportSystemModules", ImportSystemModulesText, isProductCode: true), + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("ImportSystemModules", s_importSystemModulesText, isProductCode: true), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Pause", string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString),"'"), isProductCode: true) }; @@ -5567,11 +5572,10 @@ if($paths) { { CommandProcessorBase.CheckForSevereException(e); } - } } - static private PSTraceSource _PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); + static private PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); internal static string CoreSnapin = "Microsoft.PowerShell.Core"; internal static string CoreModule = "Microsoft.PowerShell.Core"; @@ -5663,13 +5667,13 @@ if($paths) { { [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] internal static Assembly LoadPSSnapInAssembly(PSSnapInInfo psSnapInInfo, - out Dictionary cmdlets, out Dictionary providers) + out Dictionary cmdlets, out Dictionary providers) { Assembly assembly = null; cmdlets = null; providers = null; - _PSSnapInTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", psSnapInInfo.AssemblyName); + s_PSSnapInTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", psSnapInInfo.AssemblyName); try { @@ -5678,21 +5682,21 @@ if($paths) { } catch (BadImageFormatException e) { - _PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); } catch (FileNotFoundException e) { - _PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); } catch (FileLoadException e) { - _PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); } if (assembly != null) return assembly; - _PSSnapInTracer.WriteLine("Loading assembly from path: {0}", psSnapInInfo.AssemblyName); + s_PSSnapInTracer.WriteLine("Loading assembly from path: {0}", psSnapInInfo.AssemblyName); try { @@ -5701,7 +5705,7 @@ if($paths) { if (!string.Equals(assemblyName.FullName, psSnapInInfo.AssemblyName, StringComparison.OrdinalIgnoreCase)) { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInAssemblyNameMismatch, psSnapInInfo.AbsoluteModulePath, psSnapInInfo.AssemblyName); - _PSSnapInTracer.TraceError(message); + s_PSSnapInTracer.TraceError(message); throw new PSSnapInException(psSnapInInfo.Name, message); } @@ -5709,17 +5713,17 @@ if($paths) { } catch (FileLoadException e) { - _PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); throw new PSSnapInException(psSnapInInfo.Name, e.Message); } catch (BadImageFormatException e) { - _PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); throw new PSSnapInException(psSnapInInfo.Name, e.Message); } catch (FileNotFoundException e) { - _PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); + s_PSSnapInTracer.TraceError("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); throw new PSSnapInException(psSnapInInfo.Name, e.Message); } @@ -5730,13 +5734,13 @@ if($paths) { { var attributes = CustomAttributeExtensions.GetCustomAttributes(decoratedType, false); var customAttrs = attributes.ToArray(); - + Debug.Assert(customAttrs.Length <= 1, "CmdletAttribute and/or CmdletProviderAttribute cannot normally appear more than once"); return customAttrs.Length == 0 ? null : customAttrs[0]; } internal static void AnalyzePSSnapInAssembly(Assembly assembly, string name, PSSnapInInfo psSnapInInfo, PSModuleInfo moduleInfo, bool isModuleLoad, - out Dictionary cmdlets, out Dictionary> aliases, + out Dictionary cmdlets, out Dictionary> aliases, out Dictionary providers, out string helpFile) { helpFile = null; @@ -5752,9 +5756,9 @@ if($paths) { // See if this assembly has already been scanned... Dictionary>> cachedCmdlets; - if (_cmdletCache.Value.TryGetValue(assembly, out cachedCmdlets)) + if (s_cmdletCache.Value.TryGetValue(assembly, out cachedCmdlets)) { - cmdlets = new Dictionary(_cmdletCache.Value.Count, StringComparer.OrdinalIgnoreCase); + cmdlets = new Dictionary(s_cmdletCache.Value.Count, StringComparer.OrdinalIgnoreCase); aliases = new Dictionary>(StringComparer.OrdinalIgnoreCase); foreach (var pair in cachedCmdlets) @@ -5782,7 +5786,7 @@ if($paths) { alias.SetPSSnapIn(psSnapInInfo); } - var newAliasEntry = (SessionStateAliasEntry) alias.Clone(); + var newAliasEntry = (SessionStateAliasEntry)alias.Clone(); if (newAliasEntry.PSSnapIn != null && psSnapInInfo == null) { newAliasEntry.SetPSSnapIn(null); @@ -5796,9 +5800,9 @@ if($paths) { } Dictionary cachedProviders; - if (_providerCache.Value.TryGetValue(assembly, out cachedProviders)) + if (s_providerCache.Value.TryGetValue(assembly, out cachedProviders)) { - providers = new Dictionary(_providerCache.Value.Count, StringComparer.OrdinalIgnoreCase); + providers = new Dictionary(s_providerCache.Value.Count, StringComparer.OrdinalIgnoreCase); foreach (var pair in cachedProviders) { var key = pair.Key; @@ -5820,21 +5824,21 @@ if($paths) { Type[] assemblyTypes; if (cmdlets != null || providers != null) { - if (!_assembliesWithModuleInitializerCache.Value.ContainsKey(assembly)) + if (!s_assembliesWithModuleInitializerCache.Value.ContainsKey(assembly)) { - _PSSnapInTracer.WriteLine("Returning cached cmdlet and provider entries for {0}", assemblyPath); + s_PSSnapInTracer.WriteLine("Returning cached cmdlet and provider entries for {0}", assemblyPath); return; } else { - _PSSnapInTracer.WriteLine("Executing IModuleAssemblyInitializer.Import for {0}", assemblyPath); + s_PSSnapInTracer.WriteLine("Executing IModuleAssemblyInitializer.Import for {0}", assemblyPath); assemblyTypes = GetAssemblyTypes(assembly, name); ExecuteModuleInitializer(assembly, assemblyTypes, isModuleLoad); return; } } - _PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", assemblyPath); + s_PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", assemblyPath); helpFile = GetHelpFile(assemblyPath); @@ -5933,7 +5937,7 @@ if($paths) { throw e.InnerException; } } - + // Cache the cmdlet and provider info for this assembly... // We need to cache a clone of this data *before* the // module info is set on it since module info can't be shared @@ -5959,7 +5963,7 @@ if($paths) { clone[entry.Key] = new Tuple>((SessionStateCmdletEntry)entry.Value.Clone(), aliasesCloneList); } - _cmdletCache.Value[assembly] = clone; + s_cmdletCache.Value[assembly] = clone; } if (providers != null) @@ -5967,9 +5971,9 @@ if($paths) { var clone = new Dictionary(providers.Count, StringComparer.OrdinalIgnoreCase); foreach (var entry in providers) { - clone[entry.Key] = (SessionStateProviderEntry) entry.Value.Clone(); + clone[entry.Key] = (SessionStateProviderEntry)entry.Value.Clone(); } - _providerCache.Value[assembly] = providers; + s_providerCache.Value[assembly] = providers; } } @@ -6012,7 +6016,7 @@ if($paths) { { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateCmdlets, cmdletName, name); - _PSSnapInTracer.TraceError(message); + s_PSSnapInTracer.TraceError(message); throw new PSSnapInException(name, message); } @@ -6046,7 +6050,7 @@ if($paths) { aliases.Add(cmdletName, aliasList); } - _PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", cmdletName, type.FullName); + s_PSSnapInTracer.WriteLine("{0} from type {1} is added as a cmdlet. ", cmdletName, type.FullName); continue; } @@ -6070,7 +6074,7 @@ if($paths) { { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateProviders, providerName, psSnapInInfo.Name); - _PSSnapInTracer.TraceError(message); + s_PSSnapInTracer.TraceError(message); throw new PSSnapInException(psSnapInInfo.Name, message); } @@ -6089,7 +6093,7 @@ if($paths) { } providers.Add(providerName, provider); - _PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", providerName, type.FullName); + s_PSSnapInTracer.WriteLine("{0} from type {1} is added as a provider. ", providerName, type.FullName); } } } @@ -6200,7 +6204,7 @@ if($paths) { if (isModuleLoad && typeof(IModuleAssemblyInitializer).IsAssignableFrom(type) && type != typeof(IModuleAssemblyInitializer)) { - _assembliesWithModuleInitializerCache.Value[assembly] = true; + s_assembliesWithModuleInitializerCache.Value[assembly] = true; IModuleAssemblyInitializer moduleInitializer = (IModuleAssemblyInitializer)Activator.CreateInstance(type, true); moduleInitializer.OnImport(); } @@ -6232,7 +6236,7 @@ if($paths) { } } - _PSSnapInTracer.TraceError(message); + s_PSSnapInTracer.TraceError(message); throw new PSSnapInException(name, message); } @@ -6240,12 +6244,12 @@ if($paths) { } // cmdletCache holds the list of cmdlets along with its aliases per each assembly. - static private Lazy>>>> _cmdletCache = + static private Lazy>>>> s_cmdletCache = new Lazy>>>>(); - static private Lazy>> _providerCache = + static private Lazy>> s_providerCache = new Lazy>>(); // Using a ConcurrentDictionary for this so that we can avoid having a private lock variable. We use only the keys for checking. - private static Lazy> _assembliesWithModuleInitializerCache = new Lazy>(); + private static Lazy> s_assembliesWithModuleInitializerCache = new Lazy>(); static private string GetCmdletName(CmdletAttribute cmdletAttribute) { @@ -6297,7 +6301,7 @@ if($paths) { return Path.GetFileName(assemblyPath) + StringLiterals.HelpFileExtension; } - static private PSTraceSource _PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); + static private PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); } // Guid is {15d4c170-2f29-5689-a0e2-d95b0c7b4ea0} diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 0a3dbfd97..f0d745336 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -23,7 +23,7 @@ namespace Microsoft.PowerShell.Commands /// Implements a cmdlet that applies a script block /// to each element of the pipeline. /// - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] + [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] [Cmdlet("ForEach", "Object", SupportsShouldProcess = true, DefaultParameterSetName = "ScriptBlockSet", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113300", RemotingCapability = RemotingCapability.None)] public sealed class ForEachObjectCommand : PSCmdlet @@ -42,7 +42,7 @@ namespace Microsoft.PowerShell.Commands #region ScriptBlockSet - private List scripts = new List(); + private List _scripts = new List(); /// /// The script block to apply in begin processing @@ -52,7 +52,7 @@ namespace Microsoft.PowerShell.Commands { set { - scripts.Insert(0, value); + _scripts.Insert(0, value); } get { @@ -71,9 +71,9 @@ namespace Microsoft.PowerShell.Commands set { if (value == null) - scripts.Add(null); + _scripts.Add(null); else - scripts.AddRange(value); + _scripts.AddRange(value); } get { @@ -81,8 +81,8 @@ namespace Microsoft.PowerShell.Commands } } - private ScriptBlock endScript; - private bool setEndScript; + private ScriptBlock _endScript; + private bool _setEndScript; /// /// The script block to apply in complete processing /// @@ -91,12 +91,12 @@ namespace Microsoft.PowerShell.Commands { set { - endScript = value; - setEndScript = true; + _endScript = value; + _setEndScript = true; } get { - return endScript; + return _endScript; } } @@ -112,14 +112,14 @@ namespace Microsoft.PowerShell.Commands set { if (value == null) - scripts.Add(null); + _scripts.Add(null); else - scripts.AddRange(value); + _scripts.AddRange(value); } get { return null; } } - private int start, end; + private int _start, _end; #endregion ScriptBlockSet @@ -137,7 +137,7 @@ namespace Microsoft.PowerShell.Commands get { return _propertyOrMethodName; } } private string _propertyOrMethodName; - private string targetString; + private string _targetString; /// /// The arguments passed to a method invocation @@ -207,35 +207,35 @@ namespace Microsoft.PowerShell.Commands } // Calculate the start and end indexes for the processRecord script blocks - end = scripts.Count; - start = scripts.Count > 1 ? 1 : 0; + _end = _scripts.Count; + _start = _scripts.Count > 1 ? 1 : 0; // and set the end script if it wasn't explicilty set with a named parameter. - if (!setEndScript) + if (!_setEndScript) { - if (scripts.Count > 2) + if (_scripts.Count > 2) { - end = scripts.Count - 1; - endScript = scripts[end]; + _end = _scripts.Count - 1; + _endScript = _scripts[_end]; } } // only process the start script if there is more than one script... - if (end < 2) + if (_end < 2) return; - if (scripts[0] == null) + if (_scripts[0] == null) return; var emptyArray = Utils.EmptyArray(); - scripts[0].InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, + _scripts[0].InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: emptyArray, - scriptThis: AutomationNull.Value, - args: emptyArray); + dollarUnder: AutomationNull.Value, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); } /// @@ -255,15 +255,15 @@ namespace Microsoft.PowerShell.Commands switch (ParameterSetName) { case "ScriptBlockSet": - for (int i = start; i < end; i++) + for (int i = _start; i < _end; i++) { // Only execute scripts that aren't null. This isn't treated as an error // because it allows you to parameterize a command - for example you might allow // for actions before and after the main processing script. They could be null // by default and therefore ignored then filled in later... - if (scripts[i] != null) + if (_scripts[i] != null) { - scripts[i].InvokeUsingCmdlet( + _scripts[i].InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -276,11 +276,11 @@ namespace Microsoft.PowerShell.Commands break; case "PropertyAndMethodSet": - targetString = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectTarget, GetStringRepresentation(InputObject)); + _targetString = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectTarget, GetStringRepresentation(InputObject)); if (LanguagePrimitives.IsNull(InputObject)) { - if(_arguments != null && _arguments.Length > 0) + if (_arguments != null && _arguments.Length > 0) { WriteError(GenerateNameParameterError("InputObject", ParserStrings.InvokeMethodOnNull, "InvokeMethodOnNull", _inputObject)); @@ -291,7 +291,7 @@ namespace Microsoft.PowerShell.Commands string propertyAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, _propertyOrMethodName); - if (ShouldProcess(targetString, propertyAction)) + if (ShouldProcess(_targetString, propertyAction)) { if (Context.IsStrictVersion(2)) { @@ -318,7 +318,7 @@ namespace Microsoft.PowerShell.Commands ErrorRecord errorRecord = null; // if args exist, this is explicitly a method invocation - if(_arguments != null && _arguments.Length > 0) + if (_arguments != null && _arguments.Length > 0) { MethodCallWithArguments(); } @@ -329,7 +329,7 @@ namespace Microsoft.PowerShell.Commands if (GetValueFromIDictionaryInput()) { return; } PSMemberInfo member = null; - if(WildcardPattern.ContainsWildcardCharacters(_propertyOrMethodName)) + if (WildcardPattern.ContainsWildcardCharacters(_propertyOrMethodName)) { // get the matched member(s) ReadOnlyPSMemberInfoCollection members = @@ -360,7 +360,7 @@ namespace Microsoft.PowerShell.Commands member = _inputObject.Members[_propertyOrMethodName]; } - if(member == null) + if (member == null) { errorRecord = GenerateNameParameterError("Name", InternalCommandStrings.PropertyOrMethodNotFound, "PropertyOrMethodNotFound", _inputObject, @@ -373,20 +373,20 @@ namespace Microsoft.PowerShell.Commands { // first we check if the member is a ParameterizedProperty PSParameterizedProperty targetParameterizedProperty = member as PSParameterizedProperty; - if(targetParameterizedProperty != null) + if (targetParameterizedProperty != null) { // should process string propertyAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, targetParameterizedProperty.Name); - + // ParameterizedProperty always take parameters, so we output the member.Value directly - if (ShouldProcess(targetString, propertyAction)) + if (ShouldProcess(_targetString, propertyAction)) { WriteObject(member.Value); } return; } - + PSMethodInfo targetMethod = member as PSMethodInfo; Dbg.Assert(targetMethod != null, "targetMethod should not be null here."); try @@ -394,8 +394,8 @@ namespace Microsoft.PowerShell.Commands // should process string methodAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectMethodActionWithoutArguments, targetMethod.Name); - - if (ShouldProcess(targetString, methodAction)) + + if (ShouldProcess(_targetString, methodAction)) { if (!BlockMethodInLanguageMode(InputObject)) { @@ -429,8 +429,8 @@ namespace Microsoft.PowerShell.Commands // should process string propertyAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, member.Name); - - if (ShouldProcess(targetString, propertyAction)) + + if (ShouldProcess(_targetString, propertyAction)) { try { @@ -462,12 +462,12 @@ namespace Microsoft.PowerShell.Commands } // member is not null } // no args provided - if(errorRecord != null) + if (errorRecord != null) { string propertyAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, _propertyOrMethodName); - if (ShouldProcess(targetString, propertyAction)) + if (ShouldProcess(_targetString, propertyAction)) { if (Context.IsStrictVersion(2)) { @@ -528,17 +528,17 @@ namespace Microsoft.PowerShell.Commands // should process StringBuilder arglist = new StringBuilder(GetStringRepresentation(_arguments[0])); - for (int i = 1; i < _arguments.Length; i++ ) + for (int i = 1; i < _arguments.Length; i++) { arglist.AppendFormat(CultureInfo.InvariantCulture, ", {0}", GetStringRepresentation(_arguments[i])); } string methodAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectMethodActionWithArguments, targetMethod.Name, arglist); - + try { - if (ShouldProcess(targetString, methodAction)) + if (ShouldProcess(_targetString, methodAction)) { if (!BlockMethodInLanguageMode(InputObject)) { @@ -604,7 +604,7 @@ namespace Microsoft.PowerShell.Commands { string keyAction = String.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectKeyAction, _propertyOrMethodName); - if (ShouldProcess(targetString, keyAction)) + if (ShouldProcess(_targetString, keyAction)) { object result = hash[_propertyOrMethodName]; WriteToPipelineWithUnrolling(result); @@ -644,7 +644,7 @@ namespace Microsoft.PowerShell.Commands /// private void WriteOutIEnumerator(IEnumerator list) { - if(list != null) + if (list != null) { while (ParserOps.MoveNext(this.Context, null, list)) { @@ -679,7 +679,7 @@ namespace Microsoft.PowerShell.Commands if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { Object baseObject = PSObject.Base(inputObject); - + if (!CoreTypes.Contains(baseObject.GetType())) { PSInvalidOperationException exception = @@ -743,18 +743,18 @@ namespace Microsoft.PowerShell.Commands { if (ParameterSetName != "ScriptBlockSet") return; - if (endScript == null) + if (_endScript == null) return; var emptyArray = Utils.EmptyArray(); - endScript.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, + _endScript.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: emptyArray, - scriptThis: AutomationNull.Value, - args: emptyArray); + dollarUnder: AutomationNull.Value, + input: emptyArray, + scriptThis: AutomationNull.Value, + args: emptyArray); } } @@ -779,7 +779,7 @@ namespace Microsoft.PowerShell.Commands } private PSObject _inputObject = AutomationNull.Value; - private ScriptBlock script; + private ScriptBlock _script; /// /// The script block to apply /// @@ -788,11 +788,11 @@ namespace Microsoft.PowerShell.Commands { set { - script = value; + _script = value; } get { - return script; + return _script; } } @@ -901,8 +901,8 @@ namespace Microsoft.PowerShell.Commands [Alias("IEQ")] public SwitchParameter EQ { - set - { + set + { _binaryOperator = TokenKind.Ieq; _forceBooleanEvaluation = false; } @@ -1220,17 +1220,17 @@ namespace Microsoft.PowerShell.Commands #endregion binary operator parameters - private readonly CallSite> toBoolSite = + private readonly CallSite> _toBoolSite = CallSite>.Create(PSConvertBinder.Get(typeof(bool))); - private Func operationDelegate; + private Func _operationDelegate; - static Func GetCallSiteDelegate(ExpressionType expressionType, bool ignoreCase) + private static Func GetCallSiteDelegate(ExpressionType expressionType, bool ignoreCase) { var site = CallSite>.Create(PSBinaryOperationBinder.Get(expressionType, ignoreCase)); return (x, y) => site.Target.Invoke(site, x, y); } - static Tuple>, CallSite>> GetContainsCallSites(bool ignoreCase) + private static Tuple>, CallSite>> GetContainsCallSites(bool ignoreCase) { var enumerableSite = CallSite>.Create(PSEnumerableBinder.Get()); var eqSite = @@ -1240,7 +1240,7 @@ namespace Microsoft.PowerShell.Commands return Tuple.Create(enumerableSite, eqSite); } - void CheckLanguageMode() + private void CheckLanguageMode() { if (Context.LanguageMode.Equals(PSLanguageMode.RestrictedLanguage)) { @@ -1253,7 +1253,7 @@ namespace Microsoft.PowerShell.Commands } } - object GetLikeRHSOperand(object operand) + private object GetLikeRHSOperand(object operand) { var val = operand as string; if (val == null) @@ -1263,163 +1263,162 @@ namespace Microsoft.PowerShell.Commands ? WildcardOptions.IgnoreCase : WildcardOptions.None; return WildcardPattern.Get(val, wildcardOptions); - } /// protected override void BeginProcessing() { - if (script != null) + if (_script != null) return; switch (_binaryOperator) { - case TokenKind.Ieq: - if (!_forceBooleanEvaluation) - { - operationDelegate = GetCallSiteDelegate(ExpressionType.Equal, ignoreCase: true); - } - else - { - // flip 'lval' and 'rval' in the scenario '... | Where-Object property' so as to make it - // equivalent to '... | Where-Object {$true -eq property}'. Because we want the property to - // be compared under the bool context. So that '"string" | Where-Object Length' would behave - // just like '"string" | Where-Object {$_.Length}'. - var site = CallSite>.Create(PSBinaryOperationBinder.Get(ExpressionType.Equal, true)); - operationDelegate = (x, y) => site.Target.Invoke(site, y, x); - } - break; - case TokenKind.Ceq: - operationDelegate = GetCallSiteDelegate(ExpressionType.Equal, ignoreCase: false); - break; - case TokenKind.Ine: - operationDelegate = GetCallSiteDelegate(ExpressionType.NotEqual, ignoreCase: true); - break; - case TokenKind.Cne: - operationDelegate = GetCallSiteDelegate(ExpressionType.NotEqual, ignoreCase: false); - break; - case TokenKind.Igt: - operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThan, ignoreCase: true); - break; - case TokenKind.Cgt: - operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThan, ignoreCase: false); - break; - case TokenKind.Ilt: - operationDelegate = GetCallSiteDelegate(ExpressionType.LessThan, ignoreCase: true); - break; - case TokenKind.Clt: - operationDelegate = GetCallSiteDelegate(ExpressionType.LessThan, ignoreCase: false); - break; - case TokenKind.Ige: - operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThanOrEqual, ignoreCase: true); - break; - case TokenKind.Cge: - operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThanOrEqual, ignoreCase: false); - break; - case TokenKind.Ile: - operationDelegate = GetCallSiteDelegate(ExpressionType.LessThanOrEqual, ignoreCase: true); - break; - case TokenKind.Cle: - operationDelegate = GetCallSiteDelegate(ExpressionType.LessThanOrEqual, ignoreCase: false); - break; - case TokenKind.Ilike: - operationDelegate = - (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); - break; - case TokenKind.Clike: - operationDelegate = - (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); - break; - case TokenKind.Inotlike: - operationDelegate = - (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); - break; - case TokenKind.Cnotlike: - operationDelegate = - (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); - break; - case TokenKind.Imatch: - CheckLanguageMode(); - operationDelegate = - (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: false, ignoreCase: true); - break; - case TokenKind.Cmatch: - CheckLanguageMode(); - operationDelegate = - (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: false, ignoreCase: false); - break; - case TokenKind.Inotmatch: - CheckLanguageMode(); - operationDelegate = - (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: true, ignoreCase: true); - break; - case TokenKind.Cnotmatch: - CheckLanguageMode(); - operationDelegate = - (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: true, ignoreCase: false); - break; - // the second to last parameter in ContainsOperator has flipped semantics compared to others. - // "true" means "contains" while "false" means "notcontains" - case TokenKind.Icontains: - case TokenKind.Inotcontains: - case TokenKind.In: - case TokenKind.Inotin: - { - var sites = GetContainsCallSites(ignoreCase: true); - switch (_binaryOperator) - { + case TokenKind.Ieq: + if (!_forceBooleanEvaluation) + { + _operationDelegate = GetCallSiteDelegate(ExpressionType.Equal, ignoreCase: true); + } + else + { + // flip 'lval' and 'rval' in the scenario '... | Where-Object property' so as to make it + // equivalent to '... | Where-Object {$true -eq property}'. Because we want the property to + // be compared under the bool context. So that '"string" | Where-Object Length' would behave + // just like '"string" | Where-Object {$_.Length}'. + var site = CallSite>.Create(PSBinaryOperationBinder.Get(ExpressionType.Equal, true)); + _operationDelegate = (x, y) => site.Target.Invoke(site, y, x); + } + break; + case TokenKind.Ceq: + _operationDelegate = GetCallSiteDelegate(ExpressionType.Equal, ignoreCase: false); + break; + case TokenKind.Ine: + _operationDelegate = GetCallSiteDelegate(ExpressionType.NotEqual, ignoreCase: true); + break; + case TokenKind.Cne: + _operationDelegate = GetCallSiteDelegate(ExpressionType.NotEqual, ignoreCase: false); + break; + case TokenKind.Igt: + _operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThan, ignoreCase: true); + break; + case TokenKind.Cgt: + _operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThan, ignoreCase: false); + break; + case TokenKind.Ilt: + _operationDelegate = GetCallSiteDelegate(ExpressionType.LessThan, ignoreCase: true); + break; + case TokenKind.Clt: + _operationDelegate = GetCallSiteDelegate(ExpressionType.LessThan, ignoreCase: false); + break; + case TokenKind.Ige: + _operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThanOrEqual, ignoreCase: true); + break; + case TokenKind.Cge: + _operationDelegate = GetCallSiteDelegate(ExpressionType.GreaterThanOrEqual, ignoreCase: false); + break; + case TokenKind.Ile: + _operationDelegate = GetCallSiteDelegate(ExpressionType.LessThanOrEqual, ignoreCase: true); + break; + case TokenKind.Cle: + _operationDelegate = GetCallSiteDelegate(ExpressionType.LessThanOrEqual, ignoreCase: false); + break; + case TokenKind.Ilike: + _operationDelegate = + (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); + break; + case TokenKind.Clike: + _operationDelegate = + (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); + break; + case TokenKind.Inotlike: + _operationDelegate = + (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); + break; + case TokenKind.Cnotlike: + _operationDelegate = + (lval, rval) => ParserOps.LikeOperator(Context, PositionUtilities.EmptyExtent, lval, rval, _binaryOperator); + break; + case TokenKind.Imatch: + CheckLanguageMode(); + _operationDelegate = + (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: false, ignoreCase: true); + break; + case TokenKind.Cmatch: + CheckLanguageMode(); + _operationDelegate = + (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: false, ignoreCase: false); + break; + case TokenKind.Inotmatch: + CheckLanguageMode(); + _operationDelegate = + (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: true, ignoreCase: true); + break; + case TokenKind.Cnotmatch: + CheckLanguageMode(); + _operationDelegate = + (lval, rval) => ParserOps.MatchOperator(Context, PositionUtilities.EmptyExtent, lval, rval, notMatch: true, ignoreCase: false); + break; + // the second to last parameter in ContainsOperator has flipped semantics compared to others. + // "true" means "contains" while "false" means "notcontains" case TokenKind.Icontains: - operationDelegate = - (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); - break; case TokenKind.Inotcontains: - operationDelegate = - (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); - break; case TokenKind.In: - operationDelegate = - (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); - break; case TokenKind.Inotin: - operationDelegate = - (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); - break; - } - break; - } - case TokenKind.Ccontains: - case TokenKind.Cnotcontains: - case TokenKind.Cin: - case TokenKind.Cnotin: - { - var sites = GetContainsCallSites(ignoreCase: false); - switch (_binaryOperator) - { + { + var sites = GetContainsCallSites(ignoreCase: true); + switch (_binaryOperator) + { + case TokenKind.Icontains: + _operationDelegate = + (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); + break; + case TokenKind.Inotcontains: + _operationDelegate = + (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); + break; + case TokenKind.In: + _operationDelegate = + (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); + break; + case TokenKind.Inotin: + _operationDelegate = + (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); + break; + } + break; + } case TokenKind.Ccontains: - operationDelegate = - (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); - break; case TokenKind.Cnotcontains: - operationDelegate = - (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); - break; case TokenKind.Cin: - operationDelegate = - (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); - break; case TokenKind.Cnotin: - operationDelegate = - (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); + { + var sites = GetContainsCallSites(ignoreCase: false); + switch (_binaryOperator) + { + case TokenKind.Ccontains: + _operationDelegate = + (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); + break; + case TokenKind.Cnotcontains: + _operationDelegate = + (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, lval, rval); + break; + case TokenKind.Cin: + _operationDelegate = + (lval, rval) => ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); + break; + case TokenKind.Cnotin: + _operationDelegate = + (lval, rval) => !ParserOps.ContainsOperatorCompiled(Context, sites.Item1, sites.Item2, rval, lval); + break; + } + break; + } + case TokenKind.Is: + _operationDelegate = (lval, rval) => ParserOps.IsOperator(Context, PositionUtilities.EmptyExtent, lval, rval); + break; + case TokenKind.IsNot: + _operationDelegate = (lval, rval) => ParserOps.IsNotOperator(Context, PositionUtilities.EmptyExtent, lval, rval); break; - } - break; - } - case TokenKind.Is: - operationDelegate = (lval, rval) => ParserOps.IsOperator(Context, PositionUtilities.EmptyExtent, lval, rval); - break; - case TokenKind.IsNot: - operationDelegate = (lval, rval) => ParserOps.IsNotOperator(Context, PositionUtilities.EmptyExtent, lval, rval); - break; } _convertedValue = _value; @@ -1468,17 +1467,17 @@ namespace Microsoft.PowerShell.Commands if (_inputObject == AutomationNull.Value) return; - if (script != null) + if (_script != null) { - object result = script.DoInvokeReturnAsIs( - useLocalScope: false, + object result = _script.DoInvokeReturnAsIs( + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: InputObject, - input: new object[] {_inputObject}, - scriptThis: AutomationNull.Value, - args: Utils.EmptyArray()); + dollarUnder: InputObject, + input: new object[] { _inputObject }, + scriptThis: AutomationNull.Value, + args: Utils.EmptyArray()); - if (toBoolSite.Target.Invoke(toBoolSite, result)) + if (_toBoolSite.Target.Invoke(_toBoolSite, result)) { WriteObject(InputObject); } @@ -1512,8 +1511,8 @@ namespace Microsoft.PowerShell.Commands try { - object result = operationDelegate.Invoke(lvalue, _convertedValue); - if (toBoolSite.Target.Invoke(toBoolSite, result)) + object result = _operationDelegate.Invoke(lvalue, _convertedValue); + if (_toBoolSite.Target.Invoke(_toBoolSite, result)) { WriteObject(InputObject); } @@ -1554,7 +1553,7 @@ namespace Microsoft.PowerShell.Commands { if (LanguagePrimitives.IsNull(InputObject)) { - if(Context.IsStrictVersion(2)) + if (Context.IsStrictVersion(2)) { WriteError( ForEachObjectCommand. @@ -1647,7 +1646,7 @@ namespace Microsoft.PowerShell.Commands { PSMemberInfoInternalCollection restuls = new PSMemberInfoInternalCollection(); PSMemberInfo member = _inputObject.Members[_property]; - if(member != null) + if (member != null) { restuls.Add(member); } @@ -1675,10 +1674,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, 2)] public int Trace { - set { trace = value; } - get { return trace; } + set { _trace = value; } + get { return _trace; } } - private int trace = -1; + private int _trace = -1; /// /// Turns stepping on and off @@ -1686,10 +1685,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "on")] public SwitchParameter Step { - set { step = value; } - get { return (SwitchParameter)step; } + set { _step = value; } + get { return (SwitchParameter)_step; } } - private bool? step; + private bool? _step; /// /// Turns strict mode on and off. @@ -1697,10 +1696,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "on")] public SwitchParameter Strict { - set { strict = value; } - get { return (SwitchParameter)strict; } + set { _strict = value; } + get { return (SwitchParameter)_strict; } } - private bool? strict; + private bool? _strict; /// /// Turns all script debugging features off. @@ -1708,10 +1707,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "off")] public SwitchParameter Off { - get { return off; } - set { off = value; } + get { return _off; } + set { _off = value; } } - private bool off; + private bool _off; /// /// Execute the begin scriptblock at the start of processing @@ -1719,20 +1718,20 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { // -off gets processed after the others so it takes precedence... - if (off) + if (_off) { Context.Debugger.DisableTracing(); Context.EngineSessionState.GlobalScope.StrictModeVersion = null; } else { - if (trace >= 0 || step != null) + if (_trace >= 0 || _step != null) { - Context.Debugger.EnableTracing(trace, step); + Context.Debugger.EnableTracing(_trace, _step); } // Version 0 is the same as off - if (strict != null) - Context.EngineSessionState.GlobalScope.StrictModeVersion = new Version((bool)strict ? 1 : 0, 0); + if (_strict != null) + Context.EngineSessionState.GlobalScope.StrictModeVersion = new Version((bool)_strict ? 1 : 0, 0); } } } @@ -1766,10 +1765,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = "Off", Mandatory = true)] public SwitchParameter Off { - get { return off; } - set { off = value; } + get { return _off; } + set { _off = value; } } - private SwitchParameter off; + private SwitchParameter _off; /// /// To make it easier to specify a version, we add some conversions that wouldn't happen otherwise: @@ -1837,21 +1836,21 @@ namespace Microsoft.PowerShell.Commands [Alias("v")] public Version Version { - get { return version; } - set { version = value; } + get { return _version; } + set { _version = value; } } - private Version version; + private Version _version; /// /// Set the correct version for strict mode checking in the current scope. /// protected override void EndProcessing() { - if (off.IsPresent) + if (_off.IsPresent) { - version = new Version(0, 0); + _version = new Version(0, 0); } - Context.EngineSessionState.CurrentScope.StrictModeVersion = version; + Context.EngineSessionState.CurrentScope.StrictModeVersion = _version; } } #endregion Set-StrictMode diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index b9b0c432e..08468b771 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -24,11 +24,11 @@ namespace System.Management.Automation /// Contructor for InvocationInfo object when the associated command object is present. /// /// - internal InvocationInfo (InternalCommand command) + internal InvocationInfo(InternalCommand command) : this(command.CommandInfo, command.InvocationExtent ?? PositionUtilities.EmptyExtent) { - this._commandOrigin = command.CommandOrigin; + _commandOrigin = command.CommandOrigin; } /// @@ -67,9 +67,9 @@ namespace System.Management.Automation /// internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context) { - this._commandInfo = commandInfo; - this._commandOrigin = CommandOrigin.Internal; - this._scriptPosition = scriptPosition; + _commandInfo = commandInfo; + _commandOrigin = CommandOrigin.Internal; + _scriptPosition = scriptPosition; ExecutionContext contextToUse = null; if ((commandInfo != null) && (commandInfo.Context != null)) @@ -82,7 +82,7 @@ namespace System.Management.Automation } // Populate the history ID of this command - if(contextToUse != null) + if (contextToUse != null) { Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace; if (localRunspace != null && localRunspace.History != null) @@ -97,13 +97,13 @@ namespace System.Management.Automation /// internal InvocationInfo(PSObject psObject) { - this._commandOrigin = (CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin"); - this._expectingInput = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput"); - this._invocationName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName"); - this._historyId = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId"); - this._pipelineLength = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength"); - this._pipelinePosition = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition"); - + _commandOrigin = (CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin"); + _expectingInput = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput"); + _invocationName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName"); + _historyId = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId"); + _pipelineLength = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength"); + _pipelinePosition = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition"); + string scriptName = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName"); int scriptLineNumber = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber"); int offsetInLine = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine"); @@ -120,9 +120,9 @@ namespace System.Management.Automation { scriptEndPosition = scriptPosition; } - this._scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition); + _scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition); - this._commandInfo = RemoteCommandInfo.FromPSObjectForRemoting(psObject); + _commandInfo = RemoteCommandInfo.FromPSObjectForRemoting(psObject); // // Arrays are de-serialized as ArrayList so we need to convert the deserialized @@ -131,11 +131,11 @@ namespace System.Management.Automation var list = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo"); if (list != null) { - this._pipelineIterationInfo = (int[])list.ToArray(typeof(Int32)); + _pipelineIterationInfo = (int[])list.ToArray(typeof(Int32)); } else { - this._pipelineIterationInfo = Utils.EmptyArray(); + _pipelineIterationInfo = Utils.EmptyArray(); } // @@ -154,20 +154,20 @@ namespace System.Management.Automation } } - this._boundParameters = dictionary; + _boundParameters = dictionary; // // The unbound parameters are de-serialized as an ArrayList, which we need to convert to a List // var unboundArguments = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments"); - this._unboundArguments = new List(); + _unboundArguments = new List(); if (unboundArguments != null) { foreach (object o in unboundArguments) { - this._unboundArguments.Add(o); + _unboundArguments.Add(o); } } @@ -196,7 +196,7 @@ namespace System.Management.Automation private CommandOrigin _commandOrigin; private Dictionary _boundParameters; private List _unboundArguments; - + #endregion Internal or Private #region Public Members @@ -205,16 +205,16 @@ namespace System.Management.Automation /// Provide basic information about the command /// /// may be null - public CommandInfo MyCommand + public CommandInfo MyCommand { - get { return this._commandInfo; } + get { return _commandInfo; } } /// /// This member provides a dictionary of the parameters that were bound for this /// script or command. /// - public Dictionary BoundParameters + public Dictionary BoundParameters { get { @@ -387,8 +387,8 @@ namespace System.Management.Automation /// public CommandOrigin CommandOrigin { - get { return this._commandOrigin; } - internal set { this._commandOrigin = value; } + get { return _commandOrigin; } + internal set { _commandOrigin = value; } } /// @@ -399,7 +399,7 @@ namespace System.Management.Automation get { return _displayScriptPosition; } set { _displayScriptPosition = value; } } - IScriptExtent _displayScriptPosition; + private IScriptExtent _displayScriptPosition; /// /// Create @@ -445,7 +445,7 @@ namespace System.Management.Automation /// internal string GetFullScript() { - return (ScriptPosition != null) && (ScriptPosition.StartScriptPosition != null) ? + return (ScriptPosition != null) && (ScriptPosition.StartScriptPosition != null) ? ScriptPosition.StartScriptPosition.GetFullScript() : null; } @@ -498,7 +498,7 @@ namespace System.Management.Automation } else { - RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => false); + RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => false); } RemoteCommandInfo.ToPSObjectForRemoting(this.MyCommand, psObject); @@ -525,7 +525,7 @@ namespace System.Management.Automation /// /// A string representing the definition of the command. /// - public override string Definition { get { return this.definition; } } + public override string Definition { get { return _definition; } } /// /// Creates a RemoteCommandInfo from an instance serialized as a PSObject by ToPSObjectForRemoting. @@ -542,7 +542,7 @@ namespace System.Management.Automation string name = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Name"); commandInfo = new RemoteCommandInfo(name, type); - commandInfo.definition = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Definition"); + commandInfo._definition = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Definition"); commandInfo.Visibility = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Visibility"); } return commandInfo; @@ -575,7 +575,7 @@ namespace System.Management.Automation get { return null; } } - private string definition; + private string _definition; } } diff --git a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs index 21a37432b..49cdc9e97 100644 --- a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs @@ -1,9 +1,10 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -45,8 +46,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.sessionState = cmdlet.Context.EngineSessionState; + _cmdlet = cmdlet; + _sessionState = cmdlet.Context.EngineSessionState; } // CmdletProviderIntrinsics internal /// @@ -68,7 +69,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // CmdletProviderIntrinsics internal #endregion Constructors @@ -118,12 +119,12 @@ namespace System.Management.Automation public Collection Get(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetItem(new string[] { path }, false, false); + return _sessionState.GetItem(new string[] { path }, false, false); } // GetItem /// @@ -175,12 +176,12 @@ namespace System.Management.Automation public Collection Get(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetItem(path, force, literalPath); + return _sessionState.GetItem(path, force, literalPath); } // GetItem /// @@ -228,12 +229,12 @@ namespace System.Management.Automation internal void Get(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.GetItem(new string[] { path }, context); + _sessionState.GetItem(new string[] { path }, context); } // GetItem /// @@ -277,12 +278,12 @@ namespace System.Management.Automation internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetItemDynamicParameters(path, context); + return _sessionState.GetItemDynamicParameters(path, context); } // GetItemDynamicParamters #endregion GetItem @@ -334,12 +335,12 @@ namespace System.Management.Automation public Collection Set(string path, object value) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetItem(new string[] { path }, value, false, false); + return _sessionState.SetItem(new string[] { path }, value, false, false); } // SetItem /// @@ -395,12 +396,12 @@ namespace System.Management.Automation public Collection Set(string[] path, object value, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetItem(path, value, force, literalPath); + return _sessionState.SetItem(path, value, force, literalPath); } // SetItem /// @@ -452,12 +453,12 @@ namespace System.Management.Automation internal void Set(string path, object value, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.SetItem(new string[] { path }, value, context); + _sessionState.SetItem(new string[] { path }, value, context); } // SetItem /// @@ -503,19 +504,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object SetItemDynamicParameters( - string path, - object value, + string path, + object value, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetItemDynamicParameters(path, value, context); + return _sessionState.SetItemDynamicParameters(path, value, context); } // SetItemDynamicParameters - + #endregion SetItem #region ClearItem @@ -561,12 +562,12 @@ namespace System.Management.Automation public Collection Clear(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ClearItem(new string[] { path }, false, false); + return _sessionState.ClearItem(new string[] { path }, false, false); } // ClearItem /// @@ -618,12 +619,12 @@ namespace System.Management.Automation public Collection Clear(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ClearItem(path, force, literalPath); + return _sessionState.ClearItem(path, force, literalPath); } // ClearItem /// @@ -671,12 +672,12 @@ namespace System.Management.Automation internal void Clear(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearItem(new string[] { path }, context); + _sessionState.ClearItem(new string[] { path }, context); } // ClearItem /// @@ -720,14 +721,14 @@ namespace System.Management.Automation internal object ClearItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ClearItemDynamicParameters(path, context); + return _sessionState.ClearItemDynamicParameters(path, context); } // ClearItemDynamicParameters - + #endregion ClearItem #region InvokeDefaultAction @@ -769,12 +770,12 @@ namespace System.Management.Automation public void Invoke(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.InvokeDefaultAction(new string[] { path }, false); + _sessionState.InvokeDefaultAction(new string[] { path }, false); } // InvokeDefaultAction @@ -819,12 +820,12 @@ namespace System.Management.Automation public void Invoke(string[] path, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.InvokeDefaultAction(path, literalPath); + _sessionState.InvokeDefaultAction(path, literalPath); } // InvokeDefaultAction @@ -869,12 +870,12 @@ namespace System.Management.Automation internal void Invoke(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.InvokeDefaultAction(new string[] { path }, context); + _sessionState.InvokeDefaultAction(new string[] { path }, context); } // InvokeDefaultAction /// @@ -918,14 +919,14 @@ namespace System.Management.Automation internal object InvokeItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.InvokeDefaultActionDynamicParameters(path, context); + return _sessionState.InvokeDefaultActionDynamicParameters(path, context); } // InvokeItemDynamicParameters - + #endregion InvokeDefaultAction #region RenameItem @@ -975,12 +976,12 @@ namespace System.Management.Automation public Collection Rename(string path, string newName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenameItem(path, newName, false); + return _sessionState.RenameItem(path, newName, false); } // RenameItem /// @@ -1032,12 +1033,12 @@ namespace System.Management.Automation public Collection Rename(string path, string newName, bool force) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenameItem(path, newName, force); + return _sessionState.RenameItem(path, newName, force); } // RenameItem /// @@ -1087,17 +1088,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Rename( - string path, - string newName, + string path, + string newName, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RenameItem(path, newName, context); + _sessionState.RenameItem(path, newName, context); } // RenameItem /// @@ -1143,17 +1144,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object RenameItemDynamicParameters( - string path, - string newName, + string path, + string newName, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenameItemDynamicParameters(path, newName, context); + return _sessionState.RenameItemDynamicParameters(path, newName, context); } // RenameItemDynamicParameters #endregion RenameItem @@ -1211,18 +1212,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection New( - string path, - string name, - string itemTypeName, + string path, + string name, + string itemTypeName, object content) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewItem(new string[] { path }, name, itemTypeName, content, false); + return _sessionState.NewItem(new string[] { path }, name, itemTypeName, content, false); } // NewItem @@ -1288,12 +1289,12 @@ namespace System.Management.Automation bool force) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewItem(path, name, itemTypeName, content, force); + return _sessionState.NewItem(path, name, itemTypeName, content, force); } // NewItem @@ -1352,19 +1353,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void New( - string path, + string path, string name, - string type, + string type, object content, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.NewItem(new string[] { path }, name, type, content, context); + _sessionState.NewItem(new string[] { path }, name, type, content, context); } // NewItem /// @@ -1414,18 +1415,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object NewItemDynamicParameters( - string path, - string type, - object content, + string path, + string type, + object content, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewItemDynamicParameters(path, type, content, context); + return _sessionState.NewItemDynamicParameters(path, type, content, context); } // NewItemDynamicParameters #endregion NewItem @@ -1475,12 +1476,12 @@ namespace System.Management.Automation public void Remove(string path, bool recurse) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveItem(new string[] { path }, recurse, false, false); + _sessionState.RemoveItem(new string[] { path }, recurse, false, false); } // RemoveItem /// @@ -1534,12 +1535,12 @@ namespace System.Management.Automation public void Remove(string[] path, bool recurse, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveItem(path, recurse, force, literalPath); + _sessionState.RemoveItem(path, recurse, force, literalPath); } // RemoveItem /// @@ -1583,17 +1584,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Remove( - string path, - bool recurse, + string path, + bool recurse, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveItem(new string[] { path }, recurse, context); + _sessionState.RemoveItem(new string[] { path }, recurse, context); } // RemoveItem /// @@ -1641,17 +1642,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object RemoveItemDynamicParameters( - string path, - bool recurse, + string path, + bool recurse, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RemoveItemDynamicParameters(path, recurse, context); + return _sessionState.RemoveItemDynamicParameters(path, recurse, context); } // RemoveItemDynamicParameters #endregion RemoveItem @@ -1710,18 +1711,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Copy( - string path, - string destinationPath, + string path, + string destinationPath, bool recurse, CopyContainers copyContainers) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.CopyItem(new string[] { path }, destinationPath, recurse, copyContainers, false, false); + return _sessionState.CopyItem(new string[] { path }, destinationPath, recurse, copyContainers, false, false); } // CopyItem /// @@ -1792,12 +1793,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.CopyItem(path, destinationPath, recurse, copyContainers, force, literalPath); + return _sessionState.CopyItem(path, destinationPath, recurse, copyContainers, force, literalPath); } // CopyItem /// @@ -1856,19 +1857,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Copy( - string path, + string path, string destinationPath, - bool recurse, + bool recurse, CopyContainers copyContainers, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.CopyItem(new string[] { path }, destinationPath, recurse, copyContainers, context); + _sessionState.CopyItem(new string[] { path }, destinationPath, recurse, copyContainers, context); } // CopyItem /// @@ -1919,18 +1920,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object CopyItemDynamicParameters( - string path, - string destination, - bool recurse, + string path, + string destination, + bool recurse, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.CopyItemDynamicParameters(path, destination, recurse, context); + return _sessionState.CopyItemDynamicParameters(path, destination, recurse, context); } // CopyItemDynamicParameters #endregion CopyItem @@ -1991,12 +1992,12 @@ namespace System.Management.Automation public Collection Move(string path, string destination) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MoveItem(new string[] { path }, destination, false, false); + return _sessionState.MoveItem(new string[] { path }, destination, false, false); } // MoveItem @@ -2062,12 +2063,12 @@ namespace System.Management.Automation public Collection Move(string[] path, string destination, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MoveItem(path, destination, force, literalPath); + return _sessionState.MoveItem(path, destination, force, literalPath); } // MoveItem @@ -2117,19 +2118,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Move( - string path, + string path, string destination, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.MoveItem(new string[] { path }, destination, context); + _sessionState.MoveItem(new string[] { path }, destination, context); } // MoveItem - + /// /// Gets the dynamic parameters for the move-item cmdlet. /// @@ -2173,17 +2174,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object MoveItemDynamicParameters( - string path, - string destination, + string path, + string destination, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MoveItemDynamicParameters(path, destination, context); + return _sessionState.MoveItemDynamicParameters(path, destination, context); } // MoveItemDynamicParameters #endregion MoveItem @@ -2226,12 +2227,12 @@ namespace System.Management.Automation public bool Exists(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ItemExists(path, false, false); + return _sessionState.ItemExists(path, false, false); } // ItemExists /// @@ -2278,12 +2279,12 @@ namespace System.Management.Automation public bool Exists(string path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ItemExists(path, force, literalPath); + return _sessionState.ItemExists(path, force, literalPath); } // ItemExists /// @@ -2324,16 +2325,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal bool Exists( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ItemExists(path, context); + return _sessionState.ItemExists(path, context); } // ItemExists /// @@ -2374,16 +2375,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object ItemExistsDynamicParameters( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ItemExistsDynamicParameters(path, context); + return _sessionState.ItemExistsDynamicParameters(path, context); } // ItemExistsDynamicParameters #endregion ItemExists @@ -2424,14 +2425,14 @@ namespace System.Management.Automation public bool IsContainer(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.IsItemContainer(path); + return _sessionState.IsItemContainer(path); } // IsItemContainer - + /// /// Determines if the specified path is to an item that is a container. /// @@ -2469,26 +2470,26 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal bool IsContainer( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.IsItemContainer(path, context); + return _sessionState.IsItemContainer(path, context); } // IsItemContainer - + #endregion IsItemContainer - #endregion Public methods + #endregion Public methods #region private data - private Cmdlet cmdlet; - private SessionStateInternal sessionState; + private Cmdlet _cmdlet; + private SessionStateInternal _sessionState; #endregion private data } // ItemCmdletProviderIntrinsics diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 28669cb69..08ac5490b 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -249,45 +249,45 @@ namespace System.Management.Automation /// internal enum ConversionRank { - None = 0x0000, + None = 0x0000, UnrelatedArraysS2A = 0x0007, - UnrelatedArrays = 0x000F, - ToStringS2A = 0x0017, - ToString = 0x001F, - CustomS2A = 0x0027, - Custom = 0x002F, - IConvertibleS2A = 0x0037, - IConvertible = 0x003F, - ImplicitCastS2A = 0x0047, - ImplicitCast = 0x004F, - ExplicitCastS2A = 0x0057, - ExplicitCast = 0x005F, - ConstructorS2A = 0x0067, - Constructor = 0x006F, - Create = 0x0073, - ParseS2A = 0x0077, - Parse = 0x007F, - PSObjectS2A = 0x0087, - PSObject = 0x008F, - LanguageS2A = 0x0097, - Language = 0x009F, - NullToValue = 0x00AF, - NullToRef = 0x00BF, - NumericExplicitS2A = 0x00C7, - NumericExplicit = 0x00CF, + UnrelatedArrays = 0x000F, + ToStringS2A = 0x0017, + ToString = 0x001F, + CustomS2A = 0x0027, + Custom = 0x002F, + IConvertibleS2A = 0x0037, + IConvertible = 0x003F, + ImplicitCastS2A = 0x0047, + ImplicitCast = 0x004F, + ExplicitCastS2A = 0x0057, + ExplicitCast = 0x005F, + ConstructorS2A = 0x0067, + Constructor = 0x006F, + Create = 0x0073, + ParseS2A = 0x0077, + Parse = 0x007F, + PSObjectS2A = 0x0087, + PSObject = 0x008F, + LanguageS2A = 0x0097, + Language = 0x009F, + NullToValue = 0x00AF, + NullToRef = 0x00BF, + NumericExplicitS2A = 0x00C7, + NumericExplicit = 0x00CF, NumericExplicit1S2A = 0x00D7, - NumericExplicit1 = 0x00DF, - NumericStringS2A = 0x00E7, - NumericString = 0x00EF, - NumericImplicitS2A = 0x00F7, - NumericImplicit = 0x00FF, - AssignableS2A = 0x0107, - Assignable = 0x010F, - IdentityS2A = 0x0117, + NumericExplicit1 = 0x00DF, + NumericStringS2A = 0x00E7, + NumericString = 0x00EF, + NumericImplicitS2A = 0x00F7, + NumericImplicit = 0x00FF, + AssignableS2A = 0x0107, + Assignable = 0x010F, + IdentityS2A = 0x0117, StringToCharArray = 0x011A, - Identity = 0x011F, + Identity = 0x011F, - ValueDependent = 0xFFF7, + ValueDependent = 0xFFF7, } /// @@ -297,7 +297,7 @@ namespace System.Management.Automation public static class LanguagePrimitives { [TraceSource("ETS", "Extended Type System")] - static private PSTraceSource tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); + static private PSTraceSource s_tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); internal delegate void MemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType); @@ -333,21 +333,21 @@ namespace System.Management.Automation internal static void UpdateTypeConvertFromTypeTable(string typeName) { - lock (converterCache) + lock (s_converterCache) { - var toRemove = converterCache.Keys.Where( + var toRemove = s_converterCache.Keys.Where( conv => string.Equals(conv.to.FullName, typeName, StringComparison.OrdinalIgnoreCase) || string.Equals(conv.from.FullName, typeName, StringComparison.OrdinalIgnoreCase)).ToArray(); foreach (var k in toRemove) { - converterCache.Remove(k); + s_converterCache.Remove(k); } // Note we do not clear possibleTypeConverter even when removing. // // The conversion cache and the possibleTypeConverter cache are process wide, but // the type table used for any specific conversion is runspace specific. - possibleTypeConverter[typeName] = true; + s_possibleTypeConverter[typeName] = true; } } @@ -360,9 +360,9 @@ namespace System.Management.Automation /// private class EnumerableTWrapper : IEnumerable { - object _enumerable; - Type _enumerableType; - DynamicMethod _getEnumerator; + private object _enumerable; + private Type _enumerableType; + private DynamicMethod _getEnumerator; internal EnumerableTWrapper(object enumerable, Type enumerableType) { @@ -408,33 +408,33 @@ namespace System.Management.Automation return null; } - delegate IEnumerable GetEnumerableDelegate(object obj); - static Dictionary getEnumerableCache = new Dictionary(32); + private delegate IEnumerable GetEnumerableDelegate(object obj); + private static Dictionary s_getEnumerableCache = new Dictionary(32); - static GetEnumerableDelegate GetOrCalculateEnumerable(Type type) + private static GetEnumerableDelegate GetOrCalculateEnumerable(Type type) { GetEnumerableDelegate getEnumerable = null; - lock (getEnumerableCache) + lock (s_getEnumerableCache) { - if (!getEnumerableCache.TryGetValue(type, out getEnumerable)) + if (!s_getEnumerableCache.TryGetValue(type, out getEnumerable)) { getEnumerable = CalculateGetEnumerable(type); - getEnumerableCache.Add(type, getEnumerable); + s_getEnumerableCache.Add(type, getEnumerable); } } return getEnumerable; } - static void InitializeGetEnumerableCache() + private static void InitializeGetEnumerableCache() { - lock (getEnumerableCache) + lock (s_getEnumerableCache) { // PowerShell doesn't treat strings as enumerables so just return null. // we also want to return null on common numeric types very quickly - getEnumerableCache.Clear(); - getEnumerableCache.Add(typeof(string), LanguagePrimitives.ReturnNullEnumerable); - getEnumerableCache.Add(typeof(int), LanguagePrimitives.ReturnNullEnumerable); - getEnumerableCache.Add(typeof(double), LanguagePrimitives.ReturnNullEnumerable); + s_getEnumerableCache.Clear(); + s_getEnumerableCache.Add(typeof(string), LanguagePrimitives.ReturnNullEnumerable); + s_getEnumerableCache.Add(typeof(int), LanguagePrimitives.ReturnNullEnumerable); + s_getEnumerableCache.Add(typeof(double), LanguagePrimitives.ReturnNullEnumerable); } } @@ -476,19 +476,19 @@ namespace System.Management.Automation return getEnumerable(obj); } - static IEnumerable ReturnNullEnumerable(object obj) + private static IEnumerable ReturnNullEnumerable(object obj) { return null; } #if !CORECLR - static IEnumerable DataTableEnumerable(object obj) + private static IEnumerable DataTableEnumerable(object obj) { return (((DataTable)obj).Rows); } #endif - static IEnumerable TypicalEnumerable(object obj) + private static IEnumerable TypicalEnumerable(object obj) { IEnumerable e = (IEnumerable)obj; try @@ -522,7 +522,7 @@ namespace System.Management.Automation } } - static GetEnumerableDelegate CalculateGetEnumerable(Type objectType) + private static GetEnumerableDelegate CalculateGetEnumerable(Type objectType) { #if !CORECLR if (typeof(DataTable).IsAssignableFrom(objectType)) @@ -543,7 +543,7 @@ namespace System.Management.Automation } - private static readonly CallSite> _getEnumeratorSite = + private static readonly CallSite> s_getEnumeratorSite = CallSite>.Create(PSEnumerableBinder.Get()); /// @@ -556,7 +556,7 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "Since V1 code is already shipped, excluding this message for backward compatibility reasons.")] public static IEnumerator GetEnumerator(object obj) { - var result = _getEnumeratorSite.Target.Invoke(_getEnumeratorSite, obj); + var result = s_getEnumeratorSite.Target.Invoke(s_getEnumeratorSite, obj); return (result is EnumerableOps.NonEnumerableObjectEnumerator) ? null : result; } @@ -930,31 +930,31 @@ namespace System.Management.Automation { switch (objectArray.Count) { - // a zero length array is false, so condition is false - case 0: - return false; + // a zero length array is false, so condition is false + case 0: + return false; - // if the result is an array of length 1, treat it as a scalar... - case 1: - // A possible implementation would be just - // return IsTrue(objectArray[0]); - // but since we don't want this to recurse indefinately - // we explicitly check the case where it would recurse - // and deal with it. - IList firstElement = objectArray[0] as IList; + // if the result is an array of length 1, treat it as a scalar... + case 1: + // A possible implementation would be just + // return IsTrue(objectArray[0]); + // but since we don't want this to recurse indefinately + // we explicitly check the case where it would recurse + // and deal with it. + IList firstElement = objectArray[0] as IList; - if (firstElement == null) - { - return IsTrue(objectArray[0]); - } + if (firstElement == null) + { + return IsTrue(objectArray[0]); + } - if (firstElement.Count < 1) return false; + if (firstElement.Count < 1) return false; - // the first element is an array with more than zero elements - return true; + // the first element is an array with more than zero elements + return true; - default: - return true; + default: + return true; } } @@ -1126,18 +1126,18 @@ namespace System.Management.Automation [Flags] private enum TypeCodeTraits { - None = 0x00, - SignedInteger = 0x01, - UnsignedInteger = 0x02, - Floating = 0x04, - CimIntrinsicType = 0x08, - Decimal = 0x10, + None = 0x00, + SignedInteger = 0x01, + UnsignedInteger = 0x02, + Floating = 0x04, + CimIntrinsicType = 0x08, + Decimal = 0x10, - Integer = SignedInteger | UnsignedInteger, - Numeric = Integer | Floating | Decimal, + Integer = SignedInteger | UnsignedInteger, + Numeric = Integer | Floating | Decimal, } - private static readonly TypeCodeTraits[] typeCodeTraits = new TypeCodeTraits[] + private static readonly TypeCodeTraits[] s_typeCodeTraits = new TypeCodeTraits[] { /* Empty = 0 */ TypeCodeTraits.None, /* Object = 1 */ TypeCodeTraits.None, @@ -1167,7 +1167,7 @@ namespace System.Management.Automation /// true if type is a signed integer, false otherwise internal static bool IsSignedInteger(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.SignedInteger) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.SignedInteger) != 0; } /// @@ -1177,7 +1177,7 @@ namespace System.Management.Automation /// true if type is an unsigned integer, false otherwise internal static bool IsUnsignedInteger(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.UnsignedInteger) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.UnsignedInteger) != 0; } /// @@ -1187,7 +1187,7 @@ namespace System.Management.Automation /// true if type is integer, false otherwise internal static bool IsInteger(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.Integer) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Integer) != 0; } /// @@ -1197,7 +1197,7 @@ namespace System.Management.Automation /// true if type is floating point, false otherwise internal static bool IsFloating(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.Floating) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Floating) != 0; } /// @@ -1207,7 +1207,7 @@ namespace System.Management.Automation /// true if type is integer or floating point, false otherwise internal static bool IsNumeric(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.Numeric) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Numeric) != 0; } /// @@ -1217,7 +1217,7 @@ namespace System.Management.Automation /// true if type is CIM intrinsic type, false otherwise internal static bool IsCimIntrinsicScalarType(TypeCode typeCode) { - return (typeCodeTraits[(int)typeCode] & TypeCodeTraits.CimIntrinsicType) != 0; + return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.CimIntrinsicType) != 0; } internal static bool IsCimIntrinsicScalarType(Type type) @@ -1370,18 +1370,18 @@ namespace System.Management.Automation ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (ecFromTLS != null) { - tracer.WriteLine("ecFromTLS != null"); + s_tracer.WriteLine("ecFromTLS != null"); typesXmlConverter = ecFromTLS.TypeTable.GetTypeConverter(type.FullName); } if ((typesXmlConverter == null) && (backupTypeTable != null)) { - tracer.WriteLine("Using provided TypeTable to get the type converter"); + s_tracer.WriteLine("Using provided TypeTable to get the type converter"); typesXmlConverter = backupTypeTable.GetTypeConverter(type.FullName); } if (typesXmlConverter != null) { - tracer.WriteLine("typesXmlConverter != null"); + s_tracer.WriteLine("typesXmlConverter != null"); return typesXmlConverter; } @@ -1460,7 +1460,7 @@ namespace System.Management.Automation } string mappedType; - if (nameMap.TryGetValue(typeName, out mappedType)) + if (s_nameMap.TryGetValue(typeName, out mappedType)) { return ('[' + mappedType + ']'); } @@ -1481,7 +1481,7 @@ namespace System.Management.Automation // CIM name string to .NET namestring mapping table // (Considered using the MI routines but they didn't do quite the right thing. // - static Dictionary nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { + private static Dictionary s_nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "SInt8", "SByte" }, { "UInt8", "Byte" }, { "SInt16", "Int16" }, @@ -1494,7 +1494,7 @@ namespace System.Management.Automation { "Real64", "double" }, { "Boolean", "bool" }, { "String", "string" }, - { "DateTime", "DateTime" }, + { "DateTime", "DateTime" }, { "Reference", "CimInstance" }, { "Char16", "char" }, { "Instance", "CimInstance" }, @@ -1652,7 +1652,7 @@ namespace System.Management.Automation /// converted value. public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultType, bool recursion, IFormatProvider formatProvider, bool ignoreUnknownMembers) { - if(valueToConvert != null) + if (valueToConvert != null) { ConstructorInfo toConstructor = resultType.GetConstructor(PSTypeExtensions.EmptyTypes); ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(toConstructor, resultType); @@ -1673,7 +1673,7 @@ namespace System.Management.Automation { return (T)valueToConvert; } - return (T) ConvertTo(valueToConvert, typeof(T), true, CultureInfo.InvariantCulture, null); + return (T)ConvertTo(valueToConvert, typeof(T), true, CultureInfo.InvariantCulture, null); } /// @@ -1780,7 +1780,7 @@ namespace System.Management.Automation internal class EnumSingleTypeConverter : PSTypeConverter { - class EnumHashEntry + private class EnumHashEntry { internal EnumHashEntry(String[] names, Array values, UInt64 allValues, bool hasNegativeValue, bool hasFlagsAttribute) { @@ -1800,22 +1800,22 @@ namespace System.Management.Automation // This static is thread safe based on the lock in GetEnumHashEntry // It can be shared by Runspaces in different MiniShells - static readonly Dictionary enumTable = new Dictionary(); - const int maxEnumTableSize = 100; + private static readonly Dictionary s_enumTable = new Dictionary(); + private const int maxEnumTableSize = 100; private static EnumHashEntry GetEnumHashEntry(Type enumType) { - lock (enumTable) + lock (s_enumTable) { EnumHashEntry returnValue; - if (enumTable.TryGetValue(enumType, out returnValue)) + if (s_enumTable.TryGetValue(enumType, out returnValue)) { return returnValue; } - if (enumTable.Count == maxEnumTableSize) + if (s_enumTable.Count == maxEnumTableSize) { - enumTable.Clear(); + s_enumTable.Clear(); } UInt64 allValues = 0; bool hasNegativeValue = false; @@ -1852,7 +1852,7 @@ namespace System.Management.Automation bool hasFlagsAttribute = enumType.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any(); returnValue = new EnumHashEntry(Enum.GetNames(enumType), values, allValues, hasNegativeValue, hasFlagsAttribute); - enumTable.Add(enumType, returnValue); + s_enumTable.Add(enumType, returnValue); return returnValue; } } @@ -1910,7 +1910,6 @@ namespace System.Management.Automation if (enumHashEntry.hasFlagsAttribute) { - // This expression will result in a "1 bit" for bits that are // set in enumValueInt64 but not set in enumHashEntry.allValues, // and a "0 bit" otherwise. Any "bit 1" in the result, indicates this is not defined. @@ -1925,7 +1924,6 @@ namespace System.Management.Automation else isDefined = false; } - } while (false); return isDefined; @@ -2554,7 +2552,7 @@ namespace System.Management.Automation } } } - tracer.WriteLine("No converter found in original type."); + s_tracer.WriteLine("No converter found in original type."); // now ConvertFrom for the destination type valueConverter = GetConverter(resultType, backupTypeTable); @@ -2715,7 +2713,7 @@ namespace System.Management.Automation typeConversion.WriteLine("Returning CimSession.Create(value to convert)."); try { - return Microsoft.Management.Infrastructure.CimSession.Create((string) valueToConvert); + return Microsoft.Management.Infrastructure.CimSession.Create((string)valueToConvert); } catch (Microsoft.Management.Infrastructure.CimException cimException) { @@ -2742,7 +2740,7 @@ namespace System.Management.Automation { throw exception; } - + throw new PSInvalidCastException("InvalidCastFromStringToType", exception, ExtendedTypeSystem.InvalidCastException, valueToConvert.ToString(), ObjectToTypeNameString(valueToConvert), resultType.ToString()); @@ -3087,7 +3085,7 @@ namespace System.Management.Automation return ((Decimal)valueToConvert) != default(Decimal); } - static PSConverter CreateNumericToBoolConverter(Type fromType) + private static PSConverter CreateNumericToBoolConverter(Type fromType) { Diagnostics.Assert(LanguagePrimitives.IsNumeric(fromType.GetTypeCode()), "Can only convert numeric types"); @@ -3455,7 +3453,7 @@ namespace System.Management.Automation } EnumSingleTypeConverter.ThrowForUndefinedEnum("EnumParseUndefined", result, valueToConvert, resultType); - tracer.WriteLine("returning \"{0}\" from conversion to Enum.", result); + s_tracer.WriteLine("returning \"{0}\" from conversion to Enum.", result); return result; } @@ -3640,7 +3638,7 @@ namespace System.Management.Automation } else { - array = (Array) valueToConvert; + array = (Array)valueToConvert; listSize = array.Length; } @@ -3709,12 +3707,12 @@ namespace System.Management.Automation private class ConvertViaNoArgumentConstructor { - private readonly Func constructor; + private readonly Func _constructor; internal ConvertViaNoArgumentConstructor(ConstructorInfo constructor, Type type) { var newExpr = (constructor != null) ? Expression.New(constructor) : Expression.New(type); - this.constructor = Expression.Lambda>(newExpr.Cast(typeof(object))).Compile(); + _constructor = Expression.Lambda>(newExpr.Cast(typeof(object))).Compile(); } internal object Convert(object valueToConvert, @@ -3724,7 +3722,6 @@ namespace System.Management.Automation IFormatProvider formatProvider, TypeTable backupTable) { - return Convert(valueToConvert, resultType, recursion, originalValueToConvert, formatProvider, backupTable, false); } @@ -3742,7 +3739,7 @@ namespace System.Management.Automation if ((ecFromTLS == null) || (ecFromTLS != null && ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage)) { - result = constructor(); + result = _constructor(); var psobject = valueToConvert as PSObject; if (psobject != null) { @@ -4085,7 +4082,7 @@ namespace System.Management.Automation if (!(other is ConversionTypePair)) return false; - var ctp = (ConversionTypePair) other; + var ctp = (ConversionTypePair)other; return this.from == ctp.from && this.to == ctp.to; } } @@ -4114,44 +4111,44 @@ namespace System.Management.Automation internal class ConversionData : ConversionData { - private readonly PSConverter converter; - private readonly ConversionRank rank; + private readonly PSConverter _converter; + private readonly ConversionRank _rank; public ConversionData(PSConverter converter, ConversionRank rank) { - this.converter = converter; - this.rank = rank; + _converter = converter; + _rank = rank; } public object Converter { - get { return converter; } + get { return _converter; } } public ConversionRank Rank { - get { return rank; } + get { return _rank; } } public object Invoke(object valueToConvert, Type resultType, bool recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) { - return converter.Invoke(valueToConvert, resultType, recurse, originalValueToConvert, formatProvider, backupTable); + return _converter.Invoke(valueToConvert, resultType, recurse, originalValueToConvert, formatProvider, backupTable); } } - static Dictionary converterCache + private static Dictionary s_converterCache = new Dictionary(256); private static ConversionData CacheConversion(Type fromType, Type toType, PSConverter converter, ConversionRank rank) { ConversionTypePair pair = new ConversionTypePair(fromType, toType); ConversionData data = null; - lock (converterCache) + lock (s_converterCache) { - if (!converterCache.TryGetValue(pair, out data)) + if (!s_converterCache.TryGetValue(pair, out data)) { data = new ConversionData(converter, rank); - converterCache.Add(pair, data); + s_converterCache.Add(pair, data); } else { @@ -4164,10 +4161,10 @@ namespace System.Management.Automation private static ConversionData GetConversionData(Type fromType, Type toType) { - lock (converterCache) + lock (s_converterCache) { ConversionData result = null; - converterCache.TryGetValue(new ConversionTypePair(fromType, toType), out result); + s_converterCache.TryGetValue(new ConversionTypePair(fromType, toType), out result); return result; } } @@ -4177,31 +4174,31 @@ namespace System.Management.Automation return FigureConversion(fromType, toType).Rank; } - static Type[] NumericTypes = new Type[] { + private static Type[] s_numericTypes = new Type[] { typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(SByte), typeof(Byte), typeof(Single), typeof(Double), typeof(Decimal) }; - static Type[] IntegerTypes = new Type[] { + private static Type[] s_integerTypes = new Type[] { typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(SByte), typeof(Byte) }; // Do not reorder the elements of these arrays, we depend on them being ordered by increasing size. - static Type[] SignedIntegerTypes = new Type[] { typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64) }; - static Type[] UnsignedIntegerTypes = new Type[] { typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) }; + private static Type[] s_signedIntegerTypes = new Type[] { typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64) }; + private static Type[] s_unsignedIntegerTypes = new Type[] { typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) }; - static Type[] RealTypes = new Type[] { typeof(Single), typeof(Double), typeof(Decimal) }; + private static Type[] s_realTypes = new Type[] { typeof(Single), typeof(Double), typeof(Decimal) }; static internal void RebuildConversionCache() { - lock (converterCache) + lock (s_converterCache) { - converterCache.Clear(); + s_converterCache.Clear(); Type typeofString = typeof(string); Type typeofNull = typeof(Null); @@ -4210,7 +4207,7 @@ namespace System.Management.Automation Type typeofDecimal = typeof(Decimal); Type typeofBool = typeof(bool); Type typeofChar = typeof(char); - foreach (Type type in LanguagePrimitives.NumericTypes) + foreach (Type type in LanguagePrimitives.s_numericTypes) { CacheConversion(type, typeofString, LanguagePrimitives.ConvertNumericToString, ConversionRank.NumericString); CacheConversion(type, typeofChar, LanguagePrimitives.ConvertIConvertible, ConversionRank.NumericString); @@ -4229,52 +4226,52 @@ namespace System.Management.Automation CacheConversion(typeof(Double), typeofBool, ConvertDoubleToBool, ConversionRank.Language); CacheConversion(typeof(Decimal), typeofBool, ConvertDecimalToBool, ConversionRank.Language); - for (int i = 0; i < LanguagePrimitives.UnsignedIntegerTypes.Length; i++) + for (int i = 0; i < LanguagePrimitives.s_unsignedIntegerTypes.Length; i++) { // Identical types are an identity conversion. - CacheConversion(UnsignedIntegerTypes[i], UnsignedIntegerTypes[i], + CacheConversion(s_unsignedIntegerTypes[i], s_unsignedIntegerTypes[i], LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Identity); - CacheConversion(SignedIntegerTypes[i], SignedIntegerTypes[i], + CacheConversion(s_signedIntegerTypes[i], s_signedIntegerTypes[i], LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Identity); // Unsigned to signed same size is explicit - CacheConversion(UnsignedIntegerTypes[i], SignedIntegerTypes[i], + CacheConversion(s_unsignedIntegerTypes[i], s_signedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); // Signed to unsigned same size is explicit, but better than the reverse (because it is "more specific") - CacheConversion(SignedIntegerTypes[i], UnsignedIntegerTypes[i], + CacheConversion(s_signedIntegerTypes[i], s_unsignedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1); - for (int j = i+1; j < LanguagePrimitives.UnsignedIntegerTypes.Length; j++) + for (int j = i + 1; j < LanguagePrimitives.s_unsignedIntegerTypes.Length; j++) { // Conversions where the sign doesn't change, but the size is bigger, is implicit - CacheConversion(UnsignedIntegerTypes[i], UnsignedIntegerTypes[j], + CacheConversion(s_unsignedIntegerTypes[i], s_unsignedIntegerTypes[j], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit); - CacheConversion(SignedIntegerTypes[i], SignedIntegerTypes[j], + CacheConversion(s_signedIntegerTypes[i], s_signedIntegerTypes[j], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit); // Conversion from smaller unsigned to bigger signed is implicit - CacheConversion(UnsignedIntegerTypes[i], SignedIntegerTypes[j], + CacheConversion(s_unsignedIntegerTypes[i], s_signedIntegerTypes[j], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit); // Conversion from smaller signed to bigger unsigned is the "better" explicit conversion - CacheConversion(SignedIntegerTypes[i], UnsignedIntegerTypes[j], + CacheConversion(s_signedIntegerTypes[i], s_unsignedIntegerTypes[j], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1); // Conversion to a smaller type is explicit - CacheConversion(UnsignedIntegerTypes[j], UnsignedIntegerTypes[i], + CacheConversion(s_unsignedIntegerTypes[j], s_unsignedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); - CacheConversion(SignedIntegerTypes[j], SignedIntegerTypes[i], + CacheConversion(s_signedIntegerTypes[j], s_signedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); - CacheConversion(UnsignedIntegerTypes[j], SignedIntegerTypes[i], + CacheConversion(s_unsignedIntegerTypes[j], s_signedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); - CacheConversion(SignedIntegerTypes[j], UnsignedIntegerTypes[i], + CacheConversion(s_signedIntegerTypes[j], s_unsignedIntegerTypes[i], LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); } } - foreach (Type integerType in IntegerTypes) + foreach (Type integerType in s_integerTypes) { CacheConversion(typeofString, integerType, LanguagePrimitives.ConvertStringToInteger, ConversionRank.NumericString); - foreach (Type realType in RealTypes) + foreach (Type realType in s_realTypes) { CacheConversion(integerType, realType, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit); CacheConversion(realType, integerType, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit); @@ -4291,7 +4288,7 @@ namespace System.Management.Automation CacheConversion(typeofString, typeof(Regex), LanguagePrimitives.ConvertStringToRegex, ConversionRank.Language); CacheConversion(typeofString, typeof(char[]), LanguagePrimitives.ConvertStringToCharArray, ConversionRank.StringToCharArray); CacheConversion(typeofString, typeof(Type), LanguagePrimitives.ConvertStringToType, ConversionRank.Language); - CacheConversion(typeofString, typeof (Uri), LanguagePrimitives.ConvertStringToUri, ConversionRank.Language); + CacheConversion(typeofString, typeof(Uri), LanguagePrimitives.ConvertStringToUri, ConversionRank.Language); CacheConversion(typeofString, typeofDecimal, LanguagePrimitives.ConvertStringToDecimal, ConversionRank.NumericString); CacheConversion(typeofString, typeofFloat, LanguagePrimitives.ConvertStringToReal, ConversionRank.NumericString); CacheConversion(typeofString, typeofDouble, LanguagePrimitives.ConvertStringToReal, ConversionRank.NumericString); @@ -4482,7 +4479,6 @@ namespace System.Management.Automation if (pso != null && pso.Properties != null) { - foreach (PSPropertyInfo p in pso.Properties) { if (first == false) @@ -4902,9 +4898,9 @@ namespace System.Management.Automation ConstructorInfo resultConstructor = null; if (toTypeInfo.IsGenericType && !toTypeInfo.ContainsGenericParameters && - (typeof (IList).IsAssignableFrom(toType) || - typeof (ICollection).IsAssignableFrom(toType) || - typeof (IEnumerable).IsAssignableFrom(toType))) + (typeof(IList).IsAssignableFrom(toType) || + typeof(ICollection).IsAssignableFrom(toType) || + typeof(IEnumerable).IsAssignableFrom(toType))) { Type[] argTypes = toType.GetGenericArguments(); if (argTypes.Length != 1) @@ -4916,16 +4912,16 @@ namespace System.Management.Automation } elementType = argTypes[0]; - if (typeof (Array) == fromType || typeof (object[]) == fromType || + if (typeof(Array) == fromType || typeof(object[]) == fromType || elementType.IsAssignableFrom(fromType) || // WinBlue: 423899 : To support scenario like [list[int]]"4" (FigureConversion(fromType, elementType) != null)) { isScalar = elementType.IsAssignableFrom(fromType); ConstructorInfo[] ctors = toType.GetConstructors(); - Type iEnumerableClosedType = typeof (IEnumerable<>).MakeGenericType(elementType); - Type iCollectionClosedType = typeof (ICollection<>).MakeGenericType(elementType); - Type iListClosedType = typeof (IList<>).MakeGenericType(elementType); + Type iEnumerableClosedType = typeof(IEnumerable<>).MakeGenericType(elementType); + Type iCollectionClosedType = typeof(ICollection<>).MakeGenericType(elementType); + Type iListClosedType = typeof(IList<>).MakeGenericType(elementType); foreach (var ctor in ctors) { @@ -4952,9 +4948,9 @@ namespace System.Management.Automation try { - Type listClosedType = typeof (List<>).MakeGenericType(elementType); - ConstructorInfo listCtor = listClosedType.GetConstructor(new Type[] {typeof (int)}); - converter.ListCtorLambda = CreateCtorLambdaClosure(listCtor, typeof (int), false); + Type listClosedType = typeof(List<>).MakeGenericType(elementType); + ConstructorInfo listCtor = listClosedType.GetConstructor(new Type[] { typeof(int) }); + converter.ListCtorLambda = CreateCtorLambdaClosure(listCtor, typeof(int), false); ParameterInfo[] targetParams = resultConstructor.GetParameters(); Type targetParamType = targetParams[0].ParameterType; @@ -4982,11 +4978,11 @@ namespace System.Management.Automation return null; } } - catch(ArgumentException ae) + catch (ArgumentException ae) { typeConversion.WriteLine("Exception finding IEnumerable conversion: \"{0}\".", ae.Message); } - catch(InvalidOperationException ie) + catch (InvalidOperationException ie) { typeConversion.WriteLine("Exception finding IEnumerable conversion: \"{0}\".", ie.Message); } @@ -5000,12 +4996,12 @@ namespace System.Management.Automation private static Func CreateCtorLambdaClosure(ConstructorInfo ctor, Type realParamType, bool useExplicitConversion) { - ParameterExpression paramExpr = Expression.Parameter(typeof (T1), "args"); + ParameterExpression paramExpr = Expression.Parameter(typeof(T1), "args"); Expression castParamExpr = useExplicitConversion ? (Expression)Expression.Call(CachedReflectionInfo.Convert_ChangeType, paramExpr, Expression.Constant(realParamType, typeof(Type))) : Expression.Convert(paramExpr, realParamType); NewExpression ctorExpr = Expression.New(ctor, castParamExpr.Cast(realParamType)); - return Expression.Lambda>(ctorExpr.Cast(typeof (T2)), paramExpr).Compile(); + return Expression.Lambda>(ctorExpr.Cast(typeof(T2)), paramExpr).Compile(); } internal static PSConverter FigureConstructorConversion(Type fromType, Type toType) @@ -5097,12 +5093,12 @@ namespace System.Management.Automation return null; } - if (toType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Length == 0 && - toType.GetFields(BindingFlags.Public | BindingFlags.Instance).Length == 0) - { - // fromType is PSObject, toType has no properties/fields to set, so conversion should fail. - return null; - } + if (toType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Length == 0 && + toType.GetFields(BindingFlags.Public | BindingFlags.Instance).Length == 0) + { + // fromType is PSObject, toType has no properties/fields to set, so conversion should fail. + return null; + } typeConversion.WriteLine("Found Constructor."); @@ -5156,9 +5152,9 @@ namespace System.Management.Automation private static bool TypeConverterPossiblyExists(Type type) { - lock (possibleTypeConverter) + lock (s_possibleTypeConverter) { - if (possibleTypeConverter.ContainsKey(type.FullName)) + if (s_possibleTypeConverter.ContainsKey(type.FullName)) { return true; } @@ -5174,7 +5170,7 @@ namespace System.Management.Automation return false; } - private static Dictionary possibleTypeConverter = new Dictionary(16); + private static Dictionary s_possibleTypeConverter = new Dictionary(16); // This is the internal dummy type used when an IDictionary is converted to a pscustomobject // PS C:\> $ps = [pscustomobject]@{a=10;b=5} @@ -5410,7 +5406,7 @@ namespace System.Management.Automation } #if !CORECLR // AppDomain Not In CoreCLR - static Assembly AssemblyResolveHelper(object sender, ResolveEventArgs args) + private static Assembly AssemblyResolveHelper(object sender, ResolveEventArgs args) { // Dynamic assemblies don't get resolved properly by the CLR, so we // resolve them ourselves by looking through the loaded assemblies. diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 7f4284b54..f4f3d454c 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -15,6 +15,7 @@ using System.ComponentModel; using System.Management.Automation.Internal; using Microsoft.PowerShell; using Dbg = System.Management.Automation.Diagnostics; + #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation @@ -25,7 +26,6 @@ namespace System.Management.Automation /// internal abstract class BaseWMIAdapter : Adapter { - #region WMIMethodCacheEntry /// @@ -40,44 +40,44 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private string name; + private string _name; public string ClassPath { get { - return classPath; + return _classPath; } } - private string classPath; + private string _classPath; public MethodInformation MethodInfoStructure { get { - return methodInfoStructure; + return _methodInfoStructure; } } - private MethodInformation methodInfoStructure; + private MethodInformation _methodInfoStructure; public string MethodDefinition { get { - return methodDefinition; + return _methodDefinition; } } - private string methodDefinition; + private string _methodDefinition; internal WMIMethodCacheEntry(string n, string cPath, MethodData mData) { - this.name = n; - this.classPath = cPath; - methodInfoStructure = ManagementObjectAdapter.GetMethodInformation(mData); - methodDefinition = ManagementObjectAdapter.GetMethodDefinition(mData); + _name = n; + _classPath = cPath; + _methodInfoStructure = ManagementObjectAdapter.GetMethodInformation(mData); + _methodDefinition = ManagementObjectAdapter.GetMethodDefinition(mData); } } @@ -91,14 +91,14 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private string name; + private string _name; public WMIParameterInformation(string name, Type ty) : base(ty, true, null, false) { - this.name = name; + _name = name; } } @@ -160,7 +160,7 @@ namespace System.Management.Automation } } } - + /// /// Returns the TypeNameHierarchy out of an ManagementBaseObject /// @@ -251,9 +251,9 @@ namespace System.Management.Automation // obj should never be null Diagnostics.Assert(obj != null, "Input object is null"); - ManagementBaseObject wmiObject = (ManagementBaseObject) obj; + ManagementBaseObject wmiObject = (ManagementBaseObject)obj; PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); - AddAllProperties(wmiObject, returnValue); + AddAllProperties(wmiObject, returnValue); AddAllMethods(wmiObject, returnValue); return returnValue; } @@ -287,7 +287,7 @@ namespace System.Management.Automation WMIMethodCacheEntry methodEntry = (WMIMethodCacheEntry)method.adapterData; Collection returnValue = new Collection(); returnValue.Add(methodEntry.MethodDefinition); - + return returnValue; } @@ -364,7 +364,7 @@ namespace System.Management.Automation } else { - typeName = forDisplay ? ToStringCodeMethods.Type(dotNetType) : dotNetType.ToString(); + typeName = forDisplay ? ToStringCodeMethods.Type(dotNetType) : dotNetType.ToString(); } return typeName; @@ -447,7 +447,7 @@ namespace System.Management.Automation returnValue.Append("}"); return returnValue.ToString(); } - + /// /// Returns an array with the property attributes /// @@ -461,7 +461,7 @@ namespace System.Management.Automation #endregion #region Private/Internal Methods - + /// /// Retrieves the table for instance methods /// @@ -470,7 +470,7 @@ namespace System.Management.Automation protected static CacheTable GetInstanceMethodTable(ManagementBaseObject wmiObject, bool staticBinding) { - lock (instanceMethodCacheTable) + lock (s_instanceMethodCacheTable) { CacheTable typeTable = null; @@ -478,7 +478,7 @@ namespace System.Management.Automation ManagementPath classPath = wmiObject.ClassPath; string key = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", classPath.Path, staticBinding.ToString()); - typeTable = (CacheTable)instanceMethodCacheTable[key]; + typeTable = (CacheTable)s_instanceMethodCacheTable[key]; if (typeTable != null) { tracer.WriteLine("Returning method information from internal cache"); @@ -502,7 +502,7 @@ namespace System.Management.Automation mgmtClass = CreateClassFrmObject(wmiObject); } PopulateMethodTable(mgmtClass, typeTable, staticBinding); - instanceMethodCacheTable[key] = typeTable; + s_instanceMethodCacheTable[key] = typeTable; } catch (ManagementException) { @@ -627,7 +627,7 @@ namespace System.Management.Automation "Input PropertyData should not be null"); tracer.WriteLine("Getting DotNet Type for CimType : {0}", pData.Type); - + string retValue; switch (pData.Type) { @@ -678,7 +678,7 @@ namespace System.Management.Automation case CimType.Char16: retValue = typeof(char).FullName; break; - case CimType.Object: + case CimType.Object: default: retValue = typeof(object).FullName; break; @@ -688,7 +688,7 @@ namespace System.Management.Automation { retValue += "[]"; } - + return Type.GetType(retValue); } @@ -729,13 +729,13 @@ namespace System.Management.Automation { // Evaluate method and arguments object[] verifiedArguments; - + MethodInformation[] methods = new MethodInformation[1]; methods[0] = mdata.MethodInfoStructure; // This will convert Null Strings to Empty Strings GetBestMethodAndArguments(mdata.Name, methods, arguments, out verifiedArguments); - + ParameterInformation[] parameterList = mdata.MethodInfoStructure.parameters; // GetBestMethodAndArguments should fill verifiedArguments with @@ -745,7 +745,7 @@ namespace System.Management.Automation Diagnostics.Assert(parameterList.Length == verifiedArguments.Length, "The number of parameters and arguments should match"); - + // we should not cache inParameters as we are updating // inParameters object with argument values..Caching will @@ -756,7 +756,7 @@ namespace System.Management.Automation ManagementClass mClass = CreateClassFrmObject(obj); ManagementBaseObject inParameters = mClass.GetMethodParameters(mdata.Name); - for (int i = 0; i < parameterList.Length ; i++) + for (int i = 0; i < parameterList.Length; i++) { // this cast should always succeed WMIParameterInformation pInfo = (WMIParameterInformation)parameterList[i]; @@ -767,7 +767,7 @@ namespace System.Management.Automation // conversions. So dont convert input arguments if they are null. // We could have done this in the base adapter but the change would be // costly for other adpaters which dont mind the conversion. - if ( (i < arguments.Length) && (arguments[i] == null)) + if ((i < arguments.Length) && (arguments[i] == null)) { verifiedArguments[i] = null; } @@ -786,7 +786,7 @@ namespace System.Management.Automation /// /// Should not throw exceptions /// - internal static void UpdateParameters(ManagementBaseObject parameters, + internal static void UpdateParameters(ManagementBaseObject parameters, SortedList parametersList) { // ManagementObject class do not populate parameters when there are none. @@ -833,8 +833,8 @@ namespace System.Management.Automation /// internal static MethodInformation GetMethodInformation(MethodData mData) { - Diagnostics.Assert(mData != null,"MethodData should not be null"); - + Diagnostics.Assert(mData != null, "MethodData should not be null"); + // Get Method parameters SortedList parameters = new SortedList(); UpdateParameters(mData.InParameters, parameters); @@ -846,7 +846,7 @@ namespace System.Management.Automation parameters.Values.CopyTo(pInfos, 0); } - MethodInformation returnValue = new MethodInformation(false, true, pInfos); + MethodInformation returnValue = new MethodInformation(false, true, pInfos); return returnValue; } @@ -860,13 +860,13 @@ namespace System.Management.Automation UpdateParameters(mData.InParameters, parameters); StringBuilder inParameterString = new StringBuilder(); - + if (parameters.Count > 0) { foreach (WMIParameterInformation parameter in parameters.Values) { string typeName = parameter.parameterType.ToString(); - + PropertyData pData = mData.InParameters.Properties[parameter.Name]; if (pData.Type == CimType.Object) { @@ -901,7 +901,7 @@ namespace System.Management.Automation string returnValue = builder.ToString(); tracer.WriteLine("Definition constructed: {0}", returnValue); - + return returnValue; } @@ -962,7 +962,7 @@ namespace System.Management.Automation #region Private Data - private static HybridDictionary instanceMethodCacheTable = new HybridDictionary(); + private static HybridDictionary s_instanceMethodCacheTable = new HybridDictionary(); #endregion } @@ -1009,7 +1009,7 @@ namespace System.Management.Automation /// Method data. /// Method arguments. /// - protected override object InvokeManagementMethod(ManagementObject wmiObject, + protected override object InvokeManagementMethod(ManagementObject wmiObject, string methodName, ManagementBaseObject inParams) { tracer.WriteLine("Invoking class method: {0}", methodName); @@ -1148,7 +1148,7 @@ namespace System.Management.Automation PSTask.None, PSKeyword.UseAlwaysOperational, string.Format(CultureInfo.InvariantCulture, - "ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{0}, Exception:{1}, StackTrace:{2}", + "ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{0}, Exception:{1}, StackTrace:{2}", propertyName, e.Message, e.StackTrace), string.Empty, string.Empty); @@ -1210,7 +1210,7 @@ namespace System.Management.Automation foreach (WMIMethodCacheEntry methodEntry in table.memberCollection) { if (members[methodEntry.Name] == null) - { + { tracer.WriteLine("Adding method {0}", methodEntry.Name); members.Add(new PSMethod(methodEntry.Name, this, wmiObject, methodEntry) as T); } diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index e28809d84..83fb9df1d 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -34,28 +34,28 @@ namespace System.Management.Automation var result = new List(); // Replace bindable parameters - bindableParameters.Clear(); + _bindableParameters.Clear(); foreach (KeyValuePair entry in metadata.BindableParameters) { - bindableParameters.Add(entry.Key, entry.Value); + _bindableParameters.Add(entry.Key, entry.Value); result.Add(entry.Value); } - aliasedParameters.Clear(); + _aliasedParameters.Clear(); foreach (KeyValuePair entry in metadata.AliasedParameters) { - aliasedParameters.Add(entry.Key, entry.Value); + _aliasedParameters.Add(entry.Key, entry.Value); } // Replace additional meta info _defaultParameterSetName = metadata._defaultParameterSetName; - nextAvailableParameterSetIndex = metadata.nextAvailableParameterSetIndex; - - parameterSetMap.Clear(); - var parameterSetMapInList = (List) parameterSetMap; - parameterSetMapInList.AddRange(metadata.parameterSetMap); + _nextAvailableParameterSetIndex = metadata._nextAvailableParameterSetIndex; - Diagnostics.Assert(ParameterSetCount == nextAvailableParameterSetIndex, + _parameterSetMap.Clear(); + var parameterSetMapInList = (List)_parameterSetMap; + parameterSetMapInList.AddRange(metadata._parameterSetMap); + + Diagnostics.Assert(ParameterSetCount == _nextAvailableParameterSetIndex, "After replacement with the metadata of the new parameters, ParameterSetCount should be equal to nextAvailableParameterSetIndex"); return result; @@ -100,7 +100,7 @@ namespace System.Management.Automation foreach (KeyValuePair bindableParameter in parameterMetadata.BindableParameters) { - if (this.bindableParameters.ContainsKey(bindableParameter.Key)) + if (_bindableParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( @@ -112,7 +112,7 @@ namespace System.Management.Automation } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN - if (this.aliasedParameters.ContainsKey(bindableParameter.Key)) + if (_aliasedParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( @@ -120,21 +120,21 @@ namespace System.Management.Automation null, Metadata.ParameterNameConflictsWithAlias, bindableParameter.Key, - RetrieveParameterNameForAlias(bindableParameter.Key,this.aliasedParameters)); + RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters)); throw exception; } MergedCompiledCommandParameter mergedParameter = new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); - bindableParameters.Add(bindableParameter.Key, mergedParameter); + _bindableParameters.Add(bindableParameter.Key, mergedParameter); result.Add(mergedParameter); // Merge in the aliases foreach (string aliasName in bindableParameter.Value.Aliases) { - if (this.aliasedParameters.ContainsKey(aliasName)) + if (_aliasedParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( @@ -146,21 +146,20 @@ namespace System.Management.Automation } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN - if (this.bindableParameters.ContainsKey(aliasName)) + if (_bindableParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, - RetrieveParameterNameForAlias(aliasName,this.bindableParameters), + RetrieveParameterNameForAlias(aliasName, _bindableParameters), bindableParameter.Value.Name); throw exception; } - aliasedParameters.Add(aliasName, mergedParameter); + _aliasedParameters.Add(aliasName, mergedParameter); } - } return result; } @@ -171,7 +170,7 @@ namespace System.Management.Automation /// set bit is really 1 shifted left this number of times. This number also acts /// as the index for the parameter set map. /// - private uint nextAvailableParameterSetIndex; + private uint _nextAvailableParameterSetIndex; /// /// Gets the number of parameter sets that were declared for the command. @@ -181,7 +180,7 @@ namespace System.Management.Automation { get { - return parameterSetMap.Count; + return _parameterSetMap.Count; } } // ParameterSetCount @@ -203,7 +202,7 @@ namespace System.Management.Automation /// New parameter sets are added at the nextAvailableParameterSetIndex. /// /// - private IList parameterSetMap = new List(); + private IList _parameterSetMap = new List(); /// /// The name of the default parameter set @@ -239,12 +238,12 @@ namespace System.Management.Automation int index = -1; if (!String.IsNullOrEmpty(parameterSetName)) { - index = parameterSetMap.IndexOf(parameterSetName); + index = _parameterSetMap.IndexOf(parameterSetName); // A parameter set name should only be added once if (index == -1) { - if (nextAvailableParameterSetIndex == uint.MaxValue) + if (_nextAvailableParameterSetIndex == uint.MaxValue) { // Don't let the parameter set index overflow ParsingMetadataException parsingException = @@ -256,14 +255,14 @@ namespace System.Management.Automation throw parsingException; } - parameterSetMap.Add(parameterSetName); - index = parameterSetMap.IndexOf(parameterSetName); + _parameterSetMap.Add(parameterSetName); + index = _parameterSetMap.IndexOf(parameterSetName); Diagnostics.Assert( - index == nextAvailableParameterSetIndex, + index == _nextAvailableParameterSetIndex, "AddParameterSetToMap should always add the parameter set name to the map at the nextAvailableParameterSetIndex"); - nextAvailableParameterSetIndex++; + _nextAvailableParameterSetIndex++; } } return index; @@ -290,8 +289,8 @@ namespace System.Management.Automation internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSetName) { // First clear the parameter set map - parameterSetMap.Clear(); - nextAvailableParameterSetIndex = 0; + _parameterSetMap.Clear(); + _nextAvailableParameterSetIndex = 0; uint defaultParameterSetFlag = 0; @@ -389,9 +388,9 @@ namespace System.Management.Automation if (((parameterSet >> (index + 1)) & 0x1) == 0) { // Ensure that the bit found was within the map, if not return an empty string - if (index < parameterSetMap.Count) + if (index < _parameterSetMap.Count) { - result = parameterSetMap[index]; + result = _parameterSetMap[index]; } else { @@ -473,7 +472,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - Collection matchingParameters = + Collection matchingParameters = new Collection(); // Skip the leading '-' if present @@ -485,7 +484,7 @@ namespace System.Management.Automation // First try to match the bindable parameters - foreach (string parameterName in bindableParameters.Keys) + foreach (string parameterName in _bindableParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { @@ -494,18 +493,18 @@ namespace System.Management.Automation if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { - return bindableParameters[parameterName]; + return _bindableParameters[parameterName]; } else { - matchingParameters.Add(bindableParameters[parameterName]); + matchingParameters.Add(_bindableParameters[parameterName]); } } } // Now check the aliases - foreach (string parameterName in aliasedParameters.Keys) + foreach (string parameterName in _aliasedParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { @@ -514,13 +513,13 @@ namespace System.Management.Automation if (tryExactMatching && String.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { - return aliasedParameters[parameterName]; + return _aliasedParameters[parameterName]; } else { - if (!matchingParameters.Contains(aliasedParameters[parameterName])) + if (!matchingParameters.Contains(_aliasedParameters[parameterName])) { - matchingParameters.Add(aliasedParameters[parameterName]); + matchingParameters.Add(_aliasedParameters[parameterName]); } } } @@ -534,14 +533,14 @@ namespace System.Management.Automation foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters) { - if((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) || - (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters) ) + if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) || + (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters)) { filteredParameters.Add(matchingParameter); } } - if(filteredParameters.Count == 1) + if (filteredParameters.Count == 1) { matchingParameters = filteredParameters; } @@ -611,7 +610,7 @@ namespace System.Management.Automation /// internal Collection GetParametersInParameterSet(uint parameterSetFlag) { - Collection result = + Collection result = new Collection(); foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values) @@ -630,31 +629,30 @@ namespace System.Management.Automation /// The dictionary keys are the names of the parameters and /// the values are the compiled parameter metdata. /// - internal IDictionary BindableParameters { get { return bindableParameters; } } - private IDictionary bindableParameters = + internal IDictionary BindableParameters { get { return _bindableParameters; } } + private IDictionary _bindableParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); /// /// Gets a dictionary of the parameters that have been aliased to other names. The key is /// the alias name and the value is the MergedCompiledCommandParameter metadata. /// - internal IDictionary AliasedParameters { get { return aliasedParameters; } } - private IDictionary aliasedParameters = + internal IDictionary AliasedParameters { get { return _aliasedParameters; } } + private IDictionary _aliasedParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); internal void MakeReadOnly() { - bindableParameters = new ReadOnlyDictionary(bindableParameters); - aliasedParameters = new ReadOnlyDictionary(aliasedParameters); - parameterSetMap = new ReadOnlyCollection(parameterSetMap); + _bindableParameters = new ReadOnlyDictionary(_bindableParameters); + _aliasedParameters = new ReadOnlyDictionary(_aliasedParameters); + _parameterSetMap = new ReadOnlyCollection(_parameterSetMap); } internal void ResetReadOnly() { - bindableParameters = new Dictionary(bindableParameters, StringComparer.OrdinalIgnoreCase); - aliasedParameters = new Dictionary(aliasedParameters, StringComparer.OrdinalIgnoreCase); + _bindableParameters = new Dictionary(_bindableParameters, StringComparer.OrdinalIgnoreCase); + _aliasedParameters = new Dictionary(_aliasedParameters, StringComparer.OrdinalIgnoreCase); } - } // MergedCommandParameterMetadata /// diff --git a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs index 593760f3d..44e097b1f 100644 --- a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs +++ b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.ObjectModel; using System.IO; @@ -116,7 +117,7 @@ namespace System.Management.Automation if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter, - typeof (ScriptBlock), null, + typeof(ScriptBlock), null, NativeCP.NoValueForCommandParameter, "NoValueForCommandParameter"); } @@ -129,11 +130,11 @@ namespace System.Management.Automation if (!scriptBlockArgument.ArgumentSpecified || !(argumentValue is ScriptBlock)) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, CommandParameter, - typeof (ScriptBlock), argumentValue.GetType(), + typeof(ScriptBlock), argumentValue.GetType(), NativeCP.IncorrectValueForCommandParameter, "IncorrectValueForCommandParameter"); } - + // Replace the parameters with -EncodedCommand parameters[i - 1] = CommandParameterInternal.CreateParameter(parameter.ParameterExtent, EncodedCommandParameter, "-" + EncodedCommandParameter); string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString()); @@ -147,11 +148,11 @@ namespace System.Management.Automation if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, InputFormatParameter, - typeof (string), null, + typeof(string), null, NativeCP.NoValueForInputFormatParameter, "NoValueForInputFormatParameter"); } - + // Update the argument (partial arguments are allowed) i += 1; var inputFormatArg = parameters[i]; @@ -167,11 +168,11 @@ namespace System.Management.Automation if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, OutputFormatParameter, - typeof (string), null, + typeof(string), null, NativeCP.NoValueForOutputFormatParameter, "NoValueForInputFormatParameter"); } - + // Update the argument (partial arguments are allowed) i += 1; var outputFormatArg = parameters[i]; @@ -187,7 +188,7 @@ namespace System.Management.Automation if (i + 1 >= parameters.Count) { throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, ArgsParameter, - typeof (string), null, NativeCP.NoValuesSpecifiedForArgs, + typeof(string), null, NativeCP.NoValuesSpecifiedForArgs, "NoValuesSpecifiedForArgs"); } @@ -207,7 +208,7 @@ namespace System.Management.Automation if (argumentValue is ScriptBlock) { HandleSeenParameter(ref seen, MinishellParameters.Command, CommandParameter); - + // Replace the argument with -EncodedCommand string encodedScript = StringToBase64Converter.StringToBase64String(argumentValue.ToString()); parameters[i] = CommandParameterInternal.CreateParameterWithArgument( @@ -215,7 +216,6 @@ namespace System.Management.Automation parameter.ArgumentExtent, encodedScript, spaceAfterParameter: true, arrayIsSingleArgumentForNativeCommand: false); } - } } @@ -256,12 +256,12 @@ namespace System.Management.Automation ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters); - Diagnostics.Assert(emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared."); + Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared."); - return emptyReturnCollection; + return s_emptyReturnCollection; } // BindParameters - static readonly Collection emptyReturnCollection = new Collection(); + private static readonly Collection s_emptyReturnCollection = new Collection(); internal const string CommandParameter = "command"; internal const string EncodedCommandParameter = "encodedCommand"; @@ -274,7 +274,7 @@ namespace System.Management.Automation internal const string NonInteractiveParameter = "noninteractive"; [Flags] - enum MinishellParameters + private enum MinishellParameters { Command = 0x01, Arguments = 0x02, @@ -285,13 +285,13 @@ namespace System.Management.Automation /// /// Handles error handling if some parameter is specified more than once. /// - void HandleSeenParameter(ref MinishellParameters seen, MinishellParameters parameter, string parameterName) + private void HandleSeenParameter(ref MinishellParameters seen, MinishellParameters parameter, string parameterName) { if ((seen & parameter) == parameter) { - throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, + throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, "-" + parameterName, null, null, - NativeCP.ParameterSpecifiedAlready, + NativeCP.ParameterSpecifiedAlready, "ParameterSpecifiedAlready", parameterName); } @@ -307,7 +307,7 @@ namespace System.Management.Automation /// Name of the parameter for error messages. Value should be -inputFormat or -outputFormat /// value to process /// Processed value - string + private string ProcessFormatParameterValue(string parameterName, object value) { string fpValue; @@ -317,8 +317,8 @@ namespace System.Management.Automation } catch (PSInvalidCastException ex) { - throw NewParameterBindingException(ex, ErrorCategory.InvalidArgument, parameterName, - typeof (string), value.GetType(), + throw NewParameterBindingException(ex, ErrorCategory.InvalidArgument, parameterName, + typeof(string), value.GetType(), NativeCP.StringValueExpectedForFormatParameter, "StringValueExpectedForFormatParameter", parameterName); } @@ -332,25 +332,25 @@ namespace System.Management.Automation return TextFormatValue; } - throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, parameterName, - typeof (string), value.GetType(), + throw NewParameterBindingException(null, ErrorCategory.InvalidArgument, parameterName, + typeof(string), value.GetType(), NativeCP.IncorrectValueForFormatParameter, - "IncorrectValueForFormatParameter", + "IncorrectValueForFormatParameter", fpValue, parameterName); } /// /// Converts value of args parameter in to an encoded string /// - static string ConvertArgsValueToEncodedString(object value) + private static string ConvertArgsValueToEncodedString(object value) { ArrayList list = ConvertArgsValueToArrayList(value); //Serialize the list StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); //When (if) switching to XmlTextWriter.Create remember the OmitXmlDeclaration difference - XmlWriter xmlWriter = XmlWriter.Create(stringWriter); - Serializer serializer = new Serializer(xmlWriter); + XmlWriter xmlWriter = XmlWriter.Create(stringWriter); + Serializer serializer = new Serializer(xmlWriter); serializer.Serialize(list); serializer.Done(); xmlWriter.Flush(); @@ -364,7 +364,7 @@ namespace System.Management.Automation /// Converts the value of -args parameter received from /// parser in to an arraylist /// - static ArrayList ConvertArgsValueToArrayList(object value) + private static ArrayList ConvertArgsValueToArrayList(object value) { ArrayList results = new ArrayList(); IEnumerator list = LanguagePrimitives.GetEnumerator(value); @@ -382,7 +382,7 @@ namespace System.Management.Automation return results; } - ParameterBindingException NewParameterBindingException( + private ParameterBindingException NewParameterBindingException( Exception innerException, ErrorCategory errorCategory, string parameterName, diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 09189ed04..d07bb0427 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -31,10 +31,10 @@ namespace System.Management.Automation /// internal class AnalysisCache { - private static AnalysisCacheData cacheData = AnalysisCacheData.Get(); + private static AnalysisCacheData s_cacheData = AnalysisCacheData.Get(); // This dictionary shouldn't see much use, so low concurrency and capacity - private static ConcurrentDictionary modulesBeingAnalyzed = + private static ConcurrentDictionary s_modulesBeingAnalyzed = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); internal static char[] InvalidCommandNameCharacters = new[] @@ -85,7 +85,7 @@ namespace System.Management.Automation if (result != null) { - cacheData.QueueSerialization(); + s_cacheData.QueueSerialization(); ModuleIntrinsics.Tracer.WriteLine("Returning {0} exported commands.", result.Count); } else @@ -143,7 +143,7 @@ namespace System.Management.Automation TypesAnalyzed = false, Types = new ConcurrentDictionary(1, 8, StringComparer.OrdinalIgnoreCase) }; - cacheData.Entries[modulePath] = moduleCacheEntry; + s_cacheData.Entries[modulePath] = moduleCacheEntry; } else { @@ -304,7 +304,7 @@ namespace System.Management.Automation StringComparer.OrdinalIgnoreCase); // Add any directly discovered exports - foreach(var command in scriptAnalysis.DiscoveredExports) + foreach (var command in scriptAnalysis.DiscoveredExports) { if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true)) { @@ -316,14 +316,14 @@ namespace System.Management.Automation } // Add the discovered aliases - foreach(var pair in scriptAnalysis.DiscoveredAliases) + foreach (var pair in scriptAnalysis.DiscoveredAliases) { var commandName = pair.Key; // These are already filtered if (commandName.IndexOfAny(InvalidCommandNameCharacters) < 0) { result.AddOrUpdate(commandName, CommandTypes.Alias, - (_,existingCommandType) => existingCommandType | CommandTypes.Alias); + (_, existingCommandType) => existingCommandType | CommandTypes.Alias); } } @@ -338,7 +338,7 @@ namespace System.Management.Automation { var command = Path.GetFileNameWithoutExtension(item); result.AddOrUpdate(command, CommandTypes.ExternalScript, - (_,existingCommandType) => existingCommandType | CommandTypes.ExternalScript); + (_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript); } } catch (UnauthorizedAccessException) @@ -362,7 +362,7 @@ namespace System.Management.Automation TypesAnalyzed = true, Types = exportedClasses }; - cacheData.Entries[modulePath] = moduleCacheEntry; + s_cacheData.Entries[modulePath] = moduleCacheEntry; return result; } @@ -387,7 +387,7 @@ namespace System.Management.Automation try { // If we're already analyzing this module, let the recursion bottom out. - if (!modulesBeingAnalyzed.TryAdd(modulePath, modulePath)) + if (!s_modulesBeingAnalyzed.TryAdd(modulePath, modulePath)) { ModuleIntrinsics.Tracer.WriteLine("{0} is already being analyzed. Exiting.", modulePath); return null; @@ -413,7 +413,7 @@ namespace System.Management.Automation finally { ModuleIntrinsics.Tracer.WriteLine("Finished analysis: {0}", modulePath); - modulesBeingAnalyzed.TryRemove(modulePath, out modulePath); + s_modulesBeingAnalyzed.TryRemove(modulePath, out modulePath); } return null; @@ -454,7 +454,7 @@ namespace System.Management.Automation return null; } - + internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext context) { ModuleIntrinsics.Tracer.WriteLine("Requested caching for {0}", module.Name); @@ -526,7 +526,7 @@ namespace System.Management.Automation TypesAnalyzed = true, Types = exportedClasses }; - moduleCacheEntry = cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry); + moduleCacheEntry = s_cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry); } // We need to update the cache @@ -543,7 +543,7 @@ namespace System.Management.Automation moduleCacheEntry.Types.AddOrUpdate(className, pair.Value.TypeAttributes, (k, t) => t); } - cacheData.QueueSerialization(); + s_cacheData.QueueSerialization(); } private static void CallGetModuleDashList(ExecutionContext context, string modulePath) @@ -585,7 +585,7 @@ namespace System.Management.Automation lastWriteTime = DateTime.MinValue; } - if (cacheData.Entries.TryGetValue(modulePath, out moduleCacheEntry)) + if (s_cacheData.Entries.TryGetValue(modulePath, out moduleCacheEntry)) { if (lastWriteTime == moduleCacheEntry.LastWriteTime) { @@ -595,7 +595,7 @@ namespace System.Management.Automation ModuleIntrinsics.Tracer.WriteLine("{0}: cache entry out of date, cached on {1}, last updated on {2}", modulePath, moduleCacheEntry.LastWriteTime, lastWriteTime); - cacheData.Entries.TryRemove(modulePath, out moduleCacheEntry); + s_cacheData.Entries.TryRemove(modulePath, out moduleCacheEntry); } moduleCacheEntry = null; @@ -605,7 +605,7 @@ namespace System.Management.Automation internal class AnalysisCacheData { - static byte[] GetHeader() + private static byte[] GetHeader() { return new byte[] { @@ -616,10 +616,10 @@ namespace System.Management.Automation // The last time the index was maintained. public DateTime LastReadTime { get; set; } - + public ConcurrentDictionary Entries { get; set; } - int _saveCacheToDiskQueued; + private int _saveCacheToDiskQueued; public void QueueSerialization() { @@ -645,7 +645,7 @@ namespace System.Management.Automation await Task.Delay(3000); counter2 = _saveCacheToDiskQueued; } while (counter1 != counter2); - Serialize(cacheStoreLocation); + Serialize(s_cacheStoreLocation); }); } } @@ -677,13 +677,13 @@ namespace System.Management.Automation private static unsafe void Write(int val, byte[] bytes, FileStream stream) { Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array"); - fixed (byte* b = bytes) *((int*) b) = val; + fixed (byte* b = bytes) *((int*)b) = val; stream.Write(bytes, 0, 4); } private static unsafe void Write(long val, byte[] bytes, FileStream stream) { Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array"); - fixed (byte* b = bytes) *((long*) b) = val; + fixed (byte* b = bytes) *((long*)b) = val; stream.Write(bytes, 0, 8); } @@ -798,7 +798,7 @@ namespace System.Management.Automation foreach (var command in commandPairs) { Write(command.Key, bytes, stream); - Write((int) command.Value, bytes, stream); + Write((int)command.Value, bytes, stream); } // Types @@ -808,7 +808,7 @@ namespace System.Management.Automation foreach (var type in typePairs) { Write(type.Key, bytes, stream); - Write((int) type.Value, bytes, stream); + Write((int)type.Value, bytes, stream); } } } @@ -833,8 +833,8 @@ namespace System.Management.Automation Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array"); if (stream.Read(bytes, 0, 8) != 8) throw new Exception(TruncatedErrorMessage); - fixed (byte* b = bytes) - return *(long*) b; + fixed (byte* b = bytes) + return *(long*)b; } private static unsafe int ReadInt(FileStream stream, byte[] bytes) @@ -842,14 +842,14 @@ namespace System.Management.Automation Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array"); if (stream.Read(bytes, 0, 4) != 4) throw new Exception(TruncatedErrorMessage); - fixed (byte* b = bytes) - return *(int*) b; + fixed (byte* b = bytes) + return *(int*)b; } private static string ReadString(FileStream stream, ref byte[] bytes) { int length = ReadInt(stream, bytes); - if (length > 10*1024) + if (length > 10 * 1024) throw new Exception(PossibleCorruptionErrorMessage); if (length > bytes.Length) bytes = new byte[length]; @@ -880,7 +880,7 @@ namespace System.Management.Automation { using (var stream = File.OpenRead(filename)) { - var result = new AnalysisCacheData {LastReadTime = DateTime.Now}; + var result = new AnalysisCacheData { LastReadTime = DateTime.Now }; var bytes = new byte[1024]; @@ -891,7 +891,7 @@ namespace System.Management.Automation // int ( 4 bytes) -> count of entries int entries = ReadInt(stream, bytes); - if (entries > 20*1024) + if (entries > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); result.Entries = new ConcurrentDictionary(/*concurrency*/3, entries, StringComparer.OrdinalIgnoreCase); @@ -908,7 +908,7 @@ namespace System.Management.Automation // int ( 4 bytes) -> count of commands var countItems = ReadInt(stream, bytes); - if (countItems > 20*1024) + if (countItems > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); var commands = new ConcurrentDictionary(/*concurrency*/3, countItems, StringComparer.OrdinalIgnoreCase); @@ -936,7 +936,7 @@ namespace System.Management.Automation bool typesAnalyzed = countItems != -1; if (!typesAnalyzed) countItems = 0; - if (countItems > 20*1024) + if (countItems > 20 * 1024) throw new Exception(PossibleCorruptionErrorMessage); var types = new ConcurrentDictionary(1, countItems, StringComparer.OrdinalIgnoreCase); @@ -987,15 +987,15 @@ namespace System.Management.Automation { try { - if (Utils.NativeFileExists(cacheStoreLocation)) + if (Utils.NativeFileExists(s_cacheStoreLocation)) { - return Deserialize(cacheStoreLocation); + return Deserialize(s_cacheStoreLocation); } } catch (Exception e) { ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache: " + e.Message); - if ((object)e.Message == (object)TruncatedErrorMessage + if ((object)e.Message == (object)TruncatedErrorMessage || (object)e.Message == (object)InvalidSignatureErrorMessage || (object)e.Message == (object)PossibleCorruptionErrorMessage) { @@ -1021,11 +1021,11 @@ namespace System.Management.Automation { } - private static readonly string cacheStoreLocation; + private static readonly string s_cacheStoreLocation; static AnalysisCacheData() { - cacheStoreLocation = + s_cacheStoreLocation = Environment.GetEnvironmentVariable("PSModuleAnalysisCachePath") ?? (Platform.IsWindows ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @@ -1043,5 +1043,4 @@ namespace System.Management.Automation public ConcurrentDictionary Commands; public ConcurrentDictionary Types; } - } // System.Management.Automation diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index 3f5d24606..2bf7fdcb5 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -11,9 +11,9 @@ using System.Diagnostics.CodeAnalysis; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { - #region Export-ModuleMember /// /// Implements a cmdlet that loads a module @@ -147,8 +147,6 @@ namespace Microsoft.PowerShell.Commands this.Context.EngineSessionState, _functionPatterns, _cmdletPatterns, _aliasPatterns, _variablePatterns, null); } - } #endregion Export-ModuleMember - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 5b37cc487..a62cf7475 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -21,6 +21,7 @@ using Dbg = System.Management.Automation.Diagnostics; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { /// @@ -28,7 +29,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet("Get", "Module", DefaultParameterSetName = ParameterSet_Loaded, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=141552")] - [OutputType(typeof (PSModuleInfo))] + [OutputType(typeof(PSModuleInfo))] public sealed class GetModuleCommand : ModuleCmdletBase, IDisposable { #region Cmdlet parameters @@ -265,7 +266,7 @@ namespace Microsoft.PowerShell.Commands private CancellationToken CancellationToken { - get { return this._cancellationTokenSource.Token; } + get { return _cancellationTokenSource.Token; } } /// @@ -276,7 +277,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - this._cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); } #endregion @@ -304,7 +305,7 @@ namespace Microsoft.PowerShell.Commands if (disposing) { - this._cancellationTokenSource.Dispose(); + _cancellationTokenSource.Dispose(); } _disposed = true; @@ -385,7 +386,7 @@ namespace Microsoft.PowerShell.Commands AssertNameDoesNotResolveToAPath(names, Modules.RemoteDiscoveryWorksOnlyForUnQualifiedNames, "RemoteDiscoveryWorksOnlyForUnQualifiedNames"); - + GetAvailableViaPsrpSession(names, moduleSpecTable, this.PSSession); } else if (ParameterSetName.Equals(ParameterSet_AvailableInCimSession, StringComparison.OrdinalIgnoreCase)) @@ -435,7 +436,7 @@ namespace Microsoft.PowerShell.Commands private static bool ModuleMatch(PSModuleInfo moduleInfo, IDictionary moduleSpecTable, string edition) { ModuleSpecification moduleSpecification; - return (String.IsNullOrEmpty(edition) || moduleInfo.CompatiblePSEditions.Contains(edition, StringComparer.OrdinalIgnoreCase)) && + return (String.IsNullOrEmpty(edition) || moduleInfo.CompatiblePSEditions.Contains(edition, StringComparer.OrdinalIgnoreCase)) && (!moduleSpecTable.TryGetValue(moduleInfo.Name, out moduleSpecification) || ModuleIntrinsics.IsModuleMatchingModuleSpec(moduleInfo, moduleSpecification)); } @@ -515,6 +516,5 @@ namespace Microsoft.PowerShell.Commands } } } - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 3f429b20b..29d1ac982 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -53,7 +53,7 @@ namespace Microsoft.PowerShell.Commands private const string ParameterSet_ViaPsrpSession = "PSSession"; private const string ParameterSet_ViaCimSession = "CimSession"; private const string ParameterSet_FQName_ViaPsrpSession = "FullyQualifiedNameAndPSSession"; - + /// /// This parameter specifies whether to import to the current session state /// or to the global / top-level session state @@ -335,9 +335,9 @@ namespace Microsoft.PowerShell.Commands /// Imports a command to the scope specified /// [Parameter] - [ValidateSet("Local","Global")] - public String Scope - { + [ValidateSet("Local", "Global")] + public String Scope + { get { return _scope; } set { @@ -491,7 +491,6 @@ namespace Microsoft.PowerShell.Commands { foreach (KeyValuePair pair in Context.Modules.ModuleTable) { - // if the module in the moduleTable is an assembly module without path, the moduleName is the key. string moduleName = "dynamic_code_module_" + suppliedAssembly; if (pair.Value.Path == "") @@ -510,7 +509,7 @@ namespace Microsoft.PowerShell.Commands continue; } } - + if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase)) { moduleLoaded = true; @@ -560,7 +559,7 @@ namespace Microsoft.PowerShell.Commands // See if we can use the cached path for the file. If a version number has been specified, then // we won't look in the cache - if (this.MinimumVersion == null && this.MaximumVersion == null && this.RequiredVersion == null && PSModuleInfo.UseAppDomainLevelModuleCache && ! this.BaseForce) + if (this.MinimumVersion == null && this.MaximumVersion == null && this.RequiredVersion == null && PSModuleInfo.UseAppDomainLevelModuleCache && !this.BaseForce) { // See if the name is in the appdomain-level module path name cache... cachedPath = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name); @@ -597,10 +596,10 @@ namespace Microsoft.PowerShell.Commands PSModuleInfo module; if (!BaseForce && Context.Modules.ModuleTable.TryGetValue(rootedPath, out module)) { - if (RequiredVersion == null - || module.Version.Equals(RequiredVersion) - || (BaseMinimumVersion == null && BaseMaximumVersion == null) - || module.ModuleType != ModuleType.Manifest + if (RequiredVersion == null + || module.Version.Equals(RequiredVersion) + || (BaseMinimumVersion == null && BaseMaximumVersion == null) + || module.ModuleType != ModuleType.Manifest || (BaseMinimumVersion == null && BaseMaximumVersion != null && module.Version <= BaseMaximumVersion) || (BaseMinimumVersion != null && BaseMaximumVersion == null && module.Version >= BaseMinimumVersion) || (BaseMinimumVersion != null && BaseMaximumVersion != null && module.Version >= BaseMinimumVersion && module.Version <= BaseMaximumVersion)) @@ -647,7 +646,6 @@ namespace Microsoft.PowerShell.Commands foundModule = LoadModule(rootedPath, null, this.BasePrefix, null, ref importModuleOptions, ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, out found); - } else if (Directory.Exists(rootedPath)) { @@ -677,7 +675,7 @@ namespace Microsoft.PowerShell.Commands if (InitialSessionState.IsEngineModule(name)) { PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name); - + // Return the command if we found a module if (snapin != null) { @@ -805,13 +803,13 @@ namespace Microsoft.PowerShell.Commands remotelyImportedModules.AddRange(tmp); } } - + return remotelyImportedModules; } private IList ImportModule_RemotelyViaPsrpSession( - ImportModuleOptions importModuleOptions, - string moduleName, + ImportModuleOptions importModuleOptions, + string moduleName, ModuleSpecification fullyQualifiedName, PSSession psSession) { @@ -873,9 +871,9 @@ namespace Microsoft.PowerShell.Commands PSPropertyInfo nameProperty = remotelyImportedModule.Properties["Name"]; if (nameProperty != null) { - string remoteModuleName = (string) LanguagePrimitives.ConvertTo( + string remoteModuleName = (string)LanguagePrimitives.ConvertTo( nameProperty.Value, - typeof (string), + typeof(string), CultureInfo.InvariantCulture); PSPropertyInfo helpInfoProperty = remotelyImportedModule.Properties["HelpInfoUri"]; @@ -937,15 +935,15 @@ namespace Microsoft.PowerShell.Commands } private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule( - ImportModuleOptions importModuleOptions, + ImportModuleOptions importModuleOptions, string remoteModuleName, Version remoteModuleVersion, PSSession psSession) { string temporaryModulePath = RemoteDiscoveryHelper.GetModulePath( - remoteModuleName, - remoteModuleVersion, - psSession.ComputerName, + remoteModuleName, + remoteModuleVersion, + psSession.ComputerName, this.Context.CurrentRunspace); string wildcardEscapedPath = WildcardPattern.Escape(temporaryModulePath); try @@ -1004,7 +1002,7 @@ namespace Microsoft.PowerShell.Commands object[] oldArgumentList = this.ArgumentList; try { - this.ArgumentList = new object[] {psSession}; + this.ArgumentList = new object[] { psSession }; ImportModule_LocallyViaName(importModuleOptions, wildcardEscapedPsd1Path); } finally @@ -1089,8 +1087,8 @@ namespace Microsoft.PowerShell.Commands return true; } Hashtable manifestData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable( - mainManifestFile, - temporaryModuleManifestPath, + mainManifestFile, + temporaryModuleManifestPath, this, ref containedErrors); @@ -1153,21 +1151,21 @@ namespace Microsoft.PowerShell.Commands } private void ImportModule_RemotelyViaCimSession( - ImportModuleOptions importModuleOptions, - string[] moduleNames, - CimSession cimSession, - Uri resourceUri, + ImportModuleOptions importModuleOptions, + string[] moduleNames, + CimSession cimSession, + Uri resourceUri, string cimNamespace) { // // find all remote PS-CIM modules // IEnumerable remoteModules = RemoteDiscoveryHelper.GetCimModules( - cimSession, + cimSession, resourceUri, cimNamespace, - moduleNames, - false /* onlyManifests */, + moduleNames, + false /* onlyManifests */, this, this.CancellationToken).ToList(); @@ -1235,7 +1233,7 @@ namespace Microsoft.PowerShell.Commands { return false; } - + List goodEntries; if (!this.GetListOfStringsFromData(manifestData, null, goodKey, 0, out goodEntries)) { @@ -1277,7 +1275,7 @@ namespace Microsoft.PowerShell.Commands } private IEnumerable CreateCimModuleFiles( - RemoteDiscoveryHelper.CimModule remoteCimModule, + RemoteDiscoveryHelper.CimModule remoteCimModule, RemoteDiscoveryHelper.CimFileCode fileCode, Func filesFilter, string temporaryModuleDirectory) @@ -1327,8 +1325,8 @@ namespace Microsoft.PowerShell.Commands } private PSModuleInfo ImportModule_RemotelyViaCimModuleData( - ImportModuleOptions importModuleOptions, - RemoteDiscoveryHelper.CimModule remoteCimModule, + ImportModuleOptions importModuleOptions, + RemoteDiscoveryHelper.CimModule remoteCimModule, CimSession cimSession) { try @@ -1350,9 +1348,9 @@ namespace Microsoft.PowerShell.Commands // read the original manifest // string temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath( - remoteCimModule.ModuleName, - null, - cimSession.ComputerName, + remoteCimModule.ModuleName, + null, + cimSession.ComputerName, this.Context.CurrentRunspace); string temporaryModuleManifestPath = Path.Combine( temporaryModuleDirectory, @@ -1366,10 +1364,10 @@ namespace Microsoft.PowerShell.Commands ParseError[] parseErrors; scriptBlockAst = Parser.ParseInput( remoteCimModule.MainManifest.FileData, - temporaryModuleManifestPath, - out throwAwayTokens, + temporaryModuleManifestPath, + out throwAwayTokens, out parseErrors); - if ((scriptBlockAst == null) || + if ((scriptBlockAst == null) || (parseErrors != null && parseErrors.Length > 0)) { throw new ParseException(parseErrors); @@ -1401,9 +1399,9 @@ namespace Microsoft.PowerShell.Commands moduleVersion = null; } temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath( - remoteCimModule.ModuleName, - moduleVersion, - cimSession.ComputerName, + remoteCimModule.ModuleName, + moduleVersion, + cimSession.ComputerName, this.Context.CurrentRunspace); temporaryModuleManifestPath = Path.Combine( temporaryModuleDirectory, @@ -1431,7 +1429,7 @@ namespace Microsoft.PowerShell.Commands temporaryModuleDirectory); IEnumerable nestedModules = CreateCimModuleFiles( remoteCimModule, - RemoteDiscoveryHelper.CimFileCode.CmdletizationV1, + RemoteDiscoveryHelper.CimFileCode.CmdletizationV1, IsCmdletizationFile, temporaryModuleDirectory); data = RemoteDiscoveryHelper.RewriteManifest( @@ -1530,7 +1528,7 @@ namespace Microsoft.PowerShell.Commands "; ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false); onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure(); - // create a separate scope for variables set below + // create a separate scope for variables set below onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModuleDirectory); onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove); moduleInfo.OnRemove = onRemoveScriptBlock; @@ -1539,8 +1537,8 @@ namespace Microsoft.PowerShell.Commands // Some procesing common for local and remote modules // AddModuleToModuleTables( - this.Context, - this.TargetSessionState.Internal, + this.Context, + this.TargetSessionState.Internal, moduleInfo); if (BasePassThru) { @@ -1570,7 +1568,7 @@ namespace Microsoft.PowerShell.Commands } catch (Exception e) { - ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, remoteCimModule. ModuleName); + ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, remoteCimModule.ModuleName); this.WriteError(errorRecord); return null; } @@ -1587,7 +1585,7 @@ namespace Microsoft.PowerShell.Commands { get { - return this._cancellationTokenSource.Token; + return _cancellationTokenSource.Token; } } @@ -1599,7 +1597,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - this._cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); } #endregion @@ -1627,7 +1625,7 @@ namespace Microsoft.PowerShell.Commands if (disposing) { - this._cancellationTokenSource.Dispose(); + _cancellationTokenSource.Dispose(); } _disposed = true; @@ -1673,7 +1671,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - if (BaseMaximumVersion != null && BaseMaximumVersion !=null && BaseMaximumVersion < BaseMinimumVersion) + if (BaseMaximumVersion != null && BaseMaximumVersion != null && BaseMaximumVersion < BaseMinimumVersion) { string message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionInvalidRange, BaseMinimumVersion, BaseMaximumVersion); throw new PSArgumentOutOfRangeException(message); @@ -1693,7 +1691,7 @@ namespace Microsoft.PowerShell.Commands { RemoteDiscoveryHelper.DispatchModuleInfoProcessing( module, - localAction: delegate() + localAction: delegate () { ImportModule_ViaLocalModuleInfo(importModuleOptions, module); SetModuleBaseForEngineModules(module.Name, this.Context); @@ -1701,14 +1699,14 @@ namespace Microsoft.PowerShell.Commands cimSessionAction: (cimSession, resourceUri, cimNamespace) => ImportModule_RemotelyViaCimSession( importModuleOptions, - new string[] {module.Name}, + new string[] { module.Name }, cimSession, resourceUri, cimNamespace), psSessionAction: psSession => ImportModule_RemotelyViaPsrpSession( importModuleOptions, - new string[] {module.Path}, + new string[] { module.Path }, null, psSession)); } @@ -1805,5 +1803,4 @@ namespace Microsoft.PowerShell.Commands } } } - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 648674beb..52dced20c 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -258,7 +258,7 @@ namespace Microsoft.PowerShell.Commands set; } - /// + /// /// The arguments to pass to the scriptblock used to create the module /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] @@ -345,25 +345,25 @@ namespace Microsoft.PowerShell.Commands "DefaultCommandPrefix" }; - static string[] ModuleVersionMembers = new string[] { + private static string[] s_moduleVersionMembers = new string[] { "ModuleName", "GUID", "ModuleVersion" }; - private static List ServiceCoreAssemblyCmdlets = new List(new string[] { + private static List s_serviceCoreAssemblyCmdlets = new List(new string[] { "Microsoft.PowerShell.Workflow.ServiceCore\\Import-PSWorkflow", "Microsoft.PowerShell.Workflow.ServiceCore\\New-PSWorkflowExecutionOption", }); - private Dictionary currentlyProcessingModules = new Dictionary(); + private Dictionary _currentlyProcessingModules = new Dictionary(); internal bool LoadUsingModulePath(bool found, IEnumerable modulePath, string name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module) { return LoadUsingModulePath(null, found, modulePath, name, ss, options, manifestProcessingFlags, out module); } - + internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumerable modulePath, string name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module) { @@ -516,7 +516,7 @@ namespace Microsoft.PowerShell.Commands /// /// Extra variables that are allowed to be referenced in moudle manifest file /// - private static readonly string[] ExtraAllowedVariables = new string[] { "PSScriptRoot", "PSEdition" }; + private static readonly string[] s_extraAllowedVariables = new string[] { "PSScriptRoot", "PSEdition" }; /// /// Load and execute the manifest psd1 file or a localized manifest psd1 file. @@ -536,7 +536,7 @@ namespace Microsoft.PowerShell.Commands // Load the data file(s) to get the module info... try { - scriptBlock.CheckRestrictedLanguage(PermittedCmdlets, ExtraAllowedVariables, true); + scriptBlock.CheckRestrictedLanguage(PermittedCmdlets, s_extraAllowedVariables, true); } catch (RuntimeException pe) { @@ -555,7 +555,7 @@ namespace Microsoft.PowerShell.Commands object result; object oldPSScriptRoot = Context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); object oldPSCommandPath = Context.GetVariableValue(SpecialVariables.PSCommandPathVarPath); - ArrayList errors = (ArrayList) Context.GetVariableValue(SpecialVariables.ErrorVarPath); + ArrayList errors = (ArrayList)Context.GetVariableValue(SpecialVariables.ErrorVarPath); int oldErrorCount = errors.Count; try @@ -831,7 +831,7 @@ namespace Microsoft.PowerShell.Commands // The rooted files wasn't found, so don't search anymore... if (found == false && wasRooted == true) return null; - + if (searchModulePath && found == false && moduleFileFound == false) { if (VerifyIfNestedModuleIsAvailable(moduleSpecification, null, null, out tempModuleInfoFromVerification)) @@ -1069,7 +1069,6 @@ namespace Microsoft.PowerShell.Commands yield return module; } } - } } @@ -1088,7 +1087,6 @@ namespace Microsoft.PowerShell.Commands WriteError(CreateModuleNotFoundError(modulePath)); } } - } } @@ -1193,11 +1191,11 @@ namespace Microsoft.PowerShell.Commands if (!ModuleUtils.IsModuleInVersionSubdirectory(file, out directoryVersion) || directoryVersion == module.Version) { - availableModules.Add(module); + availableModules.Add(module); + } } } } - } ClearAnalysisCaches(); @@ -1207,7 +1205,7 @@ namespace Microsoft.PowerShell.Commands /// /// Get the version type of input string MaximumVersion, translate "*" if there's any. /// - internal static Version GetMaximumVersion (string stringVersion) + internal static Version GetMaximumVersion(string stringVersion) { Version maxVersion; // First, try to convert maxVersion to version directly @@ -1252,12 +1250,12 @@ namespace Microsoft.PowerShell.Commands { // Ensure we don't have any recursion in module lookup PSModuleInfo moduleInfo = null; - if (currentlyProcessingModules.TryGetValue(file, out moduleInfo)) + if (_currentlyProcessingModules.TryGetValue(file, out moduleInfo)) { return moduleInfo; } - currentlyProcessingModules[file] = null; + _currentlyProcessingModules[file] = null; // Create a fake module info for this file string extension; @@ -1304,7 +1302,7 @@ namespace Microsoft.PowerShell.Commands // It's not a module manifest, process the individual module ImportModuleOptions options = new ImportModuleOptions(); bool found = false; - + moduleInfo = LoadModule(file, null, String.Empty, null, ref options, flags, out found); } @@ -1346,7 +1344,6 @@ namespace Microsoft.PowerShell.Commands moduleInfo.SetModuleType(ModuleType.Manifest); moduleInfo.RootModule = moduleInfo.Path; } - } else if (extension.Equals(StringLiterals.DependentWorkflowAssemblyExtension, StringComparison.OrdinalIgnoreCase) || extension.Equals(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase)) { @@ -1403,7 +1400,7 @@ namespace Microsoft.PowerShell.Commands ModuleIntrinsics.Tracer.WriteLine("Caching skipped for {0} because it had errors while loading.", moduleInfo.Name); } - currentlyProcessingModules[file] = moduleInfo; + _currentlyProcessingModules[file] = moduleInfo; return moduleInfo; } @@ -2446,12 +2443,12 @@ namespace Microsoft.PowerShell.Commands { if (localizedData != null && localizedData.Contains("Description")) { - description = (string) LanguagePrimitives.ConvertTo(localizedData["Description"], + description = (string)LanguagePrimitives.ConvertTo(localizedData["Description"], typeof(string), CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(description)) { - description = (string) LanguagePrimitives.ConvertTo(data["Description"], + description = (string)LanguagePrimitives.ConvertTo(data["Description"], typeof(string), CultureInfo.InvariantCulture); } } @@ -2654,7 +2651,7 @@ namespace Microsoft.PowerShell.Commands manifestInfo.RootModuleForManifest = savedActualRootModule; if (manifestGuid != null) { - manifestInfo.SetGuid((Guid) manifestGuid); + manifestInfo.SetGuid((Guid)manifestGuid); } if (helpInfoUri != null) { @@ -2958,16 +2955,16 @@ namespace Microsoft.PowerShell.Commands this.BaseGlobal = false; string shortModuleName = null; - if (nestedModuleSpecification.Name == ServiceCoreAssemblyFullName) + if (nestedModuleSpecification.Name == _serviceCoreAssemblyFullName) { - shortModuleName = ServiceCoreAssemblyShortName; + shortModuleName = _serviceCoreAssemblyShortName; } PSModuleInfo nestedModule; if ( - string.Equals(nestedModuleSpecification.Name, ServiceCoreAssemblyFullName, + string.Equals(nestedModuleSpecification.Name, _serviceCoreAssemblyFullName, StringComparison.OrdinalIgnoreCase) || - string.Equals(nestedModuleSpecification.Name, ServiceCoreAssemblyShortName, + string.Equals(nestedModuleSpecification.Name, _serviceCoreAssemblyShortName, StringComparison.OrdinalIgnoreCase)) { nestedModule = LoadServiceCoreModule( @@ -3009,7 +3006,7 @@ namespace Microsoft.PowerShell.Commands // If this was ServiceCore, don't process its exports - as these // should not show up when a module defines WorkflowsToProcess if ( - !String.Equals(nestedModule.Name, ServiceCoreAssemblyShortName, + !String.Equals(nestedModule.Name, _serviceCoreAssemblyShortName, StringComparison.OrdinalIgnoreCase)) { foreach (string detectedCmdlet in nestedModule.ExportedCmdlets.Keys) @@ -3059,11 +3056,11 @@ namespace Microsoft.PowerShell.Commands if (workflowsToProcess != null && workflowsToProcess.Count > 0) { #if CORECLR // Workflow Not Supported On CSS - PSNotSupportedException workflowModuleNotSupported = - PSTraceSource.NewNotSupportedException( - Modules.WorkflowModuleNotSupportedInPowerShellCore, - ModuleIntrinsics.GetModuleName(moduleManifestPath)); - throw workflowModuleNotSupported; + PSNotSupportedException workflowModuleNotSupported = + PSTraceSource.NewNotSupportedException( + Modules.WorkflowModuleNotSupportedInPowerShellCore, + ModuleIntrinsics.GetModuleName(moduleManifestPath)); + throw workflowModuleNotSupported; #else // Depending on current execution policy, check the signature of Module manfiest file if required. // Reusing already created ScriptInfo object to avoid race condition when modulemanifest was not signed during first check and signed before this step. @@ -3266,7 +3263,7 @@ namespace Microsoft.PowerShell.Commands } if (newManifestInfo.Guid.Equals(Guid.Empty) && (manifestGuid != null)) { - newManifestInfo.SetGuid((Guid) manifestGuid); + newManifestInfo.SetGuid((Guid)manifestGuid); } if (newManifestInfo.HelpInfoUri == null && (helpInfoUri != null)) { @@ -3518,7 +3515,7 @@ namespace Microsoft.PowerShell.Commands if ((ss != null) && (!ss.Internal.UseExportList)) { ModuleIntrinsics.ExportModuleMembers(this, ss.Internal, MatchAll, - MatchAll, null, null, options.ServiceCoreAutoAdded ? ServiceCoreAssemblyCmdlets : null); + MatchAll, null, null, options.ServiceCoreAutoAdded ? s_serviceCoreAssemblyCmdlets : null); } // Export* fields in .psd1 subset Export-ModuleMember calls from ModuleToProcess=psm1 @@ -3611,7 +3608,7 @@ namespace Microsoft.PowerShell.Commands ss.Internal, exportedFunctions, exportedCmdlets, exportedAliases, exportedVariables, - options.ServiceCoreAutoAdded ? ServiceCoreAssemblyCmdlets : null); + options.ServiceCoreAutoAdded ? s_serviceCoreAssemblyCmdlets : null); } } @@ -3708,14 +3705,14 @@ namespace Microsoft.PowerShell.Commands } } - private readonly string ServiceCoreAssemblyFullName = "Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"; - private readonly string ServiceCoreAssemblyShortName = "Microsoft.Powershell.Workflow.ServiceCore"; + private readonly string _serviceCoreAssemblyFullName = "Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"; + private readonly string _serviceCoreAssemblyShortName = "Microsoft.Powershell.Workflow.ServiceCore"; private PSModuleInfo LoadServiceCoreModule(PSModuleInfo parentModule, string moduleBase, SessionState ss, ImportModuleOptions nestedModuleOptions, ManifestProcessingFlags manifestProcessingFlags, bool addToParentModueIfFound, out bool found) { SessionStateInternal oldSessionState = Context.EngineSessionState; - if (ss != null ) + if (ss != null) Context.EngineSessionState = ss.Internal; try @@ -3728,7 +3725,7 @@ namespace Microsoft.PowerShell.Commands PSModuleInfo nestedModule = LoadBinaryModule( parentModule, // parentModule false, // trySnapInName - ServiceCoreAssemblyFullName, // moduleName + _serviceCoreAssemblyFullName, // moduleName null, // fileName null, // assemblyToLoad moduleBase, // moduleBase @@ -3739,7 +3736,7 @@ namespace Microsoft.PowerShell.Commands true, // loadTypes true, // loadFormats out found, // found - ServiceCoreAssemblyShortName,// shortModuleName + _serviceCoreAssemblyShortName,// shortModuleName true // disableFormatUpdates ); this.BaseGlobal = oldGLobal; @@ -3756,7 +3753,7 @@ namespace Microsoft.PowerShell.Commands } else { - string errorMessage = StringUtil.Format(Modules.ManifestMemberNotFound, ServiceCoreAssemblyFullName, "NestedModules", parentModule.Name); + string errorMessage = StringUtil.Format(Modules.ManifestMemberNotFound, _serviceCoreAssemblyFullName, "NestedModules", parentModule.Name); FileNotFoundException fnf = new FileNotFoundException(errorMessage); PSInvalidOperationException invalidOperation = new PSInvalidOperationException(errorMessage, fnf, "Modules_ModuleFileNotFound", ErrorCategory.ResourceUnavailable, parentModule.Name); throw invalidOperation; @@ -3770,7 +3767,7 @@ namespace Microsoft.PowerShell.Commands #if !CORECLR // Workflow Not Supported On CSS private void ProcessWorkflowsToProcess(string moduleBase, List workflowsToProcess, List dependentWorkflows, List assemblyList, SessionState ss, PSModuleInfo manifestInfo, ImportModuleOptions options) - { + { // If we are actually processing if (ss != null) { @@ -3783,7 +3780,7 @@ namespace Microsoft.PowerShell.Commands { // However, this static internal property can be changed by tests that can already run a script // in full-language mode. - if (! SystemPolicy.XamlWorkflowSupported) + if (!SystemPolicy.XamlWorkflowSupported) { foreach (string workflowPath in ResolveWorkflowFiles(moduleBase, workflowsToProcess)) { @@ -3840,7 +3837,7 @@ namespace Microsoft.PowerShell.Commands // the members of the manifest are canonical... ModuleIntrinsics.ExportModuleMembers(this, ss.Internal, MatchAll, MatchAll, MatchAll, MatchAll, - options.ServiceCoreAutoAdded ? ServiceCoreAssemblyCmdlets : null); + options.ServiceCoreAutoAdded ? s_serviceCoreAssemblyCmdlets : null); } finally { @@ -4198,7 +4195,7 @@ namespace Microsoft.PowerShell.Commands Dictionary> requiredModules = new Dictionary>(new ModuleSpecificationComparer()); if (currentModule != null) { - requiredModules.Add(new ModuleSpecification(currentModule), new List {requiredModuleSpecification}); + requiredModules.Add(new ModuleSpecification(currentModule), new List { requiredModuleSpecification }); } // We always need to check against the module name and not the file name @@ -4286,7 +4283,7 @@ namespace Microsoft.PowerShell.Commands // This should never happen because one of the two should be true // 1) loadedModule should either be PSModuleInfo // 2) loaded = true - Dbg.Assert(false,"loadedModule should either be PSModuleInfo or loaded should be true"); + Dbg.Assert(false, "loadedModule should either be PSModuleInfo or loaded should be true"); } } @@ -4301,12 +4298,12 @@ namespace Microsoft.PowerShell.Commands { powerShell.AddCommand("Import-Module"); powerShell.AddParameter("Name", requiredModule.Name); - + if (requiredModule.RequiredVersion != null) { powerShell.AddParameter("RequiredVersion", requiredModule.RequiredVersion); } - else if(requiredModule.MaximumVersion != null) + else if (requiredModule.MaximumVersion != null) { powerShell.AddParameter("MaximumVersion", requiredModule.MaximumVersion); } @@ -4386,7 +4383,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSpec, + internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSpec, string rootedModulePath, string extension, out PSModuleInfo nestedModuleInfoIfAvailable) @@ -4395,7 +4392,7 @@ namespace Microsoft.PowerShell.Commands nestedModuleInfoIfAvailable = null; if ((nestedModuleSpec.Guid != null) || (nestedModuleSpec.Version != null) || (nestedModuleSpec.RequiredVersion != null) || (nestedModuleSpec.MaximumVersion != null)) { - if (!string.IsNullOrEmpty(extension) && + if (!string.IsNullOrEmpty(extension) && (!string.Equals(extension, StringLiterals.PowerShellDataFileExtension))) { // A module can declare its GUID/Version only in the PSD1 file. @@ -4430,7 +4427,7 @@ namespace Microsoft.PowerShell.Commands } Collection availableModules = GetModuleIfAvailable(tempSpec); - + // With Side-b-Side module version support, more than one module will be returned by GetModuleIfAvailable if (availableModules.Count < 1) { @@ -4853,7 +4850,7 @@ namespace Microsoft.PowerShell.Commands else if (WildcardPattern.ContainsWildcardCharacters(currentGPModuleName)) { WildcardPattern wildcard = WildcardPattern.Get(currentGPModuleName, WildcardOptions.IgnoreCase); - if(wildcard.IsMatch(m.Name)) + if (wildcard.IsMatch(m.Name)) { m.LogPipelineExecutionDetails = true; } @@ -5109,7 +5106,6 @@ namespace Microsoft.PowerShell.Commands { return null; } - } else { @@ -5149,7 +5145,6 @@ namespace Microsoft.PowerShell.Commands { return null; } - } else { @@ -5205,7 +5200,7 @@ namespace Microsoft.PowerShell.Commands } } - for (int i = formatIndicesToRemove.Count - 1; i >= 0; i --) + for (int i = formatIndicesToRemove.Count - 1; i >= 0; i--) { Context.RunspaceConfiguration.Formats.RemoveItem(formatIndicesToRemove[i]); } @@ -5240,7 +5235,7 @@ namespace Microsoft.PowerShell.Commands catch (RuntimeException rte) { string fullErrorId = rte.ErrorRecord.FullyQualifiedErrorId; - if (fullErrorId.Equals("ErrorsUpdatingTypes", StringComparison.Ordinal) || + if (fullErrorId.Equals("ErrorsUpdatingTypes", StringComparison.Ordinal) || fullErrorId.Equals("ErrorsUpdatingFormats", StringComparison.Ordinal)) { return; @@ -5291,7 +5286,7 @@ namespace Microsoft.PowerShell.Commands dollarUnder: AutomationNull.Value, input: AutomationNull.Value, scriptThis: AutomationNull.Value, - args: new object[] {module}); + args: new object[] { module }); } if (module.ImplementingAssembly != null && module.ImplementingAssembly.IsDynamic == false) @@ -5427,7 +5422,7 @@ namespace Microsoft.PowerShell.Commands { string message = StringUtil.Format(Modules.UnableToRemoveModuleMember, func.Name, module.Name, e.Message); InvalidOperationException memberNotRemoved = new InvalidOperationException(message, e); - ErrorRecord er = new ErrorRecord(memberNotRemoved, "Modules_MemberNotRemoved", + ErrorRecord er = new ErrorRecord(memberNotRemoved, "Modules_MemberNotRemoved", ErrorCategory.PermissionDenied, func.Name); WriteError(er); } @@ -5648,7 +5643,6 @@ namespace Microsoft.PowerShell.Commands bool throwAwayModuleFileFound = false; return LoadUsingExtensions(parentModule, moduleName, fileBaseName, extension, moduleBase, prefix, ss, options, manifestProcessingFlags, out found, out throwAwayModuleFileFound); - } /// @@ -5761,8 +5755,8 @@ namespace Microsoft.PowerShell.Commands { moduleFileFound = true; // Win8: 325243 - Added the version check so that we do not unload modules with the same name but different version - if (BaseForce && module != null && - (this.BaseRequiredVersion == null || module.Version.Equals(this.BaseRequiredVersion)) && + if (BaseForce && module != null && + (this.BaseRequiredVersion == null || module.Version.Equals(this.BaseRequiredVersion)) && (BaseGuid == null || module.Guid.Equals(BaseGuid))) // TODO/FIXME: use IsModuleAlreadyLoaded to get consistent behavior // TODO/FIXME: (for example the checks above are not lookint at this.BaseMinimumVersion) @@ -5802,13 +5796,13 @@ namespace Microsoft.PowerShell.Commands { if (localizedData != null && localizedData.Contains("DefaultCommandPrefix")) { - prefix = (string) LanguagePrimitives.ConvertTo(localizedData["DefaultCommandPrefix"], - typeof (string), CultureInfo.InvariantCulture); + prefix = (string)LanguagePrimitives.ConvertTo(localizedData["DefaultCommandPrefix"], + typeof(string), CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(prefix)) { - prefix = (string) LanguagePrimitives.ConvertTo(data["DefaultCommandPrefix"], - typeof (string), CultureInfo.InvariantCulture); + prefix = (string)LanguagePrimitives.ConvertTo(data["DefaultCommandPrefix"], + typeof(string), CultureInfo.InvariantCulture); } } } @@ -6005,7 +5999,7 @@ namespace Microsoft.PowerShell.Commands if (!module.SessionState.Internal.UseExportList) { ModuleIntrinsics.ExportModuleMembers(this, module.SessionState.Internal, MatchAll, - MatchAll, MatchAll, null, options.ServiceCoreAutoAdded ? ModuleCmdletBase.ServiceCoreAssemblyCmdlets : null); + MatchAll, MatchAll, null, options.ServiceCoreAutoAdded ? ModuleCmdletBase.s_serviceCoreAssemblyCmdlets : null); } // Add it to the all module tables @@ -6023,9 +6017,9 @@ namespace Microsoft.PowerShell.Commands else // If -pass has been specified, emit a module info... if (BasePassThru) - { - WriteObject(module); - } + { + WriteObject(module); + } } catch (RuntimeException e) { @@ -6034,7 +6028,7 @@ namespace Microsoft.PowerShell.Commands e.ErrorRecord.PreserveInvocationInfoOnce = true; } - if(e.WasThrownFromThrowStatement) + if (e.WasThrownFromThrowStatement) { ThrowTerminatingError(e.ErrorRecord); } @@ -6091,14 +6085,14 @@ namespace Microsoft.PowerShell.Commands InvocationInfo invocationInfo = new InvocationInfo(scriptInfo, scriptInfo.ScriptBlock.Ast.Extent, Context); scriptInfo.ScriptBlock.InvokeWithPipe( - useLocalScope: false, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - outputPipe: ((MshCommandRuntime) this.CommandRuntime).OutputPipe, - invocationInfo: invocationInfo, - args: this.BaseArgumentList ?? Utils.EmptyArray()); + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + outputPipe: ((MshCommandRuntime)this.CommandRuntime).OutputPipe, + invocationInfo: invocationInfo, + args: this.BaseArgumentList ?? Utils.EmptyArray()); } finally { @@ -6122,9 +6116,9 @@ namespace Microsoft.PowerShell.Commands else // If -pass has been specified, emit a module info... if (BasePassThru) - { - WriteObject(module); - } + { + WriteObject(module); + } } catch (RuntimeException e) { @@ -6305,7 +6299,7 @@ namespace Microsoft.PowerShell.Commands { scriptWriter.WriteScriptModule(cmdletizationProxyModuleWriter); ScriptBlock sb = ScriptBlock.Create(this.Context, cmdletizationProxyModuleWriter.ToString()); - + // CDXML doesn't allow script injection, so it is trusted. sb.LanguageMode = PSLanguageMode.FullLanguage; @@ -6317,7 +6311,7 @@ namespace Microsoft.PowerShell.Commands scriptWriter.ReportExportedCommands(module, prefix); ImportModuleMembers(module, prefix, options); - + AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module); } } @@ -6340,9 +6334,9 @@ namespace Microsoft.PowerShell.Commands else // If -pass has been specified, emit a module info... if (BasePassThru) - { - WriteObject(module); - } + { + WriteObject(module); + } } catch (RuntimeException e) { @@ -6409,19 +6403,19 @@ namespace Microsoft.PowerShell.Commands return shouldProcessModule; } - private static object lockObject = new object(); + private static object s_lockObject = new object(); private void ClearAnalysisCaches() - { - lock(lockObject) + { + lock (s_lockObject) { - binaryAnalysisCache.Clear(); - scriptAnalysisCache.Clear(); + s_binaryAnalysisCache.Clear(); + s_scriptAnalysisCache.Clear(); } } // Analyzes a binary module implementation for its cmdlets. - static Dictionary> binaryAnalysisCache = + private static Dictionary> s_binaryAnalysisCache = new Dictionary>(); #if CORECLR @@ -6435,13 +6429,13 @@ namespace Microsoft.PowerShell.Commands private static BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(string path, ManifestProcessingFlags manifestProcessingFlags, out Version assemblyVersion) { Tuple tuple; - - lock(lockObject) + + lock (s_lockObject) { - binaryAnalysisCache.TryGetValue(path, out tuple); + s_binaryAnalysisCache.TryGetValue(path, out tuple); } - if(tuple != null) + if (tuple != null) { assemblyVersion = tuple.Item2; return tuple.Item1; @@ -6456,10 +6450,10 @@ namespace Microsoft.PowerShell.Commands } var resultToReturn = analysisResult ?? new BinaryAnalysisResult(); - - lock(lockObject) + + lock (s_lockObject) { - binaryAnalysisCache[path] = Tuple.Create(resultToReturn, assemblyVersion); + s_binaryAnalysisCache[path] = Tuple.Create(resultToReturn, assemblyVersion); } return resultToReturn; @@ -6472,12 +6466,12 @@ namespace Microsoft.PowerShell.Commands { Tuple tuple = null; - lock(lockObject) + lock (s_lockObject) { - binaryAnalysisCache.TryGetValue(path, out tuple); + s_binaryAnalysisCache.TryGetValue(path, out tuple); } - if(tuple != null) + if (tuple != null) { assemblyVersion = tuple.Item2; return tuple.Item1; @@ -6522,9 +6516,9 @@ namespace Microsoft.PowerShell.Commands result.DetectedCmdlets = detectedCmdlets; result.DetectedAliases = detectedAliases; - lock (lockObject) + lock (s_lockObject) { - binaryAnalysisCache[path] = Tuple.Create(result, assemblyVersion); + s_binaryAnalysisCache[path] = Tuple.Create(result, assemblyVersion); } return result; @@ -6617,22 +6611,22 @@ namespace Microsoft.PowerShell.Commands #endif // Analyzes a script module implementation for its exports. - static Dictionary scriptAnalysisCache = new Dictionary(); + private static Dictionary s_scriptAnalysisCache = new Dictionary(); private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionContext context) { // We need to return a cloned version here. // This is because the Get-Module -List -All modifies the returned module info and we do not want the original one changed. PSModuleInfo module = null; - - lock(lockObject) + + lock (s_lockObject) { - scriptAnalysisCache.TryGetValue(filename, out module); + s_scriptAnalysisCache.TryGetValue(filename, out module); } - if(module != null) + if (module != null) return module.Clone(); - + // fake/empty manifestInfo for processing in (!loadElements) mode module = new PSModuleInfo(filename, null, null); @@ -6670,9 +6664,9 @@ namespace Microsoft.PowerShell.Commands } } - lock (lockObject) + lock (s_lockObject) { - scriptAnalysisCache[filename] = module; + s_scriptAnalysisCache[filename] = module; } return module; @@ -6694,7 +6688,7 @@ namespace Microsoft.PowerShell.Commands } // Add any directly discovered exports - foreach(var command in scriptAnalysis.DiscoveredExports) + foreach (var command in scriptAnalysis.DiscoveredExports) { if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true)) { @@ -6706,7 +6700,7 @@ namespace Microsoft.PowerShell.Commands } // Add the discovered aliases - foreach(var pair in scriptAnalysis.DiscoveredAliases) + foreach (var pair in scriptAnalysis.DiscoveredAliases) { var commandName = pair.Key; // These are already filtered @@ -6782,7 +6776,7 @@ namespace Microsoft.PowerShell.Commands if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, patterns, true) && SessionStateUtilities.MatchesAnyWildcardPattern(commandName, scriptAnalysisPatterns, true)) { - if (!HasInvalidCharacters(commandName.Replace("-",""))) + if (!HasInvalidCharacters(commandName.Replace("-", ""))) { module.AddDetectedFunctionExport(commandName); } @@ -6823,9 +6817,9 @@ namespace Microsoft.PowerShell.Commands ModuleIntrinsics.Tracer.WriteLine("Caching skipped for {0} because it had errors while loading.", module.Name); } - lock (lockObject) + lock (s_lockObject) { - scriptAnalysisCache[filename] = module; + s_scriptAnalysisCache[filename] = module; } return module; @@ -6942,7 +6936,7 @@ namespace Microsoft.PowerShell.Commands else { // Avoid trying to import a PowerShell assembly as Snapin as it results in PSArgementException - if ((moduleName != null) && Utils.IsPowerShellAssembly(moduleName)) + if ((moduleName != null) && Utils.IsPowerShellAssembly(moduleName)) { trySnapInName = false; } @@ -7003,7 +6997,6 @@ namespace Microsoft.PowerShell.Commands { if (importingModule) { - assembly = Context.AddAssembly(moduleName, fileName, out error); if (assembly == null) @@ -7052,7 +7045,7 @@ namespace Microsoft.PowerShell.Commands } found = true; - if(string.IsNullOrEmpty(shortModuleName)) + if (string.IsNullOrEmpty(shortModuleName)) module = new PSModuleInfo(moduleName, modulePath, Context, ss); else module = new PSModuleInfo(shortModuleName, modulePath, Context, ss); @@ -7334,7 +7327,7 @@ namespace Microsoft.PowerShell.Commands return commandName; } - /// + /// /// Removes prefix from a command name and returns the command name /// /// The command name from which the prefix needs to be removed. @@ -7383,7 +7376,7 @@ namespace Microsoft.PowerShell.Commands return isPrefixed; } - + static internal void AddModuleToModuleTables(ExecutionContext context, SessionStateInternal targetSessionState, PSModuleInfo module) { Dbg.Assert(context != null, "Caller should verify that context != null"); @@ -7557,7 +7550,6 @@ namespace Microsoft.PowerShell.Commands // Write directly into the local cmdlet cache table... message = StringUtil.Format(Modules.ImportingCmdlet, prefixedCmdlet.Name); cmdlet.WriteVerbose(message); - } } @@ -7639,7 +7631,7 @@ namespace Microsoft.PowerShell.Commands var scope = options.Local ? targetSessionState.CurrentScope : targetSessionState.ModuleScope; PSVariable newVariable = scope.NewVariable(v, true, source); - if(isImportModulePrivate) + if (isImportModulePrivate) { newVariable.Visibility = SessionStateEntryVisibility.Private; } @@ -7790,10 +7782,35 @@ namespace Microsoft.PowerShell.Commands { switch (c) { - case '#': case ',': case '(': case ')': case '{': case '}': case '[': case ']': - case '&': case '-': case '/': case '\\': case '$': case '^': case ';': case ':': - case '"': case '\'': case '<': case '>': case '|': case '?': case '@': case '`': - case '*': case '%': case '+': case '=': case '~': + case '#': + case ',': + case '(': + case ')': + case '{': + case '}': + case '[': + case ']': + case '&': + case '-': + case '/': + case '\\': + case '$': + case '^': + case ';': + case ':': + case '"': + case '\'': + case '<': + case '>': + case '|': + case '?': + case '@': + case '`': + case '*': + case '%': + case '+': + case '=': + case '~': return true; } } @@ -7839,7 +7856,6 @@ namespace Microsoft.PowerShell.Commands cmdlet.WriteVerbose(message); } } - } if (HasInvalidCharacters(noun)) @@ -7878,7 +7894,6 @@ namespace Microsoft.PowerShell.Commands return null; } - } // end ModuleCmdletBase /// @@ -7895,6 +7910,5 @@ namespace Microsoft.PowerShell.Commands internal List> DetectedAliases { get; set; } } -#endregion ModuleCmdletBase - + #endregion ModuleCmdletBase } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 8d6046551..3e39839ce 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -44,7 +44,7 @@ namespace System.Management.Automation } private readonly Dictionary _moduleTable = new Dictionary(StringComparer.OrdinalIgnoreCase); - const int MaxModuleNestingDepth = 10; + private const int MaxModuleNestingDepth = 10; internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path) { @@ -68,7 +68,7 @@ namespace System.Management.Automation get { return _moduleNestingDepth; } } - int _moduleNestingDepth; + private int _moduleNestingDepth; /// /// Create a new module object from a scriptblock specifying the path to set for the module @@ -196,7 +196,7 @@ namespace System.Management.Automation { ast = ast.Parent; } - + // The variables set in the interpretted case get set by InvokeWithPipe in the compiled case. Diagnostics.Assert(_context.SessionState.Internal.CurrentScope.LocalsTuple == null, "No locals tuple should have been created yet."); @@ -209,14 +209,14 @@ namespace System.Management.Automation // And run the scriptblock... sb.InvokeWithPipe( - useLocalScope: false, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - outputPipe: outputPipe, - invocationInfo: invocationInfo, - args: arguments ?? Utils.EmptyArray()); + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + outputPipe: outputPipe, + invocationInfo: invocationInfo, + args: arguments ?? Utils.EmptyArray()); } catch (ExitException ee) { @@ -264,7 +264,7 @@ namespace System.Management.Automation internal List GetExactMatchModules(string moduleName, bool all, bool exactMatch) { if (moduleName == null) { moduleName = String.Empty; } - return GetModuleCore(new string[] {moduleName}, all, exactMatch); + return GetModuleCore(new string[] { moduleName }, all, exactMatch); } private List GetModuleCore(string[] patterns, bool all, bool exactMatch) @@ -297,7 +297,7 @@ namespace System.Management.Automation foreach (PSModuleInfo module in ModuleTable.Values) { // See if this is the requested module... - if ((exactMatch && module.Name.Equals(targetModuleName, StringComparison.OrdinalIgnoreCase)) || + if ((exactMatch && module.Name.Equals(targetModuleName, StringComparison.OrdinalIgnoreCase)) || (!exactMatch && SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, wcpList, false))) { modulesMatched.Add(module); @@ -421,7 +421,7 @@ namespace System.Management.Automation internal static Version GetManifestModuleVersion(string manifestPath) { - if (manifestPath != null && + if (manifestPath != null && manifestPath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { try @@ -570,8 +570,8 @@ namespace System.Management.Automation /// The default system wide module path internal static string GetSystemwideModulePath() { - if (SystemWideModulePath != null) - return SystemWideModulePath; + if (s_systemWideModulePath != null) + return s_systemWideModulePath; // There is no runspace config so we use the default string string shellId = Utils.DefaultPowerShellShellID; @@ -603,13 +603,13 @@ namespace System.Management.Automation { psHome = psHome.ToLowerInvariant().Replace("\\syswow64\\", "\\system32\\"); } - Interlocked.CompareExchange(ref SystemWideModulePath, Path.Combine(psHome, Utils.ModuleDirectory), null); + Interlocked.CompareExchange(ref s_systemWideModulePath, Path.Combine(psHome, Utils.ModuleDirectory), null); } - return SystemWideModulePath; + return s_systemWideModulePath; } - private static string SystemWideModulePath; + private static string s_systemWideModulePath; /// /// Get the DSC module path. @@ -904,7 +904,7 @@ namespace System.Management.Automation string newModulePathString = GetModulePath(currentModulePath, systemWideModulePath, personalModulePath); - if(!string.IsNullOrEmpty(newModulePathString)) + if (!string.IsNullOrEmpty(newModulePathString)) { // Set the environment variable... Environment.SetEnvironmentVariable("PSMODULEPATH", newModulePathString); @@ -936,13 +936,13 @@ namespace System.Management.Automation if (!string.IsNullOrWhiteSpace(modulePathString)) { - foreach (string envPath in modulePathString.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries)) - { - var processedPath = ProcessOneModulePath(context, envPath, processedPathSet); - if (processedPath != null) - yield return processedPath; + foreach (string envPath in modulePathString.Split(Utils.Separators.Semicolon, StringSplitOptions.RemoveEmptyEntries)) + { + var processedPath = ProcessOneModulePath(context, envPath, processedPathSet); + if (processedPath != null) + yield return processedPath; + } } - } if (includeSystemModulePath) { @@ -1027,7 +1027,7 @@ namespace System.Management.Automation Dbg.Assert(input != null, "Caller should verify that input != null"); input.Sort( - delegate(T x, T y) + delegate (T x, T y) { string kx = keyGetter(x); string ky = keyGetter(y); @@ -1098,14 +1098,14 @@ namespace System.Management.Automation else { message = StringUtil.Format(Modules.ExportingFunction, entry.Key); - sessionState.ExportedFunctions.Add(entry.Value); + sessionState.ExportedFunctions.Add(entry.Value); } cmdlet.WriteVerbose(message); } } - SortAndRemoveDuplicates(sessionState.ExportedFunctions, delegate(FunctionInfo ci) { return ci.Name; }); - SortAndRemoveDuplicates(sessionState.ExportedWorkflows, delegate(WorkflowInfo ci) { return ci.Name; }); + SortAndRemoveDuplicates(sessionState.ExportedFunctions, delegate (FunctionInfo ci) { return ci.Name; }); + SortAndRemoveDuplicates(sessionState.ExportedWorkflows, delegate (WorkflowInfo ci) { return ci.Name; }); } if (cmdletPatterns != null) @@ -1130,7 +1130,8 @@ namespace System.Management.Automation cmdlet.WriteVerbose(message); // Copy the cmdlet info, changing the module association to be the current module... CmdletInfo exportedCmdlet = new CmdletInfo(element.Name, element.ImplementingType, - element.HelpFile, null, element.Context) {Module = sessionState.Module}; + element.HelpFile, null, element.Context) + { Module = sessionState.Module }; Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets"); sessionState.Module.CompiledExports.Add(exportedCmdlet); } @@ -1151,14 +1152,15 @@ namespace System.Management.Automation cmdlet.WriteVerbose(message); // Copy the cmdlet info, changing the module association to be the current module... CmdletInfo exportedCmdlet = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType, - cmdletToImport.HelpFile, null, cmdletToImport.Context) {Module = sessionState.Module}; + cmdletToImport.HelpFile, null, cmdletToImport.Context) + { Module = sessionState.Module }; Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets"); sessionState.Module.CompiledExports.Add(exportedCmdlet); } } } - SortAndRemoveDuplicates(sessionState.Module.CompiledExports, delegate(CmdletInfo ci) { return ci.Name; }); + SortAndRemoveDuplicates(sessionState.Module.CompiledExports, delegate (CmdletInfo ci) { return ci.Name; }); } if (variablePatterns != null) @@ -1167,7 +1169,6 @@ namespace System.Management.Automation foreach (KeyValuePair entry in vt) { - // The magic variables are always private as are all-scope variables... if (entry.Value.IsAllScope || Array.IndexOf(PSModuleInfo._builtinVariables, entry.Key) != -1) { @@ -1181,7 +1182,7 @@ namespace System.Management.Automation sessionState.ExportedVariables.Add(entry.Value); } } - SortAndRemoveDuplicates(sessionState.ExportedVariables, delegate(PSVariable v) { return v.Name; }); + SortAndRemoveDuplicates(sessionState.ExportedVariables, delegate (PSVariable v) { return v.Name; }); } if (aliasPatterns != null) @@ -1221,7 +1222,7 @@ namespace System.Management.Automation } } - SortAndRemoveDuplicates(sessionState.ExportedAliases, delegate(AliasInfo ci) { return ci.Name; }); + SortAndRemoveDuplicates(sessionState.ExportedAliases, delegate (AliasInfo ci) { return ci.Name; }); } } @@ -1263,5 +1264,4 @@ namespace System.Management.Automation /// void OnRemove(PSModuleInfo psModuleInfo); } - } // System.Management.Automation diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 6e9b4e6b4..ae9091592 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -14,6 +14,7 @@ using Dbg = System.Management.Automation.Diagnostics; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region Module Specification class @@ -198,7 +199,7 @@ namespace Microsoft.PowerShell.Commands { moduleSpecString += "; RequiredVersion = '" + RequiredVersion + "'"; } - else + else { if (Version != null) { @@ -206,7 +207,7 @@ namespace Microsoft.PowerShell.Commands } if (MaximumVersion != null) { - moduleSpecString += "; MaximumVersion = '" + MaximumVersion + "'"; + moduleSpecString += "; MaximumVersion = '" + MaximumVersion + "'"; } } moduleSpecString += " }"; @@ -214,7 +215,7 @@ namespace Microsoft.PowerShell.Commands return moduleSpecString; } - + /// /// Parse the specified string into a ModuleSpecification object @@ -266,10 +267,9 @@ namespace Microsoft.PowerShell.Commands /// The exact version of the module if specified, otherwise null. /// public Version RequiredVersion { get; internal set; } - } - internal class ModuleSpecificationComparer:IEqualityComparer + internal class ModuleSpecificationComparer : IEqualityComparer { public bool Equals(ModuleSpecification x, ModuleSpecification y) { @@ -357,11 +357,10 @@ namespace Microsoft.PowerShell.Commands result = result ^ obj.RequiredVersion.GetHashCode(); } } - + return result; } } #endregion - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 41a316005..892913a6e 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -128,9 +128,9 @@ namespace System.Management.Automation.Internal try { - foreach(string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(directory)) + foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(directory)) { - if(uniqueModuleFiles.Add(moduleFile)) + if (uniqueModuleFiles.Add(moduleFile)) { yield return moduleFile; } diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index 432c7639f..ebd7e5fa8 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -10,6 +10,7 @@ using System.Diagnostics.CodeAnalysis; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region New-Module @@ -211,5 +212,4 @@ namespace Microsoft.PowerShell.Commands } #endregion - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index e78a3d6d7..65b523b03 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -28,7 +28,6 @@ using Environment = System.Management.Automation.Environment; // namespace Microsoft.PowerShell.Commands { - #region New-ModuleManifest /// /// Cmdlet to create a new module manifest file. @@ -46,7 +45,7 @@ namespace Microsoft.PowerShell.Commands get { return _path; } set { _path = value; } } - string _path; + private string _path; /// /// Sets the list of files to load by default... @@ -59,7 +58,7 @@ namespace Microsoft.PowerShell.Commands get { return _nestedModules; } set { _nestedModules = value; } } - object[] _nestedModules; + private object[] _nestedModules; /// /// Set the GUID in the manifest file @@ -70,7 +69,7 @@ namespace Microsoft.PowerShell.Commands get { return _guid; } set { _guid = value; } } - Guid _guid = Guid.NewGuid(); + private Guid _guid = Guid.NewGuid(); /// /// Set the author string in the manifest @@ -82,7 +81,7 @@ namespace Microsoft.PowerShell.Commands get { return _author; } set { _author = value; } } - string _author; + private string _author; /// /// Set the company name in the manifest @@ -94,7 +93,7 @@ namespace Microsoft.PowerShell.Commands get { return _companyName; } set { _companyName = value; } } - string _companyName = ""; + private string _companyName = ""; /// /// Set the copyright string in the module manifest @@ -106,7 +105,7 @@ namespace Microsoft.PowerShell.Commands get { return _copyright; } set { _copyright = value; } } - string _copyright; + private string _copyright; /// /// Set the module version... @@ -119,7 +118,7 @@ namespace Microsoft.PowerShell.Commands get { return _rootModule; } set { _rootModule = value; } } - string _rootModule = null; + private string _rootModule = null; /// /// Set the module version... @@ -131,7 +130,7 @@ namespace Microsoft.PowerShell.Commands get { return _moduleVersion; } set { _moduleVersion = value; } } - Version _moduleVersion = new Version(1, 0); + private Version _moduleVersion = new Version(1, 0); /// /// Set the module description @@ -143,7 +142,7 @@ namespace Microsoft.PowerShell.Commands get { return _description; } set { _description = value; } } - string _description; + private string _description; /// /// Set the ProcessorArchitecture required by this module @@ -165,7 +164,7 @@ namespace Microsoft.PowerShell.Commands get { return _powerShellVersion; } set { _powerShellVersion = value; } } - Version _powerShellVersion = null; + private Version _powerShellVersion = null; /// /// Set the CLR version required by the module. @@ -176,7 +175,7 @@ namespace Microsoft.PowerShell.Commands get { return _ClrVersion; } set { _ClrVersion = value; } } - Version _ClrVersion = null; + private Version _ClrVersion = null; /// /// Set the version of .NET Framework required by the module. @@ -187,7 +186,7 @@ namespace Microsoft.PowerShell.Commands get { return _DotNetFrameworkVersion; } set { _DotNetFrameworkVersion = value; } } - Version _DotNetFrameworkVersion = null; + private Version _DotNetFrameworkVersion = null; /// /// Set the name of PowerShell host required by the module. @@ -198,7 +197,7 @@ namespace Microsoft.PowerShell.Commands get { return _PowerShellHostName; } set { _PowerShellHostName = value; } } - string _PowerShellHostName = null; + private string _PowerShellHostName = null; /// /// Set the version of PowerShell host required by the module. @@ -209,7 +208,7 @@ namespace Microsoft.PowerShell.Commands get { return _PowerShellHostVersion; } set { _PowerShellHostVersion = value; } } - Version _PowerShellHostVersion = null; + private Version _PowerShellHostVersion = null; /// /// Sets the list of Dependencies for the module @@ -223,7 +222,7 @@ namespace Microsoft.PowerShell.Commands get { return _requiredModules; } set { _requiredModules = value; } } - object[] _requiredModules; + private object[] _requiredModules; /// /// Sets the list of types files for the module @@ -237,7 +236,7 @@ namespace Microsoft.PowerShell.Commands get { return _types; } set { _types = value; } } - string[] _types; + private string[] _types; /// /// Sets the list of formats files for the module @@ -251,7 +250,7 @@ namespace Microsoft.PowerShell.Commands get { return _formats; } set { _formats = value; } } - string[] _formats; + private string[] _formats; /// /// Sets the list of ps1 scripts to run in the session state of the import-module invocation. @@ -265,7 +264,7 @@ namespace Microsoft.PowerShell.Commands get { return _scripts; } set { _scripts = value; } } - string[] _scripts; + private string[] _scripts; /// /// Set the list of assemblies to load for this module. @@ -293,7 +292,7 @@ namespace Microsoft.PowerShell.Commands get { return _miscFiles; } set { _miscFiles = value; } } - string[] _miscFiles; + private string[] _miscFiles; /// /// List of other modules included with this module. @@ -309,7 +308,7 @@ namespace Microsoft.PowerShell.Commands get { return _moduleList; } set { _moduleList = value; } } - object[] _moduleList; + private object[] _moduleList; /// /// Specify any functions to export from this manifest. @@ -323,7 +322,7 @@ namespace Microsoft.PowerShell.Commands get { return _exportedFunctions; } set { _exportedFunctions = value; } } - string[] _exportedFunctions; + private string[] _exportedFunctions; /// /// Specify any aliases to export from this manifest. @@ -337,7 +336,7 @@ namespace Microsoft.PowerShell.Commands get { return _exportedAliases; } set { _exportedAliases = value; } } - string[] _exportedAliases; + private string[] _exportedAliases; /// /// Specify any variables to export from this manifest. @@ -351,7 +350,7 @@ namespace Microsoft.PowerShell.Commands get { return _exportedVariables; } set { _exportedVariables = value; } } - string[] _exportedVariables = new string[] { "*" }; + private string[] _exportedVariables = new string[] { "*" }; /// /// Specify any cmdlets to export from this manifest. @@ -365,7 +364,7 @@ namespace Microsoft.PowerShell.Commands get { return _exportedCmdlets; } set { _exportedCmdlets = value; } } - string[] _exportedCmdlets; + private string[] _exportedCmdlets; /// /// Specify any dsc resources to export from this manifest. @@ -379,7 +378,7 @@ namespace Microsoft.PowerShell.Commands get { return _dscResourcesToExport; } set { _dscResourcesToExport = value; } } - string[] _dscResourcesToExport; + private string[] _dscResourcesToExport; /// /// Specify compatible PSEditions of this module. @@ -394,7 +393,7 @@ namespace Microsoft.PowerShell.Commands get { return _compatiblePSEditions; } set { _compatiblePSEditions = value; } } - string[] _compatiblePSEditions; + private string[] _compatiblePSEditions; /// /// Specify any module-specific private data here. @@ -406,7 +405,7 @@ namespace Microsoft.PowerShell.Commands get { return _privateData; } set { _privateData = value; } } - object _privateData; + private object _privateData; /// /// Specify any Tags. @@ -456,7 +455,7 @@ namespace Microsoft.PowerShell.Commands get { return _helpInfoUri; } set { _helpInfoUri = value; } } - string _helpInfoUri; + private string _helpInfoUri; /// /// This parameter causes the module manifest string to be to the output stream... @@ -479,7 +478,7 @@ namespace Microsoft.PowerShell.Commands get { return _defaultCommandPrefix; } set { _defaultCommandPrefix = value; } } - string _defaultCommandPrefix; + private string _defaultCommandPrefix; private string _indent = ""; @@ -488,7 +487,7 @@ namespace Microsoft.PowerShell.Commands /// /// The string to quote /// The quoted string - string QuoteName(object name) + private string QuoteName(object name) { if (name == null) return "''"; @@ -502,7 +501,7 @@ namespace Microsoft.PowerShell.Commands /// The list to quote /// Streamwriter to get end of line character from /// The quoted list - string QuoteNames(IEnumerable names, StreamWriter streamWriter) + private string QuoteNames(IEnumerable names, StreamWriter streamWriter) { if (names == null) return "@()"; @@ -575,7 +574,7 @@ namespace Microsoft.PowerShell.Commands /// The list to quote /// Streamwriter to get end of line character from /// The quoted list - string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) + private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) { StringBuilder result = new StringBuilder(); result.Append("@("); @@ -660,7 +659,7 @@ namespace Microsoft.PowerShell.Commands /// The list to quote /// Streamwriter to get end of line character from /// The quoted list - string QuoteFiles(IEnumerable names, StreamWriter streamWriter) + private string QuoteFiles(IEnumerable names, StreamWriter streamWriter) { List resolvedPaths = new List(); @@ -769,7 +768,6 @@ namespace Microsoft.PowerShell.Commands SessionState sessionState = Context.SessionState; try { - Collection filePaths = sessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider); @@ -812,19 +810,19 @@ namespace Microsoft.PowerShell.Commands /// The formatted manifest fragment /// Streamwriter to get end of line character from /// - string ManifestFragment(string key, string resourceString, string value, StreamWriter streamWriter) + private string ManifestFragment(string key, string resourceString, string value, StreamWriter streamWriter) { return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } - string ManifestFragmentForNonSpecifiedManifestMember(string key, string resourceString, string value, StreamWriter streamWriter) + private string ManifestFragmentForNonSpecifiedManifestMember(string key, string resourceString, string value, StreamWriter streamWriter) { return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } - string ManifestComment(string insert, StreamWriter streamWriter) + private string ManifestComment(string insert, StreamWriter streamWriter) { // Prefix a non-empty string with a space for formatting reasons... if (!string.IsNullOrEmpty(insert)) @@ -876,11 +874,11 @@ namespace Microsoft.PowerShell.Commands if (_rootModule != null || _nestedModules != null || _requiredModules != null) { if (_exportedFunctions == null) - _exportedFunctions = new string[] {"*"}; + _exportedFunctions = new string[] { "*" }; if (_exportedAliases == null) - _exportedAliases = new string[] {"*"}; + _exportedAliases = new string[] { "*" }; if (_exportedCmdlets == null) - _exportedCmdlets = new string[] {"*"}; + _exportedCmdlets = new string[] { "*" }; } ValidateUriParamterValue(ProjectUri, "ProjectUri"); @@ -1124,7 +1122,7 @@ namespace Microsoft.PowerShell.Commands } } - result.Append("} "); + result.Append("} "); result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PrivateData"), streamWriter)); _indent = ""; @@ -1147,7 +1145,6 @@ namespace Microsoft.PowerShell.Commands } } } - - #endregion + #endregion } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 9ae7419a3..77df7bd34 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -23,15 +23,15 @@ namespace System.Management.Automation { internal const string DynamicModulePrefixString = "__DynamicModule_"; - private static readonly ReadOnlyDictionary EmptyTypeDefinitionDictionary = + private static readonly ReadOnlyDictionary s_emptyTypeDefinitionDictionary = new ReadOnlyDictionary(new Dictionary(StringComparer.OrdinalIgnoreCase)); // This dictionary doesn't include ExportedTypes from nested modules. private ReadOnlyDictionary _exportedTypeDefinitionsNoNested { set; get; } - private static readonly HashSet ScriptModuleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - StringLiterals.PowerShellModuleFileExtension, + private static readonly HashSet s_scriptModuleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + StringLiterals.PowerShellModuleFileExtension, }; internal static void SetDefaultDynamicNameAndPath(PSModuleInfo module) @@ -157,13 +157,13 @@ namespace System.Management.Automation Pipe outputPipe = new Pipe { NullPipe = true }; // And run the scriptblock... scriptBlock.InvokeWithPipe( - useLocalScope: false, + useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - outputPipe: outputPipe, - invocationInfo: null + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + outputPipe: outputPipe, + invocationInfo: null ); } finally @@ -229,7 +229,7 @@ namespace System.Management.Automation { _name = name; } - string _name = String.Empty; + private string _name = String.Empty; /// /// The path to the file that defined this module... @@ -245,7 +245,7 @@ namespace System.Management.Automation _path = value; } } - string _path = String.Empty; + private string _path = String.Empty; /// /// If the module is a binary module or a script module that defines @@ -272,7 +272,7 @@ namespace System.Management.Automation get { return _description; } set { _description = value ?? String.Empty; } } - string _description = String.Empty; + private string _description = String.Empty; /// /// The guid for this module if one was defined in the module manifest. @@ -286,7 +286,7 @@ namespace System.Management.Automation { _guid = guid; } - Guid _guid; + private Guid _guid; /// /// The HelpInfo for this module if one was defined in the module manifest. @@ -301,7 +301,7 @@ namespace System.Management.Automation { _helpInfoUri = uri; } - string _helpInfoUri; + private string _helpInfoUri; /// /// Get the module base directory for this module. For modules loaded via a module @@ -321,7 +321,7 @@ namespace System.Management.Automation { _moduleBase = moduleBase; } - string _moduleBase; + private string _moduleBase; /// /// This value is set from the PrivateData member in the module manifest. @@ -467,7 +467,7 @@ namespace System.Management.Automation { _version = version; } - Version _version = new Version(0, 0); + private Version _version = new Version(0, 0); /// /// True if the module was compiled (i.e. a .DLL) instead of @@ -477,7 +477,7 @@ namespace System.Management.Automation { get { return _moduleType; } } - ModuleType _moduleType = ModuleType.Script; + private ModuleType _moduleType = ModuleType.Script; /// /// This this module as being a compiled module... @@ -491,7 +491,7 @@ namespace System.Management.Automation { get; internal set; } - + /// /// Controls the module access mode... /// @@ -507,8 +507,8 @@ namespace System.Management.Automation _accessMode = value; } } - ModuleAccessMode _accessMode = ModuleAccessMode.ReadWrite; - + private ModuleAccessMode _accessMode = ModuleAccessMode.ReadWrite; + /// /// CLR Version /// @@ -559,7 +559,7 @@ namespace System.Management.Automation { foreach (string fn in DeclaredFunctionExports) { - FunctionInfo tempFunction = new FunctionInfo(fn, ScriptBlock.EmptyScriptBlock, null) {Module = this}; + FunctionInfo tempFunction = new FunctionInfo(fn, ScriptBlock.EmptyScriptBlock, null) { Module = this }; exports[fn] = tempFunction; } } @@ -577,7 +577,7 @@ namespace System.Management.Automation { if (!exports.ContainsKey(fi.Name)) { - exports[ModuleCmdletBase.AddPrefixToCommandName(fi.Name,fi.Prefix)] = fi; + exports[ModuleCmdletBase.AddPrefixToCommandName(fi.Name, fi.Prefix)] = fi; } } } @@ -588,7 +588,7 @@ namespace System.Management.Automation { if (!exports.ContainsKey(detectedExport)) { - FunctionInfo tempFunction = new FunctionInfo(detectedExport, ScriptBlock.EmptyScriptBlock, null) {Module = this}; + FunctionInfo tempFunction = new FunctionInfo(detectedExport, ScriptBlock.EmptyScriptBlock, null) { Module = this }; exports[detectedExport] = tempFunction; } } @@ -601,7 +601,7 @@ namespace System.Management.Automation private bool IsScriptModuleFile(string path) { var ext = System.IO.Path.GetExtension(path); - return ext != null && ScriptModuleExtensions.Contains(ext); + return ext != null && s_scriptModuleExtensions.Contains(ext); } /// @@ -630,7 +630,7 @@ namespace System.Management.Automation } // ExternalScriptInfo.GetScriptBlockAst() uses a cache layer to avoid re-parsing. - CreateExportedTypeDefinitions(rootedPath != null && IsScriptModuleFile(rootedPath) && IO.File.Exists(rootedPath) ? + CreateExportedTypeDefinitions(rootedPath != null && IsScriptModuleFile(rootedPath) && IO.File.Exists(rootedPath) ? (new ExternalScriptInfo(rootedPath, rootedPath)).GetScriptBlockAst() : null); } @@ -671,11 +671,10 @@ namespace System.Management.Automation { if (moduleContentScriptBlockAsts == null) { - this._exportedTypeDefinitionsNoNested = EmptyTypeDefinitionDictionary; + this._exportedTypeDefinitionsNoNested = s_emptyTypeDefinitionDictionary; } else { - this._exportedTypeDefinitionsNoNested = new ReadOnlyDictionary( moduleContentScriptBlockAsts.FindAll(a => (a is TypeDefinitionAst), false) .OfType() @@ -744,7 +743,7 @@ namespace System.Management.Automation { foreach (string fn in DeclaredCmdletExports) { - CmdletInfo tempCmdlet = new CmdletInfo(fn, null, null, null, null) {Module = this}; + CmdletInfo tempCmdlet = new CmdletInfo(fn, null, null, null, null) { Module = this }; exports[fn] = tempCmdlet; } } @@ -765,7 +764,7 @@ namespace System.Management.Automation { if (!exports.ContainsKey(detectedExport)) { - CmdletInfo tempCmdlet = new CmdletInfo(detectedExport, null, null, null, null) {Module = this}; + CmdletInfo tempCmdlet = new CmdletInfo(detectedExport, null, null, null, null) { Module = this }; exports[detectedExport] = tempCmdlet; } } @@ -785,7 +784,7 @@ namespace System.Management.Automation { Dbg.Assert(cmdlet != null, "AddDetectedCmdletExport should not be called with a null value"); - if(! _detectedCmdletExports.Contains(cmdlet)) + if (!_detectedCmdletExports.Contains(cmdlet)) { _detectedCmdletExports.Add(cmdlet); } @@ -878,7 +877,7 @@ namespace System.Management.Automation } } - readonly List _compiledExports = new List(); + private readonly List _compiledExports = new List(); /// @@ -905,7 +904,7 @@ namespace System.Management.Automation } } - readonly List _compiledAliasExports = new List(); + private readonly List _compiledAliasExports = new List(); /// @@ -965,7 +964,7 @@ namespace System.Management.Automation (_readonlyNestedModules = new ReadOnlyCollection(_nestedModules)); } } - ReadOnlyCollection _readonlyNestedModules; + private ReadOnlyCollection _readonlyNestedModules; /// /// Add a module to the list of child modules. @@ -975,7 +974,7 @@ namespace System.Management.Automation { AddModuleToList(nestedModule, _nestedModules); } - readonly List _nestedModules = new List(); + private readonly List _nestedModules = new List(); /// /// PowerShell Host Name @@ -1017,7 +1016,7 @@ namespace System.Management.Automation /// Scripts to Process /// public IEnumerable Scripts - { + { get { return _scripts; } } @@ -1054,7 +1053,7 @@ namespace System.Management.Automation (_readonlyRequiredModules = new ReadOnlyCollection(_requiredModules)); } } - ReadOnlyCollection _readonlyRequiredModules; + private ReadOnlyCollection _readonlyRequiredModules; /// /// Add a module to the list of required modules. @@ -1064,7 +1063,7 @@ namespace System.Management.Automation { AddModuleToList(requiredModule, _requiredModules); } - List _requiredModules = new List(); + private List _requiredModules = new List(); /// /// Returns the list of required modules specified in the module manifest of this module. This will only @@ -1078,7 +1077,7 @@ namespace System.Management.Automation (_readonlyRequiredModulesSpecification = new ReadOnlyCollection(_requiredModulesSpecification)); } } - ReadOnlyCollection _readonlyRequiredModulesSpecification; + private ReadOnlyCollection _readonlyRequiredModulesSpecification; /// /// Add a module to the list of required modules specification @@ -1088,7 +1087,7 @@ namespace System.Management.Automation { _requiredModulesSpecification.Add(requiredModuleSpecification); } - List _requiredModulesSpecification = new List(); + private List _requiredModulesSpecification = new List(); /// /// Root Module @@ -1105,8 +1104,8 @@ namespace System.Management.Automation /// internal String RootModuleForManifest { - get; - set; + get; + set; } /// @@ -1178,7 +1177,7 @@ namespace System.Management.Automation { foreach (string fn in DeclaredAliasExports) { - AliasInfo tempAlias = new AliasInfo(fn, null, null) {Module = this}; + AliasInfo tempAlias = new AliasInfo(fn, null, null) { Module = this }; exportedAliases[fn] = tempAlias; } } @@ -1200,9 +1199,9 @@ namespace System.Management.Automation foreach (var pair in _detectedAliasExports) { string detectedExport = pair.Key; - if (! exportedAliases.ContainsKey(detectedExport)) + if (!exportedAliases.ContainsKey(detectedExport)) { - AliasInfo tempAlias = new AliasInfo(detectedExport, pair.Value, null) {Module = this}; + AliasInfo tempAlias = new AliasInfo(detectedExport, pair.Value, null) { Module = this }; exportedAliases[detectedExport] = tempAlias; } } @@ -1255,7 +1254,7 @@ namespace System.Management.Automation { foreach (string fn in DeclaredWorkflowExports) { - WorkflowInfo tempWf = new WorkflowInfo(fn, ScriptBlock.EmptyScriptBlock, context: null) {Module = this}; + WorkflowInfo tempWf = new WorkflowInfo(fn, ScriptBlock.EmptyScriptBlock, context: null) { Module = this }; exportedWorkflows[fn] = tempWf; } } @@ -1274,7 +1273,7 @@ namespace System.Management.Automation { if (!exportedWorkflows.ContainsKey(detectedExport)) { - WorkflowInfo tempWf = new WorkflowInfo(detectedExport, ScriptBlock.EmptyScriptBlock, context: null) {Module = this}; + WorkflowInfo tempWf = new WorkflowInfo(detectedExport, ScriptBlock.EmptyScriptBlock, context: null) { Module = this }; exportedWorkflows[detectedExport] = tempWf; } } @@ -1304,9 +1303,9 @@ namespace System.Management.Automation : Utils.EmptyReadOnlyCollection(); } } - + internal Collection _declaredDscResourceExports = null; - + /// /// The session state instance associated with this module. /// @@ -1517,12 +1516,12 @@ namespace System.Management.Automation { get { - return this._exportedFormatFiles; + return _exportedFormatFiles; } } internal void SetExportedFormatFiles(ReadOnlyCollection files) { - this._exportedFormatFiles = files; + _exportedFormatFiles = files; } private ReadOnlyCollection _exportedTypeFiles = new ReadOnlyCollection(new List()); @@ -1534,13 +1533,12 @@ namespace System.Management.Automation { get { - return this._exportedTypeFiles; + return _exportedTypeFiles; } - } internal void SetExportedTypeFiles(ReadOnlyCollection files) { - this._exportedTypeFiles = files; + _exportedTypeFiles = files; } /// @@ -1552,7 +1550,7 @@ namespace System.Management.Automation PSModuleInfo clone = (PSModuleInfo)this.MemberwiseClone(); clone._fileList = new List(this.FileList); - clone._moduleList = new Collection(this._moduleList); + clone._moduleList = new Collection(_moduleList); foreach (var n in this.NestedModules) { @@ -1562,15 +1560,15 @@ namespace System.Management.Automation clone._readonlyNestedModules = new ReadOnlyCollection(this.NestedModules); clone._readonlyRequiredModules = new ReadOnlyCollection(this.RequiredModules); clone._readonlyRequiredModulesSpecification = new ReadOnlyCollection(this.RequiredModulesSpecification); - clone._requiredAssemblies = new Collection(this._requiredAssemblies); + clone._requiredAssemblies = new Collection(_requiredAssemblies); clone._requiredModulesSpecification = new List(); clone._requiredModules = new List(); - foreach (var r in this._requiredModules) + foreach (var r in _requiredModules) { clone.AddRequiredModule(r); } - foreach (var r in this._requiredModulesSpecification) + foreach (var r in _requiredModulesSpecification) { clone.AddRequiredModuleSpecification(r); } @@ -1592,7 +1590,7 @@ namespace System.Management.Automation /// static public void ClearAppDomainLevelModulePathCache() { - _appdomainModulePathCache.Clear(); + s_appdomainModulePathCache.Clear(); } @@ -1603,7 +1601,7 @@ namespace System.Management.Automation /// static public object GetAppDomainLevelModuleCache() { - return _appdomainModulePathCache; + return s_appdomainModulePathCache; } #endif /// @@ -1614,7 +1612,7 @@ namespace System.Management.Automation static internal string ResolveUsingAppDomainLevelModuleCache(string moduleName) { string path; - if (_appdomainModulePathCache.TryGetValue(moduleName, out path)) + if (s_appdomainModulePathCache.TryGetValue(moduleName, out path)) { return path; } @@ -1635,11 +1633,11 @@ namespace System.Management.Automation { if (force) { - _appdomainModulePathCache.AddOrUpdate(moduleName, path, (modulename, oldPath) => path); + s_appdomainModulePathCache.AddOrUpdate(moduleName, path, (modulename, oldPath) => path); } else { - _appdomainModulePathCache.TryAdd(moduleName, path); + s_appdomainModulePathCache.TryAdd(moduleName, path); } } @@ -1651,12 +1649,11 @@ namespace System.Management.Automation static internal bool RemoveFromAppDomainLevelCache(string moduleName) { string outString; - return _appdomainModulePathCache.TryRemove(moduleName, out outString); + return s_appdomainModulePathCache.TryRemove(moduleName, out outString); } - private readonly static System.Collections.Concurrent.ConcurrentDictionary _appdomainModulePathCache = + private readonly static System.Collections.Concurrent.ConcurrentDictionary s_appdomainModulePathCache = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - } // PSModuleInfo /// @@ -1721,7 +1718,7 @@ namespace System.Management.Automation //Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; - + bool result = string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) && (x.Guid == y.Guid) && (x.Version == y.Version); @@ -1758,5 +1755,4 @@ namespace System.Management.Automation } } } - } // System.Management.Automation \ No newline at end of file diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 07b3b2f4a..de61735e9 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -110,9 +110,9 @@ namespace System.Management.Automation private static EventHandler GetStreamForwarder(Action forwardingAction, bool swallowInvalidOperationExceptions = false) { // TODO/FIXME: ETW event for extended semantics streams - return delegate(object sender, DataAddedEventArgs eventArgs) + return delegate (object sender, DataAddedEventArgs eventArgs) { - var psDataCollection = (PSDataCollection) sender; + var psDataCollection = (PSDataCollection)sender; foreach (T t in psDataCollection.ReadAll()) { try @@ -131,25 +131,25 @@ namespace System.Management.Automation } // This is a static field (instead of a constant) to make it possible to set through tests (and/or by customers if needed for a workaround) - private static readonly int BlockingCollectionCapacity = 1000; + private static readonly int s_blockingCollectionCapacity = 1000; private static IEnumerable InvokeTopLevelPowerShell( - PowerShell powerShell, - CancellationToken cancellationToken, + PowerShell powerShell, + CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { - using (var mergedOutput = new BlockingCollection>>(BlockingCollectionCapacity)) + using (var mergedOutput = new BlockingCollection>>(s_blockingCollectionCapacity)) { var asyncOutput = new PSDataCollection(); EventHandler outputHandler = GetStreamForwarder( - output => mergedOutput.Add(_ => new[] {output}), + output => mergedOutput.Add(_ => new[] { output }), swallowInvalidOperationExceptions: true); EventHandler errorHandler = GetStreamForwarder( errorRecord => mergedOutput.Add( - delegate(PSCmdlet c) + delegate (PSCmdlet c) { errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); HandleErrorFromPipeline(c, errorRecord, powerShell); @@ -159,7 +159,7 @@ namespace System.Management.Automation EventHandler warningHandler = GetStreamForwarder( warningRecord => mergedOutput.Add( - delegate(PSCmdlet c) + delegate (PSCmdlet c) { c.WriteWarning(warningRecord.Message); return Enumerable.Empty(); @@ -168,7 +168,7 @@ namespace System.Management.Automation EventHandler verboseHandler = GetStreamForwarder( verboseRecord => mergedOutput.Add( - delegate(PSCmdlet c) + delegate (PSCmdlet c) { c.WriteVerbose(verboseRecord.Message); return Enumerable.Empty(); @@ -177,7 +177,7 @@ namespace System.Management.Automation EventHandler debugHandler = GetStreamForwarder( debugRecord => mergedOutput.Add( - delegate(PSCmdlet c) + delegate (PSCmdlet c) { c.WriteDebug(debugRecord.Message); return Enumerable.Empty(); @@ -186,7 +186,7 @@ namespace System.Management.Automation EventHandler informationHandler = GetStreamForwarder( informationRecord => mergedOutput.Add( - delegate(PSCmdlet c) + delegate (PSCmdlet c) { c.WriteInformation(informationRecord); return Enumerable.Empty(); @@ -214,7 +214,7 @@ namespace System.Management.Automation { mergedOutput.CompleteAdding(); } - catch (InvalidOperationException) + catch (InvalidOperationException) // ignore exceptions thrown because mergedOutput.CompleteAdding was called { } @@ -253,14 +253,14 @@ namespace System.Management.Automation } private static IEnumerable InvokeNestedPowerShell( - PowerShell powerShell, - CancellationToken cancellationToken, + PowerShell powerShell, + CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { EventHandler errorHandler = GetStreamForwarder( - delegate(ErrorRecord errorRecord) + delegate (ErrorRecord errorRecord) { errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); HandleErrorFromPipeline(cmdlet, errorRecord, powerShell); @@ -405,46 +405,46 @@ namespace System.Management.Automation exceptionHandler(e); } if (enumerator != null) - using (enumerator) - { - bool gotResults = false; - do + using (enumerator) { - try + bool gotResults = false; + do { - gotResults = false; - gotResults = enumerator.MoveNext(); - } - catch (Exception e) - { - exceptionHandler(e); - } - - if (gotResults) - { - T currentItem = default(T); - bool gotCurrentItem = false; try { - currentItem = enumerator.Current; - gotCurrentItem = true; + gotResults = false; + gotResults = enumerator.MoveNext(); } catch (Exception e) { exceptionHandler(e); } - if (gotCurrentItem) + if (gotResults) { - yield return currentItem; + T currentItem = default(T); + bool gotCurrentItem = false; + try + { + currentItem = enumerator.Current; + gotCurrentItem = true; + } + catch (Exception e) + { + exceptionHandler(e); + } + + if (gotCurrentItem) + { + yield return currentItem; + } + else + { + yield break; + } } - else - { - yield break; - } - } - } while (gotResults); - } + } while (gotResults); + } } private static void HandleErrorFromPipeline(Cmdlet cmdlet, ErrorRecord errorRecord, PowerShell powerShell) @@ -462,8 +462,8 @@ namespace System.Management.Automation } internal static IEnumerable InvokePowerShell( - PowerShell powerShell, - CancellationToken cancellationToken, + PowerShell powerShell, + CancellationToken cancellationToken, PSCmdlet cmdlet, string errorMessageTemplate) { @@ -473,16 +473,16 @@ namespace System.Management.Automation CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Verbose"); CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Debug"); - var invocationSettings = new PSInvocationSettings {Host = cmdlet.Host}; + var invocationSettings = new PSInvocationSettings { Host = cmdlet.Host }; // TODO/FIXME: ETW events for the output stream - IEnumerable outputStream = powerShell.IsNested - ? InvokeNestedPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate) + IEnumerable outputStream = powerShell.IsNested + ? InvokeNestedPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate) : InvokeTopLevelPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate); return EnumerateWithCatch( outputStream, - delegate(Exception exception) + delegate (Exception exception) { ErrorRecord errorRecord = GetErrorRecordForRemotePipelineInvocation(exception, errorMessageTemplate); HandleErrorFromPipeline(cmdlet, errorRecord, powerShell); @@ -509,12 +509,12 @@ namespace System.Management.Automation object propertyValue = cimProperty.Value; if (propertyValue is T) { - return (T) propertyValue; + return (T)propertyValue; } if (propertyValue is string) { - string stringValue = (string) propertyValue; + string stringValue = (string)propertyValue; try { if (typeof(T) == typeof(bool)) @@ -533,7 +533,7 @@ namespace System.Management.Automation { Array.Reverse(lengthBytes); } - return (T) (object)(lengthBytes.Concat(contentBytes).ToArray()); + return (T)(object)(lengthBytes.Concat(contentBytes).ToArray()); } } catch (Exception) @@ -614,17 +614,17 @@ namespace System.Management.Automation { Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null"); Dbg.Assert( - baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderModuleClass, StringComparison.OrdinalIgnoreCase), + baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderModuleClass, StringComparison.OrdinalIgnoreCase), "Caller should make sure baseObject is an instance of the right CIM class"); - this._baseObject = baseObject; + _baseObject = baseObject; } public string ModuleName { get { - var rawModuleName = GetPropertyValue(this._baseObject, "ModuleName", string.Empty); + var rawModuleName = GetPropertyValue(_baseObject, "ModuleName", string.Empty); return Path.GetFileName(rawModuleName); } } @@ -639,8 +639,8 @@ namespace System.Management.Automation { get { - UInt16 moduleTypeInt = GetPropertyValue(this._baseObject, "ModuleType", 0); - DiscoveredModuleType moduleType = (DiscoveredModuleType) moduleTypeInt; + UInt16 moduleTypeInt = GetPropertyValue(_baseObject, "ModuleType", 0); + DiscoveredModuleType moduleType = (DiscoveredModuleType)moduleTypeInt; bool isPsCimModule = (moduleType == DiscoveredModuleType.Cim); return isPsCimModule; } @@ -650,21 +650,21 @@ namespace System.Management.Automation { get { - byte[] rawFileData = GetPropertyValue(this._baseObject, "moduleManifestFileData", Utils.EmptyArray()); + byte[] rawFileData = GetPropertyValue(_baseObject, "moduleManifestFileData", Utils.EmptyArray()); return new CimModuleManifestFile(this.ModuleName + ".psd1", rawFileData); } } public IEnumerable ModuleFiles { - get { return this._moduleFiles; } + get { return _moduleFiles; } } internal void FetchAllModuleFiles(CimSession cimSession, string cimNamespace, CimOperationOptions operationOptions) { IEnumerable associatedInstances = cimSession.EnumerateAssociatedInstances( cimNamespace, - this._baseObject, + _baseObject, DiscoveryProviderAssociationClass, DiscoveryProviderFileClass, "Antecedent", @@ -672,7 +672,7 @@ namespace System.Management.Automation operationOptions); IEnumerable associatedFiles = associatedInstances.Select(i => new CimModuleImplementationFile(i)); - this._moduleFiles = associatedFiles.ToList(); + _moduleFiles = associatedFiles.ToList(); } private List _moduleFiles; @@ -684,19 +684,19 @@ namespace System.Management.Automation Dbg.Assert(fileName != null, "Caller should make sure fileName != null"); Dbg.Assert(rawFileData != null, "Caller should make sure rawFileData != null"); - this._fileName = fileName; - this._rawFileData = rawFileData; + _fileName = fileName; + _rawFileData = rawFileData; } public override string FileName { - get { return this._fileName; } + get { return _fileName; } } private readonly string _fileName; internal override byte[] RawFileDataCore { - get { return this._rawFileData; } + get { return _rawFileData; } } private readonly byte[] _rawFileData; } @@ -709,38 +709,38 @@ namespace System.Management.Automation { Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null"); Dbg.Assert( - baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderFileClass, StringComparison.OrdinalIgnoreCase), + baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderFileClass, StringComparison.OrdinalIgnoreCase), "Caller should make sure baseObject is an instance of the right CIM class"); - this._baseObject = baseObject; + _baseObject = baseObject; } public override string FileName { get { - string rawFileName = GetPropertyValue(this._baseObject, "FileName", string.Empty); + string rawFileName = GetPropertyValue(_baseObject, "FileName", string.Empty); return Path.GetFileName(rawFileName); } } - internal override byte[] RawFileDataCore + internal override byte[] RawFileDataCore { - get { return GetPropertyValue(this._baseObject, "FileData", Utils.EmptyArray()); } + get { return GetPropertyValue(_baseObject, "FileData", Utils.EmptyArray()); } } } } internal static IEnumerable GetCimModules( - CimSession cimSession, - Uri resourceUri, - string cimNamespace, - IEnumerable moduleNamePatterns, - bool onlyManifests, - Cmdlet cmdlet, + CimSession cimSession, + Uri resourceUri, + string cimNamespace, + IEnumerable moduleNamePatterns, + bool onlyManifests, + Cmdlet cmdlet, CancellationToken cancellationToken) { - moduleNamePatterns = moduleNamePatterns ?? new[] {"*"}; + moduleNamePatterns = moduleNamePatterns ?? new[] { "*" }; HashSet alreadyEmittedNamesOfCimModules = new HashSet(StringComparer.OrdinalIgnoreCase); IEnumerable remoteModules = moduleNamePatterns @@ -757,12 +757,12 @@ namespace System.Management.Automation } private static IEnumerable GetCimModules( - CimSession cimSession, - Uri resourceUri, - string cimNamespace, - string moduleNamePattern, - bool onlyManifests, - Cmdlet cmdlet, + CimSession cimSession, + Uri resourceUri, + string cimNamespace, + string moduleNamePattern, + bool onlyManifests, + Cmdlet cmdlet, CancellationToken cancellationToken) { Dbg.Assert(cimSession != null, "Caller should verify cimSession != null"); @@ -797,7 +797,7 @@ namespace System.Management.Automation if (!onlyManifests) { cimModules = cimModules.Select( - delegate(CimModule cimModule) + delegate (CimModule cimModule) { cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options); return cimModule; @@ -806,7 +806,7 @@ namespace System.Management.Automation return EnumerateWithCatch( cimModules, - delegate(Exception exception) + delegate (Exception exception) { ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception); if (!cmdlet.MyInvocation.ExpectingInput) @@ -827,7 +827,7 @@ namespace System.Management.Automation return RewriteManifest(originalManifest, null, null, null); } - private static readonly string[] ManifestEntriesToKeepAsString = new[] { + private static readonly string[] s_manifestEntriesToKeepAsString = new[] { "GUID", "Author", "CompanyName", @@ -836,16 +836,16 @@ namespace System.Management.Automation "Description", "HelpInfoURI", }; - private static readonly string[] ManifestEntriesToKeepAsStringArray = new[] { + private static readonly string[] s_manifestEntriesToKeepAsStringArray = new[] { "FunctionsToExport", "VariablesToExport", "AliasesToExport", "CmdletsToExport", }; internal static Hashtable RewriteManifest( - Hashtable originalManifest, - IEnumerable nestedModules, - IEnumerable typesToProcess, + Hashtable originalManifest, + IEnumerable nestedModules, + IEnumerable typesToProcess, IEnumerable formatsToProcess) { nestedModules = nestedModules ?? Utils.EmptyArray(); @@ -860,14 +860,14 @@ namespace System.Management.Automation foreach (DictionaryEntry entry in originalManifest) { - if (ManifestEntriesToKeepAsString.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase)) + if (s_manifestEntriesToKeepAsString.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase)) { - var value = (string) LanguagePrimitives.ConvertTo(entry.Value, typeof (string), CultureInfo.InvariantCulture); + var value = (string)LanguagePrimitives.ConvertTo(entry.Value, typeof(string), CultureInfo.InvariantCulture); newManifest[entry.Key] = value; } - else if (ManifestEntriesToKeepAsStringArray.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase)) + else if (s_manifestEntriesToKeepAsStringArray.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase)) { - var values = (string[]) LanguagePrimitives.ConvertTo(entry.Value, typeof (string[]), CultureInfo.InvariantCulture); + var values = (string[])LanguagePrimitives.ConvertTo(entry.Value, typeof(string[]), CultureInfo.InvariantCulture); newManifest[entry.Key] = values; } } @@ -964,10 +964,10 @@ namespace System.Management.Automation } internal static CimSession CreateCimSession( - string computerName, - PSCredential credential, - string authentication, - CancellationToken cancellationToken, + string computerName, + PSCredential credential, + string authentication, + CancellationToken cancellationToken, PSCmdlet cmdlet) { var sessionOptions = new CimSessionOptions(); @@ -1046,10 +1046,10 @@ namespace System.Management.Automation static private void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, object weaklyTypedSession) { - _moduleInfoToSession.Add(moduleInfo, weaklyTypedSession); + s_moduleInfoToSession.Add(moduleInfo, weaklyTypedSession); } - private static readonly ConditionalWeakTable _moduleInfoToSession = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_moduleInfoToSession = new ConditionalWeakTable(); internal static void DispatchModuleInfoProcessing( PSModuleInfo moduleInfo, @@ -1058,7 +1058,7 @@ namespace System.Management.Automation Action psSessionAction) { object weaklyTypeSession; - if (!_moduleInfoToSession.TryGetValue(moduleInfo, out weaklyTypeSession)) + if (!s_moduleInfoToSession.TryGetValue(moduleInfo, out weaklyTypeSession)) { localAction(); return; diff --git a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs index 20976ddac..da06e8215 100644 --- a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs @@ -15,6 +15,7 @@ using Dbg = System.Management.Automation.Diagnostics; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region Remove-Module @@ -34,7 +35,7 @@ namespace Microsoft.PowerShell.Commands set { _name = value; } get { return _name; } } - private string[] _name = Utils.EmptyArray(); + private string[] _name = Utils.EmptyArray(); /// /// This parameter specifies the current pipeline object @@ -79,20 +80,20 @@ namespace Microsoft.PowerShell.Commands foreach (var m in Context.Modules.GetModules(_name, false)) { - modulesToRemove.Add(m, new List{m}); + modulesToRemove.Add(m, new List { m }); } if (FullyQualifiedName != null) { foreach (var m in Context.Modules.GetModules(FullyQualifiedName, false)) { - modulesToRemove.Add(m, new List {m}); + modulesToRemove.Add(m, new List { m }); } } foreach (var m in _moduleInfo) { - modulesToRemove.Add(m, new List{m}); + modulesToRemove.Add(m, new List { m }); } // Add any of the child modules of a manifests to the list of modules to remove... @@ -297,11 +298,11 @@ namespace Microsoft.PowerShell.Commands } } } - + /// /// Returns a map from a module to the list of modules that require it /// - Dictionary> GetRequiredDependencies() + private Dictionary> GetRequiredDependencies() { Dictionary> requiredDependencies = new Dictionary>(); @@ -364,5 +365,4 @@ namespace Microsoft.PowerShell.Commands } } #endregion Remove-Module - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index b56925c48..b4afb1aba 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -117,7 +117,7 @@ namespace System.Management.Automation internal List DiscoveredModules { get; set; } internal List DiscoveredCommandFilters { get; set; } internal bool AddsSelfToPath { get; set; } - internal List DiscoveredClasses { get; set; } + internal List DiscoveredClasses { get; set; } } // Defines the visitor that analyzes a script to determine its exports @@ -137,19 +137,19 @@ namespace System.Management.Automation static ExportVisitor() { - var nameParam = new ParameterInfo {name = "Name", position = 0}; - var valueParam = new ParameterInfo {name = "Value", position = 1}; - var aliasParameterInfo = new ParameterBindingInfo {parameterInfo = new [] {nameParam, valueParam}}; + var nameParam = new ParameterInfo { name = "Name", position = 0 }; + var valueParam = new ParameterInfo { name = "Value", position = 1 }; + var aliasParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, valueParam } }; - var functionParam = new ParameterInfo {name = "Function", position = -1}; - var cmdletParam = new ParameterInfo {name = "Cmdlet", position = -1}; - var aliasParam = new ParameterInfo {name = "Alias", position = -1}; - var ipmoParameterInfo = new ParameterBindingInfo {parameterInfo = new [] {nameParam, functionParam, cmdletParam, aliasParam}}; + var functionParam = new ParameterInfo { name = "Function", position = -1 }; + var cmdletParam = new ParameterInfo { name = "Cmdlet", position = -1 }; + var aliasParam = new ParameterInfo { name = "Alias", position = -1 }; + var ipmoParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, functionParam, cmdletParam, aliasParam } }; - functionParam = new ParameterInfo {name = "Function", position = 0}; - var exportModuleMemberInfo = new ParameterBindingInfo {parameterInfo = new[] {functionParam, cmdletParam, aliasParam}}; + functionParam = new ParameterInfo { name = "Function", position = 0 }; + var exportModuleMemberInfo = new ParameterBindingInfo { parameterInfo = new[] { functionParam, cmdletParam, aliasParam } }; - parameterBindingInfoTable = new Dictionary(StringComparer.OrdinalIgnoreCase) + s_parameterBindingInfoTable = new Dictionary(StringComparer.OrdinalIgnoreCase) { {"New-Alias", aliasParameterInfo}, {@"Microsoft.PowerShell.Utility\New-Alias", aliasParameterInfo}, @@ -345,7 +345,7 @@ namespace System.Management.Automation { ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName); DiscoveredModules.Add( - new RequiredModuleInfo + new RequiredModuleInfo { Name = moduleName, CommandsToPostFilter = commandsToPostFilter @@ -373,7 +373,7 @@ namespace System.Management.Automation { DiscoveredCommandFilters.Add(exportedCommandName); ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName); - + // If the export doesn't contain wildcards, then add it to the // discovered commands as well. It is likely that they created // the command dynamically @@ -397,7 +397,6 @@ namespace System.Management.Automation { DiscoveredAliases[exportedAlias] = null; } - }; ProcessCmdletArguments(boundParameters["Alias"], onEachAlias); @@ -452,7 +451,7 @@ namespace System.Management.Automation { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); - var parameterBindingInfo = parameterBindingInfoTable[commandName].parameterInfo; + var parameterBindingInfo = s_parameterBindingInfoTable[commandName].parameterInfo; int positionsBound = 0; @@ -540,14 +539,14 @@ namespace System.Management.Automation return result; } - private static Dictionary parameterBindingInfoTable; + private static Dictionary s_parameterBindingInfoTable; - class ParameterBindingInfo + private class ParameterBindingInfo { internal ParameterInfo[] parameterInfo; } - struct ParameterInfo + private struct ParameterInfo { internal string name; internal int position; @@ -562,5 +561,4 @@ namespace System.Management.Automation internal string Name { get; set; } internal List CommandsToPostFilter { get; set; } } - } // System.Management.Automation \ No newline at end of file diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 50fd817bd..b8ca0d1d6 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -14,6 +14,7 @@ using System.Collections; // // Now define the set of commands for manipulating modules. // + namespace Microsoft.PowerShell.Commands { #region Test-ModuleManifest @@ -33,7 +34,7 @@ namespace Microsoft.PowerShell.Commands get { return _path; } set { _path = value; } } - string _path; + private string _path; /// /// Implements the record processing for this cmdlet @@ -141,10 +142,10 @@ namespace Microsoft.PowerShell.Commands { foreach (ModuleSpecification nestedModule in nestedModules) { - if (!IsValidFilePath(nestedModule.Name, module, true) - && !IsValidFilePath(nestedModule.Name + StringLiterals.DependentWorkflowAssemblyExtension, module, true) - && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) - && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) + if (!IsValidFilePath(nestedModule.Name, module, true) + && !IsValidFilePath(nestedModule.Name + StringLiterals.DependentWorkflowAssemblyExtension, module, true) + && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) + && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) && !IsValidGacAssembly(nestedModule.Name)) { // The nested module could be dependencies. We compare if it can be loaded by loadmanifest @@ -224,8 +225,8 @@ namespace Microsoft.PowerShell.Commands // The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher. // Ensure that PowerShellVersion module manifest key value is '5.1' or higher. // - var minimumRequiredPowerShellVersion = new Version(5,1); - if((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) + var minimumRequiredPowerShellVersion = new Version(5, 1); + if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) { string errorMsg = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path); @@ -305,7 +306,6 @@ namespace Microsoft.PowerShell.Commands { return false; } - } catch (Exception exception) { @@ -323,7 +323,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - private bool IsValidGacAssembly (string assemblyName) + private bool IsValidGacAssembly(string assemblyName) { string gacPath = System.Environment.GetEnvironmentVariable("windir") + "\\Microsoft.NET\\assembly"; string assemblyFile = assemblyName; @@ -356,5 +356,4 @@ namespace Microsoft.PowerShell.Commands } #endregion - } // Microsoft.PowerShell.Commands diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 64ced58ca..70cf2281d 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -9,7 +9,7 @@ using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; -using PipelineResultTypes=System.Management.Automation.Runspaces.PipelineResultTypes; +using PipelineResultTypes = System.Management.Automation.Runspaces.PipelineResultTypes; namespace System.Management.Automation { @@ -70,21 +70,21 @@ namespace System.Management.Automation /// public struct SwitchParameter { - private bool isPresent; + private bool _isPresent; /// /// Returns true if the parameter was specified on the command line, false otherwise. /// /// True if the parameter was specified, false otherwise public bool IsPresent { - get { return isPresent; } + get { return _isPresent; } } /// /// Implicit cast operator for casting SwitchParameter to bool. /// /// The SwitchParameter object to convert to bool /// The corresponding boolean value. - public static implicit operator bool(SwitchParameter switchParameter) + public static implicit operator bool (SwitchParameter switchParameter) { return switchParameter.IsPresent; } @@ -105,7 +105,7 @@ namespace System.Management.Automation /// The boolean equivalent of the SwitchParameter public bool ToBool() { - return this.isPresent; + return _isPresent; } /// @@ -116,7 +116,7 @@ namespace System.Management.Automation /// public SwitchParameter(bool isPresent) { - this.isPresent = isPresent; + _isPresent = isPresent; } /// @@ -135,17 +135,17 @@ namespace System.Management.Automation /// True if the objects are the same value. public override bool Equals(object obj) { - if (obj is bool) - { - return this.isPresent == (bool)obj; - } - else if (obj is SwitchParameter) - { - return this.isPresent == ((SwitchParameter)obj).IsPresent; - } - else + if (obj is bool) { - return false; + return _isPresent == (bool)obj; + } + else if (obj is SwitchParameter) + { + return _isPresent == ((SwitchParameter)obj).IsPresent; + } + else + { + return false; } } /// @@ -154,7 +154,7 @@ namespace System.Management.Automation /// The hash code for this cobject. public override int GetHashCode() { - return this.isPresent.GetHashCode(); + return _isPresent.GetHashCode(); } /// @@ -173,9 +173,9 @@ namespace System.Management.Automation /// first object to compare /// second object to compare /// True if they are different - public static bool operator != (SwitchParameter first, SwitchParameter second) + public static bool operator !=(SwitchParameter first, SwitchParameter second) { - return !first.Equals (second); + return !first.Equals(second); } /// /// Implement the == operator for switch parameters and booleans. @@ -183,9 +183,9 @@ namespace System.Management.Automation /// first object to compare /// second object to compare /// True if they are the same - public static bool operator == (SwitchParameter first, bool second) + public static bool operator ==(SwitchParameter first, bool second) { - return first.Equals (second); + return first.Equals(second); } /// /// Implement the != operator for switch parameters and booleans. @@ -193,9 +193,9 @@ namespace System.Management.Automation /// first object to compare /// second object to compare /// True if they are different - public static bool operator != (SwitchParameter first, bool second) + public static bool operator !=(SwitchParameter first, bool second) { - return !first.Equals (second); + return !first.Equals(second); } /// /// Implement the == operator for bool and switch parameters @@ -203,9 +203,9 @@ namespace System.Management.Automation /// first object to compare /// second object to compare /// True if they are the same - public static bool operator == (bool first, SwitchParameter second) + public static bool operator ==(bool first, SwitchParameter second) { - return first.Equals (second); + return first.Equals(second); } /// /// Implement the != operator for bool and switch parameters @@ -213,9 +213,9 @@ namespace System.Management.Automation /// first object to compare /// second object to compare /// True if they are different - public static bool operator != (bool first, SwitchParameter second) + public static bool operator !=(bool first, SwitchParameter second) { - return !first.Equals (second); + return !first.Equals(second); } /// @@ -224,7 +224,7 @@ namespace System.Management.Automation /// The string for this object. public override string ToString() { - return isPresent.ToString(); + return _isPresent.ToString(); } } @@ -235,20 +235,20 @@ namespace System.Management.Automation { private ExecutionContext _context; private PSCmdlet _cmdlet; - private MshCommandRuntime commandRuntime; + private MshCommandRuntime _commandRuntime; internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet) { - this._context = context; + _context = context; if (cmdlet != null) { - this._cmdlet = cmdlet; - this.commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; + _cmdlet = cmdlet; + _commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; } } internal CommandInvocationIntrinsics(ExecutionContext context) - :this(context, null) + : this(context, null) { } @@ -259,11 +259,11 @@ namespace System.Management.Automation { get { - return this.commandRuntime.PipelineProcessor.ExecutionFailed; + return _commandRuntime.PipelineProcessor.ExecutionFailed; } set { - this.commandRuntime.PipelineProcessor.ExecutionFailed = value; + _commandRuntime.PipelineProcessor.ExecutionFailed = value; } } @@ -309,16 +309,16 @@ namespace System.Management.Automation try { CommandOrigin commandOrigin = CommandOrigin.Runspace; - if (this._cmdlet != null) + if (_cmdlet != null) { - commandOrigin = this._cmdlet.CommandOrigin; + commandOrigin = _cmdlet.CommandOrigin; } - else if (this._context != null) + else if (_context != null) { - commandOrigin = this._context.EngineSessionState.CurrentScope.ScopeOrigin; + commandOrigin = _context.EngineSessionState.CurrentScope.ScopeOrigin; } - result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, this._context); + result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, _context); if ((result != null) && (arguments != null) && (arguments.Length > 0)) { @@ -365,7 +365,7 @@ namespace System.Management.Automation /// The cmdletInfo object if found, null otherwise public CmdletInfo GetCmdlet(string commandName) { - return GetCmdlet(commandName, this._context); + return GetCmdlet(commandName, _context); } /// @@ -460,7 +460,7 @@ namespace System.Management.Automation string verb = ca.VerbName; string cmdletName = verb + "-" + noun; - return new CmdletInfo(cmdletName, cmdletType, null, null, this._context); + return new CmdletInfo(cmdletName, cmdletType, null, null, _context); } /// @@ -489,7 +489,7 @@ namespace System.Management.Automation pattern, SearchResolutionOptions.CommandNameIsPattern, CommandTypes.Cmdlet, - this._context); + _context); do { try @@ -543,9 +543,9 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("name"); } - + List commands = new List(); - + foreach (CommandInfo current in this.GetCommands(name, CommandTypes.All, nameIsPattern)) { if (current.CommandType == CommandTypes.Application) @@ -586,7 +586,7 @@ namespace System.Management.Automation commands.Add(current.Name); } } - + return commands; } @@ -617,7 +617,7 @@ namespace System.Management.Automation name, options, commandTypes, - this._context); + _context); if (commandOrigin != null) { @@ -661,7 +661,7 @@ namespace System.Management.Automation } } while (true); } - + /// /// Executes a piece of text as a script synchronously. /// @@ -815,24 +815,24 @@ namespace System.Management.Automation if (cmdletToUse != null) { sb.InvokeUsingCmdlet( - contextCmdlet: cmdletToUse, - useLocalScope: useNewScope, + contextCmdlet: cmdletToUse, + useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, - dollarUnder: AutomationNull.Value, - input: input, - scriptThis: AutomationNull.Value, - args: args); + dollarUnder: AutomationNull.Value, + input: input, + scriptThis: AutomationNull.Value, + args: args); rawResult = AutomationNull.Value; } else { rawResult = sb.DoInvokeReturnAsIs( - useLocalScope: useNewScope, + useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, - dollarUnder: AutomationNull.Value, - input: input, - scriptThis: AutomationNull.Value, - args: args); + dollarUnder: AutomationNull.Value, + input: input, + scriptThis: AutomationNull.Value, + args: args); } if (rawResult == AutomationNull.Value) @@ -873,10 +873,10 @@ namespace System.Management.Automation /// The source text to compile /// The compiled script block /// - public ScriptBlock NewScriptBlock (string scriptText) + public ScriptBlock NewScriptBlock(string scriptText) { - if (null != commandRuntime) - commandRuntime.ThrowIfStopping(); + if (null != _commandRuntime) + _commandRuntime.ThrowIfStopping(); ScriptBlock result = ScriptBlock.Create(_context, scriptText); return result; @@ -902,7 +902,8 @@ namespace System.Management.Automation { #region private_members - internal bool HasDynamicParameters { + internal bool HasDynamicParameters + { get { return this is IDynamicParameters; } } @@ -956,19 +957,19 @@ namespace System.Management.Automation return null; } - if (this.pagingParameters == null) + if (_pagingParameters == null) { MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { - this.pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); + _pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); } } - return this.pagingParameters; + return _pagingParameters; } } } - private PagingParameters pagingParameters; + private PagingParameters _pagingParameters; #region InvokeCommand private CommandInvocationIntrinsics _invokeCommand; diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index e174cef14..489389319 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -32,35 +32,35 @@ namespace System.Management.Automation { #region private_members - private ExecutionContext context; + private ExecutionContext _context; /// /// Gets/Set the execution context value for this runtime object. /// internal ExecutionContext Context { - get { return context; } - set { context = value; } + get { return _context; } + set { _context = value; } } - private SessionState state = null; + private SessionState _state = null; internal InternalHost CBhost; - private PSHost host; + private PSHost _host; /// /// The host object for this object /// - public PSHost Host { get { return host; } } + public PSHost Host { get { return _host; } } // Output pipes. - private Pipe inputPipe; - private Pipe outputPipe; - private Pipe errorOutputPipe; - private Pipe warningOutputPipe; - private Pipe verboseOutputPipe; - private Pipe debugOutputPipe; - private Pipe informationOutputPipe; + private Pipe _inputPipe; + private Pipe _outputPipe; + private Pipe _errorOutputPipe; + private Pipe _warningOutputPipe; + private Pipe _verboseOutputPipe; + private Pipe _debugOutputPipe; + private Pipe _informationOutputPipe; - private bool isClosed; + private bool _isClosed; /// /// IsClosed indicates to the Cmdlet whether its upstream partner /// could still write more data to its incoming queue. @@ -68,8 +68,8 @@ namespace System.Management.Automation /// internal bool IsClosed { - get { return isClosed; } - set { isClosed = value; } + get { return _isClosed; } + set { _isClosed = value; } } /// @@ -81,7 +81,7 @@ namespace System.Management.Automation { // No objects in the input pipe // The pipe is closed. So there can't be any more object - if (isClosed && (inputPipe == null || inputPipe.Empty)) + if (_isClosed && (_inputPipe == null || _inputPipe.Empty)) { return false; } @@ -103,24 +103,24 @@ namespace System.Management.Automation /// internal string OutVariable { get; set; } - internal IList OutVarList { get { return outVarList; } set { outVarList = value; } } - private IList outVarList = null; + internal IList OutVarList { get { return _outVarList; } set { _outVarList = value; } } + private IList _outVarList = null; internal PipelineProcessor PipelineProcessor { get; set; } - private CommandInfo commandInfo; - private InternalCommand thisCommand; + private CommandInfo _commandInfo; + private InternalCommand _thisCommand; #endregion private_members internal MshCommandRuntime(ExecutionContext context, CommandInfo commandInfo, InternalCommand thisCommand) { - this.context = context; - this.host = context.EngineHostInterface; + _context = context; + _host = context.EngineHostInterface; this.CBhost = (InternalHost)context.EngineHostInterface; - this.commandInfo = commandInfo; - this.thisCommand = thisCommand; - this.shouldLogPipelineExecutionDetail = InitShouldLogPipelineExecutionDetail(); + _commandInfo = commandInfo; + _thisCommand = thisCommand; + _shouldLogPipelineExecutionDetail = InitShouldLogPipelineExecutionDetail(); } /// @@ -129,12 +129,12 @@ namespace System.Management.Automation /// public override string ToString() { - if (null != commandInfo) - return commandInfo.ToString(); + if (null != _commandInfo) + return _commandInfo.ToString(); return ""; // does not require localization } - private InvocationInfo myInvocation; + private InvocationInfo _myInvocation; /// /// Return the invocation data object for this command. /// @@ -143,12 +143,12 @@ namespace System.Management.Automation { get { - if (myInvocation == null) + if (_myInvocation == null) { - myInvocation = thisCommand.MyInvocation; + _myInvocation = _thisCommand.MyInvocation; } - return myInvocation; + return _myInvocation; } } @@ -308,12 +308,12 @@ namespace System.Management.Automation ThrowIfWriteNotPermitted(true); _WriteObjectsSkipAllowCheck(sendToPipeline); } -// Trust: public void WriteObject(object sendToPipeline, DataTrustCategory trustCategory); // enumerateCollection defaults to false -// Trust: public void WriteObject(object sendToPipeline, bool enumerateCollection, DataTrustCategory trustCategory); + // Trust: public void WriteObject(object sendToPipeline, DataTrustCategory trustCategory); // enumerateCollection defaults to false + // Trust: public void WriteObject(object sendToPipeline, bool enumerateCollection, DataTrustCategory trustCategory); // Variables needed to generate a unique SourceId for // WriteProgress(ProgressRecord). - private static Int64 _lastUsedSourceId /* = 0 */; + private static Int64 s_lastUsedSourceId /* = 0 */; private Int64 _sourceId /* = 0 */; /// @@ -373,7 +373,7 @@ namespace System.Management.Automation if (0 == _sourceId) { - _sourceId = Interlocked.Increment(ref _lastUsedSourceId); + _sourceId = Interlocked.Increment(ref s_lastUsedSourceId); } this.WriteProgress(_sourceId, progressRecord, overrideInquire); @@ -502,7 +502,7 @@ namespace System.Management.Automation if (DebugOutputPipe != null) { - if (CBhost!= null && CBhost.InternalUI != null && + if (CBhost != null && CBhost.InternalUI != null && DebugOutputPipe.NullPipe) { // If redirecting to a null pipe, still write to @@ -779,7 +779,7 @@ namespace System.Management.Automation CBhost.InternalUI.WriteInformationRecord(record); - if ((record.Tags.Contains("PSHOST") && (! record.Tags.Contains("FORWARDED"))) + if ((record.Tags.Contains("PSHOST") && (!record.Tags.Contains("FORWARDED"))) || (preference == ActionPreference.Continue)) { HostInformationMessage hostOutput = record.MessageData as HostInformationMessage; @@ -810,16 +810,16 @@ namespace System.Management.Automation // It is possible for either one or the other to be empty if run from a // non-interative host, but only one was specified in Write-Host. // So fill them with defaults if they are empty. - if(! foregroundColor.HasValue) + if (!foregroundColor.HasValue) { foregroundColor = ConsoleColor.Gray; } - if(! backgroundColor.HasValue) + if (!backgroundColor.HasValue) { backgroundColor = ConsoleColor.Black; } - + if (noNewLine) { CBhost.InternalUI.Write(foregroundColor.Value, backgroundColor.Value, message); @@ -881,21 +881,21 @@ namespace System.Management.Automation /// public void WriteCommandDetail(string text) { - this.PipelineProcessor.LogExecutionInfo(this.thisCommand.MyInvocation, text); + this.PipelineProcessor.LogExecutionInfo(_thisCommand.MyInvocation, text); } - private bool shouldLogPipelineExecutionDetail = false; + private bool _shouldLogPipelineExecutionDetail = false; internal bool LogPipelineExecutionDetail { get { - return shouldLogPipelineExecutionDetail; + return _shouldLogPipelineExecutionDetail; } } private bool InitShouldLogPipelineExecutionDetail() { - CmdletInfo cmdletInfo = commandInfo as CmdletInfo; + CmdletInfo cmdletInfo = _commandInfo as CmdletInfo; if (cmdletInfo != null) { @@ -908,7 +908,7 @@ namespace System.Management.Automation { return cmdletInfo.PSSnapIn.LogPipelineExecutionDetails; } - + if (cmdletInfo.PSSnapIn == null && cmdletInfo.Module != null) { return cmdletInfo.Module.LogPipelineExecutionDetails; @@ -918,7 +918,7 @@ namespace System.Management.Automation } // Logging should be enabled for functions from modules also - FunctionInfo functionInfo = commandInfo as FunctionInfo; + FunctionInfo functionInfo = _commandInfo as FunctionInfo; if (functionInfo != null && functionInfo.Module != null) { return functionInfo.Module.LogPipelineExecutionDetails; @@ -932,7 +932,7 @@ namespace System.Management.Automation /// the cmdlet. Semantically this is equivalent to : cmd | % { $pipelineVariable = $_; (...) } /// internal string PipelineVariable { get; set; } - private PSVariable pipelineVarReference = null; + private PSVariable _pipelineVarReference = null; internal void SetupOutVariable() { @@ -946,35 +946,35 @@ namespace System.Management.Automation // Handle the creation of OutVariable in the case of Out-Default specially, // as it needs to handle much of its OutVariable support itself. if ( - (! String.IsNullOrEmpty(this.OutVariable)) && + (!String.IsNullOrEmpty(this.OutVariable)) && (!(this.OutVariable.StartsWith("+", StringComparison.Ordinal))) && - String.Equals("Out-Default", this.thisCommand.CommandInfo.Name, StringComparison.OrdinalIgnoreCase)) + String.Equals("Out-Default", _thisCommand.CommandInfo.Name, StringComparison.OrdinalIgnoreCase)) { - if (this.state == null) - this.state = new SessionState(context.EngineSessionState); + if (_state == null) + _state = new SessionState(_context.EngineSessionState); IList oldValue = null; - oldValue = PSObject.Base(this.state.PSVariable.GetValue(this.OutVariable)) as IList; + oldValue = PSObject.Base(_state.PSVariable.GetValue(this.OutVariable)) as IList; if (oldValue == null) { - outVarList = new ArrayList(); + _outVarList = new ArrayList(); } else { - outVarList = oldValue; + _outVarList = oldValue; } - if (!(thisCommand is PSScriptCmdlet)) + if (!(_thisCommand is PSScriptCmdlet)) { - this.OutputPipe.AddVariableList(VariableStreamKind.Output, outVarList); + this.OutputPipe.AddVariableList(VariableStreamKind.Output, _outVarList); } - this.state.PSVariable.Set(this.OutVariable, outVarList); + _state.PSVariable.Set(this.OutVariable, _outVarList); } else { - SetupVariable(VariableStreamKind.Output, this.OutVariable, ref outVarList); + SetupVariable(VariableStreamKind.Output, this.OutVariable, ref _outVarList); } } @@ -990,20 +990,20 @@ namespace System.Management.Automation EnsureVariableParameterAllowed(); - if (this.state == null) - this.state = new SessionState(context.EngineSessionState); + if (_state == null) + _state = new SessionState(_context.EngineSessionState); // Create the pipeline variable - pipelineVarReference = new PSVariable(this.PipelineVariable); - this.state.PSVariable.Set(pipelineVarReference); + _pipelineVarReference = new PSVariable(this.PipelineVariable); + _state.PSVariable.Set(_pipelineVarReference); // Get the reference again in case we re-used one from the // same scope. - pipelineVarReference = this.state.PSVariable.Get(this.PipelineVariable); + _pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable); - if (!(thisCommand is PSScriptCmdlet)) + if (!(_thisCommand is PSScriptCmdlet)) { - this.OutputPipe.SetPipelineVariable(pipelineVarReference); + this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } } @@ -1019,9 +1019,9 @@ namespace System.Management.Automation set { OutputPipe.OutBufferCount = value; } } - #endregion Write + #endregion Write - #region Should + #region Should #region ShouldProcess /// /// Confirm the operation with the user. Cmdlets which make changes @@ -1436,7 +1436,7 @@ namespace System.Management.Automation private bool CanShouldProcessAutoConfirm() { // retrieve ConfirmImpact from commandInfo - CommandMetadata commandMetadata = commandInfo.CommandMetadata; + CommandMetadata commandMetadata = _commandInfo.CommandMetadata; if (null == commandMetadata) { Dbg.Assert(false, "Expected CommandMetadata"); @@ -1796,7 +1796,7 @@ namespace System.Management.Automation public bool ShouldContinue( string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) { - return DoShouldContinue(query, caption, hasSecurityImpact, true, ref yesToAll, ref noToAll); + return DoShouldContinue(query, caption, hasSecurityImpact, true, ref yesToAll, ref noToAll); } /// @@ -1964,7 +1964,7 @@ namespace System.Management.Automation supportsToAllOptions, // allowNoToAll false, // replaceNoWithHalt hasSecurityImpact // hasSecurityImpact - ); + ); switch (continueStatus) { @@ -1983,46 +1983,46 @@ namespace System.Management.Automation return true; } #endregion ShouldContinue - #endregion Should + #endregion Should - #region Transaction Support - /// - /// Returns true if a transaction is available for use. - /// - public bool TransactionAvailable() - { - return UseTransactionFlagSet && Context.TransactionManager.HasTransaction; - } - - /// - /// Gets an object that surfaces the current PowerShell transaction. - /// When this object is disposed, PowerShell resets the active transaction - /// - public PSTransactionContext CurrentPSTransaction - { - get + #region Transaction Support + /// + /// Returns true if a transaction is available for use. + /// + public bool TransactionAvailable() { - if(! TransactionAvailable()) - { - string error = null; - - if (! UseTransactionFlagSet) - error = TransactionStrings.CmdletRequiresUseTx; - else - error = TransactionStrings.NoTransactionAvailable; - - // We want to throw in this situation, and want to use a - // property because it mimics the C# using(TransactionScope ...) syntax - #pragma warning suppress 56503 - throw new InvalidOperationException(error); - } - - return new PSTransactionContext(Context.TransactionManager); + return UseTransactionFlagSet && Context.TransactionManager.HasTransaction; } - } - #endregion Transaction Support - #region Misc + /// + /// Gets an object that surfaces the current PowerShell transaction. + /// When this object is disposed, PowerShell resets the active transaction + /// + public PSTransactionContext CurrentPSTransaction + { + get + { + if (!TransactionAvailable()) + { + string error = null; + + if (!UseTransactionFlagSet) + error = TransactionStrings.CmdletRequiresUseTx; + else + error = TransactionStrings.NoTransactionAvailable; + + // We want to throw in this situation, and want to use a + // property because it mimics the C# using(TransactionScope ...) syntax +#pragma warning suppress 56503 + throw new InvalidOperationException(error); + } + + return new PSTransactionContext(Context.TransactionManager); + } + } + #endregion Transaction Support + + #region Misc /// /// Implementation of ThrowTerminatingError. /// @@ -2076,7 +2076,7 @@ namespace System.Management.Automation Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogCommandHealthEvent( - this.context, + _context, textLookupError, Severity.Warning); } @@ -2101,9 +2101,9 @@ namespace System.Management.Automation // Code sees only that execution stopped throw ManageException(e); } - #endregion Misc + #endregion Misc - #region Data Merging + #region Data Merging /// /// Data streams available for merging. @@ -2161,10 +2161,10 @@ namespace System.Management.Automation /// internal MergeDataStream ErrorMergeTo { - get { return this.errorMergeTo; } - set { this.errorMergeTo = value; } + get { return _errorMergeTo; } + set { _errorMergeTo = value; } } - private MergeDataStream errorMergeTo; + private MergeDataStream _errorMergeTo; /// /// Method to set data stream merging based on passed in runtime object. @@ -2204,26 +2204,27 @@ namespace System.Management.Automation /// internal bool MergeUnclaimedPreviousErrorResults { - get { return mergeUnclaimedPreviousErrorResults; } - set { mergeUnclaimedPreviousErrorResults = value; } + get { return _mergeUnclaimedPreviousErrorResults; } + set { _mergeUnclaimedPreviousErrorResults = value; } } - private bool mergeUnclaimedPreviousErrorResults = false; + private bool _mergeUnclaimedPreviousErrorResults = false; - #endregion + #endregion - #region Internal Pipes + #region Internal Pipes /// /// Gets or sets the input pipe. /// internal Pipe InputPipe { - get { - if (inputPipe == null) - inputPipe = new Pipe(); - return inputPipe; + get + { + if (_inputPipe == null) + _inputPipe = new Pipe(); + return _inputPipe; } - set { inputPipe = value; } + set { _inputPipe = value; } } /// @@ -2231,19 +2232,20 @@ namespace System.Management.Automation /// internal Pipe OutputPipe { - get { - if (outputPipe == null) - this.outputPipe = new Pipe(); - return outputPipe; + get + { + if (_outputPipe == null) + _outputPipe = new Pipe(); + return _outputPipe; } - set { outputPipe = value; } + set { _outputPipe = value; } } internal object[] GetResultsAsArray() { - if (outputPipe == null) + if (_outputPipe == null) return StaticEmptyArray; - return outputPipe.ToArray(); + return _outputPipe.ToArray(); } /// @@ -2257,12 +2259,13 @@ namespace System.Management.Automation /// internal Pipe ErrorOutputPipe { - get { - if (errorOutputPipe == null) - errorOutputPipe = new Pipe(); - return errorOutputPipe; + get + { + if (_errorOutputPipe == null) + _errorOutputPipe = new Pipe(); + return _errorOutputPipe; } - set { errorOutputPipe = value; } + set { _errorOutputPipe = value; } } /// @@ -2270,8 +2273,8 @@ namespace System.Management.Automation /// internal Pipe WarningOutputPipe { - get { return warningOutputPipe; } - set { warningOutputPipe = value; } + get { return _warningOutputPipe; } + set { _warningOutputPipe = value; } } /// @@ -2279,8 +2282,8 @@ namespace System.Management.Automation /// internal Pipe VerboseOutputPipe { - get { return verboseOutputPipe; } - set { verboseOutputPipe = value; } + get { return _verboseOutputPipe; } + set { _verboseOutputPipe = value; } } /// @@ -2288,8 +2291,8 @@ namespace System.Management.Automation /// internal Pipe DebugOutputPipe { - get { return debugOutputPipe; } - set { debugOutputPipe = value; } + get { return _debugOutputPipe; } + set { _debugOutputPipe = value; } } /// @@ -2297,11 +2300,11 @@ namespace System.Management.Automation /// internal Pipe InformationOutputPipe { - get { return informationOutputPipe; } - set { informationOutputPipe = value; } + get { return _informationOutputPipe; } + set { _informationOutputPipe = value; } } - #endregion + #endregion #region Internal helpers /// @@ -2323,7 +2326,7 @@ namespace System.Management.Automation internal void ThrowIfWriteNotPermitted(bool needsToWriteToPipeline) { if (null == this.PipelineProcessor - || this.thisCommand != this.PipelineProcessor._permittedToWrite + || _thisCommand != this.PipelineProcessor._permittedToWrite || needsToWriteToPipeline && !this.PipelineProcessor._permittedToWriteToPipeline || Thread.CurrentThread != this.PipelineProcessor._permittedToWriteThread ) @@ -2346,7 +2349,7 @@ namespace System.Management.Automation /// IDisposable internal IDisposable AllowThisCommandToWrite(bool permittedToWriteToPipeline) { - return new AllowWrite(this.thisCommand, permittedToWriteToPipeline); + return new AllowWrite(_thisCommand, permittedToWriteToPipeline); } private class AllowWrite : IDisposable @@ -2412,7 +2415,7 @@ namespace System.Management.Automation if (null != PipelineProcessor) { - PipelineProcessor.RecordFailure(e, thisCommand); + PipelineProcessor.RecordFailure(e, _thisCommand); } // 1021203-2005/05/09-JonN @@ -2435,7 +2438,7 @@ namespace System.Management.Automation // Log a command health event MshLog.LogCommandHealthEvent( - this.context, + _context, e, Severity.Warning); } @@ -2447,7 +2450,7 @@ namespace System.Management.Automation #endregion Internal helpers #region Error PSVariable - private IList errorVarList; + private IList _errorVarList; /// /// ErrorVariable tells which variable to populate with the errors. @@ -2460,17 +2463,17 @@ namespace System.Management.Automation internal void SetupErrorVariable() { - SetupVariable(VariableStreamKind.Error, this.ErrorVariable, ref errorVarList); + SetupVariable(VariableStreamKind.Error, this.ErrorVariable, ref _errorVarList); } // SetupErrorVariable private void EnsureVariableParameterAllowed() { - if ((context.LanguageMode == PSLanguageMode.NoLanguage) || - (context.LanguageMode == PSLanguageMode.RestrictedLanguage)) + if ((_context.LanguageMode == PSLanguageMode.NoLanguage) || + (_context.LanguageMode == PSLanguageMode.RestrictedLanguage)) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), - null, "VariableReferenceNotSupportedInDataSection", - ParserStrings.VariableReferenceNotSupportedInDataSection, + null, "VariableReferenceNotSupportedInDataSection", + ParserStrings.VariableReferenceNotSupportedInDataSection, ParserStrings.DefaultAllowedVariablesInDataSection); } } @@ -2513,13 +2516,13 @@ namespace System.Management.Automation return; // not outermost scope } - context.AppendDollarError(obj); + _context.AppendDollarError(obj); } // AppendDollarError #endregion Error PSVariable #region Warning PSVariable - private IList warningVarList; + private IList _warningVarList; /// /// WarningVariable tells which variable to populate with the warnings. @@ -2532,7 +2535,7 @@ namespace System.Management.Automation internal void SetupWarningVariable() { - SetupVariable(VariableStreamKind.Warning, this.WarningVariable, ref warningVarList); + SetupVariable(VariableStreamKind.Warning, this.WarningVariable, ref _warningVarList); } // SetupWarningVariable /// @@ -2547,7 +2550,7 @@ namespace System.Management.Automation #endregion Warning PSVariable #region Information PSVariable - private IList informationVarList; + private IList _informationVarList; /// /// InformationVariable tells which variable to populate with informational output. @@ -2558,14 +2561,14 @@ namespace System.Management.Automation /// internal string InformationVariable { - get { return informationVariable; } - set { informationVariable = value; } + get { return _informationVariable; } + set { _informationVariable = value; } } - private string informationVariable; + private string _informationVariable; internal void SetupInformationVariable() { - SetupVariable(VariableStreamKind.Information, this.InformationVariable, ref informationVarList); + SetupVariable(VariableStreamKind.Information, this.InformationVariable, ref _informationVarList); } // SetupWarningVariable @@ -2578,13 +2581,13 @@ namespace System.Management.Automation EnsureVariableParameterAllowed(); - if (this.state == null) - this.state = new SessionState(context.EngineSessionState); + if (_state == null) + _state = new SessionState(_context.EngineSessionState); if (variableName.StartsWith("+", StringComparison.Ordinal)) { variableName = variableName.Substring(1); - object oldValue = PSObject.Base(this.state.PSVariable.GetValue(variableName)); + object oldValue = PSObject.Base(_state.PSVariable.GetValue(variableName)); varList = oldValue as IList; if (null == varList) { @@ -2618,11 +2621,11 @@ namespace System.Management.Automation varList = new ArrayList(); } - if (!(thisCommand is PSScriptCmdlet)) + if (!(_thisCommand is PSScriptCmdlet)) { this.OutputPipe.AddVariableList(streamKind, varList); } - this.state.PSVariable.Set(variableName, varList); + _state.PSVariable.Set(variableName, varList); } // SetupVariable /// @@ -2635,7 +2638,7 @@ namespace System.Management.Automation } // AppendInformation #endregion Information PSVariable - + #region Write internal bool UseSecurityContextRun = true; @@ -2737,7 +2740,7 @@ namespace System.Management.Automation internal void WriteError(ErrorRecord errorRecord, bool overrideInquire) { - // This check will be repeated in _WriteErrorSkipAllowCheck, + // This check will be repeated in _WriteErrorSkipAllowCheck, // but we want PipelineStoppedException to take precedence // over InvalidOperationException if the pipeline has been // closed. @@ -2751,7 +2754,7 @@ namespace System.Management.Automation #if CORECLR // SecurityContext is not supported in CoreCLR - DoWriteError(new KeyValuePair (errorRecord, preference)); + DoWriteError(new KeyValuePair(errorRecord, preference)); #else if (UseSecurityContextRun) { @@ -2764,11 +2767,10 @@ namespace System.Management.Automation PipelineProcessor.SecurityContext.CreateCopy(), delegateCallback, new KeyValuePair(errorRecord, preference)); - } else { - DoWriteError(new KeyValuePair (errorRecord, preference)); + DoWriteError(new KeyValuePair(errorRecord, preference)); } #endif } // WriteError @@ -2801,13 +2803,13 @@ namespace System.Management.Automation // If this error came from a transacted cmdlet, // rollback the transaction - if(UseTransaction) + if (UseTransaction) { - if( - (context.TransactionManager.RollbackPreference != RollbackSeverity.TerminatingError) && - (context.TransactionManager.RollbackPreference != RollbackSeverity.Never)) + if ( + (_context.TransactionManager.RollbackPreference != RollbackSeverity.TerminatingError) && + (_context.TransactionManager.RollbackPreference != RollbackSeverity.Never)) { - context.TransactionManager.Rollback(true); + _context.TransactionManager.Rollback(true); } } @@ -2849,19 +2851,19 @@ namespace System.Management.Automation Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogCommandHealthEvent( - this.context, + _context, textLookupError, Severity.Warning); } this.PipelineProcessor.ExecutionFailed = true; - if (this.shouldLogPipelineExecutionDetail) + if (_shouldLogPipelineExecutionDetail) { - this.PipelineProcessor.LogExecutionError(this.thisCommand.MyInvocation, errorRecord); + this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord); } ActionPreference preference = ErrorAction; - if(actionPreference.HasValue) + if (actionPreference.HasValue) { preference = actionPreference.Value; } @@ -2892,7 +2894,7 @@ namespace System.Management.Automation new ActionPreferenceStopException( MyInvocation, errorRecord, - StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop, + StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop, "ErrorActionPreference", errorRecord.ToString())); throw ManageException(e); @@ -2939,9 +2941,9 @@ namespace System.Management.Automation { // If this is an error pipe for a hosting application and we are logging, // then create a temporary PowerShell to log the error. - if (context.InternalHost.UI.IsTranscribing) + if (_context.InternalHost.UI.IsTranscribing) { - context.InternalHost.UI.TranscribeError(context, errorRecord.InvocationInfo, errorWrap); + _context.InternalHost.UI.TranscribeError(_context, errorRecord.InvocationInfo, errorWrap); } this.ErrorOutputPipe.AddWithoutAppendingOutVarList(errorWrap); @@ -2956,8 +2958,8 @@ namespace System.Management.Automation // workings of the command and when what information will get output. // See "User Feedback Mechanisms - Note.doc" for details. - private bool isConfirmPreferenceCached = false; - private ConfirmImpact confirmPreference = InitialSessionState.defaultConfirmPreference; + private bool _isConfirmPreferenceCached = false; + private ConfirmImpact _confirmPreference = InitialSessionState.defaultConfirmPreference; /// /// Preference setting controlling behavior of ShouldProcess() /// @@ -2977,28 +2979,28 @@ namespace System.Management.Automation return ConfirmImpact.Low; if (Debug) { - if (isConfirmFlagSet) // -Debug -Confirm:$false + if (_isConfirmFlagSet) // -Debug -Confirm:$false return ConfirmImpact.None; return ConfirmImpact.Low; } - if (isConfirmFlagSet) // -Confirm:$false + if (_isConfirmFlagSet) // -Confirm:$false return ConfirmImpact.None; - if (!isConfirmPreferenceCached) + if (!_isConfirmPreferenceCached) { bool defaultUsed = false; - confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, confirmPreference, out defaultUsed); - isConfirmPreferenceCached = true; + _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out defaultUsed); + _isConfirmPreferenceCached = true; } - return confirmPreference; + return _confirmPreference; } } - private bool isDebugPreferenceSet = false; - private ActionPreference debugPreference = InitialSessionState.defaultDebugPreference; - private bool isDebugPreferenceCached = false; + private bool _isDebugPreferenceSet = false; + private ActionPreference _debugPreference = InitialSessionState.defaultDebugPreference; + private bool _isDebugPreferenceCached = false; /// /// Preference setting /// @@ -3009,9 +3011,9 @@ namespace System.Management.Automation { get { - if (isDebugPreferenceSet) - return debugPreference; - if (isDebugFlagSet) + if (_isDebugPreferenceSet) + return _debugPreference; + if (_isDebugFlagSet) { if (Debug) { @@ -3031,32 +3033,32 @@ namespace System.Management.Automation } - if (!isDebugPreferenceCached) + if (!_isDebugPreferenceCached) { bool defaultUsed = false; - - debugPreference = context.GetEnumPreference(SpecialVariables.DebugPreferenceVarPath, debugPreference, out defaultUsed); + + _debugPreference = _context.GetEnumPreference(SpecialVariables.DebugPreferenceVarPath, _debugPreference, out defaultUsed); // If the host couldn't prompt for the debug action anyways, change it to 'Continue'. // This lets hosts still see debug output without having to implement the prompting logic. - if((CBhost.ExternalHost.UI == null) && (debugPreference == ActionPreference.Inquire)) + if ((CBhost.ExternalHost.UI == null) && (_debugPreference == ActionPreference.Inquire)) { - debugPreference = ActionPreference.Continue; + _debugPreference = ActionPreference.Continue; } - isDebugPreferenceCached = true; + _isDebugPreferenceCached = true; } - return debugPreference; + return _debugPreference; } set { - debugPreference = value; - isDebugPreferenceSet = true; + _debugPreference = value; + _isDebugPreferenceSet = true; } // set } - private bool isVerbosePreferenceCached = false; - private ActionPreference verbosePreference = InitialSessionState.defaultVerbosePreference; + private bool _isVerbosePreferenceCached = false; + private ActionPreference _verbosePreference = InitialSessionState.defaultVerbosePreference; /// /// Preference setting /// @@ -3067,7 +3069,7 @@ namespace System.Management.Automation { get { - if (isVerboseFlagSet) + if (_isVerboseFlagSet) { if (Verbose) return ActionPreference.Continue; @@ -3089,27 +3091,27 @@ namespace System.Management.Automation } } - if (!isVerbosePreferenceCached) + if (!_isVerbosePreferenceCached) { bool defaultUsed = false; - verbosePreference = context.GetEnumPreference( - SpecialVariables.VerbosePreferenceVarPath, - verbosePreference, + _verbosePreference = _context.GetEnumPreference( + SpecialVariables.VerbosePreferenceVarPath, + _verbosePreference, out defaultUsed); } - return verbosePreference; + return _verbosePreference; } } - private bool isWarningPreferenceSet = false; + private bool _isWarningPreferenceSet = false; internal bool IsWarningActionSet { - get { return isWarningPreferenceSet; } + get { return _isWarningPreferenceSet; } } - private bool isWarningPreferenceCached = false; - private ActionPreference warningPreference = InitialSessionState.defaultWarningPreference; + private bool _isWarningPreferenceCached = false; + private ActionPreference _warningPreference = InitialSessionState.defaultWarningPreference; /// /// Preference setting /// @@ -3121,8 +3123,8 @@ namespace System.Management.Automation get { // Setting CommonParameters.WarningAction has highest priority - if (isWarningPreferenceSet) - return warningPreference; + if (_isWarningPreferenceSet) + return _warningPreference; if (Debug) return ActionPreference.Inquire; @@ -3131,13 +3133,13 @@ namespace System.Management.Automation // Debug:$false and Verbose:$false ignored - if (!isWarningPreferenceCached) + if (!_isWarningPreferenceCached) { bool defaultUsed = false; - warningPreference = context.GetEnumPreference(SpecialVariables.WarningPreferenceVarPath, warningPreference, out defaultUsed); + _warningPreference = _context.GetEnumPreference(SpecialVariables.WarningPreferenceVarPath, _warningPreference, out defaultUsed); } - return warningPreference; + return _warningPreference; } set { @@ -3146,16 +3148,16 @@ namespace System.Management.Automation throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); } - warningPreference = value; - isWarningPreferenceSet = true; + _warningPreference = value; + _isWarningPreferenceSet = true; } // set } // This is used so that people can tell whether the verbose switch // was specified. This is useful in the Cmdlet-calling-Cmdlet case // where you'd like the underlying Cmdlet to have the same switches. - private bool verboseFlag = false; - private bool isVerboseFlagSet = false; + private bool _verboseFlag = false; + private bool _isVerboseFlagSet = false; /// /// Echo tells the command to articulate the actions it performs while executing. /// @@ -3164,11 +3166,11 @@ namespace System.Management.Automation /// internal bool Verbose { - get { return verboseFlag; } + get { return _verboseFlag; } set { - verboseFlag = value; - isVerboseFlagSet = true; + _verboseFlag = value; + _isVerboseFlagSet = true; } // Set } @@ -3176,12 +3178,12 @@ namespace System.Management.Automation { get { - return isVerboseFlagSet; + return _isVerboseFlagSet; } } - private bool confirmFlag = false; - private bool isConfirmFlagSet = false; + private bool _confirmFlag = false; + private bool _isConfirmFlagSet = false; /// /// Confirm tells the command to ask the admin before performing an action. /// @@ -3192,12 +3194,12 @@ namespace System.Management.Automation { get { - return confirmFlag; + return _confirmFlag; } set { - confirmFlag = value; - isConfirmFlagSet = true; + _confirmFlag = value; + _isConfirmFlagSet = true; } // set } @@ -3205,12 +3207,12 @@ namespace System.Management.Automation { get { - return isConfirmFlagSet; + return _isConfirmFlagSet; } } - private bool useTransactionFlag = false; - private bool useTransactionFlagSet = false; + private bool _useTransactionFlag = false; + private bool _useTransactionFlagSet = false; /// /// UseTransaction tells the command to activate the current PowerShell transaction. @@ -3222,12 +3224,12 @@ namespace System.Management.Automation { get { - return useTransactionFlag; + return _useTransactionFlag; } set { - useTransactionFlag = value; - useTransactionFlagSet = true; + _useTransactionFlag = value; + _useTransactionFlagSet = true; } // set } @@ -3235,7 +3237,7 @@ namespace System.Management.Automation { get { - return useTransactionFlagSet; + return _useTransactionFlagSet; } } @@ -3243,8 +3245,8 @@ namespace System.Management.Automation //This is used so that people can tell whether the debug switch was specified. This // Is useful in the Cmdlet-calling-Cmdlet case where you'd like the underlying Cmdlet to // have the same switches. - private bool debugFlag = false; - private bool isDebugFlagSet = false; + private bool _debugFlag = false; + private bool _isDebugFlagSet = false; /// /// Debug tell the command system to provide Programmer/Support type messages to understand what is really occuring /// and give the user the opportunity to stop or debug the situation @@ -3254,11 +3256,11 @@ namespace System.Management.Automation /// internal bool Debug { - get { return debugFlag; } + get { return _debugFlag; } set { - debugFlag = value; - isDebugFlagSet = true; + _debugFlag = value; + _isDebugFlagSet = true; } // set } @@ -3266,13 +3268,13 @@ namespace System.Management.Automation { get { - return isDebugFlagSet; + return _isDebugFlagSet; } } - private bool whatIfFlag = InitialSessionState.defaultWhatIfPreference; - private bool isWhatIfFlagSet /* = false */; - private bool isWhatIfPreferenceCached /* = false */; + private bool _whatIfFlag = InitialSessionState.defaultWhatIfPreference; + private bool _isWhatIfFlagSet /* = false */; + private bool _isWhatIfPreferenceCached /* = false */; /// /// WhatIf indicates that the command should not /// perform any changes to persistent state outside Monad. @@ -3284,19 +3286,19 @@ namespace System.Management.Automation { get { - if (!isWhatIfFlagSet && !isWhatIfPreferenceCached) + if (!_isWhatIfFlagSet && !_isWhatIfPreferenceCached) { bool defaultUsed = false; - whatIfFlag = context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, whatIfFlag, out defaultUsed); - isWhatIfPreferenceCached = true; + _whatIfFlag = _context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, _whatIfFlag, out defaultUsed); + _isWhatIfPreferenceCached = true; } - return whatIfFlag; + return _whatIfFlag; } set { - whatIfFlag = value; - isWhatIfFlagSet = true; + _whatIfFlag = value; + _isWhatIfFlagSet = true; } // set } @@ -3304,13 +3306,13 @@ namespace System.Management.Automation { get { - return isWhatIfFlagSet; + return _isWhatIfFlagSet; } } - private bool isErrorActionSet = false; - private ActionPreference errorAction = InitialSessionState.defaultErrorActionPreference; - private bool isErrorActionPreferenceCached = false; + private bool _isErrorActionSet = false; + private ActionPreference _errorAction = InitialSessionState.defaultErrorActionPreference; + private bool _isErrorActionPreferenceCached = false; /// /// ErrorAction tells the command what to do when an error occurs /// @@ -3325,8 +3327,8 @@ namespace System.Management.Automation get { // Setting CommonParameters.ErrorAction has highest priority - if (isErrorActionSet) - return errorAction; + if (_isErrorActionSet) + return _errorAction; // Debug takes preference over Verbose if (Debug) @@ -3335,24 +3337,23 @@ namespace System.Management.Automation return ActionPreference.Continue; // fall back to $ErrorAction - if (!isErrorActionPreferenceCached) + if (!_isErrorActionPreferenceCached) { bool defaultUsed = false; - errorAction = context.GetEnumPreference(SpecialVariables.ErrorActionPreferenceVarPath, errorAction, out defaultUsed); - isErrorActionPreferenceCached = true; + _errorAction = _context.GetEnumPreference(SpecialVariables.ErrorActionPreferenceVarPath, _errorAction, out defaultUsed); + _isErrorActionPreferenceCached = true; } - return errorAction; - + return _errorAction; } set { - if ((! (this.commandInfo is WorkflowInfo)) && (value == ActionPreference.Suspend)) + if ((!(_commandInfo is WorkflowInfo)) && (value == ActionPreference.Suspend)) { throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceSupportedOnlyOnWorkflow); } - errorAction = value; - isErrorActionSet = true; + _errorAction = value; + _isErrorActionSet = true; } // set } @@ -3360,7 +3361,7 @@ namespace System.Management.Automation { get { - return isErrorActionSet; + return _isErrorActionSet; } } @@ -3374,26 +3375,26 @@ namespace System.Management.Automation { get { - if (isProgressPreferenceSet) - return progressPreference; + if (_isProgressPreferenceSet) + return _progressPreference; - if (!isProgressPreferenceCached) + if (!_isProgressPreferenceCached) { bool defaultUsed = false; - progressPreference = context.GetEnumPreference(SpecialVariables.ProgressPreferenceVarPath, progressPreference, out defaultUsed); - isProgressPreferenceCached = true; + _progressPreference = _context.GetEnumPreference(SpecialVariables.ProgressPreferenceVarPath, _progressPreference, out defaultUsed); + _isProgressPreferenceCached = true; } - return progressPreference; + return _progressPreference; } set { - progressPreference = value; - isProgressPreferenceSet = true; + _progressPreference = value; + _isProgressPreferenceSet = true; } // set } - private ActionPreference progressPreference = InitialSessionState.defaultProgressPreference; - private bool isProgressPreferenceSet = false; - private bool isProgressPreferenceCached = false; + private ActionPreference _progressPreference = InitialSessionState.defaultProgressPreference; + private bool _isProgressPreferenceSet = false; + private bool _isProgressPreferenceCached = false; /// /// @@ -3405,16 +3406,16 @@ namespace System.Management.Automation { get { - if (isInformationPreferenceSet) - return informationPreference; + if (_isInformationPreferenceSet) + return _informationPreference; - if (!isInformationPreferenceCached) + if (!_isInformationPreferenceCached) { bool defaultUsed = false; - informationPreference = context.GetEnumPreference(SpecialVariables.InformationPreferenceVarPath, informationPreference, out defaultUsed); - isInformationPreferenceCached = true; + _informationPreference = _context.GetEnumPreference(SpecialVariables.InformationPreferenceVarPath, _informationPreference, out defaultUsed); + _isInformationPreferenceCached = true; } - return informationPreference; + return _informationPreference; } set { @@ -3423,25 +3424,25 @@ namespace System.Management.Automation throw PSTraceSource.NewNotSupportedException(ErrorPackage.SuspendActionPreferenceErrorActionOnly); } - informationPreference = value; - isInformationPreferenceSet = true; + _informationPreference = value; + _isInformationPreferenceSet = true; } // set } - private ActionPreference informationPreference = InitialSessionState.defaultInformationPreference; + private ActionPreference _informationPreference = InitialSessionState.defaultInformationPreference; internal bool IsInformationActionSet { - get { return isInformationPreferenceSet; } + get { return _isInformationPreferenceSet; } } - private bool isInformationPreferenceSet = false; - private bool isInformationPreferenceCached = false; + private bool _isInformationPreferenceSet = false; + private bool _isInformationPreferenceCached = false; - private PagingParameters pagingParameters; + private PagingParameters _pagingParameters; internal PagingParameters PagingParameters { - get { return pagingParameters; } - set { pagingParameters = value; } + get { return _pagingParameters; } + set { _pagingParameters = value; } } #endregion Preference @@ -3706,7 +3707,7 @@ namespace System.Management.Automation CBhost.InternalUI.TranscribeResult(inquireMessage); System.Text.StringBuilder textChoices = new System.Text.StringBuilder(); - foreach(ChoiceDescription choice in choices) + foreach (ChoiceDescription choice in choices) { if (textChoices.Length > 0) { @@ -3717,7 +3718,7 @@ namespace System.Management.Automation CBhost.InternalUI.TranscribeResult(textChoices.ToString()); int defaultOption = 0; - if(hasSecurityImpact) + if (hasSecurityImpact) { defaultOption = skipOneOption; } @@ -3727,7 +3728,7 @@ namespace System.Management.Automation string chosen = choices[response].Label; int labelIndex = chosen.IndexOf('&'); - if(labelIndex > -1) + if (labelIndex > -1) { chosen = chosen[labelIndex + 1].ToString(); } @@ -3752,9 +3753,8 @@ namespace System.Management.Automation return ContinueStatus.NoToAll; else if (pauseOption == response) { - // This call returns when the user exits the nested prompt. - CBhost.EnterNestedPrompt(this.thisCommand); + CBhost.EnterNestedPrompt(_thisCommand); // continue loop } else if (-1 == response) @@ -3795,31 +3795,31 @@ namespace System.Management.Automation internal void SetVariableListsInPipe() { - Diagnostics.Assert(thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); + Diagnostics.Assert(_thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - if (outVarList != null) + if (_outVarList != null) { - this.OutputPipe.AddVariableList(VariableStreamKind.Output, outVarList); + this.OutputPipe.AddVariableList(VariableStreamKind.Output, _outVarList); } - if (errorVarList != null) + if (_errorVarList != null) { - this.OutputPipe.AddVariableList(VariableStreamKind.Error, errorVarList); + this.OutputPipe.AddVariableList(VariableStreamKind.Error, _errorVarList); } - if (warningVarList != null) + if (_warningVarList != null) { - this.OutputPipe.AddVariableList(VariableStreamKind.Warning, warningVarList); + this.OutputPipe.AddVariableList(VariableStreamKind.Warning, _warningVarList); } - if (informationVarList != null) + if (_informationVarList != null) { - this.OutputPipe.AddVariableList(VariableStreamKind.Information, informationVarList); + this.OutputPipe.AddVariableList(VariableStreamKind.Information, _informationVarList); } if (this.PipelineVariable != null) { - this.OutputPipe.SetPipelineVariable(pipelineVarReference); + this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } } @@ -3827,30 +3827,30 @@ namespace System.Management.Automation { //Diagnostics.Assert(thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - if (outVarList != null) + if (_outVarList != null) { - this.OutputPipe.RemoveVariableList(VariableStreamKind.Output, outVarList); + this.OutputPipe.RemoveVariableList(VariableStreamKind.Output, _outVarList); } - if (errorVarList != null) + if (_errorVarList != null) { - this.OutputPipe.RemoveVariableList(VariableStreamKind.Error, errorVarList); + this.OutputPipe.RemoveVariableList(VariableStreamKind.Error, _errorVarList); } - if (warningVarList != null) + if (_warningVarList != null) { - this.OutputPipe.RemoveVariableList(VariableStreamKind.Warning, warningVarList); + this.OutputPipe.RemoveVariableList(VariableStreamKind.Warning, _warningVarList); } - if (informationVarList != null) + if (_informationVarList != null) { - this.OutputPipe.RemoveVariableList(VariableStreamKind.Information, informationVarList); + this.OutputPipe.RemoveVariableList(VariableStreamKind.Information, _informationVarList); } if (this.PipelineVariable != null) { this.OutputPipe.RemovePipelineVariable(); - this.state.PSVariable.Remove(this.PipelineVariable); + _state.PSVariable.Remove(this.PipelineVariable); } } } diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index e1a9d2598..323cef8b8 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -289,12 +289,12 @@ namespace System.Management.Automation /// /// Gets true if this property can be set /// - public abstract bool IsSettable { get;} + public abstract bool IsSettable { get; } /// /// Gets true if this property can be read /// - public abstract bool IsGettable { get;} + public abstract bool IsGettable { get; } internal Exception NewSetValueException(Exception e, string errorId) { @@ -331,18 +331,18 @@ namespace System.Management.Automation StringBuilder returnValue = new StringBuilder(); returnValue.Append(this.Name); returnValue.Append(" = "); - if (this.conversionType != null) + if (_conversionType != null) { returnValue.Append("("); - returnValue.Append(this.conversionType); + returnValue.Append(_conversionType); returnValue.Append(")"); } - returnValue.Append(this.referencedMemberName); + returnValue.Append(_referencedMemberName); return returnValue.ToString(); } - private string referencedMemberName; - private Type conversionType; + private string _referencedMemberName; + private Type _conversionType; /// /// Initializes a new instance of PSAliasProperty setting the name of the alias @@ -362,7 +362,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("referencedMemberName"); } - this.referencedMemberName = referencedMemberName; + _referencedMemberName = referencedMemberName; } /// @@ -385,9 +385,9 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("referencedMemberName"); } - this.referencedMemberName = referencedMemberName; + _referencedMemberName = referencedMemberName; // conversionType is optional and can be null - this.conversionType = conversionType; + _conversionType = conversionType; } /// @@ -397,7 +397,7 @@ namespace System.Management.Automation { get { - return this.referencedMemberName; + return _referencedMemberName; } } @@ -408,7 +408,7 @@ namespace System.Management.Automation { get { - return this.LookupMember(this.referencedMemberName); + return this.LookupMember(_referencedMemberName); } } @@ -420,7 +420,7 @@ namespace System.Management.Automation { get { - return this.conversionType; + return _conversionType; } } @@ -432,8 +432,8 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - PSAliasProperty alias = new PSAliasProperty(name, referencedMemberName); - alias.conversionType = this.conversionType; + PSAliasProperty alias = new PSAliasProperty(name, _referencedMemberName); + alias._conversionType = _conversionType; CloneBaseProperties(alias); return alias; } @@ -462,9 +462,9 @@ namespace System.Management.Automation { get { - if (this.conversionType != null) + if (_conversionType != null) { - return conversionType.FullName; + return _conversionType.FullName; } return this.ReferencedMember.TypeNameOfValue; } @@ -521,9 +521,9 @@ namespace System.Management.Automation LookupMember(name, new HashSet(StringComparer.OrdinalIgnoreCase), out returnValue, out hasCycle); if (hasCycle) { - throw new + throw new ExtendedTypeSystemException( - "CycleInAliasLookup", + "CycleInAliasLookup", null, ExtendedTypeSystem.CycleInAlias, this.Name); @@ -546,7 +546,7 @@ namespace System.Management.Automation if (member == null) { throw new ExtendedTypeSystemException( - "AliasLookupMemberNotPresent", + "AliasLookupMemberNotPresent", null, ExtendedTypeSystem.MemberNotPresent, name); @@ -584,9 +584,9 @@ namespace System.Management.Automation get { object returnValue = this.ReferencedMember.Value; - if (this.conversionType != null) + if (_conversionType != null) { - returnValue = LanguagePrimitives.ConvertTo(returnValue, this.conversionType, CultureInfo.InvariantCulture); + returnValue = LanguagePrimitives.ConvertTo(returnValue, _conversionType, CultureInfo.InvariantCulture); } return returnValue; } @@ -621,21 +621,21 @@ namespace System.Management.Automation if (this.IsGettable) { returnValue.Append("get="); - returnValue.Append(this.getterCodeReference.Name); + returnValue.Append(_getterCodeReference.Name); returnValue.Append(";"); } if (this.IsSettable) { returnValue.Append("set="); - returnValue.Append(this.setterCodeReference.Name); + returnValue.Append(_setterCodeReference.Name); returnValue.Append(";"); } returnValue.Append("}"); return returnValue.ToString(); } - private MethodInfo getterCodeReference; - private MethodInfo setterCodeReference; + private MethodInfo _getterCodeReference; + private MethodInfo _setterCodeReference; /// @@ -654,7 +654,7 @@ namespace System.Management.Automation // Ignore the AmbiguousMatchException. // We will generate error below if we cannot find exactly one match method. } - + if (methodAsMember == null) { throw new ExtendedTypeSystemException( @@ -689,7 +689,7 @@ namespace System.Management.Automation null, ExtendedTypeSystem.CodePropertySetterFormat); } - SetSetter(methodAsMember, this.getterCodeReference); + SetSetter(methodAsMember, _getterCodeReference); } /// @@ -699,7 +699,7 @@ namespace System.Management.Automation { if (methodForGet == null) { - this.getterCodeReference = null; + _getterCodeReference = null; return; } @@ -710,7 +710,7 @@ namespace System.Management.Automation null, ExtendedTypeSystem.CodePropertyGetterFormat); } - this.getterCodeReference = methodForGet; + _getterCodeReference = methodForGet; } internal static bool CheckGetterMethodInfo(MethodInfo methodForGet) @@ -736,9 +736,8 @@ namespace System.Management.Automation "SetterAndGetterNullFormat", null, ExtendedTypeSystem.CodePropertyGetterAndSetterNull); - } - this.setterCodeReference = null; + _setterCodeReference = null; return; } @@ -749,7 +748,7 @@ namespace System.Management.Automation null, ExtendedTypeSystem.CodePropertySetterFormat); } - this.setterCodeReference = methodForSet; + _setterCodeReference = methodForSet; } internal static bool CheckSetterMethodInfo(MethodInfo methodForSet, MethodInfo methodForGet) @@ -831,7 +830,7 @@ namespace System.Management.Automation { get { - return this.getterCodeReference; + return _getterCodeReference; } } @@ -842,7 +841,7 @@ namespace System.Management.Automation { get { - return this.setterCodeReference; + return _setterCodeReference; } } @@ -853,7 +852,7 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - PSCodeProperty property = new PSCodeProperty(name, this.getterCodeReference, this.setterCodeReference); + PSCodeProperty property = new PSCodeProperty(name, _getterCodeReference, _setterCodeReference); CloneBaseProperties(property); return property; } @@ -887,7 +886,7 @@ namespace System.Management.Automation { get { - return this.getterCodeReference != null; + return _getterCodeReference != null; } } @@ -901,7 +900,7 @@ namespace System.Management.Automation { get { - if (this.getterCodeReference == null) + if (_getterCodeReference == null) { throw new GetValueException("GetWithoutGetterFromCodePropertyValue", null, @@ -910,7 +909,7 @@ namespace System.Management.Automation } try { - return this.getterCodeReference.Invoke(null, new object[1] { this.instance }); + return _getterCodeReference.Invoke(null, new object[1] { this.instance }); } catch (TargetInvocationException ex) { @@ -935,7 +934,7 @@ namespace System.Management.Automation } set { - if (this.setterCodeReference == null) + if (_setterCodeReference == null) { throw new SetValueException("SetWithoutSetterFromCodeProperty", null, @@ -944,7 +943,7 @@ namespace System.Management.Automation } try { - this.setterCodeReference.Invoke(null, new object[2] { this.instance, value }); + _setterCodeReference.Invoke(null, new object[2] { this.instance, value }); } catch (TargetInvocationException ex) { @@ -976,14 +975,14 @@ namespace System.Management.Automation { get { - if (this.getterCodeReference == null) + if (_getterCodeReference == null) { throw new GetValueException("GetWithoutGetterFromCodePropertyTypeOfValue", null, ExtendedTypeSystem.GetWithoutGetterException, this.Name); } - return this.getterCodeReference.ReturnType.FullName; + return _getterCodeReference.ReturnType.FullName; } } #endregion virtual implementation @@ -1059,7 +1058,7 @@ namespace System.Management.Automation this.adapterData = adapterData; this.baseObject = baseObject; } - + #region virtual implementation /// /// returns a new PSMemberInfo that is a copy of this PSMemberInfo @@ -1187,7 +1186,6 @@ namespace System.Management.Automation } Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); return adapter.BasePropertyType(this); - } } #endregion virtual implementation @@ -1215,7 +1213,6 @@ namespace System.Management.Automation internal PSAdaptedProperty(string name, Adapter adapter, object baseObject, object adapterData) : base(name, adapter, baseObject, adapterData) { - } /// @@ -1409,7 +1406,7 @@ namespace System.Management.Automation } if (string.IsNullOrEmpty(displayTypeName)) { - displayTypeName = val == null + displayTypeName = val == null ? "object" : ToStringCodeMethods.Type(val.GetType(), dropNamespaces: true); } @@ -1452,7 +1449,7 @@ namespace System.Management.Automation /// The variable to wrap /// for an empty or null name public PSVariableProperty(PSVariable variable) - :base(variable != null ? variable.Name : null, null) + : base(variable != null ? variable.Name : null, null) { if (variable == null) { @@ -1599,13 +1596,13 @@ namespace System.Management.Automation return returnValue.ToString(); } - private Nullable languageMode; - private string getterScriptText; - private ScriptBlock getterScript; + private Nullable _languageMode; + private string _getterScriptText; + private ScriptBlock _getterScript; - private string setterScriptText; - private ScriptBlock setterScript; - private bool shouldCloneOnAccess; + private string _setterScriptText; + private ScriptBlock _setterScript; + private bool _shouldCloneOnAccess; /// /// Gets the script used for the property getter. It might be null. @@ -1616,36 +1613,36 @@ namespace System.Management.Automation { // If we don't have a script block for the getter, see if we // have the text for it (to support delayed script compilation). - if ((this.getterScript == null) && (this.getterScriptText != null)) + if ((_getterScript == null) && (_getterScriptText != null)) { - this.getterScript = ScriptBlock.Create(this.getterScriptText); + _getterScript = ScriptBlock.Create(_getterScriptText); - if (languageMode.HasValue) + if (_languageMode.HasValue) { - getterScript.LanguageMode = languageMode; + _getterScript.LanguageMode = _languageMode; } - getterScript.DebuggerStepThrough = true; + _getterScript.DebuggerStepThrough = true; } - if (this.getterScript == null) + if (_getterScript == null) { return null; } - if (shouldCloneOnAccess) + if (_shouldCloneOnAccess) { // returning a clone as TypeTable might be shared between multiple // runspaces and ScriptBlock is not shareable. We decided to // Clone as needed instead of Cloning whenever a shared TypeTable is // attached to a Runspace to save on Memory. - ScriptBlock newGetterScript = this.getterScript.Clone(); - newGetterScript.LanguageMode = this.getterScript.LanguageMode; + ScriptBlock newGetterScript = _getterScript.Clone(); + newGetterScript.LanguageMode = _getterScript.LanguageMode; return newGetterScript; } else { - return this.getterScript; + return _getterScript; } } } @@ -1659,36 +1656,36 @@ namespace System.Management.Automation { // If we don't have a script block for the setter, see if we // have the text for it (to support delayed script compilation). - if ((this.setterScript == null) && (this.setterScriptText != null)) + if ((_setterScript == null) && (_setterScriptText != null)) { - this.setterScript = ScriptBlock.Create(this.setterScriptText); + _setterScript = ScriptBlock.Create(_setterScriptText); - if (languageMode.HasValue) + if (_languageMode.HasValue) { - setterScript.LanguageMode = languageMode; + _setterScript.LanguageMode = _languageMode; } - setterScript.DebuggerStepThrough = true; + _setterScript.DebuggerStepThrough = true; } - if (this.setterScript == null) + if (_setterScript == null) { return null; } - if (shouldCloneOnAccess) + if (_shouldCloneOnAccess) { // returning a clone as TypeTable might be shared between multiple // runspaces and ScriptBlock is not shareable. We decided to // Clone as needed instead of Cloning whenever a shared TypeTable is // attached to a Runspace to save on Memory. - ScriptBlock newSetterScript = this.setterScript.Clone(); - newSetterScript.LanguageMode = this.setterScript.LanguageMode; + ScriptBlock newSetterScript = _setterScript.Clone(); + newSetterScript.LanguageMode = _setterScript.LanguageMode; return newSetterScript; } else { - return this.setterScript; + return _setterScript; } } } @@ -1710,7 +1707,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("getterScript"); } - this.getterScript = getterScript; + _getterScript = getterScript; } /// @@ -1743,8 +1740,8 @@ namespace System.Management.Automation setterScript.DebuggerStepThrough = true; } - this.getterScript = getterScript; - this.setterScript = setterScript; + _getterScript = getterScript; + _setterScript = setterScript; } /// @@ -1769,21 +1766,21 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("getterScript setterScript"); } - this.getterScriptText = getterScript; - this.setterScriptText = setterScript; - this.languageMode = languageMode; + _getterScriptText = getterScript; + _setterScriptText = setterScript; + _languageMode = languageMode; } internal PSScriptProperty(string name, ScriptBlock getterScript, ScriptBlock setterScript, bool shouldCloneOnAccess) - :this(name, getterScript, setterScript) + : this(name, getterScript, setterScript) { - this.shouldCloneOnAccess = shouldCloneOnAccess; + _shouldCloneOnAccess = shouldCloneOnAccess; } internal PSScriptProperty(string name, string getterScript, string setterScript, Nullable languageMode, bool shouldCloneOnAccess) : this(name, getterScript, setterScript, languageMode) { - this.shouldCloneOnAccess = shouldCloneOnAccess; + _shouldCloneOnAccess = shouldCloneOnAccess; } #region virtual implementation @@ -1795,7 +1792,7 @@ namespace System.Management.Automation { PSScriptProperty property; property = new PSScriptProperty(name, this.GetterScript, this.SetterScript); - property.shouldCloneOnAccess = this.shouldCloneOnAccess; + property._shouldCloneOnAccess = _shouldCloneOnAccess; CloneBaseProperties(property); return property; } @@ -1871,12 +1868,12 @@ namespace System.Management.Automation try { SetterScript.DoInvokeReturnAsIs( - useLocalScope: true, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: scriptThis, - args: new object[] {value}); + useLocalScope: true, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: scriptThis, + args: new object[] { value }); return value; } catch (SessionStateOverflowException e) @@ -1907,12 +1904,12 @@ namespace System.Management.Automation try { return GetterScript.DoInvokeReturnAsIs( - useLocalScope: true, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.SwallowErrors, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: scriptThis, - args: Utils.EmptyArray()); + useLocalScope: true, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.SwallowErrors, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: scriptThis, + args: Utils.EmptyArray()); } catch (SessionStateOverflowException e) { @@ -1966,7 +1963,7 @@ namespace System.Management.Automation Type[] parameterTypes) { this.MethodTargetType = methodTargetType; - this.parameterTypes = parameterTypes; + _parameterTypes = parameterTypes; } /// @@ -1981,11 +1978,11 @@ namespace System.Management.Automation { get { - return this.parameterTypes; + return _parameterTypes; } } - private readonly Type[] parameterTypes; + private readonly Type[] _parameterTypes; static internal bool EqualsForCollection(ICollection xs, ICollection ys) { @@ -2020,7 +2017,7 @@ namespace System.Management.Automation { return false; } - if (!EqualsForCollection(this.parameterTypes, other.parameterTypes)) + if (!EqualsForCollection(_parameterTypes, other._parameterTypes)) { return false; } @@ -2037,11 +2034,11 @@ namespace System.Management.Automation { return true; } - if (obj.GetType() != typeof (PSMethodInvocationConstraints)) + if (obj.GetType() != typeof(PSMethodInvocationConstraints)) { return false; } - return Equals((PSMethodInvocationConstraints) obj); + return Equals((PSMethodInvocationConstraints)obj); } public override int GetHashCode() @@ -2050,7 +2047,7 @@ namespace System.Management.Automation unchecked { int result = 61; - + result = result * 397 + (MethodTargetType != null ? MethodTargetType.GetHashCode() : 0); result = result * 397 + ParameterTypes.SequenceGetHashCode(); @@ -2069,12 +2066,12 @@ namespace System.Management.Automation separator = " "; } - if (parameterTypes != null) + if (_parameterTypes != null) { sb.Append(separator); sb.Append("args: "); separator = ""; - foreach (var p in parameterTypes) + foreach (var p in _parameterTypes) { sb.Append(separator); sb.Append(ToStringCodeMethods.Type(p, dropNamespaces: true)); @@ -2114,7 +2111,7 @@ namespace System.Management.Automation /// /// Gets a list of all the overloads for this method /// - public abstract Collection OverloadDefinitions { get;} + public abstract Collection OverloadDefinitions { get; } #region virtual implementation @@ -2134,9 +2131,9 @@ namespace System.Management.Automation } set { - throw new ExtendedTypeSystemException("CannotChangePSMethodInfoValue", + throw new ExtendedTypeSystemException("CannotChangePSMethodInfoValue", null, - ExtendedTypeSystem.CannotSetValueForMemberType, + ExtendedTypeSystem.CannotSetValueForMemberType, this.GetType().FullName); } } @@ -2169,8 +2166,8 @@ namespace System.Management.Automation return returnValue.ToString(); } - private MethodInfo codeReference; - private MethodInformation[] codeReferenceMethodInformation; + private MethodInfo _codeReference; + private MethodInformation[] _codeReferenceMethodInformation; internal static bool CheckMethodInfo(MethodInfo method) { @@ -2194,14 +2191,14 @@ namespace System.Management.Automation // Ignore the AmbiguousMatchException. // We will generate error below if we cannot find exactly one match method. } - + if (methodAsMember == null) { throw new ExtendedTypeSystemException("WrongMethodFormatFromTypeTable", null, ExtendedTypeSystem.CodeMethodMethodFormat); } - this.codeReference = methodAsMember; - if (!CheckMethodInfo(this.codeReference)) + _codeReference = methodAsMember; + if (!CheckMethodInfo(_codeReference)) { throw new ExtendedTypeSystemException("WrongMethodFormat", null, ExtendedTypeSystem.CodeMethodMethodFormat); } @@ -2241,9 +2238,9 @@ namespace System.Management.Automation { throw new ExtendedTypeSystemException("WrongMethodFormat", null, ExtendedTypeSystem.CodeMethodMethodFormat); } - + this.name = name; - this.codeReference = codeReference; + _codeReference = codeReference; } /// @@ -2253,7 +2250,7 @@ namespace System.Management.Automation { get { - return this.codeReference; + return _codeReference; } } @@ -2264,7 +2261,7 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - PSCodeMethod member = new PSCodeMethod(name, codeReference); + PSCodeMethod member = new PSCodeMethod(name, _codeReference); CloneBaseProperties(member); return member; } @@ -2306,14 +2303,14 @@ namespace System.Management.Automation newArguments[i + 1] = arguments[i]; } - if (this.codeReferenceMethodInformation == null) + if (_codeReferenceMethodInformation == null) { - this.codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new [] {this.codeReference}); + _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] { _codeReference }); } object[] convertedArguments; - Adapter.GetBestMethodAndArguments(codeReference.Name, this.codeReferenceMethodInformation, newArguments, out convertedArguments); + Adapter.GetBestMethodAndArguments(_codeReference.Name, _codeReferenceMethodInformation, newArguments, out convertedArguments); - return DotNetAdapter.AuxiliaryMethodInvoke(null, convertedArguments, this.codeReferenceMethodInformation[0], newArguments); + return DotNetAdapter.AuxiliaryMethodInvoke(null, convertedArguments, _codeReferenceMethodInformation[0], newArguments); } /// @@ -2325,7 +2322,7 @@ namespace System.Management.Automation { return new Collection { - DotNetAdapter.GetMethodInfoOverloadDefinition(null, this.codeReference, 0) + DotNetAdapter.GetMethodInfoOverloadDefinition(null, _codeReference, 0) }; } } @@ -2367,8 +2364,8 @@ namespace System.Management.Automation return returnValue.ToString(); } - private ScriptBlock script; - private bool shouldCloneOnAccess; + private ScriptBlock _script; + private bool _shouldCloneOnAccess; /// /// Gets the script implementing this PSScriptMethod @@ -2377,20 +2374,20 @@ namespace System.Management.Automation { get { - if (shouldCloneOnAccess) + if (_shouldCloneOnAccess) { // returning a clone as TypeTable might be shared between multiple // runspaces and ScriptBlock is not shareable. We decided to // Clone as needed instead of Cloning whenever a shared TypeTable is // attached to a Runspace to save on Memory. - ScriptBlock newScript = this.script.Clone(); - newScript.LanguageMode = this.script.LanguageMode; + ScriptBlock newScript = _script.Clone(); + newScript.LanguageMode = _script.LanguageMode; return newScript; } else { - return this.script; + return _script; } } } @@ -2413,7 +2410,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("script"); } - this.script = script; + _script = script; } /// @@ -2431,7 +2428,7 @@ namespace System.Management.Automation internal PSScriptMethod(string name, ScriptBlock script, bool shouldCloneOnAccess) : this(name, script) { - this.shouldCloneOnAccess = shouldCloneOnAccess; + _shouldCloneOnAccess = shouldCloneOnAccess; } #region virtual implementation @@ -2449,20 +2446,20 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("arguments"); } - return InvokeScript(Name, script, this.instance, arguments); + return InvokeScript(Name, _script, this.instance, arguments); } - private static object InvokeScript(string methodName, ScriptBlock script, object @this, object[] arguments) + internal static object InvokeScript(string methodName, ScriptBlock script, object @this, object[] arguments) { try { return script.DoInvokeReturnAsIs( - useLocalScope: true, + useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: @this, - args: arguments); + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: @this, + args: arguments); } catch (SessionStateOverflowException e) { @@ -2506,10 +2503,10 @@ namespace System.Management.Automation /// /// Gets a list of all the overloads for this method /// - public override Collection OverloadDefinitions - { - get - { + public override Collection OverloadDefinitions + { + get + { Collection retValue = new Collection(); retValue.Add(this.ToString()); return retValue; @@ -2523,8 +2520,8 @@ namespace System.Management.Automation public override PSMemberInfo Copy() { PSScriptMethod method; - method = new PSScriptMethod(this.name, this.script); - method.shouldCloneOnAccess = this.shouldCloneOnAccess; + method = new PSScriptMethod(this.name, _script); + method._shouldCloneOnAccess = _shouldCloneOnAccess; CloneBaseProperties(method); return method; } @@ -2574,11 +2571,11 @@ namespace System.Management.Automation /// This property as a string public override string ToString() { - return adapter.BaseMethodToString(this); + return _adapter.BaseMethodToString(this); } internal object adapterData; - private Adapter adapter; + private Adapter _adapter; internal object baseObject; /// @@ -2597,7 +2594,7 @@ namespace System.Management.Automation } this.name = name; this.adapterData = adapterData; - this.adapter = adapter; + _adapter = adapter; this.baseObject = baseObject; } @@ -2625,7 +2622,7 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - PSMethod member = new PSMethod(this.name, this.adapter, this.baseObject, this.adapterData, this.IsSpecial, this.IsHidden); + PSMethod member = new PSMethod(this.name, _adapter, this.baseObject, this.adapterData, this.IsSpecial, this.IsHidden); CloneBaseProperties(member); return member; } @@ -2669,7 +2666,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("arguments"); } - return adapter.BaseMethodInvoke(this, invocationConstraints, arguments); + return _adapter.BaseMethodInvoke(this, invocationConstraints, arguments); } /// @@ -2679,7 +2676,7 @@ namespace System.Management.Automation { get { - return adapter.BaseMethodDefinitions(this); + return _adapter.BaseMethodDefinitions(this); } } @@ -2809,11 +2806,11 @@ namespace System.Management.Automation this.adapter.BaseParameterizedPropertySet(this, valueToSet, arguments); } - + /// /// Returns a collection of the definitions for this property /// - public override Collection OverloadDefinitions + public override Collection OverloadDefinitions { get { @@ -2894,15 +2891,15 @@ namespace System.Management.Automation return returnValue.ToString(); } - private PSMemberInfoIntegratingCollection members; - private PSMemberInfoIntegratingCollection properties; - private PSMemberInfoIntegratingCollection methods; + private PSMemberInfoIntegratingCollection _members; + private PSMemberInfoIntegratingCollection _properties; + private PSMemberInfoIntegratingCollection _methods; internal PSMemberInfoInternalCollection internalMembers; - private PSObject constructorPSObject; + private PSObject _constructorPSObject; - static Collection> emptyMemberCollection = new Collection>(); - static Collection> emptyMethodCollection = new Collection>(); - static Collection> emptyPropertyCollection = new Collection>(); + private static Collection> s_emptyMemberCollection = new Collection>(); + private static Collection> s_emptyMethodCollection = new Collection>(); + private static Collection> s_emptyPropertyCollection = new Collection>(); /// /// Initializes a new instance of PSMemberSet with no initial members @@ -2917,9 +2914,9 @@ namespace System.Management.Automation } this.name = name; this.internalMembers = new PSMemberInfoInternalCollection(); - this.members = new PSMemberInfoIntegratingCollection(this, emptyMemberCollection); - this.properties = new PSMemberInfoIntegratingCollection(this, emptyPropertyCollection); - this.methods = new PSMemberInfoIntegratingCollection(this, emptyMethodCollection); + _members = new PSMemberInfoIntegratingCollection(this, s_emptyMemberCollection); + _properties = new PSMemberInfoIntegratingCollection(this, s_emptyPropertyCollection); + _methods = new PSMemberInfoIntegratingCollection(this, s_emptyMethodCollection); } /// @@ -2948,14 +2945,14 @@ namespace System.Management.Automation } this.internalMembers.Add(member.Copy()); } - this.members = new PSMemberInfoIntegratingCollection(this, emptyMemberCollection); - this.properties = new PSMemberInfoIntegratingCollection(this, emptyPropertyCollection); - this.methods = new PSMemberInfoIntegratingCollection(this, emptyMethodCollection); + _members = new PSMemberInfoIntegratingCollection(this, s_emptyMemberCollection); + _properties = new PSMemberInfoIntegratingCollection(this, s_emptyPropertyCollection); + _methods = new PSMemberInfoIntegratingCollection(this, s_emptyMethodCollection); } - static Collection> typeMemberCollection = GetTypeMemberCollection(); - static Collection> typeMethodCollection = GetTypeMethodCollection(); - static Collection> typePropertyCollection = GetTypePropertyCollection(); + private static Collection> s_typeMemberCollection = GetTypeMemberCollection(); + private static Collection> s_typeMethodCollection = GetTypeMethodCollection(); + private static Collection> s_typePropertyCollection = GetTypePropertyCollection(); private static Collection> GetTypeMemberCollection() { @@ -3004,11 +3001,11 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("mshObject"); } - this.constructorPSObject = mshObject; + _constructorPSObject = mshObject; this.internalMembers = mshObject.InstanceMembers; - this.members = new PSMemberInfoIntegratingCollection(this, typeMemberCollection); - this.properties = new PSMemberInfoIntegratingCollection(this, typePropertyCollection); - this.methods = new PSMemberInfoIntegratingCollection(this, typeMethodCollection); + _members = new PSMemberInfoIntegratingCollection(this, s_typeMemberCollection); + _properties = new PSMemberInfoIntegratingCollection(this, s_typePropertyCollection); + _methods = new PSMemberInfoIntegratingCollection(this, s_typeMethodCollection); } internal bool inheritMembers = true; @@ -3041,7 +3038,7 @@ namespace System.Management.Automation { get { - return this.members; + return _members; } } @@ -3052,7 +3049,7 @@ namespace System.Management.Automation { get { - return this.properties; + return _properties; } } @@ -3063,7 +3060,7 @@ namespace System.Management.Automation { get { - return this.methods; + return _methods; } } @@ -3074,7 +3071,7 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - if (constructorPSObject == null) + if (_constructorPSObject == null) { PSMemberSet memberSet = new PSMemberSet(name); foreach (PSMemberInfo member in this.Members) @@ -3086,7 +3083,7 @@ namespace System.Management.Automation } else { - return new PSMemberSet(name, constructorPSObject); + return new PSMemberSet(name, _constructorPSObject); } } @@ -3144,8 +3141,8 @@ namespace System.Management.Automation /// internal class PSInternalMemberSet : PSMemberSet { - private object syncObject = new Object(); - private PSObject psObject; + private object _syncObject = new Object(); + private PSObject _psObject; #region Constructor @@ -3162,7 +3159,7 @@ namespace System.Management.Automation : base(propertyName) { this.internalMembers = null; - this.psObject = psObject; + _psObject = psObject; } #endregion @@ -3185,7 +3182,7 @@ namespace System.Management.Automation // cache "psbase" and "psobject" if (null == internalMembers) { - lock (syncObject) + lock (_syncObject) { if (null == internalMembers) { @@ -3198,7 +3195,7 @@ namespace System.Management.Automation break; case PSObject.PSObjectMemberSetName: GenerateInternalMembersFromPSObject(); - break; + break; default: Diagnostics.Assert(false, string.Format(CultureInfo.InvariantCulture, @@ -3219,11 +3216,11 @@ namespace System.Management.Automation private void GenerateInternalMembersFromBase() { - if (psObject.isDeserialized) + if (_psObject.isDeserialized) { - if (psObject.clrMembers != null) + if (_psObject.clrMembers != null) { - foreach (PSMemberInfo member in this.psObject.clrMembers) + foreach (PSMemberInfo member in _psObject.clrMembers) { internalMembers.Add(member.Copy()); } @@ -3232,7 +3229,7 @@ namespace System.Management.Automation else { foreach (PSMemberInfo member in - PSObject.dotNetInstanceAdapter.BaseGetMembers(psObject.ImmediateBaseObject)) + PSObject.dotNetInstanceAdapter.BaseGetMembers(_psObject.ImmediateBaseObject)) { internalMembers.Add(member.Copy()); } @@ -3243,11 +3240,11 @@ namespace System.Management.Automation { PSMemberInfoInternalCollection retVal = new PSMemberInfoInternalCollection(); - if (psObject.isDeserialized) + if (_psObject.isDeserialized) { - if (psObject.adaptedMembers != null) + if (_psObject.adaptedMembers != null) { - foreach (PSMemberInfo member in psObject.adaptedMembers) + foreach (PSMemberInfo member in _psObject.adaptedMembers) { retVal.Add(member.Copy()); } @@ -3255,8 +3252,8 @@ namespace System.Management.Automation } else { - foreach (PSMemberInfo member in psObject.InternalAdapter.BaseGetMembers( - psObject.ImmediateBaseObject)) + foreach (PSMemberInfo member in _psObject.InternalAdapter.BaseGetMembers( + _psObject.ImmediateBaseObject)) { retVal.Add(member.Copy()); } @@ -3268,7 +3265,7 @@ namespace System.Management.Automation private void GenerateInternalMembersFromPSObject() { PSMemberInfoCollection members = PSObject.dotNetInstanceAdapter.BaseGetMembers( - psObject); + _psObject); foreach (PSMemberInfo member in members) { internalMembers.Add(member.Copy()); @@ -3276,7 +3273,6 @@ namespace System.Management.Automation } #endregion - } /// @@ -3297,9 +3293,9 @@ namespace System.Management.Automation StringBuilder returnValue = new StringBuilder(); returnValue.Append(this.Name); returnValue.Append(" {"); - if (referencedPropertyNames.Count != 0) + if (_referencedPropertyNames.Count != 0) { - foreach (string property in referencedPropertyNames) + foreach (string property in _referencedPropertyNames) { returnValue.Append(property); returnValue.Append(", "); @@ -3310,7 +3306,7 @@ namespace System.Management.Automation return returnValue.ToString(); } - private Collection referencedPropertyNames; + private Collection _referencedPropertyNames; /// /// Initializes a new instance of PSPropertySet with a name and list of property names @@ -3329,14 +3325,14 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("referencedPropertyNames"); } - this.referencedPropertyNames = new Collection(); + _referencedPropertyNames = new Collection(); foreach (string referencedPropertyName in referencedPropertyNames) { if (String.IsNullOrEmpty(referencedPropertyName)) { throw PSTraceSource.NewArgumentException("referencedPropertyNames"); } - this.referencedPropertyNames.Add(referencedPropertyName); + _referencedPropertyNames.Add(referencedPropertyName); } } @@ -3347,7 +3343,7 @@ namespace System.Management.Automation { get { - return this.referencedPropertyNames; + return _referencedPropertyNames; } } @@ -3358,7 +3354,7 @@ namespace System.Management.Automation /// a new PSMemberInfo that is a copy of this PSMemberInfo public override PSMemberInfo Copy() { - PSPropertySet member = new PSPropertySet(name, this.referencedPropertyNames); + PSPropertySet member = new PSPropertySet(name, _referencedPropertyNames); CloneBaseProperties(member); return member; } @@ -3749,7 +3745,7 @@ namespace System.Management.Automation /// public class ReadOnlyPSMemberInfoCollection : IEnumerable where T : PSMemberInfo { - private PSMemberInfoInternalCollection members; + private PSMemberInfoInternalCollection _members; /// /// Initializes a new instance of ReadOnlyPSMemberInfoCollection with the given members @@ -3762,7 +3758,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("members"); } - this.members = members; + _members = members; } /// @@ -3779,7 +3775,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("name"); } - return this.members[name]; + return _members[name]; } } @@ -3795,7 +3791,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("name"); } - return this.members.Match(name); + return _members.Match(name); } /// @@ -3811,7 +3807,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("name"); } - return this.members.Match(name, memberTypes); + return _members.Match(name, memberTypes); } /// @@ -3829,20 +3825,20 @@ namespace System.Management.Automation /// the enumerator for this collection public virtual IEnumerator GetEnumerator() { - return this.members.GetEnumerator(); + return _members.GetEnumerator(); } /// /// Gets the number of elements in this collection /// - public int Count { get { return this.members.Count; } } + public int Count { get { return _members.Count; } } /// /// Returns the 0 based member identified by index /// /// index of the member to retrieve /// for invalid arguments - public T this[int index] { get { return this.members[index]; } } + public T this[int index] { get { return _members[index]; } } } /// @@ -3850,27 +3846,27 @@ namespace System.Management.Automation /// internal class PSMemberInfoInternalCollection : PSMemberInfoCollection, IEnumerable where T : PSMemberInfo { - private readonly OrderedDictionary members; - private int countHidden; + private readonly OrderedDictionary _members; + private int _countHidden; /// /// Constructs this collection /// internal PSMemberInfoInternalCollection() { - members = new OrderedDictionary(StringComparer.OrdinalIgnoreCase); + _members = new OrderedDictionary(StringComparer.OrdinalIgnoreCase); } private void Replace(T oldMember, T newMember) { - members[newMember.Name] = newMember; + _members[newMember.Name] = newMember; if (oldMember.IsHidden) { - countHidden--; + _countHidden--; } if (newMember.IsHidden) { - countHidden++; + _countHidden++; } } @@ -3882,9 +3878,9 @@ namespace System.Management.Automation { Diagnostics.Assert(newMember != null, "called from internal code that checks for new member not null"); - lock (members) + lock (_members) { - var oldMember = members[newMember.Name] as T; + var oldMember = _members[newMember.Name] as T; Diagnostics.Assert(oldMember != null, "internal code checks member already exists"); Replace(oldMember, newMember); } @@ -3917,19 +3913,19 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("member"); } - lock (members) + lock (_members) { - var existingMember = members[member.Name] as T; + var existingMember = _members[member.Name] as T; if (existingMember != null) { Replace(existingMember, member); } else { - members[member.Name] = member; + _members[member.Name] = member; if (member.IsHidden) { - this.countHidden++; + _countHidden++; } } } @@ -3956,16 +3952,16 @@ namespace System.Management.Automation name); } - lock (members) + lock (_members) { - var member = members[name] as PSMemberInfo; + var member = _members[name] as PSMemberInfo; if (member != null) { if (member.IsHidden) { - this.countHidden--; + _countHidden--; } - members.Remove(name); + _members.Remove(name); } } } @@ -3985,9 +3981,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - lock (members) + lock (_members) { - return this.members[name] as T; + return _members[name] as T; } } } @@ -4045,9 +4041,9 @@ namespace System.Management.Automation private PSMemberInfoInternalCollection GetInternalMembers(MshMemberMatchOptions matchOptions) { PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); - lock (members) + lock (_members) { - foreach (T member in members.Values.OfType()) + foreach (T member in _members.Values.OfType()) { if (member.MatchesOptions(matchOptions)) { @@ -4066,9 +4062,9 @@ namespace System.Management.Automation { get { - lock (members) + lock (_members) { - return this.members.Count; + return _members.Count; } } } @@ -4080,9 +4076,9 @@ namespace System.Management.Automation { get { - lock (members) + lock (_members) { - return this.members.Count - this.countHidden; + return _members.Count - _countHidden; } } } @@ -4096,9 +4092,9 @@ namespace System.Management.Automation { get { - lock (members) + lock (_members) { - return this.members[index] as T; + return _members[index] as T; } } } @@ -4111,10 +4107,10 @@ namespace System.Management.Automation /// the enumerator for this collection public override IEnumerator GetEnumerator() { - lock (members) + lock (_members) { // Copy the members to a list so that iteration can be performed without holding a lock. - return this.members.Values.OfType().ToList().GetEnumerator(); + return _members.Values.OfType().ToList().GetEnumerator(); } } } @@ -4122,7 +4118,7 @@ namespace System.Management.Automation #region CollectionEntry - internal class CollectionEntry where T : PSMemberInfo + internal class CollectionEntry where T : PSMemberInfo { internal delegate PSMemberInfoInternalCollection GetMembersDelegate(PSObject obj); internal delegate T GetMemberDelegate(PSObject obj, string name); @@ -4130,27 +4126,27 @@ namespace System.Management.Automation internal CollectionEntry(GetMembersDelegate getMembers, GetMemberDelegate getMember, bool shouldReplicateWhenReturning, bool shouldCloneWhenReturning, string collectionNameForTracing) { - this.getMembers = getMembers; - this.getMember = getMember; - this.shouldReplicateWhenReturning = shouldReplicateWhenReturning; - this.shouldCloneWhenReturning = shouldCloneWhenReturning; - this.collectionNameForTracing = collectionNameForTracing; + _getMembers = getMembers; + _getMember = getMember; + _shouldReplicateWhenReturning = shouldReplicateWhenReturning; + _shouldCloneWhenReturning = shouldCloneWhenReturning; + _collectionNameForTracing = collectionNameForTracing; } - private GetMembersDelegate getMembers; - internal GetMembersDelegate GetMembers { get { return this.getMembers; } } + private GetMembersDelegate _getMembers; + internal GetMembersDelegate GetMembers { get { return _getMembers; } } - private GetMemberDelegate getMember; - internal GetMemberDelegate GetMember { get { return this.getMember; } } + private GetMemberDelegate _getMember; + internal GetMemberDelegate GetMember { get { return _getMember; } } - private bool shouldReplicateWhenReturning; - internal bool ShouldReplicateWhenReturning { get { return this.shouldReplicateWhenReturning; } } + private bool _shouldReplicateWhenReturning; + internal bool ShouldReplicateWhenReturning { get { return _shouldReplicateWhenReturning; } } - private bool shouldCloneWhenReturning; - internal bool ShouldCloneWhenReturning { get { return this.shouldCloneWhenReturning; } } + private bool _shouldCloneWhenReturning; + internal bool ShouldCloneWhenReturning { get { return _shouldCloneWhenReturning; } } - private string collectionNameForTracing; - internal string CollectionNameForTracing { get { return this.collectionNameForTracing; } } + private string _collectionNameForTracing; + internal string CollectionNameForTracing { get { return _collectionNameForTracing; } } } #endregion CollectionEntry @@ -4163,11 +4159,11 @@ namespace System.Management.Automation if (memberSet == null) { memberSet = new PSInternalMemberSet(name, mshOwner) - { - ShouldSerialize = false, - IsHidden = true, - IsReservedMember = true - }; + { + ShouldSerialize = false, + IsHidden = true, + IsReservedMember = true + }; mshOwner.InstanceMembers.Add(memberSet); memberSet.instance = mshOwner; } @@ -4181,7 +4177,7 @@ namespace System.Management.Automation internal static object GeneratePSAdaptedMemberSet(object obj) { - return GenerateMemberSet(PSObject.AdaptedMemberSetName, obj); + return GenerateMemberSet(PSObject.AdaptedMemberSetName, obj); } internal static object GeneratePSObjectMemberSet(object obj) @@ -4196,11 +4192,11 @@ namespace System.Management.Automation if (memberSet == null) { memberSet = new PSMemberSet(PSObject.ExtendedMemberSetName, mshOwner) - { - ShouldSerialize = false, - IsHidden = true, - IsReservedMember = true - }; + { + ShouldSerialize = false, + IsHidden = true, + IsReservedMember = true + }; memberSet.ReplicateInstance(mshOwner); memberSet.instance = mshOwner; mshOwner.InstanceMembers.Add(memberSet); @@ -4225,12 +4221,12 @@ namespace System.Management.Automation } PSCodeProperty codeProperty = new PSCodeProperty(PSObject.PSTypeNames, CachedReflectionInfo.ReservedNameMembers_PSTypeNames) - { - ShouldSerialize = false, - instance = mshOwner, - IsHidden = true, - IsReservedMember = true - }; + { + ShouldSerialize = false, + instance = mshOwner, + IsHidden = true, + IsReservedMember = true + }; mshOwner.InstanceMembers.Add(codeProperty); } } @@ -4241,14 +4237,14 @@ namespace System.Management.Automation private void GenerateAllReservedMembers() { - if (!this.mshOwner.hasGeneratedReservedMembers) + if (!_mshOwner.hasGeneratedReservedMembers) { - this.mshOwner.hasGeneratedReservedMembers = true; - ReservedNameMembers.GeneratePSExtendedMemberSet(mshOwner); - ReservedNameMembers.GeneratePSBaseMemberSet(mshOwner); - ReservedNameMembers.GeneratePSObjectMemberSet(mshOwner); - ReservedNameMembers.GeneratePSAdaptedMemberSet(mshOwner); - ReservedNameMembers.GeneratePSTypeNames(mshOwner); + _mshOwner.hasGeneratedReservedMembers = true; + ReservedNameMembers.GeneratePSExtendedMemberSet(_mshOwner); + ReservedNameMembers.GeneratePSBaseMemberSet(_mshOwner); + ReservedNameMembers.GeneratePSObjectMemberSet(_mshOwner); + ReservedNameMembers.GeneratePSAdaptedMemberSet(_mshOwner); + ReservedNameMembers.GeneratePSTypeNames(_mshOwner); } } @@ -4256,12 +4252,12 @@ namespace System.Management.Automation #region Constructor, fields and properties - private Collection> collections; - internal Collection> Collections { get { return this.collections; } } + private Collection> _collections; + internal Collection> Collections { get { return _collections; } } - private PSObject mshOwner; - private PSMemberSet memberSetOwner; + private PSObject _mshOwner; + private PSMemberSet _memberSetOwner; internal PSMemberInfoIntegratingCollection(object owner, Collection> collections) { @@ -4270,9 +4266,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("owner"); } - mshOwner = owner as PSObject; - memberSetOwner = owner as PSMemberSet; - if (mshOwner == null && memberSetOwner == null) + _mshOwner = owner as PSObject; + _memberSetOwner = owner as PSMemberSet; + if (_mshOwner == null && _memberSetOwner == null) { throw PSTraceSource.NewArgumentException("owner"); } @@ -4282,7 +4278,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("collections"); } - this.collections = collections; + _collections = collections; } #endregion Constructor, fields and properties @@ -4343,12 +4339,12 @@ namespace System.Management.Automation } - if (this.memberSetOwner != null && memberSetOwner.IsReservedMember) + if (_memberSetOwner != null && _memberSetOwner.IsReservedMember) { throw new ExtendedTypeSystemException("CannotAddToReservedNameMemberset", null, ExtendedTypeSystem.CannotChangeReservedMember, - this.memberSetOwner.Name); + _memberSetOwner.Name); } } @@ -4362,9 +4358,9 @@ namespace System.Management.Automation /// internal void AddToReservedMemberSet(T member, bool preValidated) { - if(! preValidated) + if (!preValidated) { - if (this.memberSetOwner != null && !this.memberSetOwner.IsInstance) + if (_memberSetOwner != null && !_memberSetOwner.IsInstance) { throw new ExtendedTypeSystemException("RemoveMemberFromStaticMemberSet", null, @@ -4411,14 +4407,14 @@ namespace System.Management.Automation PSMemberInfo memberToBeAdded = member.Copy(); - if (this.mshOwner != null) + if (_mshOwner != null) { if (!preValidated) { - TypeTable typeTable = this.mshOwner.GetTypeTable(); + TypeTable typeTable = _mshOwner.GetTypeTable(); if (typeTable != null) { - PSMemberInfoInternalCollection typesXmlMembers = typeTable.GetMembers(this.mshOwner.InternalTypeNames); + PSMemberInfoInternalCollection typesXmlMembers = typeTable.GetMembers(_mshOwner.InternalTypeNames); if (typesXmlMembers[member.Name] != null) { throw new ExtendedTypeSystemException( @@ -4429,19 +4425,19 @@ namespace System.Management.Automation } } } - memberToBeAdded.ReplicateInstance(this.mshOwner); - mshOwner.InstanceMembers.Add(memberToBeAdded, preValidated); + memberToBeAdded.ReplicateInstance(_mshOwner); + _mshOwner.InstanceMembers.Add(memberToBeAdded, preValidated); // All member binders may need to invalidate dynamic sites, and now must generate // different binding restrictions (specifically, must check for an instance member // before considering the type table or adapted members.) PSGetMemberBinder.SetHasInstanceMember(memberToBeAdded.Name); - PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(PSObject.Base(mshOwner).GetType()); + PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(PSObject.Base(_mshOwner).GetType()); return; } - this.memberSetOwner.InternalMembers.Add(memberToBeAdded, preValidated); + _memberSetOwner.InternalMembers.Add(memberToBeAdded, preValidated); } /// @@ -4461,13 +4457,13 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - if (this.mshOwner != null) + if (_mshOwner != null) { - this.mshOwner.InstanceMembers.Remove(name); + _mshOwner.InstanceMembers.Remove(name); return; } - if (!this.memberSetOwner.IsInstance) + if (!_memberSetOwner.IsInstance) { throw new ExtendedTypeSystemException("AddMemberToStaticMemberSet", null, @@ -4475,15 +4471,15 @@ namespace System.Management.Automation name); } - if (IsReservedName(this.memberSetOwner.Name)) + if (IsReservedName(_memberSetOwner.Name)) { throw new ExtendedTypeSystemException("CannotRemoveFromReservedNameMemberset", null, ExtendedTypeSystem.CannotChangeReservedMember, - this.memberSetOwner.Name); + _memberSetOwner.Name); } - this.memberSetOwner.InternalMembers.Remove(name); + _memberSetOwner.InternalMembers.Remove(name); } @@ -4507,23 +4503,23 @@ namespace System.Management.Automation { switch (name.ToLowerInvariant()) { - case PSObject.BaseObjectMemberSetName: - ReservedNameMembers.GeneratePSBaseMemberSet(mshOwner); - break; - case PSObject.AdaptedMemberSetName: - ReservedNameMembers.GeneratePSAdaptedMemberSet(mshOwner); - break; - case PSObject.ExtendedMemberSetName: - ReservedNameMembers.GeneratePSExtendedMemberSet(mshOwner); - break; - case PSObject.PSObjectMemberSetName: - ReservedNameMembers.GeneratePSObjectMemberSet(mshOwner); - break; - case PSObject.PSTypeNames: - ReservedNameMembers.GeneratePSTypeNames(mshOwner); - break; - default: - break; + case PSObject.BaseObjectMemberSetName: + ReservedNameMembers.GeneratePSBaseMemberSet(_mshOwner); + break; + case PSObject.AdaptedMemberSetName: + ReservedNameMembers.GeneratePSAdaptedMemberSet(_mshOwner); + break; + case PSObject.ExtendedMemberSetName: + ReservedNameMembers.GeneratePSExtendedMemberSet(_mshOwner); + break; + case PSObject.PSObjectMemberSetName: + ReservedNameMembers.GeneratePSObjectMemberSet(_mshOwner); + break; + case PSObject.PSTypeNames: + ReservedNameMembers.GeneratePSTypeNames(_mshOwner); + break; + default: + break; } } } @@ -4547,14 +4543,14 @@ namespace System.Management.Automation PSMemberInfo member; object delegateOwner; - if (this.mshOwner != null) + if (_mshOwner != null) { // this will check if name is a reserved name like PSBase, PSTypeNames // if it is a reserved name, ensures the value is loaded. EnsureReservedMemberIsLoaded(name); - delegateOwner = mshOwner; + delegateOwner = _mshOwner; PSMemberInfoInternalCollection instanceMembers; - if (PSObject.HasInstanceMembers(this.mshOwner, out instanceMembers)) + if (PSObject.HasInstanceMembers(_mshOwner, out instanceMembers)) { member = instanceMembers[name]; T memberAsT = member as T; @@ -4567,8 +4563,8 @@ namespace System.Management.Automation } else { - member = this.memberSetOwner.InternalMembers[name]; - delegateOwner = this.memberSetOwner.instance; + member = _memberSetOwner.InternalMembers[name]; + delegateOwner = _memberSetOwner.instance; T memberAsT = member as T; if (memberAsT != null) { @@ -4585,7 +4581,7 @@ namespace System.Management.Automation return null; delegateOwner = PSObject.AsPSObject(delegateOwner); - foreach (CollectionEntry collection in this.collections) + foreach (CollectionEntry collection in _collections) { Diagnostics.Assert(delegateOwner != null, "all integrating collections with non emtpty collections have an associated PSObject"); T memberAsT = collection.GetMember((PSObject)delegateOwner, name); @@ -4615,10 +4611,10 @@ namespace System.Management.Automation { PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); object delegateOwner; - if (this.mshOwner != null) + if (_mshOwner != null) { - delegateOwner = this.mshOwner; - foreach (PSMemberInfo member in this.mshOwner.InstanceMembers) + delegateOwner = _mshOwner; + foreach (PSMemberInfo member in _mshOwner.InstanceMembers) { if (member.MatchesOptions(matchOptions)) { @@ -4632,8 +4628,8 @@ namespace System.Management.Automation } else { - delegateOwner = this.memberSetOwner.instance; - foreach (PSMemberInfo member in this.memberSetOwner.InternalMembers) + delegateOwner = _memberSetOwner.instance; + foreach (PSMemberInfo member in _memberSetOwner.InternalMembers) { if (member.MatchesOptions(matchOptions)) { @@ -4651,7 +4647,7 @@ namespace System.Management.Automation return returnValue; delegateOwner = PSObject.AsPSObject(delegateOwner); - foreach (CollectionEntry collection in this.collections) + foreach (CollectionEntry collection in _collections) { PSMemberInfoInternalCollection members = collection.GetMembers((PSObject)delegateOwner); foreach (T member in members) @@ -4737,7 +4733,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - if (this.mshOwner != null) + if (_mshOwner != null) { GenerateAllReservedMembers(); } @@ -4768,9 +4764,9 @@ namespace System.Management.Automation /// internal struct Enumerator : IEnumerator where S : PSMemberInfo { - private S current; - private int currentIndex; - private PSMemberInfoInternalCollection allMembers; + private S _current; + private int _currentIndex; + private PSMemberInfoInternalCollection _allMembers; /// /// Constructs this instance to enumerate over members @@ -4780,22 +4776,21 @@ namespace System.Management.Automation { using (PSObject.memberResolution.TraceScope("Enumeration Start")) { - this.currentIndex = -1; - this.current = null; - this.allMembers = integratingCollection.GetIntegratedMembers(MshMemberMatchOptions.None); - if (integratingCollection.mshOwner != null) + _currentIndex = -1; + _current = null; + _allMembers = integratingCollection.GetIntegratedMembers(MshMemberMatchOptions.None); + if (integratingCollection._mshOwner != null) { integratingCollection.GenerateAllReservedMembers(); - PSObject.memberResolution.WriteLine("Enumerating PSObject with type \"{0}\".", integratingCollection.mshOwner.ImmediateBaseObject.GetType().FullName); - PSObject.memberResolution.WriteLine("PSObject instance members: {0}", allMembers.VisibleCount); + PSObject.memberResolution.WriteLine("Enumerating PSObject with type \"{0}\".", integratingCollection._mshOwner.ImmediateBaseObject.GetType().FullName); + PSObject.memberResolution.WriteLine("PSObject instance members: {0}", _allMembers.VisibleCount); } else { - PSObject.memberResolution.WriteLine("Enumerating PSMemberSet \"{0}\".", integratingCollection.memberSetOwner.Name); - PSObject.memberResolution.WriteLine("MemberSet instance members: {0}", allMembers.VisibleCount); + PSObject.memberResolution.WriteLine("Enumerating PSMemberSet \"{0}\".", integratingCollection._memberSetOwner.Name); + PSObject.memberResolution.WriteLine("MemberSet instance members: {0}", _allMembers.VisibleCount); } } - } /// @@ -4807,26 +4802,26 @@ namespace System.Management.Automation /// public bool MoveNext() { - this.currentIndex++; + _currentIndex++; S member = null; - while (this.currentIndex < allMembers.Count) + while (_currentIndex < _allMembers.Count) { - member = allMembers[this.currentIndex]; + member = _allMembers[_currentIndex]; if (!member.IsHidden) { break; } - this.currentIndex++; + _currentIndex++; } - if (this.currentIndex < allMembers.Count) + if (_currentIndex < _allMembers.Count) { - this.current = member; + _current = member; return true; } - this.current = null; + _current = null; return false; } @@ -4838,11 +4833,11 @@ namespace System.Management.Automation { get { - if (currentIndex == -1) + if (_currentIndex == -1) { throw PSTraceSource.NewInvalidOperationException(); } - return this.current; + return _current; } } @@ -4856,8 +4851,8 @@ namespace System.Management.Automation void IEnumerator.Reset() { - this.currentIndex = -1; - this.current = null; + _currentIndex = -1; + _current = null; } @@ -4869,7 +4864,6 @@ namespace System.Management.Automation } #endregion Member collection classes and its auxilliary classes - } #pragma warning restore 56503 diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 27df55898..8786e5d6d 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Concurrent; @@ -37,7 +38,6 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace System.Management.Automation { - /// /// Wraps an object providing alternate views of the available members /// and ways to extend them. Members can be methods, properties, @@ -51,7 +51,7 @@ namespace System.Management.Automation [TypeDescriptionProvider(typeof(PSObjectTypeDescriptionProvider))] #endif [Serializable] - public class PSObject: IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider + public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider { #region constructors @@ -134,12 +134,12 @@ namespace System.Management.Automation PSObject.memberResolution.WriteLine("Serialized adapted member: {0}.", adaptedMember == null ? "not found" : adaptedMember.Name); return adaptedMember; } - T retValue = msjObj.InternalAdapter.BaseGetMember(msjObj.immediateBaseObject, name); + T retValue = msjObj.InternalAdapter.BaseGetMember(msjObj._immediateBaseObject, name); PSObject.memberResolution.WriteLine("Adapted member: {0}.", retValue == null ? "not found" : retValue.Name); return retValue; } - internal static PSMemberInfoInternalCollection TransformMemberInfoCollection(PSMemberInfoCollection source) where T: PSMemberInfo where U: PSMemberInfo + internal static PSMemberInfoInternalCollection TransformMemberInfoCollection(PSMemberInfoCollection source) where T : PSMemberInfo where U : PSMemberInfo { if (typeof(T) == typeof(U)) { @@ -170,7 +170,7 @@ namespace System.Management.Automation PSObject.memberResolution.WriteLine("Serialized adapted members: {0}.", msjObj.adaptedMembers.Count); return TransformMemberInfoCollection(msjObj.adaptedMembers); } - PSMemberInfoInternalCollection retValue = msjObj.InternalAdapter.BaseGetMembers(msjObj.immediateBaseObject); + PSMemberInfoInternalCollection retValue = msjObj.InternalAdapter.BaseGetMembers(msjObj._immediateBaseObject); PSObject.memberResolution.WriteLine("Adapted members: {0}.", retValue.VisibleCount); return retValue; } @@ -180,7 +180,7 @@ namespace System.Management.Automation // Don't lookup dotnet members if the object doesn't insist. if (null != msjObj.InternalAdapterSet.DotNetAdapter) { - PSMemberInfoInternalCollection retValue = msjObj.InternalAdapterSet.DotNetAdapter.BaseGetMembers(msjObj.immediateBaseObject); + PSMemberInfoInternalCollection retValue = msjObj.InternalAdapterSet.DotNetAdapter.BaseGetMembers(msjObj._immediateBaseObject); PSObject.memberResolution.WriteLine("DotNet members: {0}.", retValue.VisibleCount); return retValue; } @@ -193,7 +193,7 @@ namespace System.Management.Automation // Don't lookup dotnet member if the object doesn't insist. if (null != msjObj.InternalAdapterSet.DotNetAdapter) { - T retValue = msjObj.InternalAdapterSet.DotNetAdapter.BaseGetMember(msjObj.immediateBaseObject, name); + T retValue = msjObj.InternalAdapterSet.DotNetAdapter.BaseGetMember(msjObj._immediateBaseObject, name); PSObject.memberResolution.WriteLine("DotNet member: {0}.", retValue == null ? "not found" : retValue.Name); return retValue; } @@ -201,9 +201,9 @@ namespace System.Management.Automation return null; } - static Collection> memberCollection = GetMemberCollection(PSMemberViewTypes.All); - static Collection> methodCollection = GetMethodCollection(); - static Collection> propertyCollection = GetPropertyCollection(PSMemberViewTypes.All); + private static Collection> s_memberCollection = GetMemberCollection(PSMemberViewTypes.All); + private static Collection> s_methodCollection = GetMethodCollection(); + private static Collection> s_propertyCollection = GetPropertyCollection(PSMemberViewTypes.All); /// /// A collection of delegates to get Extended/Adapated/Dotnet members based on the @@ -246,11 +246,11 @@ namespace System.Management.Automation else { returnValue.Add(new CollectionEntry( - delegate(PSObject msjObj) + delegate (PSObject msjObj) { return TypeTableGetMembersDelegate(msjObj, backupTypeTable); }, - delegate(PSObject msjObj, string name) + delegate (PSObject msjObj, string name) { return TypeTableGetMemberDelegate(msjObj, backupTypeTable, name); }, @@ -334,11 +334,11 @@ namespace System.Management.Automation else { returnValue.Add(new CollectionEntry( - delegate(PSObject msjObj) + delegate (PSObject msjObj) { return TypeTableGetMembersDelegate(msjObj, backupTypeTable); }, - delegate(PSObject msjObj, string name) + delegate (PSObject msjObj, string name) { return TypeTableGetMemberDelegate(msjObj, backupTypeTable, name); }, @@ -370,20 +370,20 @@ namespace System.Management.Automation this.immediateBaseObjectIsEmpty = true; } - this.immediateBaseObject = obj; + _immediateBaseObject = obj; var context = LocalPipeline.GetExecutionContextFromTLS(); _typeTable = context != null ? context.TypeTableWeakReference : null; } internal static readonly DotNetAdapter dotNetInstanceAdapter = new DotNetAdapter(); - private static readonly DotNetAdapter baseAdapterForAdaptedObjects = new BaseDotNetAdapterForAdaptedObjects(); + private static readonly DotNetAdapter s_baseAdapterForAdaptedObjects = new BaseDotNetAdapterForAdaptedObjects(); internal static readonly DotNetAdapter dotNetStaticAdapter = new DotNetAdapter(true); - private static readonly AdapterSet dotNetInstanceAdapterSet = new AdapterSet(dotNetInstanceAdapter, null); - private static readonly AdapterSet mshMemberSetAdapter = new AdapterSet(new PSMemberSetAdapter(), null); - private static readonly AdapterSet mshObjectAdapter = new AdapterSet(new PSObjectAdapter(), null); - private static PSObject.AdapterSet cimInstanceAdapter = - new PSObject.AdapterSet(new ThirdPartyAdapter(typeof (Microsoft.Management.Infrastructure.CimInstance), + private static readonly AdapterSet s_dotNetInstanceAdapterSet = new AdapterSet(dotNetInstanceAdapter, null); + private static readonly AdapterSet s_mshMemberSetAdapter = new AdapterSet(new PSMemberSetAdapter(), null); + private static readonly AdapterSet s_mshObjectAdapter = new AdapterSet(new PSObjectAdapter(), null); + private static PSObject.AdapterSet s_cimInstanceAdapter = + new PSObject.AdapterSet(new ThirdPartyAdapter(typeof(Microsoft.Management.Infrastructure.CimInstance), new Microsoft.PowerShell.Cim.CimInstanceAdapter()), PSObject.dotNetInstanceAdapter); @@ -391,41 +391,41 @@ namespace System.Management.Automation private static readonly AdapterSet managementObjectAdapter = new AdapterSet(new ManagementObjectAdapter(), dotNetInstanceAdapter); private static readonly AdapterSet managementClassAdapter = new AdapterSet(new ManagementClassApdapter(), dotNetInstanceAdapter); private static readonly AdapterSet directoryEntryAdapter = new AdapterSet(new DirectoryEntryAdapter(), dotNetInstanceAdapter); - private static readonly AdapterSet dataRowViewAdapter = new AdapterSet(new DataRowViewAdapter(), baseAdapterForAdaptedObjects); - private static readonly AdapterSet dataRowAdapter = new AdapterSet(new DataRowAdapter(), baseAdapterForAdaptedObjects); + private static readonly AdapterSet dataRowViewAdapter = new AdapterSet(new DataRowViewAdapter(), s_baseAdapterForAdaptedObjects); + private static readonly AdapterSet dataRowAdapter = new AdapterSet(new DataRowAdapter(), s_baseAdapterForAdaptedObjects); #endif - private static readonly AdapterSet xmlNodeAdapter = new AdapterSet(new XmlNodeAdapter(), baseAdapterForAdaptedObjects); + private static readonly AdapterSet s_xmlNodeAdapter = new AdapterSet(new XmlNodeAdapter(), s_baseAdapterForAdaptedObjects); #region Adapter Mappings - private static readonly ConcurrentDictionary _adapterMapping = new ConcurrentDictionary(); - private static readonly List> _adapterSetMappers = new List> + private static readonly ConcurrentDictionary s_adapterMapping = new ConcurrentDictionary(); + private static readonly List> s_adapterSetMappers = new List> { MappedInternalAdapterSet }; internal static void RegisterAdapterMapping(Func mapper) { - lock (_adapterSetMappers) + lock (s_adapterSetMappers) { - _adapterSetMappers.Add(mapper); + s_adapterSetMappers.Add(mapper); } } private static AdapterSet MappedInternalAdapterSet(object obj) { - if (obj is PSMemberSet) { return PSObject.mshMemberSetAdapter; } - if (obj is PSObject) { return PSObject.mshObjectAdapter; } - if (obj is CimInstance) { return PSObject.cimInstanceAdapter; } + if (obj is PSMemberSet) { return PSObject.s_mshMemberSetAdapter; } + if (obj is PSObject) { return PSObject.s_mshObjectAdapter; } + if (obj is CimInstance) { return PSObject.s_cimInstanceAdapter; } #if !CORECLR // WMIv1/ADSI/DataRow/DataRowView Adapters Not Supported On CSS - if (obj is ManagementClass) { return PSObject.managementClassAdapter; } + if (obj is ManagementClass) { return PSObject.managementClassAdapter; } if (obj is ManagementBaseObject) { return PSObject.managementObjectAdapter; } - if (obj is DirectoryEntry) { return PSObject.directoryEntryAdapter; } - if (obj is DataRowView) { return PSObject.dataRowViewAdapter; } - if (obj is DataRow) { return PSObject.dataRowAdapter; } + if (obj is DirectoryEntry) { return PSObject.directoryEntryAdapter; } + if (obj is DataRowView) { return PSObject.dataRowViewAdapter; } + if (obj is DataRow) { return PSObject.dataRowAdapter; } #endif - if (obj is XmlNode) { return PSObject.xmlNodeAdapter; } + if (obj is XmlNode) { return PSObject.s_xmlNodeAdapter; } return null; } @@ -450,14 +450,14 @@ namespace System.Management.Automation } AdapterSet result; - if (_adapterMapping.TryGetValue(objectType, out result)) + if (s_adapterMapping.TryGetValue(objectType, out result)) { return result; } - lock (_adapterSetMappers) + lock (s_adapterSetMappers) { - foreach (var mapper in _adapterSetMappers) + foreach (var mapper in s_adapterSetMappers) { result = mapper(obj); if (result != null) @@ -475,7 +475,7 @@ namespace System.Management.Automation // All WinRT types would contain the TypeAttributes flag being set to WindowsRunTime. if (WinRTHelper.IsWinRTType(objectType)) { - result = PSObject.dotNetInstanceAdapterSet; + result = PSObject.s_dotNetInstanceAdapterSet; } // We are not using IsAssignableFrom because we want to avoid @@ -491,23 +491,23 @@ namespace System.Management.Automation ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj); return info != null ? new AdapterSet(new ComAdapter(info), dotNetInstanceAdapter) - : PSObject.dotNetInstanceAdapterSet; + : PSObject.s_dotNetInstanceAdapterSet; } else { ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj); result = info != null ? new AdapterSet(new DotNetAdapterWithComTypeName(info), null) - : PSObject.dotNetInstanceAdapterSet; + : PSObject.s_dotNetInstanceAdapterSet; } } else { - result = PSObject.dotNetInstanceAdapterSet; + result = PSObject.s_dotNetInstanceAdapterSet; } } - var existingOrNew = _adapterMapping.GetOrAdd(objectType, result); + var existingOrNew = s_adapterMapping.GetOrAdd(objectType, result); Diagnostics.Assert(existingOrNew == result, "There is a logic error in caching adapter sets."); return result; @@ -517,7 +517,7 @@ namespace System.Management.Automation internal static AdapterSet CreateThirdPartyAdapterSet(Type adaptedType, PSPropertyAdapter adapter) { - return new AdapterSet(new ThirdPartyAdapter(adaptedType, adapter), baseAdapterForAdaptedObjects); + return new AdapterSet(new ThirdPartyAdapter(adaptedType, adapter), s_baseAdapterForAdaptedObjects); } #endregion private to the constructors @@ -536,7 +536,7 @@ namespace System.Management.Automation /// object we are wrapping /// if is null [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "This is shipped as part of V1. Retaining this for backward compatibility.")] - public PSObject (object obj) + public PSObject(object obj) { if (obj == null) { @@ -580,7 +580,7 @@ namespace System.Management.Automation #region fields #region instance fields - private object lockObject = new Object(); + private object _lockObject = new Object(); /// /// If this is non-null return this string as the ToString() for this wrapped object. @@ -591,7 +591,7 @@ namespace System.Management.Automation /// This is the main field in the class representing /// the System.Object we are encapsulating /// - private object immediateBaseObject; + private object _immediateBaseObject; private WeakReference _typeTable; @@ -639,21 +639,21 @@ namespace System.Management.Automation { get { - if (null == adapterSet) + if (null == _adapterSet) { - lock (lockObject) + lock (_lockObject) { - if (null == adapterSet) + if (null == _adapterSet) { - adapterSet = GetMappedAdapter(immediateBaseObject, GetTypeTable()); + _adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable()); } } } - return adapterSet; + return _adapterSet; } } - private AdapterSet adapterSet; + private AdapterSet _adapterSet; internal bool hasGeneratedReservedMembers; @@ -663,21 +663,21 @@ namespace System.Management.Automation { if (_instanceMembers == null) { - lock (lockObject) + lock (_lockObject) { if (_instanceMembers == null) { _instanceMembers = - _instanceMembersResurrectionTable.GetValue( + s_instanceMembersResurrectionTable.GetValue( GetKeyForResurrectionTables(this), _ => new PSMemberInfoInternalCollection()); - } + } } } return _instanceMembers; } - set + set { _instanceMembers = value; } @@ -693,7 +693,7 @@ namespace System.Management.Automation { if (psobj._instanceMembers == null) { - _instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(psobj), + s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(psobj), out psobj._instanceMembers); } } @@ -701,7 +701,7 @@ namespace System.Management.Automation } else if (obj != null) { - _instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out instanceMembers); + s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out instanceMembers); } else { @@ -711,7 +711,7 @@ namespace System.Management.Automation return instanceMembers != null && instanceMembers.Count > 0; } - private static readonly ConditionalWeakTable> _instanceMembersResurrectionTable = + private static readonly ConditionalWeakTable> s_instanceMembersResurrectionTable = new ConditionalWeakTable>(); /// @@ -741,7 +741,7 @@ namespace System.Management.Automation #endregion instance fields - + #endregion fields #region properties @@ -753,14 +753,14 @@ namespace System.Management.Automation { get { - if(_members == null) + if (_members == null) { - lock(lockObject) + lock (_lockObject) { - if(_members == null) + if (_members == null) { - _members = new PSMemberInfoIntegratingCollection(this, memberCollection); - } + _members = new PSMemberInfoIntegratingCollection(this, s_memberCollection); + } } } @@ -776,15 +776,14 @@ namespace System.Management.Automation { get { - if(_properties == null) + if (_properties == null) { - lock(lockObject) + lock (_lockObject) { - if(_properties == null) + if (_properties == null) { - _properties = new PSMemberInfoIntegratingCollection(this,propertyCollection); - - } + _properties = new PSMemberInfoIntegratingCollection(this, s_propertyCollection); + } } } @@ -800,14 +799,14 @@ namespace System.Management.Automation { get { - if(_methods == null) + if (_methods == null) { - lock(lockObject) + lock (_lockObject) { - if(_methods == null) + if (_methods == null) { - _methods = new PSMemberInfoIntegratingCollection(this, methodCollection); - } + _methods = new PSMemberInfoIntegratingCollection(this, s_methodCollection); + } } } @@ -826,7 +825,7 @@ namespace System.Management.Automation { get { - return this.immediateBaseObject; + return _immediateBaseObject; } } @@ -843,7 +842,7 @@ namespace System.Management.Automation PSObject mshObj = this; do { - returnValue = mshObj.immediateBaseObject; + returnValue = mshObj._immediateBaseObject; mshObj = returnValue as PSObject; } while (mshObj != null); @@ -861,12 +860,12 @@ namespace System.Management.Automation var result = InternalTypeNames; if (result.IsReadOnly) { - lock (lockObject) + lock (_lockObject) { // Check again after acquiring the lock to ensure some other thread didn't make the copy. if (result.IsReadOnly) { - _typeNames = _typeNamesResurrectionTable.GetValue( + _typeNames = s_typeNamesResurrectionTable.GetValue( GetKeyForResurrectionTables(this), _ => new ConsolidatedString(_typeNames)); @@ -886,13 +885,13 @@ namespace System.Management.Automation { get { - if(_typeNames == null) + if (_typeNames == null) { - lock(lockObject) + lock (_lockObject) { - if(_typeNames == null) + if (_typeNames == null) { - if (!_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(this), out _typeNames)) + if (!s_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(this), out _typeNames)) { // We don't cache this typename in the resurrection table because it's cached in the psobject, // and the assumption is we'll usually get the value directly from the PSObject, so it's not @@ -900,7 +899,7 @@ namespace System.Management.Automation // // If we hand out the typename to a client that could change it (through the public property // TypeNames), then we'll need to store the copy in the resurrection table. - _typeNames = InternalAdapter.BaseGetTypeNameHierarchy(immediateBaseObject); + _typeNames = InternalAdapter.BaseGetTypeNameHierarchy(_immediateBaseObject); } } } @@ -932,11 +931,11 @@ namespace System.Management.Automation internal static bool HasInstanceTypeName(object obj, out ConsolidatedString result) { - return _typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out result); + return s_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out result); } private ConsolidatedString _typeNames; - private static readonly ConditionalWeakTable _typeNamesResurrectionTable = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_typeNamesResurrectionTable = new ConditionalWeakTable(); #endregion properties @@ -1009,7 +1008,7 @@ namespace System.Management.Automation object returnValue = null; do { - returnValue = mshObj.immediateBaseObject; + returnValue = mshObj._immediateBaseObject; mshObj = returnValue as PSObject; } while ((mshObj != null) && (!mshObj.immediateBaseObjectIsEmpty)); @@ -1180,7 +1179,7 @@ namespace System.Management.Automation // Don't evaluate script properties during a ToString() operation. Object propertyValue = null; - if(property is PSScriptProperty) + if (property is PSScriptProperty) { propertyValue = property.GetType().FullName; } @@ -1283,20 +1282,20 @@ namespace System.Management.Automation case TypeCode.UInt64: return obj.ToString(); case TypeCode.DateTime: - DateTime dt = (DateTime) obj; + DateTime dt = (DateTime)obj; return dt.ToString(formatProvider); case TypeCode.Decimal: - Decimal dec = (Decimal) obj; + Decimal dec = (Decimal)obj; return dec.ToString(formatProvider); case TypeCode.Double: - double dbl = (double) obj; + double dbl = (double)obj; return dbl.ToString(formatProvider); case TypeCode.Single: - float sgl = (float) obj; + float sgl = (float)obj; return sgl.ToString(formatProvider); } - + #region recurse if (recurse) { @@ -1355,7 +1354,7 @@ namespace System.Management.Automation ExtendedTypeSystem.ToStringException, e.Message); } #endregion object ToString - } + } #endregion plain object #region PSObject @@ -1471,7 +1470,7 @@ namespace System.Management.Automation // Since we don't have a brokered ToString and the enumerations were not necessary or failed // we try the BaseObject's ToString - object baseObject = mshObj.immediateBaseObject; + object baseObject = mshObj._immediateBaseObject; IFormattable msjObjFormattable = baseObject as IFormattable; try { @@ -1512,13 +1511,13 @@ namespace System.Management.Automation /// if an exception was thrown by the BaseObject's ToString public override string ToString() { - //If ToString value from deserialization is available, - //simply return it. - if (toStringFromDeserialization != null) - { - return toStringFromDeserialization; - } - return PSObject.ToString(null, this, null, null, null, true, false); + //If ToString value from deserialization is available, + //simply return it. + if (_toStringFromDeserialization != null) + { + return _toStringFromDeserialization; + } + return PSObject.ToString(null, this, null, null, null, true, false); } /// @@ -1530,15 +1529,15 @@ namespace System.Management.Automation /// repassed to baseObject's IFormatable if present /// the string representation for baseObject /// if an exception was thrown by the BaseObject's ToString - public string ToString (string format, IFormatProvider formatProvider) + public string ToString(string format, IFormatProvider formatProvider) { - //If ToString value from deserialization is available, - //simply return it. - if (toStringFromDeserialization != null) - { - return toStringFromDeserialization; - } - return PSObject.ToString(null, this, null, format, formatProvider, true, false); + //If ToString value from deserialization is available, + //simply return it. + if (_toStringFromDeserialization != null) + { + return _toStringFromDeserialization; + } + return PSObject.ToString(null, this, null, format, formatProvider, true, false); } private string PrivateToString() @@ -1546,9 +1545,9 @@ namespace System.Management.Automation string result; try { - result = this.ToString(); + result = this.ToString(); } - catch(ExtendedTypeSystemException) + catch (ExtendedTypeSystemException) { result = this.BaseObject.GetType().FullName; } @@ -1570,12 +1569,12 @@ namespace System.Management.Automation if (this.BaseObject is PSCustomObject) { - returnValue.immediateBaseObject = PSCustomObject.SelfInstance; + returnValue._immediateBaseObject = PSCustomObject.SelfInstance; returnValue.immediateBaseObjectIsEmpty = true; } else { - returnValue.immediateBaseObject = this.immediateBaseObject; + returnValue._immediateBaseObject = _immediateBaseObject; returnValue.immediateBaseObjectIsEmpty = false; } @@ -1585,21 +1584,21 @@ namespace System.Management.Automation // especially on a PSCustomObject - e.g. to a help object where we want to force a different view. returnValue._typeNames = null; - returnValue._members = new PSMemberInfoIntegratingCollection(returnValue, memberCollection); - returnValue._properties = new PSMemberInfoIntegratingCollection(returnValue, propertyCollection); - returnValue._methods = new PSMemberInfoIntegratingCollection(returnValue, methodCollection); + returnValue._members = new PSMemberInfoIntegratingCollection(returnValue, s_memberCollection); + returnValue._properties = new PSMemberInfoIntegratingCollection(returnValue, s_propertyCollection); + returnValue._methods = new PSMemberInfoIntegratingCollection(returnValue, s_methodCollection); - returnValue.adapterSet = GetMappedAdapter(returnValue.immediateBaseObject, returnValue.GetTypeTable()); + returnValue._adapterSet = GetMappedAdapter(returnValue._immediateBaseObject, returnValue.GetTypeTable()); - ICloneable cloneableBase = returnValue.immediateBaseObject as ICloneable; + ICloneable cloneableBase = returnValue._immediateBaseObject as ICloneable; if (cloneableBase != null) { - returnValue.immediateBaseObject = cloneableBase.Clone(); + returnValue._immediateBaseObject = cloneableBase.Clone(); } - if (returnValue.immediateBaseObject is ValueType) + if (returnValue._immediateBaseObject is ValueType) { - returnValue.immediateBaseObject = CopyValueType(returnValue.immediateBaseObject); + returnValue._immediateBaseObject = CopyValueType(returnValue._immediateBaseObject); } @@ -1791,7 +1790,7 @@ namespace System.Management.Automation internal const string PSTypeNames = "pstypenames"; #endregion public const strings - + #region serialization /// @@ -1844,8 +1843,8 @@ namespace System.Management.Automation /// PSObject to be used while replicating the owner for PSMemeberSet /// /// - internal static object GetNoteSettingValue(PSMemberSet settings, string noteName, - object defaultValue, Type expectedType, + internal static object GetNoteSettingValue(PSMemberSet settings, string noteName, + object defaultValue, Type expectedType, bool shouldReplicateInstance, PSObject ownerObject) { if (settings == null) @@ -1879,7 +1878,7 @@ namespace System.Management.Automation TypeTable typeTable = backupTypeTable ?? this.GetTypeTable(); if (null != typeTable) { - PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, + PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, typeTable, TypeTable.PSStandardMembers); result = (int)GetNoteSettingValue(standardMemberSet, TypeTable.SerializationDepth, 0, typeof(int), true, this); } @@ -1916,7 +1915,7 @@ namespace System.Management.Automation TypeTable typeTable = backupTypeTable != null ? backupTypeTable : this.GetTypeTable(); if (null != typeTable) { - PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, + PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, typeTable, TypeTable.PSStandardMembers); result = (SerializationMethod)GetNoteSettingValue(standardMemberSet, TypeTable.SerializationMethodNode, TypeTable.defaultSerializationMethod, typeof(SerializationMethod), true, this); @@ -1930,11 +1929,11 @@ namespace System.Management.Automation get { PSMemberSet retVal = null; - + retVal = TypeTableGetMemberDelegate(this, TypeTable.PSStandardMembers); if (retVal != null) { - retVal = (PSMemberSet) retVal.Copy(); + retVal = (PSMemberSet)retVal.Copy(); retVal.ReplicateInstance(this); return retVal; } @@ -1956,9 +1955,9 @@ namespace System.Management.Automation if (null != standardMemberSet) { standardMemberSet.ReplicateInstance(this); - PSMemberInfoIntegratingCollection members = + PSMemberInfoIntegratingCollection members = new PSMemberInfoIntegratingCollection( - standardMemberSet, + standardMemberSet, GetMemberCollection(PSMemberViewTypes.All, backupTypeTable)); result = members[memberName]; } @@ -2015,16 +2014,15 @@ namespace System.Management.Automation return new Collection(new List()); } - internal bool ShouldSerializeAdapter () + internal bool ShouldSerializeAdapter() { if (this.isDeserialized) { return this.adaptedMembers != null; } return !this.immediateBaseObjectIsEmpty; - } - internal bool ShouldSerializeBase () + internal bool ShouldSerializeBase() { if (this.isDeserialized) { @@ -2037,17 +2035,17 @@ namespace System.Management.Automation return (this.InternalAdapter.GetType() != typeof(DotNetAdapter)); } - internal PSMemberInfoInternalCollection GetAdaptedProperties () + internal PSMemberInfoInternalCollection GetAdaptedProperties() { - return GetProperties (this.adaptedMembers, this.InternalAdapter); + return GetProperties(this.adaptedMembers, this.InternalAdapter); } - internal PSMemberInfoInternalCollection GetBaseProperties () + internal PSMemberInfoInternalCollection GetBaseProperties() { return GetProperties(this.clrMembers, dotNetInstanceAdapter); } - private PSMemberInfoInternalCollection GetProperties (PSMemberInfoInternalCollection serializedMembers, Adapter particularAdapter) + private PSMemberInfoInternalCollection GetProperties(PSMemberInfoInternalCollection serializedMembers, Adapter particularAdapter) { if (this.isDeserialized) { @@ -2055,7 +2053,7 @@ namespace System.Management.Automation } PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); - foreach (PSPropertyInfo member in particularAdapter.BaseGetMembers(this.immediateBaseObject)) + foreach (PSPropertyInfo member in particularAdapter.BaseGetMembers(_immediateBaseObject)) { returnValue.Add(member); } @@ -2077,9 +2075,9 @@ namespace System.Management.Automation target.clrMembers = source.clrMembers; } - if (target.toStringFromDeserialization == null) + if (target._toStringFromDeserialization == null) { - target.toStringFromDeserialization = source.toStringFromDeserialization; + target._toStringFromDeserialization = source._toStringFromDeserialization; target.TokenText = source.TokenText; } } @@ -2095,8 +2093,8 @@ namespace System.Management.Automation Diagnostics.Assert(this.immediateBaseObjectIsEmpty, "BaseObject should be PSCustomObject for deserialized objects"); Diagnostics.Assert(value != null, "known objects are never null"); this.immediateBaseObjectIsEmpty = false; - immediateBaseObject = value; - adapterSet = GetMappedAdapter(immediateBaseObject, GetTypeTable()); + _immediateBaseObject = value; + _adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable()); if (overrideTypeInfo) { this.InternalTypeNames = this.InternalAdapter.BaseGetTypeNameHierarchy(value); @@ -2104,7 +2102,7 @@ namespace System.Management.Automation } //This is toString value set on deserialization - private string toStringFromDeserialization = null; + private string _toStringFromDeserialization = null; internal bool preserveToString = false; internal bool preserveToStringSet = false; @@ -2124,7 +2122,7 @@ namespace System.Management.Automation } preserveToString = false; - + return preserveToString; } } @@ -2136,11 +2134,11 @@ namespace System.Management.Automation { get { - return toStringFromDeserialization; + return _toStringFromDeserialization; } set { - toStringFromDeserialization = value; + _toStringFromDeserialization = value; } } @@ -2171,9 +2169,9 @@ namespace System.Management.Automation #region Private Data // orginal adapter like Xml, ManagementClass, DirectoryEntry etc. - private Adapter originalAdapter; + private Adapter _originalAdapter; // .net adapter - private DotNetAdapter ultimatedotNetAdapter; + private DotNetAdapter _ultimatedotNetAdapter; #endregion @@ -2183,15 +2181,15 @@ namespace System.Management.Automation /// This property can be accessed only internally and hence /// no checks are performed on input. /// - internal Adapter OriginalAdapter - { - get { return originalAdapter; } - set { originalAdapter = value; } + internal Adapter OriginalAdapter + { + get { return _originalAdapter; } + set { _originalAdapter = value; } } - internal DotNetAdapter DotNetAdapter - { - get { return ultimatedotNetAdapter; } + internal DotNetAdapter DotNetAdapter + { + get { return _ultimatedotNetAdapter; } } #endregion @@ -2200,8 +2198,8 @@ namespace System.Management.Automation internal AdapterSet(Adapter adapter, DotNetAdapter dotnetAdapter) { - originalAdapter = adapter; - ultimatedotNetAdapter = dotnetAdapter; + _originalAdapter = adapter; + _ultimatedotNetAdapter = dotnetAdapter; } #endregion @@ -2216,7 +2214,7 @@ namespace System.Management.Automation { } - new PSObject Value { get { return (PSObject)base.Value; } } + private new PSObject Value { get { return (PSObject)base.Value; } } private DynamicMetaObject GetUnwrappedObject() { @@ -2378,10 +2376,10 @@ namespace System.Management.Automation internal bool IsHelpObject { - get { return isHelpObject; } - set { isHelpObject = value; } + get { return _isHelpObject; } + set { _isHelpObject = value; } } - private bool isHelpObject = false; + private bool _isHelpObject = false; #endregion } diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 4415995ee..5cd1002af 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.ComponentModel; using System.Management.Automation.Runspaces; @@ -41,7 +42,7 @@ namespace System.Management.Automation internal SettingValueExceptionEventArgs(Exception exception) { _exception = exception; - this._shouldThrow = true; + _shouldThrow = true; } } @@ -77,7 +78,7 @@ namespace System.Management.Automation { _exception = exception; _valueReplacement = null; - this._shouldThrow = true; + _shouldThrow = true; } private object _valueReplacement; @@ -86,10 +87,10 @@ namespace System.Management.Automation /// method of . If this property is not set /// to a value other than null then the exception associated with this event is thrown. /// - public object ValueReplacement - { - get { return _valueReplacement; } - set {_valueReplacement = value; } + public object ValueReplacement + { + get { return _valueReplacement; } + set { _valueReplacement = value; } } } @@ -133,7 +134,7 @@ namespace System.Management.Automation /// Gets a value indicating whether this property is read-only. /// public override bool IsReadOnly { get { return _isReadOnly; } } - + /// /// This method has no effect for . /// CanResetValue returns false. @@ -147,7 +148,7 @@ namespace System.Management.Automation /// The component to test for reset capability. /// false public override bool CanResetValue(object component) { return false; } - + /// /// Returns true to indicate that the value of this property needs to be persisted. /// @@ -170,7 +171,7 @@ namespace System.Management.Automation /// /// Gets the type of the property value. /// - public override Type PropertyType { get { return this._propertyType; } } + public override Type PropertyType { get { return _propertyType; } } /// /// Gets the current value of the property on a component. @@ -204,8 +205,8 @@ namespace System.Management.Automation if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", this.Name); - ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", - null, + ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", + null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name); bool shouldThrow; object returnValue = DealWithGetValueException(e, out shouldThrow); @@ -221,7 +222,7 @@ namespace System.Management.Automation { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception getting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message); bool shouldThrow; - object returnValue = DealWithGetValueException(e, out shouldThrow); + object returnValue = DealWithGetValueException(e, out shouldThrow); if (shouldThrow) { throw; @@ -242,8 +243,8 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("component", ExtendedTypeSystem.InvalidComponent, "component", - typeof (PSObject).Name, - typeof (PSObjectTypeDescriptor).Name); + typeof(PSObject).Name, + typeof(PSObjectTypeDescriptor).Name); } mshObj = descriptor.Instance; } @@ -297,7 +298,7 @@ namespace System.Management.Automation { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue", - null, + null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name); bool shouldThrow; DealWithSetValueException(e, out shouldThrow); @@ -335,7 +336,6 @@ namespace System.Management.Automation shouldThrow = eventArgs.ShouldThrow; return; } - } /// @@ -370,14 +370,14 @@ namespace System.Management.Automation /// The this class retrieves property information from. public PSObjectTypeDescriptor(PSObject instance) { - this._instance = instance; + _instance = instance; } private PSObject _instance; /// /// Gets the this class retrieves property information from. /// - public PSObject Instance { get { return this._instance; } } + public PSObject Instance { get { return _instance; } } private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { @@ -463,7 +463,7 @@ namespace System.Management.Automation { return returnValue; } - + foreach (PSPropertyInfo property in _instance.Properties) { CheckAndAddProperty(property, attributes, ref returnValue); @@ -488,20 +488,20 @@ namespace System.Management.Automation { return ReferenceEquals(this, other); } - return other.Instance.Equals(this.Instance); + return other.Instance.Equals(this.Instance); } /// /// Provides a value for hashing algorithms. /// /// A hash code for the current object - public override int GetHashCode() + public override int GetHashCode() { if (this.Instance == null) { return base.GetHashCode(); } - return this.Instance.GetHashCode(); + return this.Instance.GetHashCode(); } /// @@ -613,12 +613,12 @@ namespace System.Management.Automation } return TypeDescriptor.GetDefaultEvent(this.Instance.BaseObject); } - + /// /// Returns the events for this instance of a component. /// /// An that represents the events for this component instance. - public override EventDescriptorCollection GetEvents() + public override EventDescriptorCollection GetEvents() { if (this.Instance == null) { @@ -640,7 +640,7 @@ namespace System.Management.Automation } return TypeDescriptor.GetEvents(this.Instance.BaseObject, attributes); } - + /// /// Returns a collection of type for this object. /// @@ -666,7 +666,7 @@ namespace System.Management.Automation } return TypeDescriptor.GetClassName(this.Instance.BaseObject); } - + /// /// Returns the name of this object. /// @@ -679,7 +679,7 @@ namespace System.Management.Automation } return TypeDescriptor.GetComponentName(this.Instance.BaseObject); } - + /// /// Returns an editor of the specified type for this object. /// diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 958905d2f..8a65bbcde 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index fe69b6fb0..18af40f3b 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Diagnostics; @@ -13,11 +14,11 @@ namespace System.Management.Automation /// internal sealed class NativeCommand : InternalCommand { - private NativeCommandProcessor myCommandProcessor; + private NativeCommandProcessor _myCommandProcessor; internal NativeCommandProcessor MyCommandProcessor { - get { return myCommandProcessor; } - set { myCommandProcessor = value; } + get { return _myCommandProcessor; } + set { _myCommandProcessor = value; } } /// @@ -27,8 +28,8 @@ namespace System.Management.Automation { try { - if (myCommandProcessor != null) - myCommandProcessor.StopProcessing(); + if (_myCommandProcessor != null) + _myCommandProcessor.StopProcessing(); } catch (Exception e) { diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 102ba2ede..e65202ef1 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -32,7 +32,7 @@ namespace System.Management.Automation internal NativeCommandParameterBinder( NativeCommand command) : base(command.MyInvocation, command.Context, command) { - this.nativeCommand = command; + _nativeCommand = command; } #endregion ctor @@ -73,18 +73,18 @@ namespace System.Management.Automation { if (!first) { - arguments.Append(' '); + _arguments.Append(' '); } first = false; if (parameter.ParameterNameSpecified) { Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace"); - arguments.Append(parameter.ParameterText); + _arguments.Append(parameter.ParameterText); if (parameter.SpaceAfterParameter) { - arguments.Append(' '); + _arguments.Append(' '); } } @@ -124,11 +124,11 @@ namespace System.Management.Automation { get { - return arguments.ToString(); + return _arguments.ToString(); } } // Arguments - private readonly StringBuilder arguments = new StringBuilder(); - + private readonly StringBuilder _arguments = new StringBuilder(); + #endregion internal members #region private members @@ -167,7 +167,7 @@ namespace System.Management.Automation { if (needSeparator) { - arguments.Append(separator); + _arguments.Append(separator); } else { @@ -177,7 +177,7 @@ namespace System.Management.Automation if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); - arguments.Append(arg); + _arguments.Append(arg); } else { @@ -211,13 +211,13 @@ namespace System.Management.Automation if (needQuotes) { - arguments.Append('"'); - arguments.Append(arg); - arguments.Append('"'); + _arguments.Append('"'); + _arguments.Append(arg); + _arguments.Append('"'); } else { - arguments.Append(arg); + _arguments.Append(arg); } } } @@ -227,8 +227,7 @@ namespace System.Management.Automation /// /// The native command to bind to /// - private NativeCommand nativeCommand; + private NativeCommand _nativeCommand; #endregion private members } - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs index 4c327c95c..5f29422dd 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs @@ -87,14 +87,13 @@ namespace System.Management.Automation { ((NativeCommandParameterBinder)DefaultParameterBinder).BindParameters(parameters); - Diagnostics.Assert(emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared."); + Diagnostics.Assert(s_emptyReturnCollection.Count == 0, "This list shouldn't be used for anything as it's shared."); - return emptyReturnCollection; + return s_emptyReturnCollection; } // BindParameters - static readonly Collection emptyReturnCollection = new Collection(); + private static readonly Collection s_emptyReturnCollection = new Collection(); } - } diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index fb025bce9..507a5bb7b 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -112,22 +112,22 @@ namespace System.Management.Automation /// internal class ProcessOutputObject { - private object data; + private object _data; /// /// Get the data from this object /// /// The data - internal object Data { get { return data; } } - + internal object Data { get { return _data; } } + /// /// Stream to which data belongs /// - private MinishellStream stream; + private MinishellStream _stream; internal MinishellStream Stream { get { - return stream; + return _stream; } } @@ -138,15 +138,15 @@ namespace System.Management.Automation /// stream to which data belongs internal ProcessOutputObject(object data, MinishellStream stream) { - this.data = data; - this.stream = stream; + _data = data; + _stream = stream; } } /// /// Provides way to create and execute native commands. /// - internal class NativeCommandProcessor: CommandProcessorBase + internal class NativeCommandProcessor : CommandProcessorBase { #region ctor/native command properties @@ -154,7 +154,7 @@ namespace System.Management.Automation /// Information about application which is invoked by this instance of /// NativeCommandProcessor /// - private ApplicationInfo applicationInfo; + private ApplicationInfo _applicationInfo; /// /// Initializes the new instance of NativeCommandProcessor class. @@ -171,7 +171,7 @@ namespace System.Management.Automation /// /// or is null /// - internal NativeCommandProcessor(ApplicationInfo applicationInfo,ExecutionContext context) + internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContext context) : base(applicationInfo) { if (applicationInfo == null) @@ -179,7 +179,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("applicationInfo"); } - this.applicationInfo = applicationInfo; + _applicationInfo = applicationInfo; this._context = context; this.Command = new NativeCommand(); @@ -193,9 +193,9 @@ namespace System.Management.Automation //When kill is called on the command object, //it calls this NCP back to kill the process... ((NativeCommand)Command).MyCommandProcessor = this; - + //Create input writer for providing input to the process. - inputWriter = new ProcessInputWriter(Command); + _inputWriter = new ProcessInputWriter(Command); } /// @@ -218,11 +218,11 @@ namespace System.Management.Automation { get { - string name = this.applicationInfo.Name; + string name = _applicationInfo.Name; return name; } } - + /// /// Gets or sets path to the native command. /// @@ -230,7 +230,7 @@ namespace System.Management.Automation { get { - string path = applicationInfo.Path; + string path = _applicationInfo.Path; return path; } } @@ -243,13 +243,13 @@ namespace System.Management.Automation /// Variable which is set to true when prepare is called. /// Parameter Binder should only be created after Prepare method is called /// - bool isPreparedCalled = false; + private bool _isPreparedCalled = false; /// /// Parameter binder used by this command processor /// - private NativeCommandParameterBinderController nativeParameterBinderController; - + private NativeCommandParameterBinderController _nativeParameterBinderController; + /// /// Gets a new instance of a ParameterBinderController using a NativeCommandParameterBinder /// @@ -264,38 +264,38 @@ namespace System.Management.Automation /// internal ParameterBinderController NewParameterBinderController(InternalCommand command) { - Dbg.Assert(isPreparedCalled, "parameter binder should not be created before prepared is called"); + Dbg.Assert(_isPreparedCalled, "parameter binder should not be created before prepared is called"); - if (isMiniShell) + if (_isMiniShell) { - nativeParameterBinderController = + _nativeParameterBinderController = new MinishellParameterBinderController( this.nativeCommand); } else { - nativeParameterBinderController = + _nativeParameterBinderController = new NativeCommandParameterBinderController( this.nativeCommand); } - return nativeParameterBinderController; + return _nativeParameterBinderController; } internal NativeCommandParameterBinderController NativeParameterBinderController { get { - if (nativeParameterBinderController == null) + if (_nativeParameterBinderController == null) { NewParameterBinderController(this.Command); } - return nativeParameterBinderController; + return _nativeParameterBinderController; } } #endregion parameter binder - + #region internal overrides /// @@ -303,14 +303,14 @@ namespace System.Management.Automation /// internal override void Prepare(IDictionary psDefaultParameterValues) { - isPreparedCalled = true; + _isPreparedCalled = true; //Check if the application is minishell - isMiniShell = IsMiniShell(); + _isMiniShell = IsMiniShell(); //For minishell parameter binding is done in Complete method because we need //to know if output is redirected before we can bind parameters. - if (!isMiniShell) + if (!_isMiniShell) { this.NativeParameterBinderController.BindParameters(arguments); } @@ -324,24 +324,24 @@ namespace System.Management.Automation while (Read()) { // Accumulate everything from the pipe and execute at the end. - inputWriter.Add(Command.CurrentPipelineObject); + _inputWriter.Add(Command.CurrentPipelineObject); } } - + /// /// Process object for the invoked application /// - private System.Diagnostics.Process nativeProcess; + private System.Diagnostics.Process _nativeProcess; /// /// This is used for writing input to the process /// - private ProcessInputWriter inputWriter = null; + private ProcessInputWriter _inputWriter = null; /// /// This is used for reading input form the process /// - ProcessOutputReader outputReader = null; + private ProcessOutputReader _outputReader = null; /// /// Is true if this command is to be run "standalone" - that is, with @@ -353,7 +353,7 @@ namespace System.Management.Automation /// object used for synchronization between StopProcessing thread and /// Pipeline thread. /// - private object sync = new object(); + private object _sync = new object(); /// /// Executes the native command once all of the input has been gathered. @@ -431,18 +431,18 @@ namespace System.Management.Automation //If StopProcessing gets the lock first, then it will set the stopped //flag and this method will throw PipelineStoppedException when it gets //the lock. - lock (sync) + lock (_sync) { - if (stopped) + if (_stopped) { throw new PipelineStoppedException(); } try { - nativeProcess = new Process(); - nativeProcess.StartInfo = startInfo; - nativeProcess.Start(); + _nativeProcess = new Process(); + _nativeProcess.StartInfo = startInfo; + _nativeProcess.Start(); } catch (Win32Exception) { @@ -469,7 +469,7 @@ namespace System.Management.Automation startInfo.FileName = executable; try { - nativeProcess.Start(); + _nativeProcess.Start(); notDone = false; } catch (Win32Exception) @@ -490,7 +490,7 @@ namespace System.Management.Automation startInfo.RedirectStandardInput = false; startInfo.RedirectStandardOutput = false; startInfo.RedirectStandardError = false; - nativeProcess.Start(); + _nativeProcess.Start(); } else { @@ -514,7 +514,7 @@ namespace System.Management.Automation background = true; if (startInfo.UseShellExecute == false) { - background = IsWindowsApplication(nativeProcess.StartInfo.FileName); + background = IsWindowsApplication(_nativeProcess.StartInfo.FileName); } } @@ -524,15 +524,15 @@ namespace System.Management.Automation if (startInfo.RedirectStandardInput) { NativeCommandIOFormat inputFormat = NativeCommandIOFormat.Text; - if (isMiniShell) + if (_isMiniShell) { inputFormat = ((MinishellParameterBinderController)NativeParameterBinderController).InputFormat; } - lock (sync) + lock (_sync) { - if (!stopped) + if (!_stopped) { - inputWriter.Start(nativeProcess, inputFormat); + _inputWriter.Start(_nativeProcess, inputFormat); } } } @@ -542,15 +542,15 @@ namespace System.Management.Automation //if output is redirected, start reading output of process. if (startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { - lock (sync) + lock (_sync) { - if (!stopped) + if (!_stopped) { - outputReader = new ProcessOutputReader(nativeProcess, Path, redirectOutput, redirectError); - outputReader.Start(); + _outputReader = new ProcessOutputReader(_nativeProcess, Path, redirectOutput, redirectError); + _outputReader.Start(); } } - if (outputReader != null) + if (_outputReader != null) { ProcessOutputHelper(); } @@ -567,15 +567,15 @@ namespace System.Management.Automation if (background == false) { //Wait for process to exit - nativeProcess.WaitForExit(); + _nativeProcess.WaitForExit(); //Wait for input writer to finish. - inputWriter.Done(); + _inputWriter.Done(); //Wait for outputReader to finish - if (outputReader != null) + if (_outputReader != null) { - outputReader.Done(); + _outputReader.Done(); } // Capture screen output if we are transcribing @@ -616,16 +616,15 @@ namespace System.Management.Automation this.Command.Context.InternalHost.UI.TranscribeResult(bufferText.ToString()); } - this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, nativeProcess.ExitCode); - if (nativeProcess.ExitCode != 0) + this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, _nativeProcess.ExitCode); + if (_nativeProcess.ExitCode != 0) this.commandRuntime.PipelineProcessor.ExecutionFailed = true; } - } + } } catch (Win32Exception e) { exceptionToRethrow = e; - } // try catch (PipelineStoppedException) { @@ -675,7 +674,7 @@ namespace System.Management.Automation /// then we try to get a fresh handle based on the original process id. /// /// The process to kill - static void KillProcess(Process processToKill) + private static void KillProcess(Process processToKill) { if (NativeCommandProcessor.IsServerSide) { @@ -720,24 +719,24 @@ namespace System.Management.Automation internal struct ProcessWithParentId { public Process OriginalProcessInstance; - private int parentId; + private int _parentId; public int ParentId { get { // Construct parent id only once. - if (int.MinValue == parentId) + if (int.MinValue == _parentId) { ConstructParentId(); } - return parentId; + return _parentId; } } public ProcessWithParentId(Process originalProcess) { OriginalProcessInstance = originalProcess; - parentId = int.MinValue; + _parentId = int.MinValue; } public static ProcessWithParentId[] Construct(Process[] originalProcCollection) @@ -758,12 +757,12 @@ namespace System.Management.Automation // retreiving parent id might throw exceptions..so // setting this to -1 so that we dont try again to // get the parent id. - parentId = -1; + _parentId = -1; Process parentProcess = PsUtils.GetParentProcess(OriginalProcessInstance); if (parentProcess != null) { - parentId = parentProcess.Id; + _parentId = parentProcess.Id; } } catch (Win32Exception) @@ -783,7 +782,7 @@ namespace System.Management.Automation /// /// /// - static void KillProcessAndChildProcesses(Process processToKill, + private static void KillProcessAndChildProcesses(Process processToKill, ProcessWithParentId[] currentlyRunningProcs) { try @@ -818,7 +817,7 @@ namespace System.Management.Automation } } - static void KillChildProcesses(int parentId, ProcessWithParentId[] currentlyRunningProcs) + private static void KillChildProcesses(int parentId, ProcessWithParentId[] currentlyRunningProcs) { foreach (ProcessWithParentId proc in currentlyRunningProcs) { @@ -838,7 +837,7 @@ namespace System.Management.Automation /// /// /// - static bool IsConsoleApplication(string fileName) + private static bool IsConsoleApplication(string fileName) { return !IsWindowsApplication(fileName); } @@ -849,7 +848,7 @@ namespace System.Management.Automation /// /// [ArchitectureSensitive] - static bool IsWindowsApplication(string fileName) + private static bool IsWindowsApplication(string fileName) { #if CORECLR return false; @@ -880,32 +879,32 @@ namespace System.Management.Automation /// /// This is set to true when StopProcessing is called /// - bool stopped = false; + private bool _stopped = false; /// /// Routine used to stop this processing on this node... /// internal void StopProcessing() { - lock (sync) + lock (_sync) { - if (stopped) return; - stopped = true; + if (_stopped) return; + _stopped = true; } - if (nativeProcess != null) + if (_nativeProcess != null) { if (!_runStandAlone) { //Stop input writer - inputWriter.Stop(); + _inputWriter.Stop(); //stop output writer - if (outputReader != null) + if (_outputReader != null) { - outputReader.Stop(); + _outputReader.Stop(); } - KillProcess(nativeProcess); + KillProcess(_nativeProcess); } } } @@ -915,13 +914,13 @@ namespace System.Management.Automation /// /// Aggressively clean everything up... /// - void CleanUp() + private void CleanUp() { - try + try { - if (nativeProcess != null) + if (_nativeProcess != null) { - nativeProcess.Dispose(); + _nativeProcess.Dispose(); } } catch (Exception e) // ignore non-severe exceptions @@ -935,9 +934,9 @@ namespace System.Management.Automation /// private void ProcessOutputHelper() { - Dbg.Assert(outputReader != null, "this should be called only when output has been created"); + Dbg.Assert(_outputReader != null, "this should be called only when output has been created"); - object value = outputReader.Read(); + object value = _outputReader.Read(); while (value != AutomationNull.Value) { ProcessOutputObject outputValue = value as ProcessOutputObject; @@ -1007,7 +1006,7 @@ namespace System.Management.Automation this.StopProcessing(); break; } - value = outputReader.Read(); + value = _outputReader.Read(); } } @@ -1063,7 +1062,7 @@ namespace System.Management.Automation //For minishell value of -outoutFormat parameter depends on value of redirectOutput. //So we delay the parameter binding. Do parameter binding for minishell now. - if (isMiniShell) + if (_isMiniShell) { MinishellParameterBinderController mpc = (MinishellParameterBinderController)NativeParameterBinderController; mpc.BindParameters(arguments, redirectOutput, this.Command.Context.EngineHostInterface.Name); @@ -1164,12 +1163,12 @@ namespace System.Management.Automation //In minishell scenario, if output is redirected //then error should also be redirected. - if (redirectError == false && redirectOutput == true && isMiniShell) + if (redirectError == false && redirectOutput == true && _isMiniShell) { redirectError = true; } - if (inputWriter.Count == 0 && (!this.Command.MyInvocation.ExpectingInput)) + if (_inputWriter.Count == 0 && (!this.Command.MyInvocation.ExpectingInput)) redirectInput = false; // Remoting server consideration. @@ -1188,7 +1187,7 @@ namespace System.Management.Automation redirectError = true; } #if !CORECLR // UI doesn't exist on OneCore, so all applications running on an OneCore client should be console applications. - // The powershell on the OneCore client should already have a console attached. + // The powershell on the OneCore client should already have a console attached. else if (IsConsoleApplication(this.Path)) { // Allocate a console if there isn't one attached already... @@ -1255,7 +1254,7 @@ namespace System.Management.Automation private static string FindExecutable(string filename) { // Preallocate a - StringBuilder objResultBuffer = new StringBuilder(MaxExecutablePath); + StringBuilder objResultBuffer = new StringBuilder(MaxExecutablePath); IntPtr resultCode = (IntPtr)0; try @@ -1286,9 +1285,9 @@ namespace System.Management.Automation #region Interop for SHGetFileInfo private const int SCS_32BIT_BINARY = 0; // A 32-bit Windows-based application - private const int SCS_DOS_BINARY = 1; // An MS-DOS - based application - private const int SCS_WOW_BINARY = 2; // A 16-bit Windows-based application - private const int SCS_PIF_BINARY = 3; // A PIF file that executes an MS-DOS - based application + private const int SCS_DOS_BINARY = 1; // An MS-DOS - based application + private const int SCS_WOW_BINARY = 2; // A 16-bit Windows-based application + private const int SCS_PIF_BINARY = 3; // A PIF file that executes an MS-DOS - based application private const int SCS_POSIX_BINARY = 4; // A POSIX - based application private const int SCS_OS216_BINARY = 5; // A 16-bit OS/2-based application private const int SCS_64BIT_BINARY = 6; // A 64-bit Windows-based application. @@ -1308,7 +1307,7 @@ namespace System.Management.Automation private const uint SHGFI_EXETYPE = 0x000002000; // flag used to ask to return exe type [DllImport("shell32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, + private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); #endregion @@ -1316,7 +1315,7 @@ namespace System.Management.Automation #region Minishell Interop - private bool isMiniShell = false; + private bool _isMiniShell = false; /// /// Returns true if native command being invoked is mini-shell. /// @@ -1343,17 +1342,17 @@ namespace System.Management.Automation #endregion Minishell Interop - static private bool _isServerSide; + static private bool s_isServerSide; internal static bool IsServerSide { get { - return _isServerSide; + return s_isServerSide; } set { - _isServerSide = value; - } + s_isServerSide = value; + } } } @@ -1363,15 +1362,15 @@ namespace System.Management.Automation internal class ProcessInputWriter { #region constructor - - InternalCommand command; + + private InternalCommand _command; /// /// Creates an instance of ProcessInputWriter /// internal ProcessInputWriter(InternalCommand command) { Dbg.Assert(command != null, "Caller should validate the parameter"); - this.command = command; + _command = command; } #endregion constructor @@ -1379,14 +1378,14 @@ namespace System.Management.Automation /// /// Input is collected in this list /// - ArrayList inputList = new ArrayList(); + private ArrayList _inputList = new ArrayList(); /// /// Add an object to write to process /// /// internal void Add(object input) { - inputList.Add(input); + _inputList.Add(input); } /// @@ -1396,24 +1395,24 @@ namespace System.Management.Automation { get { - return inputList.Count; + return _inputList.Count; } } /// /// Stream to which input is written /// - StreamWriter streamWriter; + private StreamWriter _streamWriter; /// /// Format of input. /// - NativeCommandIOFormat inputFormat; + private NativeCommandIOFormat _inputFormat; /// /// Thread which writes the input /// - Thread inputThread; + private Thread _inputThread; /// /// Start writing input to process @@ -1430,31 +1429,31 @@ namespace System.Management.Automation //Get the encoding for writing to native command. Note we get the Encoding //from the current scope so a script or function can use a different encoding //than global value. - Encoding pipeEncoding = command.Context.GetVariableValue(SpecialVariables.OutputEncodingVarPath) as System.Text.Encoding; + Encoding pipeEncoding = _command.Context.GetVariableValue(SpecialVariables.OutputEncodingVarPath) as System.Text.Encoding; if (pipeEncoding == null) { pipeEncoding = Encoding.ASCII; } - streamWriter = new StreamWriter(process.StandardInput.BaseStream, + _streamWriter = new StreamWriter(process.StandardInput.BaseStream, pipeEncoding); - this.inputFormat = inputFormat; + _inputFormat = inputFormat; if (inputFormat == NativeCommandIOFormat.Text) { ConvertToString(); } - inputThread = new Thread(new ThreadStart(this.WriterThreadProc)); - inputThread.Start(); + _inputThread = new Thread(new ThreadStart(this.WriterThreadProc)); + _inputThread.Start(); } - bool stopping = false; + private bool _stopping = false; /// /// Stop writing input to process /// internal void Stop() { - stopping = true; + _stopping = true; } /// @@ -1462,9 +1461,9 @@ namespace System.Management.Automation /// internal void Done() { - if (inputThread != null) + if (_inputThread != null) { - inputThread.Join(); + _inputThread.Join(); } } @@ -1475,7 +1474,7 @@ namespace System.Management.Automation { try { - if (inputFormat == NativeCommandIOFormat.Text) + if (_inputFormat == NativeCommandIOFormat.Text) { WriteTextInput(); } @@ -1493,17 +1492,17 @@ namespace System.Management.Automation { try { - foreach (object o in inputList) + foreach (object o in _inputList) { - if (stopping) return; + if (_stopping) return; - string line = PSObject.ToStringParser(command.Context, o); - streamWriter.Write(line); + string line = PSObject.ToStringParser(_command.Context, o); + _streamWriter.Write(line); } } finally { - streamWriter.Dispose(); + _streamWriter.Dispose(); } } @@ -1512,21 +1511,21 @@ namespace System.Management.Automation try { //Write header - streamWriter.WriteLine("#< CLIXML"); + _streamWriter.WriteLine("#< CLIXML"); // When (if) switching to XmlTextWriter.Create remember the OmitXmlDeclaration difference - XmlWriter writer = XmlWriter.Create(streamWriter); + XmlWriter writer = XmlWriter.Create(_streamWriter); Serializer ser = new Serializer(writer); - foreach (object o in inputList) + foreach (object o in _inputList) { - if (stopping) return; + if (_stopping) return; ser.Serialize(o); } ser.Done(); } finally { - streamWriter.Dispose(); + _streamWriter.Dispose(); } } @@ -1538,12 +1537,12 @@ namespace System.Management.Automation /// private void ConvertToString() { - Dbg.Assert(this.inputFormat == NativeCommandIOFormat.Text, "InputFormat should be Text"); + Dbg.Assert(_inputFormat == NativeCommandIOFormat.Text, "InputFormat should be Text"); PipelineProcessor p = new PipelineProcessor(); - p.Add(command.Context.CreateCommand("out-string", false)); - object[] result = (object[])p.SynchronousExecuteEnumerate(this.inputList.ToArray()); - inputList = new ArrayList(result); + p.Add(_command.Context.CreateCommand("out-string", false)); + object[] result = (object[])p.SynchronousExecuteEnumerate(_inputList.ToArray()); + _inputList = new ArrayList(result); } } @@ -1558,16 +1557,16 @@ namespace System.Management.Automation /// /// Process whose output is to be read. /// - Process process; + private Process _process; /// /// Path of the process application /// - string processPath; + private string _processPath; - bool redirectOutput; + private bool _redirectOutput; - bool redirectError; + private bool _redirectError; /// /// Process whose output is read @@ -1577,10 +1576,10 @@ namespace System.Management.Automation Dbg.Assert(process != null, "caller should validate the parameter"); Dbg.Assert(processPath != null, "caller should validate the parameter"); Dbg.Assert(redirectOutput || redirectError, "Either redirectOutput or redirectError must be true"); - this.process = process; - this.processPath = processPath; - this.redirectOutput = redirectOutput; - this.redirectError = redirectError; + _process = process; + _processPath = processPath; + _redirectOutput = redirectOutput; + _redirectError = redirectError; } #endregion constructor @@ -1588,41 +1587,41 @@ namespace System.Management.Automation /// /// Reader for output stream of process /// - ProcessStreamReader outputReader; + private ProcessStreamReader _outputReader; /// /// Reader for error stream of process /// - ProcessStreamReader errorReader; + private ProcessStreamReader _errorReader; /// /// Synchronized object queue in which object read form output and /// error streams are deposited /// - private ObjectStream processOutput; + private ObjectStream _processOutput; /// /// Start reading the output/error. Note all the work is done asynchronously. /// internal void Start() { - processOutput = new ObjectStream(128); + _processOutput = new ObjectStream(128); // Start async reading of error and output // readercount variable is used by multiple threads to close "processOutput" ObjectStream. // Without properly initializing the readercount, the ObjectStream might get // closed early. readerCount is protected here by using the lock. - lock (readerLock) + lock (_readerLock) { - if (redirectOutput) + if (_redirectOutput) { - readerCount++; - outputReader = new ProcessStreamReader(process.StandardOutput, processPath, true, processOutput.ObjectWriter, this); - outputReader.Start(); + _readerCount++; + _outputReader = new ProcessStreamReader(_process.StandardOutput, _processPath, true, _processOutput.ObjectWriter, this); + _outputReader.Start(); } - if (redirectError) + if (_redirectError) { - readerCount++; - errorReader = new ProcessStreamReader(process.StandardError, processPath, false, processOutput.ObjectWriter, this); - errorReader.Start(); + _readerCount++; + _errorReader = new ProcessStreamReader(_process.StandardError, _processPath, false, _processOutput.ObjectWriter, this); + _errorReader.Start(); } } } @@ -1635,12 +1634,12 @@ namespace System.Management.Automation /// internal void Stop() { - if (processOutput != null) + if (_processOutput != null) { try { //Close the reader for the stream. - processOutput.ObjectReader.Close(); + _processOutput.ObjectReader.Close(); } catch (Exception e) // ignore non-severe exceptions { @@ -1649,7 +1648,7 @@ namespace System.Management.Automation try { - processOutput.Close(); + _processOutput.Close(); } catch (Exception e) // ignore non-severe exceptions { @@ -1663,13 +1662,13 @@ namespace System.Management.Automation /// internal void Done() { - if (outputReader != null) + if (_outputReader != null) { - outputReader.Done(); + _outputReader.Done(); } - if (errorReader != null) + if (_errorReader != null) { - errorReader.Done(); + _errorReader.Done(); } } @@ -1682,19 +1681,19 @@ namespace System.Management.Automation /// internal object Read() { - return processOutput.ObjectReader.Read(); + return _processOutput.ObjectReader.Read(); } /// /// object used for synchronizing ReaderDone call between two readers /// - object readerLock = new object(); + private object _readerLock = new object(); /// /// Count of readers - this is set by Start. If both output and error /// are redirected, it will be 2. If only one is redirected, it'll be 1. /// - int readerCount; + private int _readerCount; /// /// This method is called by output or error reader when they are @@ -1704,13 +1703,13 @@ namespace System.Management.Automation internal void ReaderDone(bool isOutput) { int temp; - lock (readerLock) + lock (_readerLock) { - temp = --readerCount; + temp = --_readerCount; } if (temp == 0) { - processOutput.ObjectWriter.Close(); + _processOutput.ObjectWriter.Close(); } } } @@ -1730,27 +1729,27 @@ namespace System.Management.Automation /// /// Stream from which data is read. /// - StreamReader streamReader; + private StreamReader _streamReader; /// /// Flag which tells if streamReader is for stdout or stderr stream of process /// - bool isOutput; + private bool _isOutput; /// /// Writer to which data read from stream are written /// - PipelineWriter writer; + private PipelineWriter _writer; /// /// Path to the process. This is used for setting the name of the thread. /// - string processPath; + private string _processPath; /// /// ProcessReader which owns this stream reader /// - ProcessOutputReader processOutputReader; + private ProcessOutputReader _processOutputReader; /// /// Creates an instance of ProcessStreamReader @@ -1779,11 +1778,11 @@ namespace System.Management.Automation Dbg.Assert(writer != null, "Caller should validate the parameter"); Dbg.Assert(processOutputReader != null, "Caller should validate the parameter"); - this.streamReader = streamReader; - this.processPath = processPath; - this.isOutput = isOutput; - this.writer = writer; - this.processOutputReader = processOutputReader; + _streamReader = streamReader; + _processPath = processPath; + _isOutput = isOutput; + _writer = writer; + _processOutputReader = processOutputReader; } #endregion constructor @@ -1791,23 +1790,23 @@ namespace System.Management.Automation /// /// Thread on which reading happens /// - Thread thread = null; + private Thread _thread = null; /// /// Launches a new thread to start reading. /// internal void Start() { - thread = new Thread(new ThreadStart(ReaderStartProc)); - if (isOutput) + _thread = new Thread(new ThreadStart(ReaderStartProc)); + if (_isOutput) { - thread.Name = string.Format(CultureInfo.InvariantCulture, "{0} :Output Reader", processPath); + _thread.Name = string.Format(CultureInfo.InvariantCulture, "{0} :Output Reader", _processPath); } else { - thread.Name = string.Format(CultureInfo.InvariantCulture, "{0} :Error Reader", processPath); + _thread.Name = string.Format(CultureInfo.InvariantCulture, "{0} :Error Reader", _processPath); } - thread.Start(); + _thread.Start(); } /// @@ -1815,16 +1814,16 @@ namespace System.Management.Automation /// internal void Done() { - if (thread != null) + if (_thread != null) { - thread.Join(); + _thread.Join(); } } /// /// Thread proc for reading /// - void ReaderStartProc() + private void ReaderStartProc() { try { @@ -1836,15 +1835,15 @@ namespace System.Management.Automation } finally { - processOutputReader.ReaderDone(isOutput); + _processOutputReader.ReaderDone(_isOutput); } } - void ReaderStartProcHelper() + private void ReaderStartProcHelper() { //read the first line to detect the format. //for xml, first line is #< CLIXML - string line = streamReader.ReadLine(); + string line = _streamReader.ReadLine(); if (line == null) { // nothing to do @@ -1859,14 +1858,14 @@ namespace System.Management.Automation } } - void ReadText(string line) + private void ReadText(string line) { - if (isOutput) + if (_isOutput) { while (line != null) { AddObjectToWriter(line, MinishellStream.Output); - line = streamReader.ReadLine(); + line = _streamReader.ReadLine(); } } else @@ -1885,7 +1884,7 @@ namespace System.Management.Automation int read = 0; - while ((read = streamReader.Read(buffer, 0, buffer.Length)) != 0) + while ((read = _streamReader.Read(buffer, 0, buffer.Length)) != 0) { StringBuilder errorMessage = new StringBuilder().Append(buffer, 0, read); @@ -1893,18 +1892,18 @@ namespace System.Management.Automation new ErrorRecord( new RemoteException(errorMessage.ToString()), "NativeCommandErrorMessage", - ErrorCategory.NotSpecified, - null), + ErrorCategory.NotSpecified, + null), MinishellStream.Error); } } } - void ReadXml() + private void ReadXml() { try { - XmlReader xmlReader = XmlReader.Create(streamReader, InternalDeserializer.XmlReaderSettingsForCliXml); + XmlReader xmlReader = XmlReader.Create(_streamReader, InternalDeserializer.XmlReaderSettingsForCliXml); Deserializer des = new Deserializer(xmlReader); while (!des.Done()) { @@ -1919,7 +1918,7 @@ namespace System.Management.Automation } if (stream == MinishellStream.Unknown) { - stream = isOutput ? MinishellStream.Output : MinishellStream.Error; + stream = _isOutput ? MinishellStream.Output : MinishellStream.Error; } //Null is allowed only in output stream @@ -1993,18 +1992,18 @@ namespace System.Management.Automation string message = string.Format( null, template, - this.isOutput ? MinishellStream.Output : MinishellStream.Error, - this.processPath, + _isOutput ? MinishellStream.Output : MinishellStream.Error, + _processPath, originalException.Message); XmlException newException = new XmlException( message, originalException); ErrorRecord error = new ErrorRecord( - newException, - "ProcessStreamReader_CliXmlError", - ErrorCategory.SyntaxError, - this.processPath); + newException, + "ProcessStreamReader_CliXmlError", + ErrorCategory.SyntaxError, + _processPath); AddObjectToWriter(error, MinishellStream.Error); } } @@ -2012,15 +2011,15 @@ namespace System.Management.Automation /// /// Adds one object to writer /// - void AddObjectToWriter(object data, MinishellStream stream) + private void AddObjectToWriter(object data, MinishellStream stream) { try { ProcessOutputObject dataObject = new ProcessOutputObject(data, stream); //writer is shared between Error and Output reader. - lock (writer) + lock (_writer) { - writer.Write(dataObject); + _writer.Write(dataObject); } } catch (PipelineClosedException) @@ -2104,7 +2103,7 @@ namespace System.Management.Automation /// true if the window was brought to the foreground [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool SetForegroundWindow(IntPtr hWnd); + private static extern bool SetForegroundWindow(IntPtr hWnd); /// /// If no console window is attached to this process, then allocate one, @@ -2199,7 +2198,7 @@ namespace System.Management.Automation /// [Serializable] [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] - public class RemoteException: RuntimeException + public class RemoteException : RuntimeException { /// /// Initializes a new instance of RemoteException diff --git a/src/System.Management.Automation/engine/NullString.cs b/src/System.Management.Automation/engine/NullString.cs index 1a6ea5556..001d5b8ae 100644 --- a/src/System.Management.Automation/engine/NullString.cs +++ b/src/System.Management.Automation/engine/NullString.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; namespace System.Management.Automation.Language @@ -13,7 +14,7 @@ namespace System.Management.Automation.Language #region private_members // Private member for instance. - private static readonly NullString _value = new NullString(); + private static readonly NullString s_value = new NullString(); #endregion private_members @@ -32,7 +33,7 @@ namespace System.Management.Automation.Language /// public static NullString Value { - get { return _value; } + get { return s_value; } } #endregion public_property diff --git a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs index 732f36d35..71eef7d67 100644 --- a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs +++ b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; @@ -21,14 +22,14 @@ namespace Microsoft.PowerShell.Commands { get { - return sourceIdentifier; + return _sourceIdentifier; } set { - sourceIdentifier = value; + _sourceIdentifier = value; } } - private string sourceIdentifier = Guid.NewGuid().ToString(); + private string _sourceIdentifier = Guid.NewGuid().ToString(); /// @@ -39,14 +40,14 @@ namespace Microsoft.PowerShell.Commands { get { - return action; + return _action; } set { - action = value; + _action = value; } } - private ScriptBlock action = null; + private ScriptBlock _action = null; /// /// Parameter for additional data to be associated with this event subscription @@ -56,14 +57,14 @@ namespace Microsoft.PowerShell.Commands { get { - return messageData; + return _messageData; } set { - messageData = value; + _messageData = value; } } - private PSObject messageData = null; + private PSObject _messageData = null; /// /// Parameter for the flag that determines if this subscription is used to support @@ -74,32 +75,32 @@ namespace Microsoft.PowerShell.Commands { get { - return supportEvent; + return _supportEvent; } set { - supportEvent = value; + _supportEvent = value; } } - private SwitchParameter supportEvent = new SwitchParameter(); + private SwitchParameter _supportEvent = new SwitchParameter(); /// /// Parameter for the flag that determines whether this /// subscription will forward its events to the PowerShell client during remote executions /// [Parameter] - public SwitchParameter Forward + public SwitchParameter Forward { get { - return forward; + return _forward; } set { - forward = value; + _forward = value; } } - private SwitchParameter forward = new SwitchParameter(); + private SwitchParameter _forward = new SwitchParameter(); /// /// Parameter to indicate that the subscriber should be auto-unregistered after being triggered for specified times. @@ -112,7 +113,7 @@ namespace Microsoft.PowerShell.Commands { return _maxTriggerCount; } - set + set { _maxTriggerCount = value <= 0 ? 0 : value; } @@ -136,16 +137,16 @@ namespace Microsoft.PowerShell.Commands /// protected PSEventSubscriber NewSubscriber { - get { return newSubscriber; } + get { return _newSubscriber; } } - private PSEventSubscriber newSubscriber; + private PSEventSubscriber _newSubscriber; /// /// Check arguments /// protected override void BeginProcessing() { - if (((bool)forward) && (action != null)) + if (((bool)_forward) && (_action != null)) { ThrowTerminatingError( new ErrorRecord( @@ -163,12 +164,12 @@ namespace Microsoft.PowerShell.Commands { Object inputObject = PSObject.Base(GetSourceObject()); string eventName = GetSourceObjectEventName(); - + try { if ( ((inputObject != null) || (eventName != null)) && - (Events.GetEventSubscribers(sourceIdentifier).GetEnumerator().MoveNext()) + (Events.GetEventSubscribers(_sourceIdentifier).GetEnumerator().MoveNext()) ) { // Detect if the event identifier already exists @@ -176,7 +177,7 @@ namespace Microsoft.PowerShell.Commands new ArgumentException( String.Format( System.Globalization.CultureInfo.CurrentCulture, - EventingResources.SubscriberExists, sourceIdentifier)), + EventingResources.SubscriberExists, _sourceIdentifier)), "SUBSCRIBER_EXISTS", ErrorCategory.InvalidArgument, inputObject); @@ -185,17 +186,17 @@ namespace Microsoft.PowerShell.Commands } else { - newSubscriber = + _newSubscriber = Events.SubscribeEvent( inputObject, eventName, - sourceIdentifier, messageData, action, (bool) supportEvent, (bool) forward, _maxTriggerCount); - - if((action != null) && (! (bool) supportEvent)) - WriteObject(newSubscriber.Action); + _sourceIdentifier, _messageData, _action, (bool)_supportEvent, (bool)_forward, _maxTriggerCount); + + if ((_action != null) && (!(bool)_supportEvent)) + WriteObject(_newSubscriber.Action); } } - catch(ArgumentException e) + catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord( e, diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index c35fda0df..2ce8aa0c4 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -12,17 +12,17 @@ namespace System.Management.Automation /// /// Contains a PS Class information /// - public sealed class PSClassInfo + public sealed class PSClassInfo { /// /// Initializes a new instance of the PSClassInfo class /// /// Name of the PS Class. - internal PSClassInfo(string name) + internal PSClassInfo(string name) { - this.Name = name; + this.Name = name; } - + /// /// Name of the class. /// @@ -32,7 +32,7 @@ namespace System.Management.Automation /// Collection of members of the class. /// public ReadOnlyCollection Members { get; private set; } - + /// /// Updates members of the class. /// @@ -46,8 +46,8 @@ namespace System.Management.Automation /// /// Module in which the class is implemented in. /// - public PSModuleInfo Module { get ; internal set; } - + public PSModuleInfo Module { get; internal set; } + /// /// Gets the help file path for the cmdlet. /// @@ -55,14 +55,14 @@ namespace System.Management.Automation { get { - return helpFilePath; + return _helpFilePath; } internal set { - helpFilePath = value; + _helpFilePath = value; } } // HelpFile - private string helpFilePath = String.Empty; + private string _helpFilePath = String.Empty; } @@ -93,10 +93,10 @@ namespace System.Management.Automation /// Gets or sets type of the member /// public string TypeName { get; private set; } - + /// /// Default value of the Field. /// - public string DefaultValue { get; private set; } + public string DefaultValue { get; private set; } } } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 9b3b37e27..829775ed9 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -23,12 +23,12 @@ namespace System.Management.Automation ExecutionContext context) { Diagnostics.Assert(context != null, "caller to verify context is not null"); - this._context = context; + _context = context; Diagnostics.Assert(className != null, "caller to verify className is not null"); - this._className = className; - this._useWildCards = useWildCards; - this.moduleInfoCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + _className = className; + _useWildCards = useWildCards; + _moduleInfoCache = new Dictionary(StringComparer.OrdinalIgnoreCase); } #region private properties @@ -36,11 +36,11 @@ namespace System.Management.Automation private string _className = null; private ExecutionContext _context = null; private PSClassInfo _currentMatch = null; - private IEnumerator matchingClass = null; - private Collection matchingClassList = null; + private IEnumerator _matchingClass = null; + private Collection _matchingClassList = null; private bool _useWildCards = false; - private Dictionary moduleInfoCache = null; - private object lockObject = new Object(); + private Dictionary _moduleInfoCache = null; + private object _lockObject = new Object(); #endregion @@ -52,7 +52,7 @@ namespace System.Management.Automation public void Reset() { _currentMatch = null; - matchingClass = null; + _matchingClass = null; } /// @@ -132,23 +132,23 @@ namespace System.Management.Automation PSClassInfo returnValue = null; WildcardPattern classNameMatcher = WildcardPattern.Get(_className, WildcardOptions.IgnoreCase); - if (matchingClassList == null) + if (_matchingClassList == null) { - matchingClassList = new Collection(); + _matchingClassList = new Collection(); if (FindTypeByModulePath(classNameMatcher)) - matchingClass = matchingClassList.GetEnumerator(); + _matchingClass = _matchingClassList.GetEnumerator(); else return null; } - if (!matchingClass.MoveNext()) + if (!_matchingClass.MoveNext()) { - matchingClass = null; + _matchingClass = null; } else { - returnValue = matchingClass.Current; + returnValue = _matchingClass.Current; } return returnValue; @@ -175,7 +175,7 @@ namespace System.Management.Automation var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath); if (classInfo != null) { - matchingClassList.Add(classInfo); + _matchingClassList.Add(classInfo); matchFound = true; } } @@ -189,7 +189,7 @@ namespace System.Management.Automation var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath); if (classInfo != null) { - matchingClassList.Add(classInfo); + _matchingClassList.Add(classInfo); matchFound = true; } } @@ -209,7 +209,7 @@ namespace System.Management.Automation /// Path to the module where the class is defined. /// Converted PSClassInfo object. private PSClassInfo CachedItemToPSClassInfo(WildcardPattern classNameMatcher, string modulePath) - { + { foreach (var module in GetPSModuleInfo(modulePath)) { var exportedTypes = module.GetExportedTypeDefinitions(); @@ -249,12 +249,12 @@ namespace System.Management.Automation { PSModuleInfo moduleInfo = null; - lock(lockObject) + lock (_lockObject) { - moduleInfoCache.TryGetValue(modulePath, out moduleInfo); + _moduleInfoCache.TryGetValue(modulePath, out moduleInfo); } - if(moduleInfo != null) + if (moduleInfo != null) { var returnValue = new Collection(); returnValue.Add(moduleInfo); @@ -277,11 +277,11 @@ namespace System.Management.Automation .AddParameter("Debug", false) .Invoke(); - lock (lockObject) + lock (_lockObject) { foreach (var module in modules) { - moduleInfoCache.Add(module.Path, module); + _moduleInfoCache.Add(module.Path, module); } } @@ -326,6 +326,5 @@ namespace System.Management.Automation } #endregion - } } diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs index 8d35a9838..96bed98d0 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/InternalMISerializer.cs @@ -27,7 +27,6 @@ using System.Management.Automation.Remoting; namespace System.Management.Automation { - /// /// This internal helper class provides methods for serializing mshObject. /// @@ -65,21 +64,21 @@ namespace System.Management.Automation /// avaliable (to get the ExecutionContext's TypeTable) private TypeTable _typeTable; - private Collection> allPropertiesCollection; + private Collection> _allPropertiesCollection; private Collection> AllPropertiesCollection { get { - if (allPropertiesCollection == null) + if (_allPropertiesCollection == null) { - allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); + _allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); } - return allPropertiesCollection; + return _allPropertiesCollection; } } // Similar to the property by the same name in serialization.cs - private bool? canUseDefaultRunspaceInThreadSafeManner; + private bool? _canUseDefaultRunspaceInThreadSafeManner; private bool CanUseDefaultRunspaceInThreadSafeManner { @@ -96,9 +95,9 @@ namespace System.Management.Automation // to avoid a race condition where a pipeline is started // after this property getter did all the checks - if (!canUseDefaultRunspaceInThreadSafeManner.HasValue) + if (!_canUseDefaultRunspaceInThreadSafeManner.HasValue) { - canUseDefaultRunspaceInThreadSafeManner = false; + _canUseDefaultRunspaceInThreadSafeManner = false; RunspaceBase runspace = Runspace.DefaultRunspace as RunspaceBase; if (runspace != null) @@ -107,20 +106,20 @@ namespace System.Management.Automation LocalPipeline localPipeline = currentPipeline as LocalPipeline; if ((localPipeline != null) && (localPipeline.NestedPipelineExecutionThread != null)) { - canUseDefaultRunspaceInThreadSafeManner = + _canUseDefaultRunspaceInThreadSafeManner = (localPipeline.NestedPipelineExecutionThread.ManagedThreadId == Threading.Thread.CurrentThread.ManagedThreadId); } } } - return canUseDefaultRunspaceInThreadSafeManner.Value; + return _canUseDefaultRunspaceInThreadSafeManner.Value; } } #endregion Properties - internal CimInstance Serialize (object o) + internal CimInstance Serialize(object o) { return CreateCimInstanceForOneTopLevelObject(o); } @@ -300,7 +299,7 @@ namespace System.Management.Automation Dbg.Assert(false, "All containers should be handled in the switch"); break; } - + CimInstance[] instanceArray = listOfCimInstances.ToArray(); CimProperty valueProperty = CimProperty.Create("Value", instanceArray, Microsoft.Management.Infrastructure.CimType.InstanceArray, CimFlags.Property); result.CimInstanceProperties.Add(valueProperty); @@ -362,7 +361,7 @@ namespace System.Management.Automation } // This will create a CimInstance for PS_Object and populate the typenames. - result = CreateCimInstanceForPSObject(cimClassName: "PS_Object", + result = CreateCimInstanceForPSObject(cimClassName: "PS_Object", psObj: mshSource, writeToString: writeToString); @@ -394,7 +393,7 @@ namespace System.Management.Automation { CreateCimInstanceForPSObjectProperties(mshSource, depth, specificPropertiesToSerialize, out listOfCimInstancesProperties); } - + //TODO, insivara : Implement serialization of CimInstance //if (isCimInstance) //{ @@ -404,7 +403,7 @@ namespace System.Management.Automation //TODO, insivara : ExtendedProperties implementation will be done in a subsequent checkin //SerializeExtendedProperties(mshSource, depth, specificPropertiesToSerialize, out listOfCimInstancesExtendedProperties); - + if (listOfCimInstancesProperties != null && listOfCimInstancesProperties.Count > 0) { CimInstance[] referenceArray = listOfCimInstancesProperties.ToArray(); @@ -452,7 +451,7 @@ namespace System.Management.Automation bool hasNotes = false; //hasNotes = PSObjectHasNotes(source); - + bool hasModifiedToString = (toStringValue != null); if (hasNotes || hasModifiedTypesCollection || hasModifiedToString) @@ -702,7 +701,7 @@ namespace System.Management.Automation /// serialization information about source internal static CimInstance CreateCimInstanceForPrimitiveType(string property, object source, MITypeSerializationInfo entry) { - CimInstance c; + CimInstance c; if (property != null) { c = CreateCimInstanceWhenPropertyNameExists(property, source, entry); @@ -738,8 +737,8 @@ namespace System.Management.Automation } return c; } - - #endregion + + #endregion #region Serialization Helper Methods @@ -767,8 +766,8 @@ namespace System.Management.Automation if (writeToString) { - CimProperty toStringProperty = CimProperty.Create("ToString", - SerializationUtilities.GetToString(psObj), + CimProperty toStringProperty = CimProperty.Create("ToString", + SerializationUtilities.GetToString(psObj), Microsoft.Management.Infrastructure.CimType.String, Microsoft.Management.Infrastructure.CimFlags.Property); cimInstance.CimInstanceProperties.Add(toStringProperty); @@ -778,7 +777,7 @@ namespace System.Management.Automation private static CimInstance CreateRawStringCimInstance(string property, string value, MITypeSerializationInfo entry) { - CimInstance c; + CimInstance c; if (property != null) { c = CreateCimInstanceWhenPropertyNameExists(property, value, entry); @@ -787,7 +786,7 @@ namespace System.Management.Automation { c = CreateCimInstance(entry.CimClassName); CimProperty p1 = CimProperty.Create("Value", value, entry.CimType, CimFlags.Property); - c.CimInstanceProperties.Add(p1); + c.CimInstanceProperties.Add(p1); } return c; } @@ -799,11 +798,11 @@ namespace System.Management.Automation innerInstance.CimInstanceProperties.Add(valueProperty); CimInstance c = CreateCimInstance("PS_ObjectProperty"); CimProperty name = CimProperty.Create("Name", property, - Microsoft.Management.Infrastructure.CimType.String, + Microsoft.Management.Infrastructure.CimType.String, CimFlags.Property); c.CimInstanceProperties.Add(name); CimProperty outerInstanceValueProperty = CimProperty.Create("Value", innerInstance, - Microsoft.Management.Infrastructure.CimType.Reference, + Microsoft.Management.Infrastructure.CimType.Reference, CimFlags.Property); c.CimInstanceProperties.Add(outerInstanceValueProperty); @@ -814,10 +813,10 @@ namespace System.Management.Automation { CimInstance enumCimInstance = null; object baseObject = mshSource.ImmediateBaseObject; - CreateCimInstanceForOneObject(source:System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()),System.Globalization.CultureInfo.InvariantCulture), - property:null, - depth:depth, - result:out enumCimInstance); + CreateCimInstanceForOneObject(source: System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), + property: null, + depth: depth, + result: out enumCimInstance); return enumCimInstance; } @@ -905,6 +904,5 @@ namespace System.Management.Automation } #endregion - } } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs b/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs index 7f1401d4f..7b7eb8ed4 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/KnownMITypes.cs @@ -38,9 +38,9 @@ namespace System.Management.Automation /// static KnownMITypes() { - for (int i = 0; i < _TypeSerializationInfo.Length; i++) + for (int i = 0; i < s_typeSerializationInfo.Length; i++) { - _knownTableKeyType.Add(_TypeSerializationInfo[i].Type.FullName, _TypeSerializationInfo[i]); + s_knownTableKeyType.Add(s_typeSerializationInfo[i].Type.FullName, s_typeSerializationInfo[i]); } } @@ -52,7 +52,7 @@ namespace System.Management.Automation internal static MITypeSerializationInfo GetTypeSerializationInfo(Type type) { MITypeSerializationInfo temp = null; - _knownTableKeyType.TryGetValue(type.FullName, out temp); + s_knownTableKeyType.TryGetValue(type.FullName, out temp); return temp; } @@ -61,10 +61,10 @@ namespace System.Management.Automation /// /// Array of known types. /// - private static readonly MITypeSerializationInfo[] _TypeSerializationInfo = new MITypeSerializationInfo[] - { - new MITypeSerializationInfo(typeof(Boolean), - InternalMISerializer.CreateCimInstanceForPrimitiveType, + private static readonly MITypeSerializationInfo[] s_typeSerializationInfo = new MITypeSerializationInfo[] + { + new MITypeSerializationInfo(typeof(Boolean), + InternalMISerializer.CreateCimInstanceForPrimitiveType, "PS_ObjectProperty_boolean"), new MITypeSerializationInfo(typeof(Byte), @@ -72,7 +72,7 @@ namespace System.Management.Automation "PS_ObjectProperty_uint8"), new MITypeSerializationInfo(typeof(Char), - InternalMISerializer.CreateCimInstanceForPrimitiveType, + InternalMISerializer.CreateCimInstanceForPrimitiveType, "PS_ObjectProperty_char16"), new MITypeSerializationInfo(typeof(Double), @@ -148,14 +148,13 @@ namespace System.Management.Automation //new MITypeSerializationInfo(typeof(SecureString), // InternalSerializer.WriteSecureString), - }; /// /// Dictionary of knowntypes. /// Key is Type.FullName and value is Type object. /// - private static readonly Dictionary _knownTableKeyType = new Dictionary(); + private static readonly Dictionary s_knownTableKeyType = new Dictionary(); #endregion private_fields } diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs index 5b954fd2f..69d6bc35d 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/MISerializer.cs @@ -32,7 +32,7 @@ namespace System.Management.Automation public MISerializer(int depth) { - internalSerializer = new InternalMISerializer(depth); + internalSerializer = new InternalMISerializer(depth); } public CimInstance Serialize(object source) diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs b/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs index b80fa6e09..aee4482cf 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/MITypeSerializationInfo.cs @@ -26,7 +26,6 @@ using System.Management.Automation.Remoting; namespace System.Management.Automation { - /// /// A delegate for serializing known type /// @@ -62,7 +61,7 @@ namespace System.Management.Automation /// For some .NET types (Guid, Decimal, etc.), there are no equivalent Cim Types. So, we serialize them as string /// The CimClass name whose instance needs to be created for this type internal MITypeSerializationInfo(Type type, MITypeSerializerDelegate serializer, - Microsoft.Management.Infrastructure.CimType cimType, string cimClassName):this(type, serializer, cimClassName) + Microsoft.Management.Infrastructure.CimType cimType, string cimClassName) : this(type, serializer, cimClassName) { _cimType = cimType; } diff --git a/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs b/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs index 48c21674f..ee33dde77 100644 --- a/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs +++ b/src/System.Management.Automation/engine/PSMI/Serialization/PSMISerializer.cs @@ -22,12 +22,11 @@ namespace System.Management.Automation /// internal class PSMISerializer { - //TODO, insivara : Depth implementation will be added subsequently /// /// Default depth of serialization /// - private static int mshDefaultMISerializationDepth = 1; + private static int s_mshDefaultMISerializationDepth = 1; internal PSMISerializer() { @@ -40,7 +39,7 @@ namespace System.Management.Automation /// The serialized object, as CimInstancen public static CimInstance Serialize(Object source) { - return Serialize(source, mshDefaultMISerializationDepth); + return Serialize(source, s_mshDefaultMISerializationDepth); } /// diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 7a8ba3b8b..57bc06f8a 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Diagnostics; using System.Reflection; using System.Collections; @@ -20,7 +21,7 @@ namespace System.Management.Automation internal const string PSVersionName = "PSVersion"; internal const string SerializationVersionName = "SerializationVersion"; internal const string WSManStackVersionName = "WSManStackVersion"; - static private Hashtable _psVersionTable = null; + static private Hashtable s_psVersionTable = null; /// /// A constant to track current PowerShell Version. @@ -33,13 +34,13 @@ namespace System.Management.Automation /// For each later relase of PowerShell, this constant needs to /// be updated to reflect the right version. /// - static Version _psV1Version = new Version(1, 0); - static Version _psV2Version = new Version(2, 0); - static Version _psV3Version = new Version(3, 0); - static Version _psV4Version = new Version(4, 0); - static Version _psV5Version = new Version(5, 0); - static Version _psV51Version = new Version(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); - static SemanticVersion _psV6Version = new SemanticVersion(6, 0, 0, "alpha"); + private static Version s_psV1Version = new Version(1, 0); + private static Version s_psV2Version = new Version(2, 0); + private static Version s_psV3Version = new Version(3, 0); + private static Version s_psV4Version = new Version(4, 0); + private static Version s_psV5Version = new Version(5, 0); + private static Version s_psV51Version = new Version(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); + private static SemanticVersion s_psV6Version = new SemanticVersion(6, 0, 0, "alpha"); /// /// A constant to track current PowerShell Edition @@ -58,26 +59,26 @@ namespace System.Management.Automation // Static Constructor. static PSVersionInfo() { - _psVersionTable = new Hashtable(StringComparer.OrdinalIgnoreCase); + s_psVersionTable = new Hashtable(StringComparer.OrdinalIgnoreCase); - _psVersionTable[PSVersionInfo.PSVersionName] = _psV6Version; - _psVersionTable["PSEdition"] = PSEditionValue; - _psVersionTable["BuildVersion"] = GetBuildVersion(); - _psVersionTable["GitCommitId"] = GetCommitInfo(); - _psVersionTable["PSCompatibleVersions"] = new Version[] { _psV1Version, _psV2Version, _psV3Version, _psV4Version, _psV5Version, _psV51Version, _psV6Version }; - _psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); - _psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; - _psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion(); + s_psVersionTable[PSVersionInfo.PSVersionName] = s_psV6Version; + s_psVersionTable["PSEdition"] = PSEditionValue; + s_psVersionTable["BuildVersion"] = GetBuildVersion(); + s_psVersionTable["GitCommitId"] = GetCommitInfo(); + s_psVersionTable["PSCompatibleVersions"] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version }; + s_psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); + s_psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; + s_psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion(); #if CORECLR - _psVersionTable["CLRVersion"] = null; + s_psVersionTable["CLRVersion"] = null; #else - _psVersionTable["CLRVersion"] = Environment.Version; + s_psVersionTable["CLRVersion"] = Environment.Version; #endif } static internal Hashtable GetPSVersionTable() { - return _psVersionTable; + return s_psVersionTable; } static internal Version GetBuildVersion() @@ -90,11 +91,13 @@ namespace System.Management.Automation // Get the commit id from the powershell.version file. If the powershell.version file doesn't exist, use the string "N/A" static internal string GetCommitInfo() { - try { + try + { string assemblyPath = IO.Path.GetDirectoryName(typeof(PSVersionInfo).GetTypeInfo().Assembly.Location); - return (IO.File.ReadAllLines(IO.Path.Combine(assemblyPath,"powershell.version"))[0]); + return (IO.File.ReadAllLines(IO.Path.Combine(assemblyPath, "powershell.version"))[0]); } - catch (Exception e){ + catch (Exception e) + { return e.Message; } } @@ -143,7 +146,7 @@ namespace System.Management.Automation { get { - return (SemanticVersion) GetPSVersionTable()[PSVersionInfo.PSVersionName]; + return (SemanticVersion)GetPSVersionTable()[PSVersionInfo.PSVersionName]; } } @@ -151,7 +154,7 @@ namespace System.Management.Automation { get { - return (Version) GetPSVersionTable()["CLRVersion"]; + return (Version)GetPSVersionTable()["CLRVersion"]; } } @@ -159,7 +162,7 @@ namespace System.Management.Automation { get { - return (Version) GetPSVersionTable()["BuildVersion"]; + return (Version)GetPSVersionTable()["BuildVersion"]; } } @@ -167,7 +170,7 @@ namespace System.Management.Automation { get { - return (Version[]) GetPSVersionTable()["PSCompatibleVersions"]; + return (Version[])GetPSVersionTable()["PSCompatibleVersions"]; } } @@ -183,7 +186,7 @@ namespace System.Management.Automation { get { - return (Version) GetPSVersionTable()["SerializationVersion"]; + return (Version)GetPSVersionTable()["SerializationVersion"]; } } @@ -250,29 +253,29 @@ namespace System.Management.Automation static internal bool IsValidPSVersion(Version version) { - if (version.Major == _psV6Version.Major) + if (version.Major == s_psV6Version.Major) { - return version.Minor == _psV6Version.Minor; + return version.Minor == s_psV6Version.Minor; } - if (version.Major == _psV5Version.Major) + if (version.Major == s_psV5Version.Major) { - return (version.Minor == _psV5Version.Minor || version.Minor == _psV51Version.Minor); + return (version.Minor == s_psV5Version.Minor || version.Minor == s_psV51Version.Minor); } - if (version.Major == _psV4Version.Major) + if (version.Major == s_psV4Version.Major) { - return (version.Minor == _psV4Version.Minor); + return (version.Minor == s_psV4Version.Minor); } - else if (version.Major == _psV3Version.Major) + else if (version.Major == s_psV3Version.Major) { - return version.Minor == _psV3Version.Minor; + return version.Minor == s_psV3Version.Minor; } - else if (version.Major == _psV2Version.Major) + else if (version.Major == s_psV2Version.Major) { - return version.Minor == _psV2Version.Minor; + return version.Minor == s_psV2Version.Minor; } - else if (version.Major == _psV1Version.Major) + else if (version.Major == s_psV1Version.Major) { - return version.Minor == _psV1Version.Minor; + return version.Minor == s_psV1Version.Minor; } return false; @@ -280,26 +283,25 @@ namespace System.Management.Automation static internal Version PSV4Version { - get { return _psV4Version; } + get { return s_psV4Version; } } static internal Version PSV5Version { - get { return _psV5Version; } + get { return s_psV5Version; } } static internal Version PSV51Version { - get { return _psV51Version; } + get { return s_psV51Version; } } static internal SemanticVersion PSV6Version { - get { return _psV6Version; } + get { return s_psV6Version; } } #endregion - } /// @@ -371,8 +373,8 @@ namespace System.Management.Automation Patch = patch; Label = null; } - - const string LabelPropertyName = "PSSemanticVersionLabel"; + + private const string LabelPropertyName = "PSSemanticVersionLabel"; /// /// Construct a from a , @@ -636,7 +638,8 @@ namespace System.Management.Automation /// public static bool operator ==(SemanticVersion v1, SemanticVersion v2) { - if (object.ReferenceEquals(v1, null)) { + if (object.ReferenceEquals(v1, null)) + { return object.ReferenceEquals(v2, null); } @@ -656,7 +659,7 @@ namespace System.Management.Automation /// public static bool operator <(SemanticVersion v1, SemanticVersion v2) { - if ((object) v1 == null) throw PSTraceSource.NewArgumentException(nameof(v1)); + if ((object)v1 == null) throw PSTraceSource.NewArgumentException(nameof(v1)); return (v1.CompareTo(v2) < 0); } @@ -665,7 +668,7 @@ namespace System.Management.Automation /// public static bool operator <=(SemanticVersion v1, SemanticVersion v2) { - if ((object) v1 == null) throw PSTraceSource.NewArgumentException(nameof(v1)); + if ((object)v1 == null) throw PSTraceSource.NewArgumentException(nameof(v1)); return (v1.CompareTo(v2) <= 0); } @@ -686,10 +689,10 @@ namespace System.Management.Automation } internal enum ParseFailureKind - { - ArgumentException, - ArgumentOutOfRangeException, - FormatException + { + ArgumentException, + ArgumentOutOfRangeException, + FormatException } internal struct VersionResult diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 9742026d5..0ba091fbe 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -13,6 +13,7 @@ using System.Reflection; using System.Globalization; using System.Diagnostics.CodeAnalysis; using Dbg = System.Management.Automation.Diagnostics; + namespace System.Management.Automation { /// @@ -34,7 +35,7 @@ namespace System.Management.Automation /// /// Set when the argument should not be validated or recorded in BoundParameters /// - IsDefaultValue = 0x02, + IsDefaultValue = 0x02, /// /// Set when script blocks can be bound as a script block parameter instead of a normal argument @@ -56,14 +57,14 @@ namespace System.Management.Automation internal abstract class ParameterBinderBase { #region tracer - [TraceSource("ParameterBinderBase","A abstract helper class for the CommandProcessor that binds parameters to the specified object.")] - static private PSTraceSource tracer = PSTraceSource.GetTracer ("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object."); + [TraceSource("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object.")] + static private PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object."); - [TraceSource ("ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.")] - static internal PSTraceSource bindingTracer = - PSTraceSource.GetTracer ( - "ParameterBinding", - "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.", + [TraceSource("ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.")] + static internal PSTraceSource bindingTracer = + PSTraceSource.GetTracer( + "ParameterBinding", + "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.", false); #endregion tracer @@ -103,13 +104,13 @@ namespace System.Management.Automation bindingTracer.ShowHeaders = false; - this.command = command; - this.target = target; - this.invocationInfo = invocationInfo; - this.context = context; - this.engine = context.EngineIntrinsics; - this.isTranscribing = context.EngineHostInterface.UI.IsTranscribing; - } + _command = command; + _target = target; + _invocationInfo = invocationInfo; + _context = context; + _engine = context.EngineIntrinsics; + _isTranscribing = context.EngineHostInterface.UI.IsTranscribing; + } /// @@ -139,13 +140,13 @@ namespace System.Management.Automation bindingTracer.ShowHeaders = false; - this.command = command; - this.invocationInfo = invocationInfo; - this.context = context; - this.engine = context.EngineIntrinsics; - this.isTranscribing = context.EngineHostInterface.UI.IsTranscribing; - } - + _command = command; + _invocationInfo = invocationInfo; + _context = context; + _engine = context.EngineIntrinsics; + _isTranscribing = context.EngineHostInterface.UI.IsTranscribing; + } + #endregion ctor #region internal members @@ -159,22 +160,22 @@ namespace System.Management.Automation get { Diagnostics.Assert( - target != null, + _target != null, "The target should always be set for the binder"); - return target; + return _target; } set { - target = value; + _target = value; } } /// /// The bindable object that parameters will be bound to. /// - private object target; + private object _target; /// /// Holds the set of parameters that have been bound from the command line... @@ -182,15 +183,15 @@ namespace System.Management.Automation internal CommandLineParameters CommandLineParameters { // Setter is needed to pass into RuntimeParameterBinder instances - set { commandLineParameters = value; } + set { _commandLineParameters = value; } get { - if (commandLineParameters == null) - commandLineParameters = new CommandLineParameters(); - return commandLineParameters; + if (_commandLineParameters == null) + _commandLineParameters = new CommandLineParameters(); + return _commandLineParameters; } } - private CommandLineParameters commandLineParameters; + private CommandLineParameters _commandLineParameters; /// /// If this is true, then we want to record the list of bound parameters... @@ -246,7 +247,7 @@ namespace System.Management.Automation { Dbg.Assert(parameter != null, "Caller should verify parameter != null"); Dbg.Assert(parameterMetadata != null, "Caller should verify parameterMetadata != null"); - + if (parameterValue == null) { return; @@ -261,7 +262,7 @@ namespace System.Management.Automation PSInvalidCastException e = new PSInvalidCastException(ErrorCategory.InvalidArgument.ToString(), null, ParameterBinderStrings.MismatchedPSTypeName, - (null != invocationInfo) && (null != invocationInfo.MyCommand) ? invocationInfo.MyCommand.Name : string.Empty, + (null != _invocationInfo) && (null != _invocationInfo.MyCommand) ? _invocationInfo.MyCommand.Name : string.Empty, parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), @@ -301,7 +302,7 @@ namespace System.Management.Automation throw parameterBindingException; } - } + } /// /// Does all the type coercion, data generation, and validation necessary to bind the @@ -419,7 +420,7 @@ namespace System.Management.Automation { if (coerceTypeIfNeeded) { - parameterValue = argumentTypeConverter.Transform(engine, parameterValue, true, usesCmdletBinding); + parameterValue = argumentTypeConverter.Transform(_engine, parameterValue, true, usesCmdletBinding); } } else @@ -440,7 +441,7 @@ namespace System.Management.Automation parameterMetadata.CannotBeNull || dma.TransformNullOptionalParameters))) { - parameterValue = dma.Transform(engine, parameterValue); + parameterValue = dma.Transform(_engine, parameterValue); } } @@ -487,7 +488,6 @@ namespace System.Management.Automation parameterMetadata.Type, parameterMetadata.CollectionTypeInformation, parameterValue); - } else { @@ -531,7 +531,7 @@ namespace System.Management.Automation { try { - validationAttribute.InternalValidate(parameterValue, engine); + validationAttribute.InternalValidate(parameterValue, _engine); } catch (Exception e) // Catch-all OK, 3rd party callout { @@ -554,7 +554,7 @@ namespace System.Management.Automation e.Message); throw bindingException; } - tracer.WriteLine("Validation attribute on {0} returned {1}.", parameterMetadata.Name, result); + s_tracer.WriteLine("Validation attribute on {0} returned {1}.", parameterMetadata.Name, result); } } @@ -646,7 +646,7 @@ namespace System.Management.Automation MshCommandRuntime cmdRuntime = this.Command.commandRuntime as MshCommandRuntime; if ((cmdRuntime != null) && - (cmdRuntime.LogPipelineExecutionDetail || isTranscribing) && + (cmdRuntime.LogPipelineExecutionDetail || _isTranscribing) && (cmdRuntime.PipelineProcessor != null)) { string stringToPrint = null; @@ -921,45 +921,45 @@ namespace System.Management.Automation /// /// The invocation information for the code that is being bound /// - private InvocationInfo invocationInfo; + private InvocationInfo _invocationInfo; internal InvocationInfo InvocationInfo { get { - return invocationInfo; + return _invocationInfo; } } /// /// The context of the currently running engine /// - private ExecutionContext context; + private ExecutionContext _context; internal ExecutionContext Context { get { - return context; + return _context; } } /// /// An instance of InternalCommand that the binder is binding to. /// - private InternalCommand command; + private InternalCommand _command; internal InternalCommand Command { get { - return command; + return _command; } } /// /// The engine APIs that need to be passed the attributes when evaluated. /// - private EngineIntrinsics engine; + private EngineIntrinsics _engine; - private bool isTranscribing; + private bool _isTranscribing; #endregion internal members @@ -1064,15 +1064,14 @@ namespace System.Management.Automation // He always gets a shell object regardless of the actual type of the object. if (toType == typeof(PSObject)) { - // It may be the case that we're binding the current pipeline object // as is to a PSObject parameter in which case, we want to make // sure that we're using the same shell object instead of creating an // alias object. - if (command != null && - currentValue == command.CurrentPipelineObject.BaseObject) + if (_command != null && + currentValue == _command.CurrentPipelineObject.BaseObject) { - currentValue = command.CurrentPipelineObject; + currentValue = _command.CurrentPipelineObject; } bindingTracer.WriteLine( @@ -1196,7 +1195,6 @@ namespace System.Management.Automation ""); throw pbe; - } break; } @@ -1272,7 +1270,7 @@ namespace System.Management.Automation // Don't allow Hashtable-to-Object conversion (PSObject and IDictionary), though, // as those can lead to property setters that probably aren't expected. bool changeLanguageModeForTrustedCommand = false; - if(context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + if (_context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { var basedObject = PSObject.Base(currentValue); var supportsPropertyConversion = basedObject is PSObject; @@ -1289,7 +1287,7 @@ namespace System.Management.Automation { if (changeLanguageModeForTrustedCommand) { - context.LanguageMode = PSLanguageMode.FullLanguage; + _context.LanguageMode = PSLanguageMode.FullLanguage; } result = LanguagePrimitives.ConvertTo(currentValue, toType, CultureInfo.CurrentCulture); @@ -1298,7 +1296,7 @@ namespace System.Management.Automation { if (changeLanguageModeForTrustedCommand) { - context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + _context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } } @@ -1398,39 +1396,38 @@ namespace System.Management.Automation ""); throw exception; - } else if (toType == typeof(SwitchParameter)) - { - bindingTracer.WriteLine( - "Arg is null or not present, parameter type is SWITCHPARAMTER, value is true."); - result = SwitchParameter.Present; - } - else if (currentValue == UnboundParameter.Value) - { - bindingTracer.TraceError( - "ERROR: No argument was specified for the parameter and the parameter is not of type bool"); + { + bindingTracer.WriteLine( + "Arg is null or not present, parameter type is SWITCHPARAMTER, value is true."); + result = SwitchParameter.Present; + } + else if (currentValue == UnboundParameter.Value) + { + bindingTracer.TraceError( + "ERROR: No argument was specified for the parameter and the parameter is not of type bool"); - ParameterBindingException exception = - new ParameterBindingException( - ErrorCategory.InvalidArgument, - this.InvocationInfo, - GetParameterErrorExtent(argument), - parameterName, - toType, - null, - ParameterBinderStrings.MissingArgument, - "MissingArgument"); + ParameterBindingException exception = + new ParameterBindingException( + ErrorCategory.InvalidArgument, + this.InvocationInfo, + GetParameterErrorExtent(argument), + parameterName, + toType, + null, + ParameterBinderStrings.MissingArgument, + "MissingArgument"); - throw exception; - } - else - { - bindingTracer.WriteLine( - "Arg is null, parameter type not bool or SwitchParameter, value is null."); - result = null; - } + throw exception; + } + else + { + bindingTracer.WriteLine( + "Arg is null, parameter type not bool or SwitchParameter, value is null."); + result = null; + } return result; } @@ -1528,7 +1525,7 @@ namespace System.Management.Automation { numberOfElements = currentValueAsIList.Count; - tracer.WriteLine("current value is an IList with {0} elements", numberOfElements); + s_tracer.WriteLine("current value is an IList with {0} elements", numberOfElements); bindingTracer.WriteLine( "Arg is IList with {0} elements", numberOfElements); @@ -1565,7 +1562,6 @@ namespace System.Management.Automation (IList)Array.CreateInstance( collectionElementType, numberOfElements); - } else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList || collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) @@ -1704,7 +1700,6 @@ namespace System.Management.Automation error.Message); throw bindingException; } - } else { @@ -1944,7 +1939,7 @@ namespace System.Management.Automation if (result != null) { // Reference comparison to determine if 'value' is a PSObject - tracer.WriteLine(baseObj == value + s_tracer.WriteLine(baseObj == value ? "argument is IList" : "argument is PSObject with BaseObject as IList"); } @@ -1973,7 +1968,6 @@ namespace System.Management.Automation } #endregion private helpers - } // ParameterBinderBase /// @@ -1997,7 +1991,7 @@ namespace System.Management.Automation // Private member for Value. - private static readonly object _singletonValue = new object(); + private static readonly object s_singletonValue = new object(); #endregion private_members @@ -2006,7 +2000,7 @@ namespace System.Management.Automation /// /// Represents an object of the same class (singleton class). /// - internal static object Value { get { return _singletonValue; } } + internal static object Value { get { return s_singletonValue; } } #endregion public_property } @@ -2021,10 +2015,10 @@ namespace System.Management.Automation : base(StringComparer.OrdinalIgnoreCase) { BoundPositionally = new List(); - ImplicitUsingParameters = EmptyUsingParameters; + ImplicitUsingParameters = s_emptyUsingParameters; } - static readonly IDictionary EmptyUsingParameters = new ReadOnlyDictionary(new Dictionary()); + private static readonly IDictionary s_emptyUsingParameters = new ReadOnlyDictionary(new Dictionary()); public List BoundPositionally { get; private set; } internal IDictionary ImplicitUsingParameters { get; set; } @@ -2037,13 +2031,13 @@ namespace System.Management.Automation internal bool ContainsKey(string name) { Dbg.Assert(!string.IsNullOrEmpty(name), "parameter names should not be empty"); - return this._dictionary.ContainsKey(name); + return _dictionary.ContainsKey(name); } internal void Add(string name, object value) { Dbg.Assert(!string.IsNullOrEmpty(name), "parameter names should not be empty"); - this._dictionary[name] = value; + _dictionary[name] = value; } internal void MarkAsBoundPositionally(string name) @@ -2091,7 +2085,7 @@ namespace System.Management.Automation internal void UpdateInvocationInfo(InvocationInfo invocationInfo) { Dbg.Assert(invocationInfo != null, "caller should verify that invocationInfo != null"); - invocationInfo.BoundParameters = this._dictionary; + invocationInfo.BoundParameters = _dictionary; } internal HashSet CopyBoundPositionalParameters() @@ -2105,6 +2099,5 @@ namespace System.Management.Automation return result; } } - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index 053202247..77b47296b 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// and the parameter binder(s). It holds the state of the arguments and parameters. /// [DebuggerDisplay("InvocationInfo = {InvocationInfo}")] - internal abstract class ParameterBinderController + internal abstract class ParameterBinderController { #region ctor @@ -44,10 +44,10 @@ namespace System.Management.Automation Diagnostics.Assert(context != null, "call to verify context is not null."); this.DefaultParameterBinder = parameterBinder; - this._context = context; - this._invocationInfo = invocationInfo; + _context = context; + _invocationInfo = invocationInfo; } - + #endregion ctor #region internal_members @@ -106,7 +106,7 @@ namespace System.Management.Automation private readonly Dictionary _boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - internal CommandLineParameters CommandLineParameters + internal CommandLineParameters CommandLineParameters { get { return this.DefaultParameterBinder.CommandLineParameters; } } @@ -171,7 +171,7 @@ namespace System.Management.Automation /// The name of the argument matches more than one parameter. /// /// - internal void ReparseUnboundArguments () + internal void ReparseUnboundArguments() { Collection result = new Collection(); @@ -215,7 +215,7 @@ namespace System.Management.Automation if (IsSwitchAndSetValue(parameterName, argument, matchingParameter.Parameter)) { - result.Add (argument); + result.Add(argument); continue; } @@ -235,8 +235,8 @@ namespace System.Management.Automation // an argument value for that parameter or a parameter itself. MergedCompiledCommandParameter nextMatchingParameter = - _bindableParameters.GetMatchingParameter ( - nextArgument.ParameterName, + _bindableParameters.GetMatchingParameter( + nextArgument.ParameterName, false, true, new InvocationInfo(this.InvocationInfo.MyCommand, nextArgument.ParameterExtent)); @@ -265,7 +265,7 @@ namespace System.Management.Automation ++index; argument.ParameterName = matchingParameter.Parameter.Name; argument.SetArgumentValue(nextArgument.ArgumentExtent, nextArgument.ParameterText); - result.Add (argument); + result.Add(argument); continue; } @@ -275,15 +275,15 @@ namespace System.Management.Automation ++index; argument.ParameterName = matchingParameter.Parameter.Name; argument.SetArgumentValue(nextArgument.ArgumentExtent, nextArgument.ArgumentValue); - result.Add (argument); + result.Add(argument); } else { // It is an error to have a argument that is a parameter name // but doesn't have a value - ParameterBindingException exception = - new ParameterBindingException ( + ParameterBindingException exception = + new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, GetParameterErrorExtent(argument), @@ -418,7 +418,7 @@ namespace System.Management.Automation } } } - + /// /// Bind the argument to the specified parameter /// @@ -456,7 +456,7 @@ namespace System.Management.Automation MergedCompiledCommandParameter matchingParameter = BindableParameters.GetMatchingParameter( - argument.ParameterName, + argument.ParameterName, (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != 0, true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); @@ -468,7 +468,7 @@ namespace System.Management.Automation if (BoundParameters.ContainsKey(matchingParameter.Parameter.Name)) { - ParameterBindingException bindingException = + ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, @@ -545,7 +545,7 @@ namespace System.Management.Automation /// internal virtual bool BindParameter( uint parameterSets, - CommandParameterInternal argument, + CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { @@ -554,9 +554,9 @@ namespace System.Management.Automation switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: - result = + result = this.DefaultParameterBinder.BindParameter( - argument, + argument, parameter.Parameter, flags); break; @@ -651,7 +651,7 @@ namespace System.Management.Automation // The parameter set declaration is ambiguous so // throw an exception. - ParameterBindingException bindingException = + ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, @@ -684,8 +684,8 @@ namespace System.Management.Automation } CommandParameterInternal argument = GetNextPositionalArgument( - unboundArgumentsCollection, - result, + unboundArgumentsCollection, + result, ref unboundArgumentsIndex); if (argument == null) @@ -883,7 +883,6 @@ namespace System.Management.Automation bindableArgument, parameter.Parameter, flags); - } catch (ParameterBindingArgumentTransformationException pbex) { @@ -915,7 +914,7 @@ namespace System.Management.Automation if (parameterBindingExceptionToThrown != null) { - if(!DefaultParameterBindingInUse) + if (!DefaultParameterBindingInUse) { throw parameterBindingExceptionToThrown; } @@ -971,7 +970,7 @@ namespace System.Management.Automation pbex, resourceString, oldMsg, defaultParamsGetBound); - + throw newBindingException; } @@ -1158,7 +1157,7 @@ namespace System.Management.Automation { get { return _parametersBoundThroughPipelineInput; } } - private readonly Collection _parametersBoundThroughPipelineInput = + private readonly Collection _parametersBoundThroughPipelineInput = new Collection(); /// @@ -1252,7 +1251,6 @@ namespace System.Management.Automation return result; } - #endregion internal_members } } diff --git a/src/System.Management.Automation/engine/ParameterInfo.cs b/src/System.Management.Automation/engine/ParameterInfo.cs index 418bf54c0..777194956 100644 --- a/src/System.Management.Automation/engine/ParameterInfo.cs +++ b/src/System.Management.Automation/engine/ParameterInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -32,19 +33,19 @@ namespace System.Management.Automation /// If is null. /// /// - internal CommandParameterInfo ( + internal CommandParameterInfo( CompiledCommandParameter parameter, uint parameterSetFlag) { if (parameter == null) { - throw PSTraceSource.NewArgumentNullException ("parameter"); + throw PSTraceSource.NewArgumentNullException("parameter"); } - this.name = parameter.Name; - this.parameterType = parameter.Type; - this.isDynamic = parameter.IsDynamic; - this.aliases = new ReadOnlyCollection (parameter.Aliases); + _name = parameter.Name; + _parameterType = parameter.Type; + _isDynamic = parameter.IsDynamic; + _aliases = new ReadOnlyCollection(parameter.Aliases); SetAttributes(parameter.CompiledAttributes); SetParameterSetData(parameter.GetParameterSetData(parameterSetFlag)); @@ -61,10 +62,10 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private string name = String.Empty; + private string _name = String.Empty; /// /// Gets the type of the parameter. @@ -73,10 +74,10 @@ namespace System.Management.Automation { get { - return parameterType; + return _parameterType; } } - private Type parameterType; + private Type _parameterType; /// /// Gets whether or not the parameter is a dynamic parameter. @@ -89,10 +90,10 @@ namespace System.Management.Automation { get { - return isMandatory; + return _isMandatory; } } - private bool isMandatory; + private bool _isMandatory; /// /// Gets whether or not the parameter is mandatory. @@ -105,11 +106,11 @@ namespace System.Management.Automation { get { - return isDynamic; + return _isDynamic; } } - private bool isDynamic; - + private bool _isDynamic; + /// /// Gets the position in which the parameter can be specified on the command line /// if not named. If the returned value is int.MinValue then the parameter must be named. @@ -118,12 +119,12 @@ namespace System.Management.Automation { get { - return position; + return _position; } } - private int position = int.MinValue; + private int _position = int.MinValue; - private bool valueFromPipeline; + private bool _valueFromPipeline; /// /// Gets whether the parameter can take values from the incoming pipeline object. /// @@ -131,11 +132,11 @@ namespace System.Management.Automation { get { - return valueFromPipeline; + return _valueFromPipeline; } } - private bool valueFromPipelineByPropertyName; + private bool _valueFromPipelineByPropertyName; /// /// Gets whether the parameter can take values from a property inn the incoming /// pipeline object with the same name as the parameter. @@ -144,7 +145,7 @@ namespace System.Management.Automation { get { - return valueFromPipelineByPropertyName; + return _valueFromPipelineByPropertyName; } } @@ -155,10 +156,10 @@ namespace System.Management.Automation { get { - return valueFromRemainingArguments; + return _valueFromRemainingArguments; } } - private bool valueFromRemainingArguments; + private bool _valueFromRemainingArguments; /// /// Gets the help message for this parameter. @@ -167,10 +168,10 @@ namespace System.Management.Automation { get { - return helpMessage; + return _helpMessage; } } - private string helpMessage = String.Empty; + private string _helpMessage = String.Empty; /// /// Gets the aliases by which this parameter can be referenced. @@ -179,10 +180,10 @@ namespace System.Management.Automation { get { - return aliases; + return _aliases; } } - private ReadOnlyCollection aliases; + private ReadOnlyCollection _aliases; /// /// Gets the attributes that are specified on the parameter. @@ -191,18 +192,18 @@ namespace System.Management.Automation { get { - return attributes; + return _attributes; } } - private ReadOnlyCollection attributes; + private ReadOnlyCollection _attributes; #endregion public members #region private members - private void SetAttributes (IList attributeMetadata) + private void SetAttributes(IList attributeMetadata) { - Diagnostics.Assert ( + Diagnostics.Assert( attributeMetadata != null, "The compiled attribute collection should never be null"); @@ -213,22 +214,21 @@ namespace System.Management.Automation processedAttributes.Add(attribute); } - this.attributes = new ReadOnlyCollection (processedAttributes); + _attributes = new ReadOnlyCollection(processedAttributes); } - private void SetParameterSetData (ParameterSetSpecificMetadata parameterMetadata) + private void SetParameterSetData(ParameterSetSpecificMetadata parameterMetadata) { - this.isMandatory = parameterMetadata.IsMandatory; - this.position = parameterMetadata.Position; - this.valueFromPipeline = parameterMetadata.valueFromPipeline; - this.valueFromPipelineByPropertyName = parameterMetadata.valueFromPipelineByPropertyName; - this.valueFromRemainingArguments = parameterMetadata.ValueFromRemainingArguments; - this.helpMessage = parameterMetadata.HelpMessage; + _isMandatory = parameterMetadata.IsMandatory; + _position = parameterMetadata.Position; + _valueFromPipeline = parameterMetadata.valueFromPipeline; + _valueFromPipelineByPropertyName = parameterMetadata.valueFromPipelineByPropertyName; + _valueFromRemainingArguments = parameterMetadata.ValueFromRemainingArguments; + _helpMessage = parameterMetadata.HelpMessage; } #endregion private members } // class CommandParameterInfo - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 1f57c02fb..3f7e45124 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -50,9 +51,9 @@ namespace System.Management.Automation /// If is null. /// /// - internal CommandParameterSetInfo ( - string name, - bool isDefaultParameterSet, + internal CommandParameterSetInfo( + string name, + bool isDefaultParameterSet, uint parameterSetFlag, MergedCommandParameterMetadata parameterMetadata) { @@ -114,7 +115,7 @@ namespace System.Management.Automation GenerateParametersInDisplayOrder(isCapabilityWorkflow, parameter => AppendFormatCommandParameterInfo(parameter, ref result), - delegate(string str) + delegate (string str) { if (result.Length > 0) { @@ -127,7 +128,7 @@ namespace System.Management.Automation return result.ToString(); } - + /// /// GenerateParameters parameters in display order /// ie., Postional followed by @@ -145,7 +146,7 @@ namespace System.Management.Automation /// /// /// - internal void GenerateParametersInDisplayOrder(bool isCapabilityWorkflow, + internal void GenerateParametersInDisplayOrder(bool isCapabilityWorkflow, Action parameterAction, Action commonParameterAction) { @@ -178,8 +179,8 @@ namespace System.Management.Automation if (parameter.Position >= sortedPositionalParameters.Count) { - for (int fillerIndex = sortedPositionalParameters.Count; - fillerIndex <= parameter.Position; + for (int fillerIndex = sortedPositionalParameters.Count; + fillerIndex <= parameter.Position; ++fillerIndex) { sortedPositionalParameters.Add(null); @@ -364,12 +365,12 @@ namespace System.Management.Automation private void Initialize(MergedCommandParameterMetadata parameterMetadata, uint parameterSetFlag) { - Diagnostics.Assert ( + Diagnostics.Assert( parameterMetadata != null, "The parameterMetadata should never be null"); Collection processedParameters = - new Collection (); + new Collection(); // Get the parameters in the parameter set Collection compiledParameters = @@ -384,11 +385,10 @@ namespace System.Management.Automation } } - Parameters = new ReadOnlyCollection (processedParameters); + Parameters = new ReadOnlyCollection(processedParameters); } #endregion private members - } // class CommandParameterSetInfo - + } // class CommandParameterSetInfo } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ParameterSetPromptingData.cs b/src/System.Management.Automation/engine/ParameterSetPromptingData.cs index 5d4373202..09f56e901 100644 --- a/src/System.Management.Automation/engine/ParameterSetPromptingData.cs +++ b/src/System.Management.Automation/engine/ParameterSetPromptingData.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -20,8 +21,8 @@ namespace System.Management.Automation { internal ParameterSetPromptingData(uint parameterSet, bool isDefaultSet) { - this.parameterSet = parameterSet; - this.isDefaultSet = isDefaultSet; + _parameterSet = parameterSet; + _isDefaultSet = isDefaultSet; } /// @@ -30,9 +31,9 @@ namespace System.Management.Automation /// internal bool IsDefaultSet { - get { return isDefaultSet; } + get { return _isDefaultSet; } } - private bool isDefaultSet; + private bool _isDefaultSet; /// /// The parameter set this data represents @@ -40,16 +41,16 @@ namespace System.Management.Automation /// internal uint ParameterSet { - get { return parameterSet; } + get { return _parameterSet; } } - private uint parameterSet = 0; + private uint _parameterSet = 0; /// /// True if the parameter set represents parameters in all the parameter sets /// internal bool IsAllSet { - get { return parameterSet == uint.MaxValue; } + get { return _parameterSet == uint.MaxValue; } } /// @@ -57,9 +58,9 @@ namespace System.Management.Automation /// internal Dictionary PipelineableMandatoryParameters { - get { return pipelineableMandatoryParameters; } + get { return _pipelineableMandatoryParameters; } } - private Dictionary pipelineableMandatoryParameters = + private Dictionary _pipelineableMandatoryParameters = new Dictionary(); /// @@ -67,9 +68,9 @@ namespace System.Management.Automation /// internal Dictionary PipelineableMandatoryByValueParameters { - get { return pipelineableMandatoryByValueParameters; } + get { return _pipelineableMandatoryByValueParameters; } } - private Dictionary pipelineableMandatoryByValueParameters = + private Dictionary _pipelineableMandatoryByValueParameters = new Dictionary(); /// @@ -77,9 +78,9 @@ namespace System.Management.Automation /// internal Dictionary PipelineableMandatoryByPropertyNameParameters { - get { return pipelineableMandatoryByPropertyNameParameters; } + get { return _pipelineableMandatoryByPropertyNameParameters; } } - private Dictionary pipelineableMandatoryByPropertyNameParameters = + private Dictionary _pipelineableMandatoryByPropertyNameParameters = new Dictionary(); @@ -88,9 +89,9 @@ namespace System.Management.Automation /// internal Dictionary NonpipelineableMandatoryParameters { - get { return nonpipelineableMandatoryParameters; } + get { return _nonpipelineableMandatoryParameters; } } - private Dictionary nonpipelineableMandatoryParameters = + private Dictionary _nonpipelineableMandatoryParameters = new Dictionary(); } } diff --git a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs index fb1f1ce84..70d0d187f 100644 --- a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs +++ b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; @@ -31,15 +32,15 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("attribute"); } - this.attribute = attribute; - this.isMandatory = attribute.Mandatory; - this.position = attribute.Position; - this.valueFromRemainingArguments = attribute.ValueFromRemainingArguments; + _attribute = attribute; + _isMandatory = attribute.Mandatory; + _position = attribute.Position; + _valueFromRemainingArguments = attribute.ValueFromRemainingArguments; this.valueFromPipeline = attribute.ValueFromPipeline; this.valueFromPipelineByPropertyName = attribute.ValueFromPipelineByPropertyName; - this.helpMessage = attribute.HelpMessage; - this.helpMessageBaseName = attribute.HelpMessageBaseName; - this.helpMessageResourceId = attribute.HelpMessageResourceId; + _helpMessage = attribute.HelpMessage; + _helpMessageBaseName = attribute.HelpMessageBaseName; + _helpMessageResourceId = attribute.HelpMessageResourceId; } internal ParameterSetSpecificMetadata( @@ -52,14 +53,14 @@ namespace System.Management.Automation string helpMessageResourceId, string helpMessage) { - this.isMandatory = isMandatory; - this.position = position; - this.valueFromRemainingArguments = valueFromRemainingArguments; + _isMandatory = isMandatory; + _position = position; + _valueFromRemainingArguments = valueFromRemainingArguments; this.valueFromPipeline = valueFromPipeline; this.valueFromPipelineByPropertyName = valueFromPipelineByPropertyName; - this.helpMessageBaseName = helpMessageBaseName; - this.helpMessageResourceId = helpMessageResourceId; - this.helpMessage = helpMessage; + _helpMessageBaseName = helpMessageBaseName; + _helpMessageResourceId = helpMessageResourceId; + _helpMessage = helpMessage; } #endregion ctor @@ -72,10 +73,10 @@ namespace System.Management.Automation { get { - return isMandatory; + return _isMandatory; } } - private bool isMandatory; + private bool _isMandatory; /// /// If the parameter is allowed to be positional for this parameter set, this returns @@ -86,10 +87,10 @@ namespace System.Management.Automation { get { - return position; + return _position; } } - private int position = int.MinValue; + private int _position = int.MinValue; /// /// Returns true if the parameter is positional for this parameter set, or false otherwise. @@ -99,7 +100,7 @@ namespace System.Management.Automation { get { - return position != int.MinValue; + return _position != int.MinValue; } } @@ -112,10 +113,10 @@ namespace System.Management.Automation { get { - return valueFromRemainingArguments; + return _valueFromRemainingArguments; } } - private bool valueFromRemainingArguments; + private bool _valueFromRemainingArguments; internal bool valueFromPipeline; /// @@ -142,7 +143,7 @@ namespace System.Management.Automation } } - private string helpMessage; + private string _helpMessage; /// /// A short description for this parameter, suitable for presentation as a tool tip. /// @@ -150,11 +151,11 @@ namespace System.Management.Automation { get { - return helpMessage; + return _helpMessage; } } - private string helpMessageBaseName; + private string _helpMessageBaseName; /// /// The base name of the resource for a help message. /// @@ -162,11 +163,11 @@ namespace System.Management.Automation { get { - return helpMessageBaseName; + return _helpMessageBaseName; } } - private string helpMessageResourceId = null; + private string _helpMessageResourceId = null; /// /// The Id of the resource for a help message. /// @@ -174,7 +175,7 @@ namespace System.Management.Automation { get { - return helpMessageResourceId; + return _helpMessageResourceId; } } @@ -188,14 +189,14 @@ namespace System.Management.Automation { get { - return isInAllSets; + return _isInAllSets; } set { - isInAllSets = value; + _isInAllSets = value; } } - private bool isInAllSets; + private bool _isInAllSets; /// /// Gets the parameter set flag that represents the parameter set @@ -206,12 +207,12 @@ namespace System.Management.Automation { get { - return parameterSetFlag; + return _parameterSetFlag; } set { - parameterSetFlag = value; + _parameterSetFlag = value; } } @@ -288,9 +289,9 @@ namespace System.Management.Automation } - private uint parameterSetFlag; + private uint _parameterSetFlag; - private ParameterAttribute attribute; + private ParameterAttribute _attribute; } // ParameterSetSpecificMetadata } diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 9547efdba..1ccde8e68 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -1,12 +1,13 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -50,7 +51,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // PathInterfaces internal #endregion Constructors @@ -69,10 +70,10 @@ namespace System.Management.Automation get { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.CurrentLocation; + return _sessionState.CurrentLocation; } // get } // CurrentLocation @@ -98,12 +99,12 @@ namespace System.Management.Automation public PathInfo CurrentProviderLocation(string providerName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - - return sessionState.GetNamespaceCurrentLocation(providerName); + + return _sessionState.GetNamespaceCurrentLocation(providerName); } // CurrentProviderLocation /// @@ -118,10 +119,10 @@ namespace System.Management.Automation get { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return CurrentProviderLocation(sessionState.ExecutionContext.ProviderNames.FileSystem); + return CurrentProviderLocation(_sessionState.ExecutionContext.ProviderNames.FileSystem); } // get } // CurrentFileSystemLocation @@ -162,12 +163,12 @@ namespace System.Management.Automation public PathInfo SetLocation(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - - return sessionState.SetLocation(path); + + return _sessionState.SetLocation(path); } // SetLocation /// @@ -211,12 +212,12 @@ namespace System.Management.Automation internal PathInfo SetLocation(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - - return sessionState.SetLocation(path, context); + + return _sessionState.SetLocation(path, context); } // SetLocation /// @@ -270,12 +271,12 @@ namespace System.Management.Automation internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - - return sessionState.IsCurrentLocationOrAncestor(path, context); + + return _sessionState.IsCurrentLocationOrAncestor(path, context); } // IsCurrentLocationOrAncestor /// @@ -288,10 +289,10 @@ namespace System.Management.Automation public void PushCurrentLocation(string stackName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - sessionState.PushCurrentLocation(stackName); + _sessionState.PushCurrentLocation(stackName); } // PushCurrentLocation /// @@ -332,10 +333,10 @@ namespace System.Management.Automation public PathInfo PopLocation(string stackName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.PopLocation(stackName); + return _sessionState.PopLocation(stackName); } // PopLocation /// @@ -348,10 +349,10 @@ namespace System.Management.Automation public PathInfoStack LocationStack(string stackName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.LocationStack(stackName); + return _sessionState.LocationStack(stackName); } // LocationStack /// @@ -368,10 +369,10 @@ namespace System.Management.Automation public PathInfoStack SetDefaultLocationStack(string stackName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.SetDefaultLocationStack(stackName); + return _sessionState.SetDefaultLocationStack(stackName); } /// @@ -473,7 +474,7 @@ namespace System.Management.Automation /// could not be found. /// internal Collection GetResolvedPSPathFromPSPath( - string path, + string path, CmdletProviderContext context) { // The parameters will be verified by the path resolver @@ -536,7 +537,7 @@ namespace System.Management.Automation /// could not be found. /// public Collection GetResolvedProviderPathFromPSPath( - string path, + string path, out ProviderInfo provider) { // The parameters will be verified by the path resolver @@ -545,7 +546,7 @@ namespace System.Management.Automation } // GetResolvedProviderPathFromPSPath internal Collection GetResolvedProviderPathFromPSPath( - string path, + string path, bool allowNonexistingPaths, out ProviderInfo provider) { @@ -614,7 +615,7 @@ namespace System.Management.Automation /// could not be found. /// internal Collection GetResolvedProviderPathFromPSPath( - string path, + string path, CmdletProviderContext context, out ProviderInfo provider) { @@ -623,7 +624,7 @@ namespace System.Management.Automation Provider.CmdletProvider providerInstance = null; return PathResolver.GetGlobbedProviderPathsFromMonadPath(path, false, context, out provider, out providerInstance); } // GetResolvedProviderPathFromPSPath - + /// /// Resolves a drive or provider qualified absolute or relative path that may contain /// wildcard characters into one or more provider-internal paths. @@ -669,7 +670,7 @@ namespace System.Management.Automation /// could not be found. /// public Collection GetResolvedProviderPathFromProviderPath( - string path, + string path, string providerId) { // The parameters will be verified by the path resolver @@ -727,7 +728,7 @@ namespace System.Management.Automation /// could not be found. /// internal Collection GetResolvedProviderPathFromProviderPath( - string path, + string path, string providerId, CmdletProviderContext context) { @@ -849,7 +850,7 @@ namespace System.Management.Automation out ProviderInfo provider, out PSDriveInfo drive) { - CmdletProviderContext context = new CmdletProviderContext(sessionState.ExecutionContext); + CmdletProviderContext context = new CmdletProviderContext(_sessionState.ExecutionContext); // The parameters will be verified by the path resolver @@ -1031,12 +1032,12 @@ namespace System.Management.Automation public string Combine(string parent, string child) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MakePath(parent, child); + return _sessionState.MakePath(parent, child); } // Combine /// @@ -1082,12 +1083,12 @@ namespace System.Management.Automation internal string Combine(string parent, string child, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MakePath(parent, child, context); + return _sessionState.MakePath(parent, child, context); } // Combine #endregion Combine @@ -1128,14 +1129,14 @@ namespace System.Management.Automation public string ParseParent(string path, string root) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetParentPath(path, root); + return _sessionState.GetParentPath(path, root); } // GetParentPath - + /// /// Gets the parent path of the specified path. /// @@ -1172,17 +1173,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal string ParseParent( - string path, + string path, string root, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetParentPath(path, root, context, false); + return _sessionState.GetParentPath(path, root, context, false); } // GetParentPath @@ -1234,14 +1235,14 @@ namespace System.Management.Automation bool useDefaultProvider) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetParentPath(path, root, context, useDefaultProvider); + return _sessionState.GetParentPath(path, root, context, useDefaultProvider); } - + #endregion ParseParent #region ParseChildName @@ -1281,14 +1282,14 @@ namespace System.Management.Automation public string ParseChildName(string path) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildName(path); + return _sessionState.GetChildName(path); } // ParseChildName - + /// /// Gets the child name of the specified path. /// @@ -1326,16 +1327,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal string ParseChildName( - string path, + string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildName(path, context, false); + return _sessionState.GetChildName(path, context, false); } // ParseChildName @@ -1387,14 +1388,14 @@ namespace System.Management.Automation bool useDefaultProvider) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetChildName(path, context, useDefaultProvider); + return _sessionState.GetChildName(path, context, useDefaultProvider); } // ParseChildName - + #endregion ParseChildName #region NormalizeRelativePath @@ -1435,12 +1436,12 @@ namespace System.Management.Automation public string NormalizeRelativePath(string path, string basePath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NormalizeRelativePath(path, basePath); + return _sessionState.NormalizeRelativePath(path, basePath); } // NormalizeRelativePath /// @@ -1481,19 +1482,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal string NormalizeRelativePath( - string path, + string path, string basePath, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NormalizeRelativePath(path, basePath, context); + return _sessionState.NormalizeRelativePath(path, basePath, context); } // NormalizeRelativePath - + #endregion NormalizeRelativePath #region IsValid @@ -1532,13 +1533,13 @@ namespace System.Management.Automation /// public bool IsValid(string path) { - Dbg.Diagnostics.Assert ( - sessionState != null, + Dbg.Diagnostics.Assert( + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.IsValidPath (path); + return _sessionState.IsValidPath(path); } // IsValid /// @@ -1581,13 +1582,13 @@ namespace System.Management.Automation string path, CmdletProviderContext context) { - Dbg.Diagnostics.Assert ( - sessionState != null, + Dbg.Diagnostics.Assert( + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.IsValidPath (path, context); + return _sessionState.IsValidPath(path, context); } // IsValid #endregion IsValid @@ -1601,19 +1602,19 @@ namespace System.Management.Automation get { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - if (pathResolver == null) + if (_pathResolver == null) { - pathResolver = this.sessionState.ExecutionContext.LocationGlobber; + _pathResolver = _sessionState.ExecutionContext.LocationGlobber; } - return pathResolver; + return _pathResolver; } // get } // PathResolver - private LocationGlobber pathResolver; - private SessionStateInternal sessionState; + private LocationGlobber _pathResolver; + private SessionStateInternal _sessionState; #endregion private data } // PathIntrinsics diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index 60f58d676..62ccda703 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -285,7 +286,7 @@ namespace System.Management.Automation.Internal internal void RemovePipelineVariable() { - if (_pipelineVariableObject != null) + if (_pipelineVariableObject != null) { _pipelineVariableObject.Value = null; _pipelineVariableObject = null; diff --git a/src/System.Management.Automation/engine/PositionalCommandParameter.cs b/src/System.Management.Automation/engine/PositionalCommandParameter.cs index 5b34d236a..584310f31 100644 --- a/src/System.Management.Automation/engine/PositionalCommandParameter.cs +++ b/src/System.Management.Automation/engine/PositionalCommandParameter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -21,7 +22,7 @@ namespace System.Management.Automation /// internal PositionalCommandParameter(MergedCompiledCommandParameter parameter) { - this.parameter = parameter; + _parameter = parameter; } #endregion ctor @@ -30,20 +31,19 @@ namespace System.Management.Automation { get { - return parameter; + return _parameter; } } - private MergedCompiledCommandParameter parameter; + private MergedCompiledCommandParameter _parameter; internal Collection ParameterSetData { get { - return parameterSetData; + return _parameterSetData; } } - private Collection parameterSetData = new Collection(); - + private Collection _parameterSetData = new Collection(); } } diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 66ad6aaeb..cade8aa55 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -21,7 +21,7 @@ namespace System.Management.Automation /// [DataContract()] - public + public class ProgressRecord { #region Public API @@ -66,9 +66,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("activity", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "statusDescription"); } - this.id = activityId; - this.activity = activity; - this.status = statusDescription; + _id = activityId; + _activity = activity; + _status = statusDescription; } /// @@ -77,14 +77,14 @@ namespace System.Management.Automation /// internal ProgressRecord(ProgressRecord other) { - this.activity = other.activity; - this.currentOperation = other.currentOperation; - this.id = other.id; - this.parentId = other.parentId; - this.percent = other.percent; - this.secondsRemaining = other.secondsRemaining; - this.status = other.status; - this.type = other.type; + _activity = other._activity; + _currentOperation = other._currentOperation; + _id = other._id; + _parentId = other._parentId; + _percent = other._percent; + _secondsRemaining = other._secondsRemaining; + _status = other._status; + _type = other._type; } /// @@ -106,7 +106,7 @@ namespace System.Management.Automation { get { - return id; + return _id; } } @@ -133,13 +133,13 @@ namespace System.Management.Automation /// /// - public - int + public + int ParentActivityId { get { - return parentId; + return _parentId; } set { @@ -147,7 +147,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ParentActivityIdCantBeActivityId); } - parentId = value; + _parentId = value; } } @@ -165,13 +165,13 @@ namespace System.Management.Automation /// /// - public - string + public + string Activity { get { - return activity; + return _activity; } set { @@ -179,10 +179,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "value"); } - activity = value; + _activity = value; } } - + /// @@ -191,13 +191,13 @@ namespace System.Management.Automation /// /// - public - string + public + string StatusDescription { get { - return status; + return _status; } set { @@ -205,7 +205,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "value"); } - status = value; + _status = value; } } @@ -220,21 +220,21 @@ namespace System.Management.Automation /// public - string + string CurrentOperation { get { - return currentOperation; + return _currentOperation; } set { // null or empty string is allowed - currentOperation= value; + _currentOperation = value; } } - + /// @@ -250,20 +250,20 @@ namespace System.Management.Automation { get { - return percent; + return _percent; } set { // negative values are allowed - + if (value > 100) { - throw + throw PSTraceSource.NewArgumentOutOfRangeException( "value", value, ProgressRecordStrings.PercentMayNotBeMoreThan100, "PercentComplete"); } - percent = value; + _percent = value; } } @@ -289,13 +289,13 @@ namespace System.Management.Automation { get { - return secondsRemaining; + return _secondsRemaining; } set { // negative values are allowed - secondsRemaining = value; + _secondsRemaining = value; } } @@ -306,14 +306,14 @@ namespace System.Management.Automation /// Gets and sets the type of record represented by this instance. /// /// - + public ProgressRecordType RecordType { get { - return type; + return _type; } set { @@ -322,7 +322,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("value"); } - type = value; + _type = value; } } @@ -341,22 +341,22 @@ namespace System.Management.Automation /// /// - public override - string + public override + string ToString() { - return + return String.Format( System.Globalization.CultureInfo.CurrentCulture, "parent = {0} id = {1} act = {2} stat = {3} cur = {4} pct = {5} sec = {6} type = {7}", - parentId, - id, - activity, - status, - currentOperation, - percent, - secondsRemaining, - type); + _parentId, + _id, + _activity, + _status, + _currentOperation, + _percent, + _secondsRemaining, + _type); } #endregion @@ -368,7 +368,7 @@ namespace System.Management.Automation Dbg.Assert(percentageComplete >= 0.0, "Caller should verify percentageComplete >= 0.0"); Dbg.Assert(percentageComplete <= 1.0, "Caller should verify percentageComplete <= 1.0"); Dbg.Assert( - startTime.Kind == DateTimeKind.Utc, + startTime.Kind == DateTimeKind.Utc, "DateTime arithmetic should always be done in utc mode [to avoid problems when some operands are calculated right before and right after switching to /from a daylight saving time"); if ((percentageComplete < 0.00001) || double.IsNaN(percentageComplete)) @@ -395,7 +395,7 @@ namespace System.Management.Automation } TimeSpan remainingTime = totalTime - elapsedTime; - return (int) (remainingTime.TotalSeconds); + return (int)(remainingTime.TotalSeconds); } /// @@ -416,7 +416,7 @@ namespace System.Management.Automation DateTime now = DateTime.UtcNow; Dbg.Assert( - startTime.Kind == DateTimeKind.Utc, + startTime.Kind == DateTimeKind.Utc, "DateTime arithmetic should always be done in utc mode [to avoid problems when some operands are calculated right before and right after switching to /from a daylight saving time"); if (startTime > now) @@ -474,28 +474,28 @@ namespace System.Management.Automation #endregion [DataMemberAttribute()] - private int id; + private int _id; [DataMemberAttribute()] - private int parentId = -1; + private int _parentId = -1; [DataMemberAttribute()] - private string activity; + private string _activity; [DataMemberAttribute()] - private string status; + private string _status; [DataMemberAttribute()] - private string currentOperation; + private string _currentOperation; [DataMemberAttribute()] - private int percent = -1; + private int _percent = -1; [DataMemberAttribute()] - private int secondsRemaining = -1; + private int _secondsRemaining = -1; [DataMemberAttribute()] - private ProgressRecordType type = ProgressRecordType.Processing; + private ProgressRecordType _type = ProgressRecordType.Processing; #region Serialization / deserialization for remoting @@ -547,7 +547,7 @@ namespace System.Management.Automation progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, this.Activity)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_ActivityId, this.ActivityId)); - progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_StatusDescription, this.StatusDescription)); + progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_StatusDescription, this.StatusDescription)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_CurrentOperation, this.CurrentOperation)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_ParentActivityId, this.ParentActivityId)); @@ -558,13 +558,11 @@ namespace System.Management.Automation return progressAsPSObject; } - #endregion - } //ProgressRecord - + /// /// /// Defines two types of progress record that refer to the beginning (or middle) and end of an operation. diff --git a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs index 7d565293c..49f3cb894 100644 --- a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs @@ -1,9 +1,10 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -45,8 +46,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.sessionState = cmdlet.Context.EngineSessionState; + _cmdlet = cmdlet; + _sessionState = cmdlet.Context.EngineSessionState; } // PropertyCmdletProviderIntrinsics internal /// @@ -68,7 +69,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // PropertyCmdletProviderIntrinsics internal #endregion Constructors @@ -121,16 +122,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Get( - string path, + string path, Collection providerSpecificPickList) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetProperty(new string[] { path }, providerSpecificPickList, false); + return _sessionState.GetProperty(new string[] { path }, providerSpecificPickList, false); } // GetProperty /// @@ -186,12 +187,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetProperty(path, providerSpecificPickList, literalPath); + return _sessionState.GetProperty(path, providerSpecificPickList, literalPath); } // GetProperty /// @@ -243,17 +244,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Get( - string path, + string path, Collection providerSpecificPickList, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.GetProperty(new string[] { path }, providerSpecificPickList, context); + _sessionState.GetProperty(new string[] { path }, providerSpecificPickList, context); } // GetProperty /// @@ -300,17 +301,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object GetPropertyDynamicParameters( - string path, - Collection providerSpecificPickList, + string path, + Collection providerSpecificPickList, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetPropertyDynamicParameters(path, providerSpecificPickList, context); + return _sessionState.GetPropertyDynamicParameters(path, providerSpecificPickList, context); } // GetPropertyDynamicParameters #endregion GetProperty @@ -359,16 +360,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Set( - string path, + string path, PSObject propertyValue) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetProperty(new string[] { path }, propertyValue, false, false); + return _sessionState.SetProperty(new string[] { path }, propertyValue, false, false); } // SetProperty @@ -428,12 +429,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetProperty(path, propertyValue, force, literalPath); + return _sessionState.SetProperty(path, propertyValue, force, literalPath); } // SetProperty @@ -483,17 +484,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Set( - string path, + string path, PSObject propertyValue, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.SetProperty(new string[] { path }, propertyValue, context); + _sessionState.SetProperty(new string[] { path }, propertyValue, context); } // SetProperty /// @@ -539,19 +540,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object SetPropertyDynamicParameters( - string path, - PSObject propertyValue, + string path, + PSObject propertyValue, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.SetPropertyDynamicParameters(path, propertyValue, context); + return _sessionState.SetPropertyDynamicParameters(path, propertyValue, context); } // SetPropertyDynamicParameters - + #endregion SetProperty #region ClearProperty @@ -594,16 +595,16 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public void Clear( - string path, + string path, Collection propertyToClear) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearProperty(new string[] { path }, propertyToClear, false, false); + _sessionState.ClearProperty(new string[] { path }, propertyToClear, false, false); } // ClearProperty /// @@ -618,7 +619,7 @@ namespace System.Management.Automation /// The properties to clear from the item(s). /// /// - /// + /// /// Passed on to providers to force operations. /// /// @@ -626,7 +627,7 @@ namespace System.Management.Automation /// If true, globbing is not done on paths. /// /// - /// + /// /// If or is null. /// /// @@ -658,12 +659,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearProperty(path, propertyToClear, force, literalPath); + _sessionState.ClearProperty(path, propertyToClear, force, literalPath); } // ClearProperty /// @@ -708,17 +709,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Clear( - string path, + string path, Collection propertyToClear, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.ClearProperty(new string[] { path }, propertyToClear, context); + _sessionState.ClearProperty(new string[] { path }, propertyToClear, context); } // ClearProperty /// @@ -764,17 +765,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object ClearPropertyDynamicParameters( - string path, - Collection propertyToClear, + string path, + Collection propertyToClear, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.ClearPropertyDynamicParameters(path, propertyToClear, context); + return _sessionState.ClearPropertyDynamicParameters(path, propertyToClear, context); } // ClearPropertyDynamicParameters #endregion ClearProperty @@ -832,18 +833,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection New( - string path, - string propertyName, - string propertyTypeName, + string path, + string propertyName, + string propertyTypeName, object value) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewProperty(new string[] { path }, propertyName, propertyTypeName, value, false, false); + return _sessionState.NewProperty(new string[] { path }, propertyName, propertyTypeName, value, false, false); } // NewProperty /// @@ -913,12 +914,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewProperty(path, propertyName, propertyTypeName, value, force, literalPath); + return _sessionState.NewProperty(path, propertyName, propertyTypeName, value, force, literalPath); } // NewProperty /// @@ -984,12 +985,12 @@ namespace System.Management.Automation CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.NewProperty(new string[] { path }, propertyName, type, value, context); + _sessionState.NewProperty(new string[] { path }, propertyName, type, value, context); } // NewProperty /// @@ -1043,19 +1044,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object NewPropertyDynamicParameters( - string path, - string propertyName, - string type, - object value, + string path, + string propertyName, + string type, + object value, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewPropertyDynamicParameters(path, propertyName, type, value, context); + return _sessionState.NewPropertyDynamicParameters(path, propertyName, type, value, context); } // NewPropertyDynamicParameters #endregion NewProperty @@ -1102,12 +1103,12 @@ namespace System.Management.Automation public void Remove(string path, string propertyName) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveProperty(new string[] { path }, propertyName, false, false); + _sessionState.RemoveProperty(new string[] { path }, propertyName, false, false); } // RemoveProperty /// @@ -1158,12 +1159,12 @@ namespace System.Management.Automation public void Remove(string[] path, string propertyName, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveProperty(path, propertyName, force, literalPath); + _sessionState.RemoveProperty(path, propertyName, force, literalPath); } // RemoveProperty /// @@ -1208,17 +1209,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Remove( - string path, + string path, string propertyName, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveProperty(new string[] { path }, propertyName, context); + _sessionState.RemoveProperty(new string[] { path }, propertyName, context); } // RemoveProperty /// @@ -1264,17 +1265,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object RemovePropertyDynamicParameters( - string path, - string propertyName, + string path, + string propertyName, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RemovePropertyDynamicParameters(path, propertyName, context); + return _sessionState.RemovePropertyDynamicParameters(path, propertyName, context); } // RemovePropertyDynamicParameters #endregion RemoveProperty @@ -1328,17 +1329,17 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Rename( - string path, - string sourceProperty, + string path, + string sourceProperty, string destinationProperty) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenameProperty(new string[] { path }, sourceProperty, destinationProperty, false, false); + return _sessionState.RenameProperty(new string[] { path }, sourceProperty, destinationProperty, false, false); } // RenameProperty /// @@ -1403,12 +1404,12 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenameProperty(path, sourceProperty, destinationProperty, force, literalPath); + return _sessionState.RenameProperty(path, sourceProperty, destinationProperty, force, literalPath); } // RenameProperty /// @@ -1463,18 +1464,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Rename( - string path, + string path, string sourceProperty, string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RenameProperty(new string[] { path }, sourceProperty, destinationProperty, context); + _sessionState.RenameProperty(new string[] { path }, sourceProperty, destinationProperty, context); } // RenameProperty /// @@ -1524,18 +1525,18 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object RenamePropertyDynamicParameters( - string path, - string sourceProperty, - string destinationProperty, + string path, + string sourceProperty, + string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty, context); + return _sessionState.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty, context); } // RenamePropertyDynamicParameters #endregion RenameProperty @@ -1595,22 +1596,22 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Copy( - string sourcePath, - string sourceProperty, + string sourcePath, + string sourceProperty, string destinationPath, string destinationProperty) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return - sessionState.CopyProperty( + return + _sessionState.CopyProperty( new string[] { sourcePath }, - sourceProperty, - destinationPath, + sourceProperty, + destinationPath, destinationProperty, false, false); } // CopyProperty @@ -1685,13 +1686,13 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return - sessionState.CopyProperty( + _sessionState.CopyProperty( sourcePath, sourceProperty, destinationPath, @@ -1759,22 +1760,22 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Copy( - string sourcePath, - string sourceProperty, + string sourcePath, + string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.CopyProperty( + _sessionState.CopyProperty( new string[] { sourcePath }, - sourceProperty, - destinationPath, + sourceProperty, + destinationPath, destinationProperty, context); } // CopyProperty @@ -1831,19 +1832,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object CopyPropertyDynamicParameters( - string path, - string sourceProperty, - string destinationPath, - string destinationProperty, + string path, + string sourceProperty, + string destinationPath, + string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty, context); + return _sessionState.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty, context); } // CopyPropertyDynamicParameters #endregion CopyProperty @@ -1907,22 +1908,22 @@ namespace System.Management.Automation /// If the provider threw an exception. /// public Collection Move( - string sourcePath, - string sourceProperty, + string sourcePath, + string sourceProperty, string destinationPath, string destinationProperty) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return - sessionState.MoveProperty( - new string[] { sourcePath }, - sourceProperty, - destinationPath, + return + _sessionState.MoveProperty( + new string[] { sourcePath }, + sourceProperty, + destinationPath, destinationProperty, false, false); @@ -2002,13 +2003,13 @@ namespace System.Management.Automation bool literalPath) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object return - sessionState.MoveProperty( + _sessionState.MoveProperty( sourcePath, sourceProperty, destinationPath, @@ -2080,22 +2081,22 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal void Move( - string sourcePath, - string sourceProperty, + string sourcePath, + string sourceProperty, string destinationPath, string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.MoveProperty( + _sessionState.MoveProperty( new string[] { sourcePath }, - sourceProperty, - destinationPath, + sourceProperty, + destinationPath, destinationProperty, context); } // MoveProperty @@ -2152,19 +2153,19 @@ namespace System.Management.Automation /// If the provider threw an exception. /// internal object MovePropertyDynamicParameters( - string path, - string sourceProperty, - string destinationPath, - string destinationProperty, + string path, + string sourceProperty, + string destinationPath, + string destinationProperty, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty, context); + return _sessionState.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty, context); } // MovePropertyDynamicParameters #endregion MoveProperty @@ -2173,8 +2174,8 @@ namespace System.Management.Automation #region private data - private Cmdlet cmdlet; - private SessionStateInternal sessionState; + private Cmdlet _cmdlet; + private SessionStateInternal _sessionState; #endregion private data } // PropertyCmdletProviderIntrinsics diff --git a/src/System.Management.Automation/engine/ProviderInterfaces.cs b/src/System.Management.Automation/engine/ProviderInterfaces.cs index bbb854c2c..965acac69 100644 --- a/src/System.Management.Automation/engine/ProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ProviderInterfaces.cs @@ -1,11 +1,12 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -46,7 +47,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // CmdletProviderManagementIntrinsics internal #endregion Constructors @@ -77,12 +78,12 @@ namespace System.Management.Automation public Collection Get(string name) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetProvider(name); + return _sessionState.GetProvider(name); } // Get /// @@ -113,24 +114,24 @@ namespace System.Management.Automation public ProviderInfo GetOne(string name) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetSingleProvider(name); + return _sessionState.GetSingleProvider(name); } // Get - + /// /// Gets all the Cmdlet Providers that are loaded. /// public IEnumerable GetAll() { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return sessionState.ProviderList; + return _sessionState.ProviderList; } // GetAll #endregion Public methods @@ -170,7 +171,7 @@ namespace System.Management.Automation { get { - return sessionState.ProviderCount; + return _sessionState.ProviderCount; } } // Count @@ -178,7 +179,7 @@ namespace System.Management.Automation #region private data - private SessionStateInternal sessionState; + private SessionStateInternal _sessionState; #endregion private data } // ProviderIntrinsics diff --git a/src/System.Management.Automation/engine/ProviderNames.cs b/src/System.Management.Automation/engine/ProviderNames.cs index d9d89139c..fa17f783d 100644 --- a/src/System.Management.Automation/engine/ProviderNames.cs +++ b/src/System.Management.Automation/engine/ProviderNames.cs @@ -60,8 +60,8 @@ namespace System.Management.Automation /// /// Gets the name of the EnvironmentProvider /// - internal override string Environment - { + internal override string Environment + { get { return "Environment"; @@ -71,8 +71,8 @@ namespace System.Management.Automation /// /// Gets the name of the Certificate /// - internal override string Certificate - { + internal override string Certificate + { get { return "Certificate"; @@ -82,8 +82,8 @@ namespace System.Management.Automation /// /// Gets the name of the VariableProvider /// - internal override string Variable - { + internal override string Variable + { get { return "Variable"; @@ -93,8 +93,8 @@ namespace System.Management.Automation /// /// Gets the name of the AliasProvider /// - internal override string Alias - { + internal override string Alias + { get { return "Alias"; @@ -104,8 +104,8 @@ namespace System.Management.Automation /// /// Gets the name of the FunctionProvider /// - internal override string Function - { + internal override string Function + { get { return "Function"; @@ -115,8 +115,8 @@ namespace System.Management.Automation /// /// Gets the name of the FileSystemProvider /// - internal override string FileSystem - { + internal override string FileSystem + { get { return "FileSystem"; @@ -126,8 +126,8 @@ namespace System.Management.Automation /// /// Gets the name of the RegistryProvider /// - internal override string Registry - { + internal override string Registry + { get { return "Registry"; @@ -143,8 +143,8 @@ namespace System.Management.Automation /// /// Gets the name of the EnvironmentProvider /// - internal override string Environment - { + internal override string Environment + { get { return "Microsoft.PowerShell.Core\\Environment"; @@ -154,8 +154,8 @@ namespace System.Management.Automation /// /// Gets the name of the Certificate /// - internal override string Certificate - { + internal override string Certificate + { get { return "Microsoft.PowerShell.Security\\Certificate"; @@ -165,8 +165,8 @@ namespace System.Management.Automation /// /// Gets the name of the VariableProvider /// - internal override string Variable - { + internal override string Variable + { get { return "Microsoft.PowerShell.Core\\Variable"; @@ -176,8 +176,8 @@ namespace System.Management.Automation /// /// Gets the name of the AliasProvider /// - internal override string Alias - { + internal override string Alias + { get { return "Microsoft.PowerShell.Core\\Alias"; @@ -187,8 +187,8 @@ namespace System.Management.Automation /// /// Gets the name of the FunctionProvider /// - internal override string Function - { + internal override string Function + { get { return "Microsoft.PowerShell.Core\\Function"; @@ -198,8 +198,8 @@ namespace System.Management.Automation /// /// Gets the name of the FileSystemProvider /// - internal override string FileSystem - { + internal override string FileSystem + { get { return "Microsoft.PowerShell.Core\\FileSystem"; @@ -209,14 +209,13 @@ namespace System.Management.Automation /// /// Gets the name of the RegistryProvider /// - internal override string Registry - { + internal override string Registry + { get { return "Microsoft.PowerShell.Core\\Registry"; } } } - } diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index f8cb5b55b..db8999ff4 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -244,7 +244,7 @@ namespace System.Management.Automation return commandMetadata.GetEndBlock(); } - private static T GetProperty(PSObject obj, string property) where T: class + private static T GetProperty(PSObject obj, string property) where T : class { T result = null; if (obj != null && obj.Properties[property] != null) @@ -364,7 +364,7 @@ namespace System.Management.Automation break; } } - + if (!isHelpObject) { string error = ProxyCommandStrings.HelpInfoObjectRequired; diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index 4885cbd09..c70dd3a5d 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.ObjectModel; @@ -35,8 +36,8 @@ namespace System.Management.Automation /// The Command line parameter collection to update... /// /// - internal RuntimeDefinedParameterBinder ( - RuntimeDefinedParameterDictionary target, + internal RuntimeDefinedParameterBinder( + RuntimeDefinedParameterDictionary target, InternalCommand command, CommandLineParameters commandLineParameters) : base(target, command.MyInvocation, command.Context, command) @@ -144,6 +145,5 @@ namespace System.Management.Automation } // BindParameter #endregion Parameter binding - } // RuntimeDefinedParameterBinder } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index b70d537c3..196874460 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -31,7 +32,7 @@ namespace System.Management.Automation /// /// Constructs a runtime-defined parameter instance. /// - public RuntimeDefinedParameter () + public RuntimeDefinedParameter() { } // RuntimeDefinedParameter @@ -62,9 +63,9 @@ namespace System.Management.Automation /// public RuntimeDefinedParameter(string name, Type parameterType, Collection attributes) { - if (String.IsNullOrEmpty (name)) + if (String.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException ("name"); + throw PSTraceSource.NewArgumentException("name"); } if (parameterType == null) @@ -72,12 +73,12 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("parameterType"); } - this._name = name; - this._parameterType = parameterType; + _name = name; + _parameterType = parameterType; if (attributes != null) { - this._attributes = attributes; + _attributes = attributes; } } // RuntimeDefinedParameter @@ -88,17 +89,17 @@ namespace System.Management.Automation /// /// If is null or empty on set. /// - public string Name - { + public string Name + { get { return _name; } set { - if (String.IsNullOrEmpty (value)) + if (String.IsNullOrEmpty(value)) { - throw PSTraceSource.NewArgumentException ("name"); + throw PSTraceSource.NewArgumentException("name"); } _name = value; } @@ -127,7 +128,7 @@ namespace System.Management.Automation { if (value == null) { - throw PSTraceSource.NewArgumentNullException ("value"); + throw PSTraceSource.NewArgumentNullException("value"); } _parameterType = value; } @@ -142,7 +143,7 @@ namespace System.Management.Automation /// If the value is set prior to parameter binding, the value will be /// reset before each pipeline object is processed. /// - public object Value + public object Value { get { @@ -152,7 +153,7 @@ namespace System.Management.Automation set { this.IsSet = true; - this._value = value; + _value = value; } } private object _value; @@ -170,8 +171,7 @@ namespace System.Management.Automation /// This can be any attribute that can be applied to a normal parameter. /// public Collection Attributes { get { return _attributes; } } - private readonly Collection _attributes = new Collection (); - + private readonly Collection _attributes = new Collection(); } // class RuntimeDefinedParameter /// @@ -203,10 +203,10 @@ namespace System.Management.Automation /// /// Gets or sets the help file that documents these parameters /// - public string HelpFile + public string HelpFile { get { return _helpFile; } - set { _helpFile = String.IsNullOrEmpty (value) ? String.Empty : value; } + set { _helpFile = String.IsNullOrEmpty(value) ? String.Empty : value; } } private string _helpFile = String.Empty; @@ -217,5 +217,4 @@ namespace System.Management.Automation internal static RuntimeDefinedParameter[] EmptyParameterArray = new RuntimeDefinedParameter[0]; } // class RuntimeDefinedParameterDictionary - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/QuestionMarkVariable.cs b/src/System.Management.Automation/engine/QuestionMarkVariable.cs index e16694979..6d0234ae0 100644 --- a/src/System.Management.Automation/engine/QuestionMarkVariable.cs +++ b/src/System.Management.Automation/engine/QuestionMarkVariable.cs @@ -22,7 +22,7 @@ namespace System.Management.Automation /// /// Execution context /// - internal QuestionMarkVariable (ExecutionContext context) + internal QuestionMarkVariable(ExecutionContext context) : base(SpecialVariables.Question, true, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.DollarHookDescription) { _context = context; @@ -48,6 +48,6 @@ namespace System.Management.Automation base.Value = value; } } - } - } + } +} diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index d030326bd..58ada8673 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -171,61 +172,61 @@ namespace System.Management.Automation static ReflectionParameterBinder() { // Statically add delegates that we typically need on startup or every time we run PowerShell - this avoids the JIT - _getterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), o => ((OutDefaultCommand)o).InputObject); - _setterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), (o, v) => ((OutDefaultCommand)o).InputObject = (PSObject)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), o => ((OutDefaultCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), (o, v) => ((OutDefaultCommand)o).InputObject = (PSObject)v); - _getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), o => ((OutLineOutputCommand)o).InputObject); - _getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), o => ((OutLineOutputCommand)o).LineOutput); - _setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), (o, v) => ((OutLineOutputCommand)o).InputObject = (PSObject)v); - _setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), (o, v) => ((OutLineOutputCommand)o).LineOutput = v); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), o => ((OutLineOutputCommand)o).InputObject); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), o => ((OutLineOutputCommand)o).LineOutput); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), (o, v) => ((OutLineOutputCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), (o, v) => ((OutLineOutputCommand)o).LineOutput = v); - _getterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), o => ((FormatDefaultCommand)o).InputObject); - _setterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), (o, v) => ((FormatDefaultCommand)o).InputObject = (PSObject)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), o => ((FormatDefaultCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), (o, v) => ((FormatDefaultCommand)o).InputObject = (PSObject)v); - _setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Off"), (o, v) => ((SetStrictModeCommand)o).Off = (SwitchParameter)v); - _setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Version"), (o, v) => ((SetStrictModeCommand)o).Version = (Version)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Off"), (o, v) => ((SetStrictModeCommand)o).Off = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Version"), (o, v) => ((SetStrictModeCommand)o).Version = (Version)v); - _getterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), o => ((ForEachObjectCommand)o).InputObject); - _setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), (o, v) => ((ForEachObjectCommand)o).InputObject = (PSObject)v); - _setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "Process"), (o, v) => ((ForEachObjectCommand)o).Process = (ScriptBlock[])v); + s_getterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), o => ((ForEachObjectCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), (o, v) => ((ForEachObjectCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "Process"), (o, v) => ((ForEachObjectCommand)o).Process = (ScriptBlock[])v); - _getterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), o => ((WhereObjectCommand)o).InputObject); - _setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), (o, v) => ((WhereObjectCommand)o).InputObject = (PSObject)v); - _setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "FilterScript"), (o, v) => ((WhereObjectCommand)o).FilterScript = (ScriptBlock)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), o => ((WhereObjectCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), (o, v) => ((WhereObjectCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "FilterScript"), (o, v) => ((WhereObjectCommand)o).FilterScript = (ScriptBlock)v); - _setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Name"), (o, v) => ((ImportModuleCommand)o).Name = (string[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "ModuleInfo"), (o, v) => ((ImportModuleCommand)o).ModuleInfo = (PSModuleInfo[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Scope"), (o, v) => ((ImportModuleCommand)o).Scope = (string)v); - _setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "PassThru"), (o, v) => ((ImportModuleCommand)o).PassThru = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Name"), (o, v) => ((ImportModuleCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "ModuleInfo"), (o, v) => ((ImportModuleCommand)o).ModuleInfo = (PSModuleInfo[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Scope"), (o, v) => ((ImportModuleCommand)o).Scope = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "PassThru"), (o, v) => ((ImportModuleCommand)o).PassThru = (SwitchParameter)v); - _setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Name"), (o, v) => ((GetCommandCommand)o).Name = (string[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Module"), (o, v) => ((GetCommandCommand)o).Module = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Name"), (o, v) => ((GetCommandCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Module"), (o, v) => ((GetCommandCommand)o).Module = (string[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "Name"), (o, v) => ((GetModuleCommand)o).Name = (string[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "ListAvailable"), (o, v) => ((GetModuleCommand)o).ListAvailable = (SwitchParameter)v); - _setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "FullyQualifiedName"), (o, v) => ((GetModuleCommand)o).FullyQualifiedName = (ModuleSpecification[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "Name"), (o, v) => ((GetModuleCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "ListAvailable"), (o, v) => ((GetModuleCommand)o).ListAvailable = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "FullyQualifiedName"), (o, v) => ((GetModuleCommand)o).FullyQualifiedName = (ModuleSpecification[])v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorAction"), (o, v) => ((CommonParameters)o).ErrorAction = (ActionPreference)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningAction"), (o, v) => ((CommonParameters)o).WarningAction = (ActionPreference)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationAction"), (o, v) => ((CommonParameters)o).InformationAction = (ActionPreference)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningVariable"), (o, v) => ((CommonParameters)o).WarningVariable = (string)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationVariable"), (o, v) => ((CommonParameters)o).InformationVariable = (string)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutVariable"), (o, v) => ((CommonParameters)o).OutVariable = (string)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutBuffer"), (o, v) => ((CommonParameters)o).OutBuffer = (int)v); - _setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "PipelineVariable"), (o, v) => ((CommonParameters)o).PipelineVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorAction"), (o, v) => ((CommonParameters)o).ErrorAction = (ActionPreference)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningAction"), (o, v) => ((CommonParameters)o).WarningAction = (ActionPreference)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationAction"), (o, v) => ((CommonParameters)o).InformationAction = (ActionPreference)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningVariable"), (o, v) => ((CommonParameters)o).WarningVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationVariable"), (o, v) => ((CommonParameters)o).InformationVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutVariable"), (o, v) => ((CommonParameters)o).OutVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutBuffer"), (o, v) => ((CommonParameters)o).OutBuffer = (int)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "PipelineVariable"), (o, v) => ((CommonParameters)o).PipelineVariable = (string)v); } - private static readonly ConcurrentDictionary, Func> _getterMethods + private static readonly ConcurrentDictionary, Func> s_getterMethods = new ConcurrentDictionary, Func>(); - private static readonly ConcurrentDictionary, Action> _setterMethods = + private static readonly ConcurrentDictionary, Action> s_setterMethods = new ConcurrentDictionary, Action>(); private static Func GetGetter(Type type, string property) { - return _getterMethods.GetOrAdd(Tuple.Create(type, property), + return s_getterMethods.GetOrAdd(Tuple.Create(type, property), (Tuple _) => { var target = Expression.Parameter(typeof(object)); @@ -233,13 +234,13 @@ namespace System.Management.Automation Expression.Convert( GetPropertyOrFieldExpr(type, property, Expression.Convert(target, type)), typeof(object)), - new[] {target}).Compile(); + new[] { target }).Compile(); }); } private static Action GetSetter(Type type, string property) { - return _setterMethods.GetOrAdd(Tuple.Create(type, property), + return s_setterMethods.GetOrAdd(Tuple.Create(type, property), _ => { var target = Expression.Parameter(typeof(object)); @@ -247,7 +248,7 @@ namespace System.Management.Automation var propertyExpr = GetPropertyOrFieldExpr(type, property, Expression.Convert(target, type)); Expression expr = Expression.Assign(propertyExpr, Expression.Convert(value, propertyExpr.Type)); - if (propertyExpr.Type.GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(propertyExpr.Type) == null ) + if (propertyExpr.Type.GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(propertyExpr.Type) == null) { var throwInvalidCastExceptionExpr = Expression.Call(Language.CachedReflectionInfo.LanguagePrimitives_ThrowInvalidCastException, @@ -262,7 +263,7 @@ namespace System.Management.Automation expr); } - return Expression.Lambda>(expr, new[] {target, value}).Compile(); + return Expression.Lambda>(expr, new[] { target, value }).Compile(); }); } diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index 2659572a3..a83385530 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation /// The type of items that the derived class returns. /// /// - internal abstract class ScopedItemSearcher : IEnumerator, IEnumerable + internal abstract class ScopedItemSearcher : IEnumerator, IEnumerable { #region ctor @@ -38,7 +38,7 @@ namespace System.Management.Automation /// /// internal ScopedItemSearcher( - SessionStateInternal sessionState, + SessionStateInternal sessionState, VariablePath lookupPath) { if (sessionState == null) @@ -52,7 +52,7 @@ namespace System.Management.Automation } this.sessionState = sessionState; - this.lookupPath = lookupPath; + _lookupPath = lookupPath; InitializeScopeEnumerator(); } @@ -91,27 +91,27 @@ namespace System.Management.Automation { bool result = true; - if (!isInitialized) + if (!_isInitialized) { InitializeScopeEnumerator(); } // Enumerate the scopes until a matching scoped item is found - while (scopeEnumerable.MoveNext()) + while (_scopeEnumerable.MoveNext()) { T newCurrentItem; - if (TryGetNewScopeItem(((IEnumerator)scopeEnumerable).Current, out newCurrentItem)) + if (TryGetNewScopeItem(((IEnumerator)_scopeEnumerable).Current, out newCurrentItem)) { - currentScope = ((IEnumerator)scopeEnumerable).Current; - current = newCurrentItem; + _currentScope = ((IEnumerator)_scopeEnumerable).Current; + _current = newCurrentItem; result = true; break; } result = false; - if (isSingleScopeLookup) + if (_isSingleScopeLookup) { break; } @@ -129,7 +129,7 @@ namespace System.Management.Automation { get { - return current; + return _current; } } @@ -138,7 +138,7 @@ namespace System.Management.Automation { get { - return current; + return _current; } } @@ -152,10 +152,10 @@ namespace System.Management.Automation public void Dispose() { - current = default(T); - scopeEnumerable.Dispose(); - scopeEnumerable = null; - isInitialized = false; + _current = default(T); + _scopeEnumerable.Dispose(); + _scopeEnumerable = null; + _isInitialized = false; GC.SuppressFinalize(this); } @@ -181,8 +181,8 @@ namespace System.Management.Automation /// /// protected abstract bool GetScopeItem( - SessionStateScope scope, - VariablePath name, + SessionStateScope scope, + VariablePath name, out T newCurrentItem); #endregion IEnumerable/IEnumerator members @@ -193,10 +193,10 @@ namespace System.Management.Automation /// internal SessionStateScope CurrentLookupScope { - get { return currentScope; } + get { return _currentScope; } } - private SessionStateScope currentScope; + private SessionStateScope _currentScope; /// /// Gets the scope in which the search begins. @@ -204,9 +204,9 @@ namespace System.Management.Automation /// internal SessionStateScope InitialScope { - get { return initialScope; } + get { return _initialScope; } } - private SessionStateScope initialScope; + private SessionStateScope _initialScope; #region private members @@ -216,7 +216,7 @@ namespace System.Management.Automation { bool result = GetScopeItem( lookupScope, - lookupPath, + _lookupPath, out newCurrentItem); return result; @@ -227,37 +227,37 @@ namespace System.Management.Automation // Define the lookup scope and if we have to do single // level or dynamic lookup based on the lookup variable - initialScope = sessionState.CurrentScope; + _initialScope = sessionState.CurrentScope; - if (lookupPath.IsGlobal) + if (_lookupPath.IsGlobal) { - initialScope = sessionState.GlobalScope; - isSingleScopeLookup = true; + _initialScope = sessionState.GlobalScope; + _isSingleScopeLookup = true; } - else if (lookupPath.IsLocal || - lookupPath.IsPrivate) + else if (_lookupPath.IsLocal || + _lookupPath.IsPrivate) { - initialScope = sessionState.CurrentScope; - isSingleScopeLookup = true; + _initialScope = sessionState.CurrentScope; + _isSingleScopeLookup = true; } - else if (lookupPath.IsScript) + else if (_lookupPath.IsScript) { - initialScope = sessionState.ScriptScope; - isSingleScopeLookup = true; + _initialScope = sessionState.ScriptScope; + _isSingleScopeLookup = true; } - scopeEnumerable = - new SessionStateScopeEnumerator(initialScope); + _scopeEnumerable = + new SessionStateScopeEnumerator(_initialScope); - isInitialized = true; + _isInitialized = true; } - private T current; + private T _current; protected SessionStateInternal sessionState; - private VariablePath lookupPath; - private SessionStateScopeEnumerator scopeEnumerable; - private bool isSingleScopeLookup; - private bool isInitialized; + private VariablePath _lookupPath; + private SessionStateScopeEnumerator _scopeEnumerable; + private bool _isSingleScopeLookup; + private bool _isInitialized; #endregion private members } // class ScopedItemSearcher @@ -271,7 +271,7 @@ namespace System.Management.Automation public VariableScopeItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath, - CommandOrigin origin) : base (sessionState, lookupPath) + CommandOrigin origin) : base(sessionState, lookupPath) { _origin = origin; } @@ -300,8 +300,8 @@ namespace System.Management.Automation /// /// protected override bool GetScopeItem( - SessionStateScope scope, - VariablePath name, + SessionStateScope scope, + VariablePath name, out PSVariable variable) { Diagnostics.Assert(!(name is FunctionLookupPath), @@ -333,7 +333,7 @@ namespace System.Management.Automation { public AliasScopeItemSearcher( SessionStateInternal sessionState, - VariablePath lookupPath) : base (sessionState, lookupPath) + VariablePath lookupPath) : base(sessionState, lookupPath) { } @@ -359,8 +359,8 @@ namespace System.Management.Automation /// /// protected override bool GetScopeItem( - SessionStateScope scope, - VariablePath name, + SessionStateScope scope, + VariablePath name, out AliasInfo alias) { Diagnostics.Assert(!(name is FunctionLookupPath), @@ -392,7 +392,7 @@ namespace System.Management.Automation public FunctionScopeItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath, - CommandOrigin origin) : base (sessionState, lookupPath) + CommandOrigin origin) : base(sessionState, lookupPath) { _origin = origin; } @@ -422,8 +422,8 @@ namespace System.Management.Automation /// /// protected override bool GetScopeItem( - SessionStateScope scope, - VariablePath path, + SessionStateScope scope, + VariablePath path, out FunctionInfo script) { Diagnostics.Assert(path is FunctionLookupPath, @@ -431,9 +431,9 @@ namespace System.Management.Automation bool result = true; - name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName; + _name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName; - script = scope.GetFunction(name); + script = scope.GetFunction(_name); if (script != null) @@ -473,9 +473,9 @@ namespace System.Management.Automation internal string Name { - get { return name; } + get { return _name; } } - private string name = String.Empty; + private string _name = String.Empty; } // FunctionScopeItemSearcher /// @@ -485,7 +485,7 @@ namespace System.Management.Automation { public DriveScopeItemSearcher( SessionStateInternal sessionState, - VariablePath lookupPath) : base (sessionState, lookupPath) + VariablePath lookupPath) : base(sessionState, lookupPath) { } @@ -511,8 +511,8 @@ namespace System.Management.Automation /// /// protected override bool GetScopeItem( - SessionStateScope scope, - VariablePath name, + SessionStateScope scope, + VariablePath name, out PSDriveInfo drive) { Diagnostics.Assert(!(name is FunctionLookupPath), diff --git a/src/System.Management.Automation/engine/ScriptCommand.cs b/src/System.Management.Automation/engine/ScriptCommand.cs index 4601da2a0..c1f2ab7a7 100644 --- a/src/System.Management.Automation/engine/ScriptCommand.cs +++ b/src/System.Management.Automation/engine/ScriptCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Management.Automation; diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index d81a140d8..7e0ef36f9 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -21,7 +22,7 @@ namespace System.Management.Automation { this._dontUseScopeCommandOrigin = false; this.CommandInfo = new ScriptInfo(String.Empty, scriptBlock, context); - + this._fromScriptFile = false; CommonInitialization(scriptBlock, context, useLocalScope, origin, sessionState); @@ -98,7 +99,7 @@ namespace System.Management.Automation this._rethrowExitException = this.Context.ScriptCommandProcessorShouldRethrowExit; this._context.ScriptCommandProcessorShouldRethrowExit = false; - ScriptCommand scriptCommand = new ScriptCommand {CommandInfo = this.CommandInfo}; + ScriptCommand scriptCommand = new ScriptCommand { CommandInfo = this.CommandInfo }; this.Command = scriptCommand; // WinBlue: 219115 @@ -142,7 +143,7 @@ namespace System.Management.Automation { Dictionary scriptBlockTokenCache = new Dictionary(); string unused; - HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context:Context, commandInfo:CommandInfo, + HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo, dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused); if (helpInfo == null) { @@ -230,7 +231,7 @@ namespace System.Management.Automation /// current powershell session. /// /// - internal sealed class DlrScriptCommandProcessor: ScriptCommandProcessorBase + internal sealed class DlrScriptCommandProcessor : ScriptCommandProcessorBase { private new ScriptBlock _scriptBlock; private readonly ArrayList _input = new ArrayList(); @@ -263,12 +264,12 @@ namespace System.Management.Automation Init(); } - void Init() + private void Init() { - this._scriptBlock = base._scriptBlock; - this._obsoleteAttribute = this._scriptBlock.ObsoleteAttribute; - this._runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope); - this._localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode); + _scriptBlock = base._scriptBlock; + _obsoleteAttribute = _scriptBlock.ObsoleteAttribute; + _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope); + _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode); } /// @@ -291,16 +292,16 @@ namespace System.Management.Automation _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, this.Command.MyInvocation, _context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, _context); _functionContext = new FunctionContext - { - _executionContext = _context, - _outputPipe = commandRuntime.OutputPipe, - _localsTuple = _localsTuple, - _scriptBlock = _scriptBlock, - _file = _scriptBlock.File, - _debuggerHidden = _scriptBlock.DebuggerHidden, - _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, - _sequencePoints = _scriptBlock.SequencePoints, - }; + { + _executionContext = _context, + _outputPipe = commandRuntime.OutputPipe, + _localsTuple = _localsTuple, + _scriptBlock = _scriptBlock, + _file = _scriptBlock.File, + _debuggerHidden = _scriptBlock.DebuggerHidden, + _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, + _sequencePoints = _scriptBlock.SequencePoints, + }; } /// @@ -457,11 +458,11 @@ namespace System.Management.Automation // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if ((this._scriptBlock.LanguageMode.HasValue) && - (this._scriptBlock.LanguageMode != Context.LanguageMode)) + if ((_scriptBlock.LanguageMode.HasValue) && + (_scriptBlock.LanguageMode != Context.LanguageMode)) { oldLanguageMode = Context.LanguageMode; - newLanguageMode = this._scriptBlock.LanguageMode; + newLanguageMode = _scriptBlock.LanguageMode; } try diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index 8031cb420..afc221a13 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation.Runspaces; using System.Collections.ObjectModel; @@ -60,7 +61,7 @@ namespace System.Management.Automation /// internal override CommandInfo CreateGetCommandCopy(object[] argumentList) { - ScriptInfo copy = new ScriptInfo(this) {IsGetCommandCopy = true, Arguments = argumentList}; + ScriptInfo copy = new ScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList }; return copy; } @@ -68,7 +69,7 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { - get { return HelpCategory.ScriptCommand; } + get { return HelpCategory.ScriptCommand; } } /// @@ -127,6 +128,6 @@ namespace System.Management.Automation new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } - CommandMetadata _commandMetadata; + private CommandMetadata _commandMetadata; } // ScriptInfo } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs index bfbb4b7f7..e181cece4 100644 --- a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System.Collections.ObjectModel; using System.Security.AccessControl; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -42,8 +42,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("cmdlet"); } - this.cmdlet = cmdlet; - this.sessionState = cmdlet.Context.EngineSessionState; + _cmdlet = cmdlet; + _sessionState = cmdlet.Context.EngineSessionState; } // CmdletProviderIntrinsics internal /// @@ -61,7 +61,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // CmdletProviderIntrinsics internal #endregion Constructors @@ -89,11 +89,11 @@ namespace System.Management.Automation public Collection Get(string path, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetSecurityDescriptor(path, includeSections); + return _sessionState.GetSecurityDescriptor(path, includeSections); } // GetSecurityDescriptor /// @@ -120,11 +120,11 @@ namespace System.Management.Automation CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.GetSecurityDescriptor(path, includeSections, context); + _sessionState.GetSecurityDescriptor(path, includeSections, context); } // GetSecurityDescriptor #endregion GetSecurityDescriptor @@ -149,11 +149,11 @@ namespace System.Management.Automation public Collection Set(string path, ObjectSecurity sd) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - Collection result = sessionState.SetSecurityDescriptor(path, sd); + Collection result = _sessionState.SetSecurityDescriptor(path, sd); return result; } // SetSecurityDescriptor @@ -179,12 +179,12 @@ namespace System.Management.Automation internal void Set(string path, ObjectSecurity sd, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.SetSecurityDescriptor(path, sd, context); + _sessionState.SetSecurityDescriptor(path, sd, context); } // SetSecurityDescriptor #endregion SetSecurityDescriptor @@ -210,11 +210,11 @@ namespace System.Management.Automation public ObjectSecurity NewFromPath(string path, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewSecurityDescriptorFromPath(path, includeSections); + return _sessionState.NewSecurityDescriptorFromPath(path, includeSections); } // NewSecurityDescriptor @@ -241,12 +241,12 @@ namespace System.Management.Automation public ObjectSecurity NewOfType(string providerId, string type, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.NewSecurityDescriptorOfType(providerId, + return _sessionState.NewSecurityDescriptorOfType(providerId, type, includeSections); } // NewSecurityDescriptor @@ -257,8 +257,8 @@ namespace System.Management.Automation #region private data - private Cmdlet cmdlet; - private SessionStateInternal sessionState; + private Cmdlet _cmdlet; + private SessionStateInternal _sessionState; #endregion private data } // SecurityDescriptorCmdletProviderIntrinsics diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 0d06b776e..cbdd0b03c 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -2,7 +2,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Reflection; using System.Collections; using System.Security; @@ -10,7 +10,6 @@ using System.Management.Automation.Host; namespace System.Management.Automation { - /// /// This enum defines the dispatch origin of a command. /// @@ -47,7 +46,7 @@ namespace System.Management.Automation { #region constructor - private string shellId; + private string _shellId; /// /// Creates an instance of authorization manager using specified shellID /// @@ -55,12 +54,12 @@ namespace System.Management.Automation /// public AuthorizationManager(string shellId) { - this.shellId = shellId; + _shellId = shellId; } #endregion constructor - private object policyCheckLock = new object(); + private object _policyCheckLock = new object(); #region methods to use internally @@ -111,7 +110,7 @@ namespace System.Management.Automation try { - lock (policyCheckLock) + lock (_policyCheckLock) { result = this.ShouldRun(commandInfo, origin, host, out authorizationManagerException); } @@ -123,8 +122,6 @@ namespace System.Management.Automation while(Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } } #endif - - } catch (Exception e) // Catch-all OK. 3rd party callout { @@ -170,7 +167,7 @@ namespace System.Management.Automation { get { - return shellId; + return _shellId; } } @@ -206,7 +203,6 @@ namespace System.Management.Automation } #endregion methods for derived class to override - } } diff --git a/src/System.Management.Automation/engine/SerializationStrings.cs b/src/System.Management.Automation/engine/SerializationStrings.cs index bdd2b6677..92e1494bd 100644 --- a/src/System.Management.Automation/engine/SerializationStrings.cs +++ b/src/System.Management.Automation/engine/SerializationStrings.cs @@ -2,6 +2,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation { /// @@ -22,7 +23,7 @@ namespace System.Management.Automation /// Element tag for PSObject /// internal const string PSObjectTag = "Obj"; - + /// /// Element tag for properties /// @@ -204,7 +205,7 @@ namespace System.Management.Automation /// /// This property is used for System.Security.SecureString type internal const string SecureStringTag = "SS"; - + /// /// Element tag for unsignedShort property. /// @@ -288,7 +289,7 @@ namespace System.Management.Automation /// String for stream attribute /// internal const string StreamNameAttribute = "S"; - + #endregion attribute tags #region namespace values diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 99f6166e2..653fa0cbc 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -9,7 +9,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation.Runspaces; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation @@ -21,7 +21,6 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a bridge class between internal classes and a public interface. It requires this much coupling.")] internal sealed partial class SessionStateInternal { - #region tracer /// @@ -29,10 +28,10 @@ namespace System.Management.Automation /// using "SessionState" as the category. /// [Dbg.TraceSourceAttribute( - "SessionState", + "SessionState", "SessionState Class")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("SessionState", + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("SessionState", "SessionState Class"); #endregion tracer @@ -61,16 +60,16 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("context"); } - this._context = context; + _context = context; // Create the working directory stack. This // is used for the pushd and popd commands - workingLocationStack = new Dictionary>(StringComparer.OrdinalIgnoreCase); + _workingLocationStack = new Dictionary>(StringComparer.OrdinalIgnoreCase); _globalScope = new SessionStateScope(null); _moduleScope = _globalScope; - currentScope = _globalScope; + _currentScope = _globalScope; InitializeSessionStateInternalSpecialVariables(false); @@ -101,7 +100,7 @@ namespace System.Management.Automation } else { - currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); + _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); } } @@ -148,14 +147,14 @@ namespace System.Management.Automation { get { - if (globberPrivate == null) + if (_globberPrivate == null) { - globberPrivate = _context.LocationGlobber; + _globberPrivate = _context.LocationGlobber; } - return globberPrivate; + return _globberPrivate; } } - private LocationGlobber globberPrivate; + private LocationGlobber _globberPrivate; /// /// The context of the runspace to which this session state object belongs. @@ -213,7 +212,7 @@ namespace System.Management.Automation // This is used to maintain the order in which modules were imported. // This is used by Get-Command -All to order by last imported internal List ModuleTableKeys = new List(); - + /// /// The private module table for this session state object... /// @@ -257,7 +256,7 @@ namespace System.Management.Automation { get { return _scripts; } } - List _scripts = new List(new string[] { "*" }); + private List _scripts = new List(new string[] { "*" }); /// /// See if a script is allowed to be run. @@ -277,7 +276,7 @@ namespace System.Management.Automation { get { return _applications; } } - List _applications = new List(new string[] { "*" }); + private List _applications = new List(new string[] { "*" }); /// @@ -437,7 +436,7 @@ namespace System.Management.Automation // $Console - set the console file for this shell, if there is one, "" otherwise... string consoleFileName = string.Empty; RunspaceConfigForSingleShell rcss = _context.RunspaceConfiguration as RunspaceConfigForSingleShell; - if (rcss != null && rcss.ConsoleInfo != null && ! string.IsNullOrEmpty(rcss.ConsoleInfo.Filename)) + if (rcss != null && rcss.ConsoleInfo != null && !string.IsNullOrEmpty(rcss.ConsoleInfo.Filename)) { consoleFileName = rcss.ConsoleInfo.Filename; } @@ -518,7 +517,7 @@ namespace System.Management.Automation if (String.Equals(p, path, StringComparison.OrdinalIgnoreCase)) return SessionStateEntryVisibility.Public; - if(WildcardPattern.ContainsWildcardCharacters(p)) + if (WildcardPattern.ContainsWildcardCharacters(p)) { WildcardPattern pattern = WildcardPattern.Get(p, WildcardOptions.IgnoreCase); if (pattern.IsMatch(path)) @@ -530,7 +529,7 @@ namespace System.Management.Automation return SessionStateEntryVisibility.Private; } - #if RELATIONSHIP_SUPPORTED +#if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release /// @@ -545,7 +544,7 @@ namespace System.Management.Automation #endif #endregion Private data - + /// /// Notification for SessionState to do cleanup /// before runspace is closed. @@ -557,12 +556,12 @@ namespace System.Management.Automation { // Remove all providers at the top level... - CmdletProviderContext context = new CmdletProviderContext (this.ExecutionContext); + CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); - Collection keys = new Collection (); + Collection keys = new Collection(); foreach (string key in Providers.Keys) { - keys.Add (key); + keys.Add(key); } foreach (string providerName in keys) @@ -573,7 +572,7 @@ namespace System.Management.Automation } } } - + #region Errors /// @@ -622,7 +621,7 @@ namespace System.Management.Automation return NewProviderInvocationException(resourceId, resourceStr, provider, path, e, true); } - + /// /// Constructs a new instance of a ProviderInvocationException /// using the specified data @@ -664,7 +663,7 @@ namespace System.Management.Automation /// and then throws it. /// /// - internal ProviderInvocationException NewProviderInvocationException ( + internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, @@ -683,12 +682,12 @@ namespace System.Management.Automation return pie; } - pie = new ProviderInvocationException (resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); + pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( - this._context, + _context, provider.Name, pie, Severity.Warning); @@ -697,6 +696,4 @@ namespace System.Management.Automation } #endregion Errors } // SessionStateInternal class - - } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs index f89d25d54..172c0f738 100644 --- a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Management.Automation.Runspaces; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation @@ -48,7 +49,7 @@ namespace System.Management.Automation new Dictionary(StringComparer.OrdinalIgnoreCase); SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -60,7 +61,7 @@ namespace System.Management.Automation // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || - scope == currentScope) + scope == _currentScope) { result.Add(entry.Name, entry); } @@ -104,7 +105,7 @@ namespace System.Management.Automation // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || - scope == currentScope) + scope == _currentScope) { result.Add(entry.Name, entry); } @@ -125,7 +126,7 @@ namespace System.Management.Automation } private List _exportedAliases = new List(); - + /// /// Gets the value of the specified alias from the alias table. /// @@ -154,7 +155,7 @@ namespace System.Management.Automation // appropriate scoping rules SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -169,7 +170,7 @@ namespace System.Management.Automation // scope is the same scope the alias was retrieved from. if ((result.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { result = null; } @@ -244,7 +245,7 @@ namespace System.Management.Automation if (result != null && (result.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { result = null; } @@ -300,7 +301,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("value"); } - AliasInfo info = currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin); + AliasInfo info = _currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin); return info; } // SetAliasValue @@ -385,7 +386,7 @@ namespace System.Management.Automation /// /// internal AliasInfo SetAliasValue( - string aliasName, + string aliasName, string value, ScopedItemOptions options, bool force, @@ -401,10 +402,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("value"); } - AliasInfo info = currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin); + AliasInfo info = _currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin); return info; - } // SetAliasValue /// @@ -493,7 +493,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("alias"); } - AliasInfo info = currentScope.SetAliasItem(alias, force, origin); + AliasInfo info = _currentScope.SetAliasItem(alias, force, origin); return info; } // SetAliasItem @@ -563,13 +563,13 @@ namespace System.Management.Automation } SessionStateScope scope = GetScopeByID(scopeID); - + AliasInfo info = scope.SetAliasItem(alias, force, origin); return info; } // SetAliasItemAtScope - /// + /// /// Sets the alias with specified name to the specified value in the current scope. /// /// @@ -618,7 +618,7 @@ namespace System.Management.Automation { return SetAliasItemAtScope(alias, scopeID, force, CommandOrigin.Internal); } - + /// /// Removes the specified alias. /// @@ -649,7 +649,7 @@ namespace System.Management.Automation // Use the scope enumerator to find an existing function SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -663,7 +663,7 @@ namespace System.Management.Automation // scope is the same scope the alias was retrieved from. if ((alias.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { alias = null; } @@ -685,7 +685,7 @@ namespace System.Management.Automation internal IEnumerable GetAliasesByCommandName(string command) { SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { diff --git a/src/System.Management.Automation/engine/SessionStateCapacityVariable.cs b/src/System.Management.Automation/engine/SessionStateCapacityVariable.cs index d722eded6..0b9fa267c 100644 --- a/src/System.Management.Automation/engine/SessionStateCapacityVariable.cs +++ b/src/System.Management.Automation/engine/SessionStateCapacityVariable.cs @@ -53,8 +53,8 @@ namespace System.Management.Automation ValidateRangeAttribute validateRange = new ValidateRangeAttribute(minCapacity, maxCapacity); - this.minCapacity = minCapacity; - this.maxCapacity = maxCapacity; + _minCapacity = minCapacity; + _maxCapacity = maxCapacity; base.Attributes.Add(validateRange); _fastValue = defaultCapacity; } @@ -87,14 +87,14 @@ namespace System.Management.Automation new ValidateRangeAttribute(0, int.MaxValue); base.Attributes.Add(validateRange); - this.sharedCapacityVariable = sharedCapacityVariable; + _sharedCapacityVariable = sharedCapacityVariable; // Also propagate the description to prevent re-fetching them from the // resource manager. That causes a measurable performance degradation. this.Description = sharedCapacityVariable.Description; // Initialize the fast value... - _fastValue = (int) sharedCapacityVariable.Value; + _fastValue = (int)sharedCapacityVariable.Value; } #endregion ctor @@ -110,9 +110,9 @@ namespace System.Management.Automation { object result; - if (sharedCapacityVariable != null) + if (_sharedCapacityVariable != null) { - result = sharedCapacityVariable.Value; + result = _sharedCapacityVariable.Value; } else { @@ -123,7 +123,7 @@ namespace System.Management.Automation set { - sharedCapacityVariable = null; + _sharedCapacityVariable = null; base.Value = LanguagePrimitives.ConvertTo(value, typeof(int), CultureInfo.InvariantCulture); _fastValue = (int)base.Value; } @@ -162,16 +162,16 @@ namespace System.Management.Automation // If the value is within the limits, then return true // otherwise call the base validator so we'll get the error // from the validation attribute... - if (capacity >= minCapacity && capacity <= maxCapacity) + if (capacity >= _minCapacity && capacity <= _maxCapacity) return true; else - return base.IsValidValue (value); + return base.IsValidValue(value); } - private int minCapacity; - private int maxCapacity = int.MaxValue; + private int _minCapacity; + private int _maxCapacity = int.MaxValue; - private SessionStateCapacityVariable sharedCapacityVariable; + private SessionStateCapacityVariable _sharedCapacityVariable; } // class SessionStateCapacityVariable - } +} diff --git a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs index c0ea9a936..d86ca15f3 100644 --- a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using Dbg = System.Management.Automation; @@ -60,7 +61,7 @@ namespace System.Management.Automation // appropriate scoping rules SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -75,7 +76,7 @@ namespace System.Management.Automation // scope is the same scope the cmdlet was retrieved from. if ((result.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { result = null; } @@ -133,7 +134,7 @@ namespace System.Management.Automation if (result != null && (result.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { result = null; } @@ -151,7 +152,7 @@ namespace System.Management.Automation new Dictionary>(StringComparer.OrdinalIgnoreCase); SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -166,7 +167,7 @@ namespace System.Management.Automation foreach (CmdletInfo cmdletInfo in entry.Value) { if ((cmdletInfo.Options & ScopedItemOptions.Private) == 0 || - scope == currentScope) + scope == _currentScope) { toBeAdded.Add(cmdletInfo); } @@ -213,9 +214,8 @@ namespace System.Management.Automation List toBeAdded = new List(); foreach (CmdletInfo cmdletInfo in entry.Value) { - if ((cmdletInfo.Options & ScopedItemOptions.Private) == 0 || - scope == currentScope) + scope == _currentScope) { toBeAdded.Add(cmdletInfo); } @@ -269,7 +269,7 @@ namespace System.Management.Automation // Use the scope enumerator to find an existing function SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -283,7 +283,7 @@ namespace System.Management.Automation // scope is the same scope the cmdlet was retrieved from. if ((cmdletInfo.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { cmdletInfo = null; } @@ -326,7 +326,7 @@ namespace System.Management.Automation // Use the scope enumerator to find an existing function SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); foreach (SessionStateScope scope in scopeEnumerator) { @@ -339,7 +339,7 @@ namespace System.Management.Automation // scope is the same scope the cmdlet was retrieved from. if ((cmdletInfo.Options & ScopedItemOptions.Private) != 0 && - scope != currentScope) + scope != _currentScope) { cmdletInfo = null; } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 5cc6d8134..4d4292020 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.ObjectModel; using System.Management.Automation.Provider; @@ -713,7 +714,6 @@ namespace System.Management.Automation foreach (string providerPath in providerPaths) { - result = IsItemContainer(providerInstance, providerPath, context); if (result == false) { @@ -2758,11 +2758,10 @@ namespace System.Management.Automation if (recurse) { // Now get all the children that are containers and recurse into them - + // Limiter for recursion if (depth > 0) // this includes special case 'depth == uint.MaxValue' for unlimited recursion { - GetChildNames( providerInstance, newProviderPath, @@ -3714,13 +3713,13 @@ namespace System.Management.Automation bool isSymbolicJunctionOrHardLink = false; // Symbolic link targets are allowed to not exist on both Windows and Linux bool allowNonexistingPath = false; - - if(type != null) + + if (type != null) { WildcardPattern typeEvaluator = WildcardPattern.Get(type + "*", WildcardOptions.IgnoreCase | WildcardOptions.Compiled); if (typeEvaluator.IsMatch("symboliclink") || typeEvaluator.IsMatch("junction") || typeEvaluator.IsMatch("hardlink")) - { + { isSymbolicJunctionOrHardLink = true; allowNonexistingPath = typeEvaluator.IsMatch("symboliclink"); } @@ -3750,22 +3749,22 @@ namespace System.Management.Automation out targetProvider, out targetProviderInstance); - if(String.Compare(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase) != 0) + if (String.Compare(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase) != 0) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.MustBeFileSystemPath); } - - if(globbedTarget.Count > 1) + + if (globbedTarget.Count > 1) { throw PSTraceSource.NewInvalidOperationException(SessionStateStrings.PathResolvedToMultiple, targetPath); } - if(globbedTarget.Count == 0) + if (globbedTarget.Count == 0) { throw PSTraceSource.NewInvalidOperationException(SessionStateStrings.PathNotFound, targetPath); } - content = globbedTarget[0]; + content = globbedTarget[0]; } NewItemPrivate(providerInstance, composedPath, type, content, context); @@ -4544,12 +4543,12 @@ namespace System.Management.Automation if (!destinationIsRemote) { - providerDestinationPath = - Globber.GetProviderPath( - copyPath, - context, - out destinationProvider, - out unusedDrive); + providerDestinationPath = + Globber.GetProviderPath( + copyPath, + context, + out destinationProvider, + out unusedDrive); } else { @@ -4561,14 +4560,14 @@ namespace System.Management.Automation new ArgumentNullException( String.Format( System.Globalization.CultureInfo.InvariantCulture, - SessionStateStrings.CopyItemRemotelyPathIsNullOrEmpty, + SessionStateStrings.CopyItemRemotelyPathIsNullOrEmpty, "Destination")), "CopyItemRemoteDestinationIsNullOrEmpty", ErrorCategory.InvalidArgument, providerDestinationPath)); return; } - + string root = ValidateRemotePathAndGetRoot(providerDestinationPath, session, context, remoteLanguageMode, false); if (root == null) { @@ -4576,7 +4575,7 @@ namespace System.Management.Automation } } - tracer.WriteLine("providerDestinationPath = {0}", providerDestinationPath); + s_tracer.WriteLine("providerDestinationPath = {0}", providerDestinationPath); ProviderInfo provider = null; CmdletProvider providerInstance = null; @@ -4599,7 +4598,7 @@ namespace System.Management.Automation return; } - providerInstance = this._context.SessionState.Internal.GetProviderInstance("FileSystem"); + providerInstance = _context.SessionState.Internal.GetProviderInstance("FileSystem"); providerPaths = new Collection(); providerPaths.Add(path); } @@ -4633,7 +4632,7 @@ namespace System.Management.Automation return; } - + bool destinationIsContainer = false; if (!destinationIsRemote) @@ -4643,7 +4642,7 @@ namespace System.Management.Automation providerDestinationPath, context); - tracer.WriteLine("destinationIsContainer = {0}", destinationIsContainer); + s_tracer.WriteLine("destinationIsContainer = {0}", destinationIsContainer); } foreach (string providerPath in providerPaths) @@ -4671,7 +4670,7 @@ namespace System.Management.Automation providerPath, context); - tracer.WriteLine("sourcIsContainer = {0}", sourceIsContainer); + s_tracer.WriteLine("sourcIsContainer = {0}", sourceIsContainer); if (sourceIsContainer) { @@ -4692,7 +4691,6 @@ namespace System.Management.Automation "CopyContainerToContainerWithoutRecurseOrContainer", ErrorCategory.InvalidArgument, providerPath)); - } else if (recurse && copyContainers == CopyContainers.CopyChildrenOfTargetContainer) { @@ -4715,7 +4713,6 @@ namespace System.Management.Automation recurse, context); } - } else { @@ -4852,7 +4849,6 @@ namespace System.Management.Automation path, e); } - } // CopyItem /// @@ -5046,7 +5042,7 @@ namespace System.Management.Automation if (fileSystemProviders.Count > 0) { providerPath = path; - providerInstance = this._context.EngineSessionState.GetProviderInstance( + providerInstance = _context.EngineSessionState.GetProviderInstance( fileSystemProviders[0]); } } @@ -5229,7 +5225,7 @@ namespace System.Management.Automation // If the remote path is not absolute, display an error to the user. if (op["IsAbsolute"] != null) { - bool isAbsolute = (bool) op["IsAbsolute"]; + bool isAbsolute = (bool)op["IsAbsolute"]; if (!isAbsolute) { context.WriteError(new ErrorRecord( @@ -5281,8 +5277,8 @@ namespace System.Management.Automation { context.WriteError(new ErrorRecord( new InvalidOperationException( - String.Format(System.Globalization.CultureInfo.InvariantCulture, - SessionStateStrings.CopyItemSessionProperties, + String.Format(System.Globalization.CultureInfo.InvariantCulture, + SessionStateStrings.CopyItemSessionProperties, "Availability", session.Availability)), "SessionIsNotAvailable", ErrorCategory.InvalidOperation, @@ -5296,7 +5292,7 @@ namespace System.Management.Automation return true; } - + #endregion CopyItem #endregion ContainerCmdletProvider accessors @@ -5318,7 +5314,6 @@ namespace System.Management.Automation /// Delete = 2 } - } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/SessionStateContent.cs b/src/System.Management.Automation/engine/SessionStateContent.cs index 20a82587c..0d8061f2a 100644 --- a/src/System.Management.Automation/engine/SessionStateContent.cs +++ b/src/System.Management.Automation/engine/SessionStateContent.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -195,8 +196,8 @@ namespace System.Management.Automation /// /// private IContentReader GetContentReaderPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -287,7 +288,7 @@ namespace System.Management.Automation /// /// internal object GetContentReaderDynamicParameters( - string path, + string path, CmdletProviderContext context) { if (path == null) @@ -356,7 +357,7 @@ namespace System.Management.Automation /// /// private object GetContentReaderDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, CmdletProviderContext context) { @@ -406,7 +407,7 @@ namespace System.Management.Automation } return result; } // GetContentReaderDynamicParameters - + #endregion GetContentReader #region GetContentWriter @@ -584,8 +585,8 @@ namespace System.Management.Automation /// /// private IContentWriter GetContentWriterPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -675,7 +676,7 @@ namespace System.Management.Automation /// /// internal object GetContentWriterDynamicParameters( - string path, + string path, CmdletProviderContext context) { if (path == null) @@ -744,7 +745,7 @@ namespace System.Management.Automation /// /// private object GetContentWriterDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, CmdletProviderContext context) { @@ -785,7 +786,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetContentWriterDynamicParametersProviderException", SessionStateStrings.GetContentWriterDynamicParametersProviderException, providerInstance.ProviderInfo, @@ -794,9 +795,9 @@ namespace System.Management.Automation } return result; } // GetContentWriterDynamicParameters - + #endregion GetContentWriter - + #region ClearContent /// @@ -953,8 +954,8 @@ namespace System.Management.Automation /// /// private void ClearContentPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1042,7 +1043,7 @@ namespace System.Management.Automation /// /// internal object ClearContentDynamicParameters( - string path, + string path, CmdletProviderContext context) { if (path == null) @@ -1110,7 +1111,7 @@ namespace System.Management.Automation /// /// private object ClearContentDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, CmdletProviderContext context) { @@ -1160,7 +1161,7 @@ namespace System.Management.Automation } return result; } // ClearContentDynamicParameters - + #endregion ClearContent #endregion IContentCmdletProvider accessors diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 618189068..e11597a93 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -7,7 +7,7 @@ using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Globalization; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings @@ -23,7 +23,7 @@ namespace System.Management.Automation /// /// The currently active drive. It determines the current working directory. /// - private PSDriveInfo currentDrive; + private PSDriveInfo _currentDrive; #region NewDrive @@ -204,7 +204,7 @@ namespace System.Management.Automation try { - SessionStateScope scope = currentScope; + SessionStateScope scope = _currentScope; if (!String.IsNullOrEmpty(scopeID)) { @@ -270,7 +270,7 @@ namespace System.Management.Automation break; } - if (name.IndexOfAny( _charactersInvalidInDriveName ) >= 0) + if (name.IndexOfAny(s_charactersInvalidInDriveName) >= 0) { result = false; break; @@ -279,7 +279,7 @@ namespace System.Management.Automation return result; } // IsValidDriveName - private static char[] _charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; + private static char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; /// /// Tries to resolve the drive root as an MSH path. If it successfully resolves @@ -447,7 +447,7 @@ namespace System.Management.Automation #endregion NewDrive #region GetDrive - + /// /// Searches through the session state scopes to find a drive /// @@ -478,7 +478,6 @@ namespace System.Management.Automation if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); - } PSDriveInfo result = null; @@ -498,26 +497,23 @@ namespace System.Management.Automation { if (result.IsAutoMounted) { - - // Validate or remove the auto-mounted drive + // Validate or remove the auto-mounted drive - if (!ValidateOrRemoveAutoMountedDrive(result, processingScope)) - { - result = null; - } - + if (!ValidateOrRemoveAutoMountedDrive(result, processingScope)) + { + result = null; + } } if (result != null) { - tracer.WriteLine("Drive found in scope {0}", scopeID); + s_tracer.WriteLine("Drive found in scope {0}", scopeID); break; } } // Increment the scope ID ++scopeID; - } // foreach scope if (result == null && automount) @@ -584,7 +580,6 @@ namespace System.Management.Automation if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); - } PSDriveInfo result = null; @@ -700,7 +695,7 @@ namespace System.Management.Automation if (!IsProviderLoaded(this.ExecutionContext.ProviderNames.FileSystem)) { - tracer.WriteLine("The {0} provider is not loaded", this.ExecutionContext.ProviderNames.FileSystem); + s_tracer.WriteLine("The {0} provider is not loaded", this.ExecutionContext.ProviderNames.FileSystem); return result; } @@ -813,7 +808,7 @@ namespace System.Management.Automation internal static void MountDefaultDrive(string name, ExecutionContext context) { - PSModuleAutoLoadingPreference moduleAutoLoadingPreference = + PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if (moduleAutoLoadingPreference == PSModuleAutoLoadingPreference.None) { @@ -832,17 +827,17 @@ namespace System.Management.Automation { moduleName = "Microsoft.PowerShell.Security"; } - else if(String.Equals("WSMan", name, StringComparison.OrdinalIgnoreCase)) + else if (String.Equals("WSMan", name, StringComparison.OrdinalIgnoreCase)) { moduleName = "Microsoft.WSMan.Management"; } if (!String.IsNullOrEmpty(moduleName)) { - tracer.WriteLine("Auto-mounting built-in drive: {0}", name); + s_tracer.WriteLine("Auto-mounting built-in drive: {0}", name); CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null, null, context); Exception exception = null; - tracer.WriteLine("Attempting to load module: {0}", moduleName); + s_tracer.WriteLine("Attempting to load module: {0}", moduleName); CommandDiscovery.AutoloadSpecifiedModule(moduleName, context, commandInfo.Visibility, out exception); if (exception != null) { @@ -1002,7 +997,6 @@ namespace System.Management.Automation } } } - } catch (ArgumentException) { @@ -1180,7 +1174,6 @@ namespace System.Management.Automation { context.ThrowFirstErrorOrDoNothing(); } - } // RemoveDrive /// @@ -1212,9 +1205,9 @@ namespace System.Management.Automation /// /// internal void RemoveDrive( - PSDriveInfo drive, - bool force, - string scopeID, + PSDriveInfo drive, + bool force, + string scopeID, CmdletProviderContext context) { // Make sure that the CanRemoveDrive is called even if we are forcing @@ -1222,7 +1215,7 @@ namespace System.Management.Automation // cleanup. bool canRemove = false; - + try { canRemove = CanRemoveDrive(drive, context); @@ -1303,17 +1296,16 @@ namespace System.Management.Automation { PSInvalidOperationException e = (PSInvalidOperationException) - PSTraceSource.NewInvalidOperationException ( + PSTraceSource.NewInvalidOperationException( SessionStateStrings.DriveRemovalPreventedByProvider, - drive.Name, + drive.Name, drive.Provider); - context.WriteError ( - new ErrorRecord ( + context.WriteError( + new ErrorRecord( e.ErrorRecord, e)); } - } // RemoveDrive /// @@ -1353,7 +1345,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("drive"); } - tracer.WriteLine("Drive name = {0}", drive.Name); + s_tracer.WriteLine("Drive name = {0}", drive.Name); // First set the drive data @@ -1408,13 +1400,12 @@ namespace System.Management.Automation } return driveRemovable; - } // CanRemoveDrive #endregion RemoveDrive #region Drives - + /// /// Gets an enumerable list of the drives that are mounted in /// the specified scope. @@ -1439,7 +1430,7 @@ namespace System.Management.Automation { Dictionary driveTable = new Dictionary(); - SessionStateScope startingScope = this.currentScope; + SessionStateScope startingScope = _currentScope; if (!String.IsNullOrEmpty(scope)) { @@ -1450,11 +1441,11 @@ namespace System.Management.Automation new SessionStateScopeEnumerator(startingScope); DriveInfo[] alldrives = DriveInfo.GetDrives(); Collection driveNames = new Collection(); - foreach(DriveInfo drive in alldrives) + foreach (DriveInfo drive in alldrives) { - driveNames.Add(drive.Name.Substring(0,1)); + driveNames.Add(drive.Name.Substring(0, 1)); } - + foreach (SessionStateScope lookupScope in scopeEnumerator) { @@ -1475,13 +1466,13 @@ namespace System.Management.Automation driveIsValid = ValidateOrRemoveAutoMountedDrive(drive, lookupScope); } #endif - if(drive.Name.Length == 1) + if (drive.Name.Length == 1) { - if(!(driveNames.Contains(drive.Name))) + if (!(driveNames.Contains(drive.Name))) driveTable.Remove(drive.Name); } - - + + if (driveIsValid && !driveTable.ContainsKey(drive.Name)) { @@ -1550,7 +1541,7 @@ namespace System.Management.Automation if (this != _context.TopLevelSessionState) return _context.TopLevelSessionState.CurrentDrive; else - return currentDrive; + return _currentDrive; } // get set @@ -1558,11 +1549,10 @@ namespace System.Management.Automation if (this != _context.TopLevelSessionState) _context.TopLevelSessionState.CurrentDrive = value; else - currentDrive = value; + _currentDrive = value; } // set } // CurrentDrive } // SessionStateInternal class - } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs index 20853a303..1f30789df 100644 --- a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -74,9 +75,9 @@ namespace System.Management.Automation /// /// internal Collection NewProperty( - string[] paths, - string property, - string type, + string[] paths, + string property, + string type, object value, bool force, bool literalPath) @@ -241,8 +242,8 @@ namespace System.Management.Automation /// /// private void NewProperty( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, string property, string type, object value, @@ -288,7 +289,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "NewPropertyProviderException", SessionStateStrings.NewPropertyProviderException, providerInstance.ProviderInfo, @@ -349,7 +350,7 @@ namespace System.Management.Automation /// /// internal object NewPropertyDynamicParameters( - string path, + string path, string propertyName, string type, object value, @@ -434,7 +435,7 @@ namespace System.Management.Automation /// /// private object NewPropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string propertyName, string type, @@ -478,7 +479,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "NewPropertyDynamicParametersProviderException", SessionStateStrings.NewPropertyDynamicParametersProviderException, providerInstance.ProviderInfo, @@ -487,7 +488,7 @@ namespace System.Management.Automation } return result; } // NewPropertyDynamicParameters - + #endregion NewProperty #region RemoveProperty @@ -669,8 +670,8 @@ namespace System.Management.Automation /// /// private void RemoveProperty( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, string property, CmdletProviderContext context) { @@ -714,7 +715,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "RemovePropertyProviderException", SessionStateStrings.RemovePropertyProviderException, providerInstance.ProviderInfo, @@ -767,7 +768,7 @@ namespace System.Management.Automation /// /// internal object RemovePropertyDynamicParameters( - string path, + string path, string propertyName, CmdletProviderContext context) { @@ -842,7 +843,7 @@ namespace System.Management.Automation /// /// private object RemovePropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string propertyName, CmdletProviderContext context) @@ -885,7 +886,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "RemovePropertyDynamicParametersProviderException", SessionStateStrings.RemovePropertyDynamicParametersProviderException, providerInstance.ProviderInfo, @@ -953,8 +954,8 @@ namespace System.Management.Automation /// internal Collection CopyProperty( string[] sourcePaths, - string sourceProperty, - string destinationPath, + string sourceProperty, + string destinationPath, string destinationProperty, bool force, bool literalPath) @@ -1171,8 +1172,8 @@ namespace System.Management.Automation /// /// private void CopyProperty( - CmdletProvider providerInstance, - string sourcePath, + CmdletProvider providerInstance, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, @@ -1226,7 +1227,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "CopyPropertyProviderException", SessionStateStrings.CopyPropertyProviderException, providerInstance.ProviderInfo, @@ -1287,7 +1288,7 @@ namespace System.Management.Automation /// /// internal object CopyPropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationPath, string destinationProperty, @@ -1321,8 +1322,8 @@ namespace System.Management.Automation // Get the dynamic parameters for the first resolved path return CopyPropertyDynamicParameters( - providerInstance, - providerPaths[0], + providerInstance, + providerPaths[0], sourceProperty, destinationPath, destinationProperty, @@ -1377,7 +1378,7 @@ namespace System.Management.Automation /// /// private object CopyPropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string sourceProperty, string destinationPath, @@ -1498,8 +1499,8 @@ namespace System.Management.Automation /// internal Collection MoveProperty( string[] sourcePaths, - string sourceProperty, - string destinationPath, + string sourceProperty, + string destinationPath, string destinationProperty, bool force, bool literalPath) @@ -1643,12 +1644,12 @@ namespace System.Management.Automation if (destinationProviderPaths.Count > 1) { - ArgumentException argException = + ArgumentException argException = PSTraceSource.NewArgumentException( "destinationPath", SessionStateStrings.MovePropertyDestinationResolveToSingle); - context.WriteError (new ErrorRecord (argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destinationProviderPaths)); + context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destinationProviderPaths)); } else { @@ -1717,8 +1718,8 @@ namespace System.Management.Automation /// /// private void MoveProperty( - CmdletProvider providerInstance, - string sourcePath, + CmdletProvider providerInstance, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty, @@ -1833,7 +1834,7 @@ namespace System.Management.Automation /// /// internal object MovePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationPath, string destinationProperty, @@ -1867,8 +1868,8 @@ namespace System.Management.Automation // Get the dynamic parameters for the first resolved path return MovePropertyDynamicParameters( - providerInstance, - providerPaths[0], + providerInstance, + providerPaths[0], sourceProperty, destinationPath, destinationProperty, @@ -1923,7 +1924,7 @@ namespace System.Management.Automation /// /// private object MovePropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string sourceProperty, string destinationPath, @@ -1983,7 +1984,7 @@ namespace System.Management.Automation } return result; } // MovePropertyDynamicParameters - + #endregion MoveProperty #region RenameProperty @@ -2036,7 +2037,7 @@ namespace System.Management.Automation /// internal Collection RenameProperty( string[] sourcePaths, - string sourceProperty, + string sourceProperty, string destinationProperty, bool force, bool literalPath) @@ -2199,8 +2200,8 @@ namespace System.Management.Automation /// /// private void RenameProperty( - CmdletProvider providerInstance, - string sourcePath, + CmdletProvider providerInstance, + string sourcePath, string sourceProperty, string destinationProperty, CmdletProviderContext context) @@ -2306,7 +2307,7 @@ namespace System.Management.Automation /// /// internal object RenamePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationProperty, CmdletProviderContext context) @@ -2339,8 +2340,8 @@ namespace System.Management.Automation // Get the dynamic parameters for the first resolved path return RenamePropertyDynamicParameters( - providerInstance, - providerPaths[0], + providerInstance, + providerPaths[0], sourceProperty, destinationProperty, newContext); @@ -2390,7 +2391,7 @@ namespace System.Management.Automation /// /// private object RenamePropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string sourceProperty, string destinationProperty, @@ -2451,7 +2452,6 @@ namespace System.Management.Automation #endregion IDynamicPropertyCmdletProvider accessors } // SessionStateInternal class - } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index fa8464386..5a700f461 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -1,12 +1,13 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using Dbg=System.Management.Automation.Diagnostics; +using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation @@ -62,9 +63,9 @@ namespace System.Management.Automation /// /// internal IDictionary GetFunctionTable() - { + { SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -116,7 +117,7 @@ namespace System.Management.Automation // scope is the same scope the alias was retrieved from. if ((entry.Options & ScopedItemOptions.Private) == 0 || - scope == currentScope) + scope == _currentScope) { result.Add(entry.Name, entry); } @@ -218,7 +219,7 @@ namespace System.Management.Automation return GetFunction(name, CommandOrigin.Internal); } // GetFunction - IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) + private IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) { if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; @@ -229,7 +230,7 @@ namespace System.Management.Automation var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); if (attributeType == typeof(AliasAttribute)) { - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; for (int i = 0; i < attributeAst.PositionalArguments.Count; i++) { yield return Compiler._attrArgToStringConverter.Target(Compiler._attrArgToStringConverter, @@ -424,7 +425,7 @@ namespace System.Management.Automation /// /// internal FunctionInfo SetFunction( - string name, + string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, @@ -762,7 +763,7 @@ namespace System.Management.Automation FunctionInfo result = null; SessionStateScope scope = searcher.InitialScope; - + if (searcher.MoveNext()) { scope = searcher.CurrentLookupScope; @@ -774,7 +775,6 @@ namespace System.Management.Automation FunctionInfo existingFunction = scope.GetFunction(name); options |= existingFunction.Options; result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext); - } else { @@ -862,7 +862,7 @@ namespace System.Management.Automation /// If the function is constant. /// /// - internal void RemoveFunction (string name, bool force, CommandOrigin origin) + internal void RemoveFunction(string name, bool force, CommandOrigin origin) { if (String.IsNullOrEmpty(name)) { @@ -871,7 +871,7 @@ namespace System.Management.Automation // Use the scope enumerator to find an existing function - SessionStateScope scope = currentScope; + SessionStateScope scope = _currentScope; FunctionLookupPath path = new FunctionLookupPath(name); @@ -945,8 +945,6 @@ namespace System.Management.Automation } } - - #endregion Functions } // SessionStateInternal class } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index 265521986..cc485d398 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -129,7 +130,7 @@ namespace System.Management.Automation /// /// internal void GetItem( - string[] paths, + string[] paths, CmdletProviderContext context) { if (paths == null) @@ -191,8 +192,8 @@ namespace System.Management.Automation /// /// private void GetItemPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -209,12 +210,12 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); try { - itemCmdletProvider.GetItem (path, context); + itemCmdletProvider.GetItem(path, context); } catch (LoopFlowException) { @@ -231,7 +232,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetItemProviderException", SessionStateStrings.GetItemProviderException, itemCmdletProvider.ProviderInfo, @@ -347,8 +348,8 @@ namespace System.Management.Automation /// /// private object GetItemDynamicParameters( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -365,7 +366,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); object result = null; @@ -388,7 +389,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetItemDynamicParametersProviderException", SessionStateStrings.GetItemDynamicParametersProviderException, itemCmdletProvider.ProviderInfo, @@ -582,8 +583,8 @@ namespace System.Management.Automation /// /// private void SetItem( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, object value, CmdletProviderContext context) { @@ -601,7 +602,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); try @@ -623,7 +624,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "SetItemProviderException", SessionStateStrings.SetItemProviderException, itemCmdletProvider.ProviderInfo, @@ -747,8 +748,8 @@ namespace System.Management.Automation /// /// private object SetItemDynamicParameters( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, object value, CmdletProviderContext context) { @@ -766,7 +767,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); object result = null; @@ -789,7 +790,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "SetItemDynamicParametersProviderException", SessionStateStrings.SetItemDynamicParametersProviderException, itemCmdletProvider.ProviderInfo, @@ -976,8 +977,8 @@ namespace System.Management.Automation /// /// private void ClearItemPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -994,7 +995,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); try @@ -1016,7 +1017,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "ClearItemProviderException", SessionStateStrings.ClearItemProviderException, itemCmdletProvider.ProviderInfo, @@ -1132,8 +1133,8 @@ namespace System.Management.Automation /// /// private object ClearItemDynamicParameters( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1150,7 +1151,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); object result = null; @@ -1173,7 +1174,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "ClearItemProviderException", SessionStateStrings.ClearItemProviderException, itemCmdletProvider.ProviderInfo, @@ -1347,8 +1348,8 @@ namespace System.Management.Automation /// /// private void InvokeDefaultActionPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1365,7 +1366,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); try @@ -1387,7 +1388,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "InvokeDefaultActionProviderException", SessionStateStrings.InvokeDefaultActionProviderException, itemCmdletProvider.ProviderInfo, @@ -1503,8 +1504,8 @@ namespace System.Management.Automation /// /// private object InvokeDefaultActionDynamicParameters( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1521,7 +1522,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetItemProviderInstance(providerInstance); object result = null; @@ -1544,7 +1545,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "InvokeDefaultActionDynamicParametersProviderException", SessionStateStrings.InvokeDefaultActionDynamicParametersProviderException, itemCmdletProvider.ProviderInfo, @@ -1553,7 +1554,7 @@ namespace System.Management.Automation } return result; } // InvokeDefaultActionDynamicParameters - + #endregion InvokeDefaultAction #endregion ItemCmdletProvider accessors diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index 62c5ef7b9..2702dcb94 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -9,7 +9,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Threading; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation @@ -351,7 +351,6 @@ namespace System.Management.Automation string currentPath = path; try { - string providerName = null; currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName); if (currentPathisProviderQualifiedPath) @@ -502,7 +501,6 @@ namespace System.Management.Automation "path", SessionStateStrings.PathResolvedToMultiple, originalPath); - } else { @@ -534,7 +532,7 @@ namespace System.Management.Automation path = path.Substring(1); } - tracer.WriteLine( + s_tracer.WriteLine( "New working path = {0}", path); @@ -638,7 +636,7 @@ namespace System.Management.Automation if (drive != null) { - tracer.WriteLine("Tracing drive"); + s_tracer.WriteLine("Tracing drive"); drive.Trace(); } @@ -694,7 +692,7 @@ namespace System.Management.Automation normalizePathContext.ThrowFirstErrorOrDoNothing(); } - tracer.WriteLine("Provider path = {0}", providerSpecificPath); + s_tracer.WriteLine("Provider path = {0}", providerSpecificPath); // Get the current working directory provider specific path @@ -703,24 +701,24 @@ namespace System.Management.Automation string currentWorkingPath = Globber.GetProviderPath( - ".", - context, - out currentDriveProvider, + ".", + context, + out currentDriveProvider, out currentWorkingDrive); Dbg.Diagnostics.Assert( currentWorkingDrive == CurrentDrive, "The current working drive should be the CurrentDrive."); - - tracer.WriteLine( - "Current working path = {0}", + + s_tracer.WriteLine( + "Current working path = {0}", currentWorkingPath); // See if the path is the current working directory or a parent // of the current working directory - tracer.WriteLine( - "Comparing {0} to {1}", + s_tracer.WriteLine( + "Comparing {0} to {1}", providerSpecificPath, currentWorkingPath); @@ -729,7 +727,7 @@ namespace System.Management.Automation // The path is the current working directory so // return true - tracer.WriteLine("The path is the current working directory"); + s_tracer.WriteLine("The path is the current working directory"); result = true; } @@ -747,15 +745,15 @@ namespace System.Management.Automation // than the mount point for this drive. That is // why we are passing the empty string as the root here. - lockedDirectory = + lockedDirectory = GetParentPath( drive.Provider, lockedDirectory, String.Empty, context); - tracer.WriteLine( - "Comparing {0} to {1}", + s_tracer.WriteLine( + "Comparing {0} to {1}", lockedDirectory, providerSpecificPath); @@ -764,7 +762,7 @@ namespace System.Management.Automation // The path is a parent of the current working // directory - tracer.WriteLine( + s_tracer.WriteLine( "The path is a parent of the current working directory: {0}", lockedDirectory); @@ -776,7 +774,7 @@ namespace System.Management.Automation } else { - tracer.WriteLine("Drives are not the same"); + s_tracer.WriteLine("Drives are not the same"); } return result; @@ -789,13 +787,13 @@ namespace System.Management.Automation /// /// A stack of the most recently pushed locations /// - private Dictionary> workingLocationStack; + private Dictionary> _workingLocationStack; private const string startingDefaultStackName = "default"; /// /// The name of the default location stack /// - private string defaultStackName = startingDefaultStackName; + private string _defaultStackName = startingDefaultStackName; /// /// Pushes the current location onto the working @@ -811,13 +809,13 @@ namespace System.Management.Automation { if (String.IsNullOrEmpty(stackName)) { - stackName = defaultStackName; + stackName = _defaultStackName; } // Create a new instance of the directory/drive pair ProviderInfo provider = CurrentDrive.Provider; - string mshQualifiedPath = + string mshQualifiedPath = LocationGlobber.GetMshQualifiedPath(CurrentDrive.CurrentLocation, CurrentDrive); PathInfo newPushLocation = @@ -827,7 +825,7 @@ namespace System.Management.Automation mshQualifiedPath, new SessionState(this)); - tracer.WriteLine( + s_tracer.WriteLine( "Pushing drive: {0} directory: {1}", CurrentDrive.Name, mshQualifiedPath); @@ -836,12 +834,12 @@ namespace System.Management.Automation Stack locationStack = null; - if (!workingLocationStack.TryGetValue(stackName, out locationStack)) + if (!_workingLocationStack.TryGetValue(stackName, out locationStack)) { locationStack = new Stack(); - workingLocationStack[stackName] = locationStack; + _workingLocationStack[stackName] = locationStack; } - + // Push the directory/drive pair onto the stack locationStack.Push(newPushLocation); @@ -890,7 +888,7 @@ namespace System.Management.Automation { if (String.IsNullOrEmpty(stackName)) { - stackName = defaultStackName; + stackName = _defaultStackName; } if (WildcardPattern.ContainsWildcardCharacters(stackName)) @@ -899,22 +897,20 @@ namespace System.Management.Automation bool haveMatch = false; - WildcardPattern stackNamePattern = - WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase); + WildcardPattern stackNamePattern = + WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase); - foreach (string key in workingLocationStack.Keys) + foreach (string key in _workingLocationStack.Keys) { if (stackNamePattern.IsMatch(key)) { if (haveMatch) { - throw PSTraceSource.NewArgumentException( "stackName", SessionStateStrings.StackNameResolvedToMultiple, stackName); - } haveMatch = true; stackName = key; @@ -927,7 +923,7 @@ namespace System.Management.Automation try { Stack locationStack = null; - if (!workingLocationStack.TryGetValue(stackName, out locationStack)) + if (!_workingLocationStack.TryGetValue(stackName, out locationStack)) { if (!string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase)) { @@ -947,12 +943,12 @@ namespace System.Management.Automation "All items in the workingLocationStack should be " + "of type PathInfo"); - string newPath = + string newPath = LocationGlobber.GetMshQualifiedPath( WildcardPattern.Escape(poppedWorkingDirectory.Path), poppedWorkingDirectory.GetDrive()); - result = SetLocation (newPath); + result = SetLocation(newPath); if (locationStack.Count == 0 && !String.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase)) @@ -960,7 +956,7 @@ namespace System.Management.Automation // Remove the stack from the stack list if it // no longer contains any paths. - workingLocationStack.Remove(stackName); + _workingLocationStack.Remove(stackName); } } catch (InvalidOperationException) @@ -996,12 +992,12 @@ namespace System.Management.Automation { if (String.IsNullOrEmpty(stackName)) { - stackName = defaultStackName; + stackName = _defaultStackName; } Stack locationStack = null; - - if (!workingLocationStack.TryGetValue(stackName, out locationStack)) + + if (!_workingLocationStack.TryGetValue(stackName, out locationStack)) { // If the request was for the default stack, but it doesn't // yet exist, create a dummy stack and return it. @@ -1048,7 +1044,7 @@ namespace System.Management.Automation stackName = startingDefaultStackName; } - if (!workingLocationStack.ContainsKey(stackName)) + if (!_workingLocationStack.ContainsKey(stackName)) { if (String.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase)) { @@ -1065,21 +1061,19 @@ namespace System.Management.Automation throw itemNotFound; } - defaultStackName = stackName; + _defaultStackName = stackName; - Stack locationStack = workingLocationStack[defaultStackName]; + Stack locationStack = _workingLocationStack[_defaultStackName]; if (locationStack != null) { - return new PathInfoStack(defaultStackName, locationStack); + return new PathInfoStack(_defaultStackName, locationStack); } return null; } // SetDefaultLocationStack #endregion push-Pop current working directory - } // SessionStateInternal class - } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index c6a51d0f5..ccad7a913 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -17,7 +18,7 @@ namespace System.Management.Automation internal sealed partial class SessionStateInternal { #region NavigationCmdletProvider accessors - + #region GetParentPath /// @@ -66,7 +67,6 @@ namespace System.Management.Automation context.ThrowFirstErrorOrDoNothing(); return result; - } //GetParentPath /// @@ -142,7 +142,7 @@ namespace System.Management.Automation /// The path to the parent object /// internal string GetParentPath( - string path, + string path, string root, CmdletProviderContext context, bool useDefaultProvider) @@ -430,9 +430,9 @@ namespace System.Management.Automation /// /// internal string GetParentPath( - CmdletProvider providerInstance, - string path, - string root, + CmdletProvider providerInstance, + string path, + string root, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -453,7 +453,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - NavigationCmdletProvider navigationCmdletProvider = + NavigationCmdletProvider navigationCmdletProvider = GetNavigationProviderInstance(providerInstance, false); string result = null; @@ -477,7 +477,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetParentPathProviderException", SessionStateStrings.GetParentPathProviderException, navigationCmdletProvider.ProviderInfo, @@ -488,7 +488,7 @@ namespace System.Management.Automation } // GetParentPath #endregion GetParentPath - + #region NormalizeRelativePath /// @@ -539,7 +539,6 @@ namespace System.Management.Automation context.ThrowFirstErrorOrDoNothing(); return result; - } //NormalizeRelativePath /// @@ -581,7 +580,7 @@ namespace System.Management.Automation /// /// internal string NormalizeRelativePath( - string path, + string path, string basePath, CmdletProviderContext context) { @@ -680,13 +679,13 @@ namespace System.Management.Automation // 1. Test for the drive root ending with a path separator. bool driveRootEndsWithPathSeparator = IsPathSeparator(drive.Root[drive.Root.Length - 1]); - + // 2. Test for the path starting with the drive root followed by a path separator int indexAfterDriveRoot = drive.Root.Length; bool pathStartsWithDriveRootAndPathSeparator = indexAfterDriveRoot < path.Length && IsPathSeparator(path[indexAfterDriveRoot]); - + // 3. Test for the drive root exactly matching the path. // Since we know the path starts with the drive root then they are equal if the lengths are equal. bool pathEqualsDriveRoot = drive.Root.Length == path.Length; @@ -757,9 +756,9 @@ namespace System.Management.Automation /// /// internal string NormalizeRelativePath( - ProviderInfo provider, - string path, - string basePath, + ProviderInfo provider, + string path, + string basePath, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -783,7 +782,6 @@ namespace System.Management.Automation NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; if (navigationCmdletProvider != null) { - try { path = navigationCmdletProvider.NormalizeRelativePath(path, basePath, context); @@ -803,7 +801,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "NormalizeRelativePathProviderException", SessionStateStrings.NormalizeRelativePathProviderException, navigationCmdletProvider.ProviderInfo, @@ -822,7 +820,7 @@ namespace System.Management.Automation return path; } // NormalizeRelativePath - + #endregion NormalizeRelativePath #region MakePath @@ -864,7 +862,7 @@ namespace System.Management.Automation /// /// internal string MakePath( - string parent, + string parent, string child) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -913,7 +911,7 @@ namespace System.Management.Automation /// /// internal string MakePath( - string parent, + string parent, string child, CmdletProviderContext context) { @@ -1073,9 +1071,9 @@ namespace System.Management.Automation /// /// internal string MakePath( - CmdletProvider providerInstance, - string parent, - string child, + CmdletProvider providerInstance, + string parent, + string child, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1186,7 +1184,6 @@ namespace System.Management.Automation context.ThrowFirstErrorOrDoNothing(); return result; - } // GetChildName /// @@ -1255,7 +1252,7 @@ namespace System.Management.Automation /// The leaf element in the path. /// internal string GetChildName( - string path, + string path, CmdletProviderContext context, bool useDefaultProvider) { @@ -1336,8 +1333,8 @@ namespace System.Management.Automation /// /// private string GetChildName( - ProviderInfo provider, - string path, + ProviderInfo provider, + string path, CmdletProviderContext context) { // All parameters should have been validated by caller @@ -1393,8 +1390,8 @@ namespace System.Management.Automation /// /// private string GetChildName( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, CmdletProviderContext context, bool acceptNonContainerProviders ) @@ -1411,7 +1408,7 @@ namespace System.Management.Automation Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); - + string result = null; NavigationCmdletProvider navigationCmdletProvider = @@ -1439,7 +1436,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetChildNameProviderException", SessionStateStrings.GetChildNameProviderException, navigationCmdletProvider.ProviderInfo, @@ -1450,7 +1447,7 @@ namespace System.Management.Automation } // GetChildName #endregion GetChildName - + #region MoveItem /// @@ -1592,21 +1589,21 @@ namespace System.Management.Automation ProviderInfo provider = null; CmdletProvider providerInstance = null; - Collection providerDestinationPaths = + Collection providerDestinationPaths = Globber.GetGlobbedMonadPathsFromMonadPath( - destination, + destination, true, context, out providerInstance); - + if (providerDestinationPaths.Count > 1) { - ArgumentException argException = + ArgumentException argException = PSTraceSource.NewArgumentException( "destination", SessionStateStrings.MoveItemOneDestination); - context.WriteError (new ErrorRecord (argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destination)); + context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destination)); } else { @@ -1729,8 +1726,8 @@ namespace System.Management.Automation /// /// private void MoveItemPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, string destination, CmdletProviderContext context) { @@ -1748,7 +1745,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - NavigationCmdletProvider navigationCmdletProvider = + NavigationCmdletProvider navigationCmdletProvider = GetNavigationProviderInstance(providerInstance, false); try @@ -1770,7 +1767,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "MoveItemProviderException", SessionStateStrings.MoveItemProviderException, navigationCmdletProvider.ProviderInfo, @@ -1823,7 +1820,7 @@ namespace System.Management.Automation /// /// internal object MoveItemDynamicParameters( - string path, + string path, string destination, CmdletProviderContext context) { @@ -1897,7 +1894,7 @@ namespace System.Management.Automation /// /// private object MoveItemDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, string destination, CmdletProviderContext context) @@ -1916,7 +1913,7 @@ namespace System.Management.Automation "Caller should validate context before calling this method"); - NavigationCmdletProvider navigationCmdletProvider = + NavigationCmdletProvider navigationCmdletProvider = GetNavigationProviderInstance(providerInstance, false); object result = null; @@ -1944,7 +1941,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "MoveItemDynamicParametersProviderException", SessionStateStrings.MoveItemDynamicParametersProviderException, navigationCmdletProvider.ProviderInfo, @@ -1958,7 +1955,6 @@ namespace System.Management.Automation #endregion NavigationCmdletProvider accessors } // SessionStateInternal class - } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index d5b5b99a8..499c52e79 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.ObjectModel; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -62,7 +63,7 @@ namespace System.Management.Automation /// /// internal Collection GetProperty( - string[] paths, + string[] paths, Collection providerSpecificPickList, bool literalPath) { @@ -202,8 +203,8 @@ namespace System.Management.Automation /// /// private void GetPropertyPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, Collection providerSpecificPickList, CmdletProviderContext context) { @@ -243,7 +244,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetPropertyProviderException", SessionStateStrings.GetPropertyProviderException, providerInstance.ProviderInfo, @@ -296,7 +297,7 @@ namespace System.Management.Automation /// /// internal object GetPropertyDynamicParameters( - string path, + string path, Collection providerSpecificPickList, CmdletProviderContext context) { @@ -370,7 +371,7 @@ namespace System.Management.Automation /// /// private object GetPropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, Collection providerSpecificPickList, CmdletProviderContext context) @@ -412,7 +413,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetPropertyDynamicParametersProviderException", SessionStateStrings.GetPropertyDynamicParametersProviderException, providerInstance.ProviderInfo, @@ -619,8 +620,8 @@ namespace System.Management.Automation /// /// private void SetPropertyPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, PSObject property, CmdletProviderContext context) { @@ -664,14 +665,13 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "SetPropertyProviderException", SessionStateStrings.SetPropertyProviderException, providerInstance.ProviderInfo, path, e); } - } // SetPropertyPrivate /// @@ -718,7 +718,7 @@ namespace System.Management.Automation /// /// internal object SetPropertyDynamicParameters( - string path, + string path, PSObject propertyValue, CmdletProviderContext context) { @@ -792,7 +792,7 @@ namespace System.Management.Automation /// /// private object SetPropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, PSObject propertyValue, CmdletProviderContext context) @@ -835,7 +835,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "SetPropertyDynamicParametersProviderException", SessionStateStrings.SetPropertyDynamicParametersProviderException, providerInstance.ProviderInfo, @@ -891,7 +891,7 @@ namespace System.Management.Automation /// /// internal void ClearProperty( - string[] paths, + string[] paths, Collection propertyToClear, bool force, bool literalPath) @@ -1030,8 +1030,8 @@ namespace System.Management.Automation /// /// private void ClearPropertyPrivate( - CmdletProvider providerInstance, - string path, + CmdletProvider providerInstance, + string path, Collection propertyToClear, CmdletProviderContext context) { @@ -1075,7 +1075,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "ClearPropertyProviderException", SessionStateStrings.ClearPropertyProviderException, providerInstance.ProviderInfo, @@ -1128,7 +1128,7 @@ namespace System.Management.Automation /// /// internal object ClearPropertyDynamicParameters( - string path, + string path, Collection propertyToClear, CmdletProviderContext context) { @@ -1202,7 +1202,7 @@ namespace System.Management.Automation /// /// private object ClearPropertyDynamicParameters( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, Collection propertyToClear, CmdletProviderContext context) @@ -1245,7 +1245,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "ClearPropertyDynamicParametersProviderException", SessionStateStrings.ClearPropertyDynamicParametersProviderException, providerInstance.ProviderInfo, diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index 61196d6b7..a7f0ea90e 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -1,13 +1,14 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Management.Automation.Runspaces; using System.Text; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -121,7 +122,6 @@ namespace System.Management.Automation providerConfig.PSSnapIn, null ); - } private ProviderInfo AddProvider(Type implementingType, string name, string helpFileName, PSSnapInInfo psSnapIn, PSModuleInfo module) @@ -223,7 +223,7 @@ namespace System.Management.Automation drive != null, "drive should have been validated by the caller"); - DriveCmdletProvider namespaceProvider = + DriveCmdletProvider namespaceProvider = GetDriveProviderInstance(drive.Provider); return ValidateDriveWithProvider(namespaceProvider, drive, context, resolvePathIfPossible); @@ -402,7 +402,7 @@ namespace System.Management.Automation return possibleMatches.ToString(); } - + /// /// Gets an instance of an DriveCmdletProvider given the provider ID. /// @@ -435,7 +435,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("providerId"); } - DriveCmdletProvider driveCmdletProvider = + DriveCmdletProvider driveCmdletProvider = GetProviderInstance(providerId) as DriveCmdletProvider; if (driveCmdletProvider == null) @@ -526,7 +526,7 @@ namespace System.Management.Automation return driveCmdletProvider; } // GetDriveProviderInstance - + /// /// Gets an instance of an ItemCmdletProvider given the provider ID. /// @@ -559,7 +559,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("providerId"); } - ItemCmdletProvider itemCmdletProvider = + ItemCmdletProvider itemCmdletProvider = GetProviderInstance(providerId) as ItemCmdletProvider; if (itemCmdletProvider == null) @@ -683,7 +683,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("providerId"); } - ContainerCmdletProvider containerCmdletProvider = + ContainerCmdletProvider containerCmdletProvider = GetProviderInstance(providerId) as ContainerCmdletProvider; if (containerCmdletProvider == null) @@ -851,7 +851,7 @@ namespace System.Management.Automation NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if ((navigationCmdletProvider == null) && (! acceptNonContainerProviders)) + if ((navigationCmdletProvider == null) && (!acceptNonContainerProviders)) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); @@ -881,7 +881,7 @@ namespace System.Management.Automation internal bool IsProviderLoaded(string name) { bool result = false; - + if (String.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); @@ -923,7 +923,7 @@ namespace System.Management.Automation /// could not be found. /// /// - internal Collection GetProvider(string name) + internal Collection GetProvider(string name) { if (String.IsNullOrEmpty(name)) { @@ -1013,7 +1013,7 @@ namespace System.Management.Automation // Get the provider from the providers container List matchingProviders = null; - + if (!Providers.TryGetValue(providerName.ShortName, out matchingProviders)) { // If the provider was not found, we may need to auto-mount it. @@ -1041,7 +1041,7 @@ namespace System.Management.Automation if (String.Equals( provider.PSSnapInName, providerName.PSSnapInName, - StringComparison.OrdinalIgnoreCase) || + StringComparison.OrdinalIgnoreCase) || String.Equals( provider.ModuleName, providerName.PSSnapInName, @@ -1050,7 +1050,6 @@ namespace System.Management.Automation result.Add(provider); } } - } else { @@ -1061,7 +1060,7 @@ namespace System.Management.Automation } return result; } // GetProvider - + /// /// Gets all the CoreCommandProviders /// @@ -1104,7 +1103,7 @@ namespace System.Management.Automation #endregion GetProvider #region NewProvider - + /// /// Initializes a provider by loading the assembly, creating an instance of the /// provider, calling its start method followed by the InitializeDefaultDrives method. The @@ -1143,8 +1142,8 @@ namespace System.Management.Automation /// /// internal void InitializeProvider( - Provider.CmdletProvider providerInstance, - ProviderInfo provider, + Provider.CmdletProvider providerInstance, + ProviderInfo provider, CmdletProviderContext context) { if (provider == null) @@ -1161,7 +1160,7 @@ namespace System.Management.Automation // that it needs. List newDrives = new List(); - DriveCmdletProvider driveProvider = + DriveCmdletProvider driveProvider = GetDriveProviderInstance(providerInstance); if (driveProvider != null) @@ -1198,11 +1197,11 @@ namespace System.Management.Automation String.Empty, e); - context.WriteError ( - new ErrorRecord ( - providerException, + context.WriteError( + new ErrorRecord( + providerException, "InitializeDefaultDrivesException", - ErrorCategory.InvalidOperation, + ErrorCategory.InvalidOperation, provider)); } } @@ -1236,13 +1235,11 @@ namespace System.Management.Automation _globalScope.NewDrive(validatedNewDrive); } - } catch (SessionStateException exception) { - context.WriteError (exception.ErrorRecord); + context.WriteError(exception.ErrorRecord); } - } // foreach (drive in newDrives) } } // InitializeProvider @@ -1307,7 +1304,7 @@ namespace System.Management.Automation // Make sure we are able to create an instance of the provider. // Note, this will also set the friendly name if the user didn't // specify one. - + Provider.CmdletProvider providerInstance = provider.CreateInstance(); // Now call start to let the provider initialize itself @@ -1342,7 +1339,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-call OK, 3rd party callout { CommandProcessorBase.CheckForSevereException(e); - throw + throw NewProviderInvocationException( "ProviderStartException", SessionStateStrings.ProviderStartException, @@ -1437,7 +1434,7 @@ namespace System.Management.Automation initializeProviderError = true; throw; } - finally + finally { if (initializeProviderError) { @@ -1631,8 +1628,8 @@ namespace System.Management.Automation /// /// internal void RemoveProvider( - string providerName, - bool force, + string providerName, + bool force, CmdletProviderContext context) { if (context == null) @@ -1642,7 +1639,7 @@ namespace System.Management.Automation if (String.IsNullOrEmpty(providerName)) { - throw PSTraceSource.NewArgumentException ("providerName"); + throw PSTraceSource.NewArgumentException("providerName"); } bool errors = false; @@ -1741,7 +1738,6 @@ namespace System.Management.Automation throw; } } - } catch (LoopFlowException) { @@ -1759,11 +1755,11 @@ namespace System.Management.Automation { CommandProcessorBase.CheckForSevereException(e); errors = true; - context.WriteError ( - new ErrorRecord ( - e, - "RemoveProviderUnexpectedException", - ErrorCategory.InvalidArgument, + context.WriteError( + new ErrorRecord( + e, + "RemoveProviderUnexpectedException", + ErrorCategory.InvalidArgument, providerName)); } finally @@ -1786,7 +1782,6 @@ namespace System.Management.Automation // Now make sure no relationship reference this provider relationships.ProcessRelationshipsOnCmdletProviderRemoval (providerName); #endif - } } } // RemoveProvider @@ -1839,9 +1834,7 @@ namespace System.Management.Automation return count; } } // ProviderCount - } // SessionStateInternal class - } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index eeee281c3..ddd6b744d 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -9,7 +10,7 @@ using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -39,8 +40,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; - + _sessionState = sessionState; #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release @@ -73,14 +73,14 @@ namespace System.Management.Automation if (createAsChild) { - sessionState = new SessionStateInternal(context.EngineSessionState, linkToGlobal, context); + _sessionState = new SessionStateInternal(context.EngineSessionState, linkToGlobal, context); } else { - sessionState = new SessionStateInternal(context); + _sessionState = new SessionStateInternal(context); } - sessionState.PublicSessionState = this; + _sessionState.PublicSessionState = this; } // SessionState @@ -92,9 +92,9 @@ namespace System.Management.Automation ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS(); if (ecFromTLS == null) throw new InvalidOperationException("ExecutionContext"); - - sessionState = new SessionStateInternal(ecFromTLS); - sessionState.PublicSessionState = this; + + _sessionState = new SessionStateInternal(ecFromTLS); + _sessionState.PublicSessionState = this; } #endregion Constructors @@ -108,11 +108,11 @@ namespace System.Management.Automation { get { - if (drive == null) + if (_drive == null) { - this.drive = new DriveManagementIntrinsics(sessionState); + _drive = new DriveManagementIntrinsics(_sessionState); } - return drive; + return _drive; } } // Drive @@ -123,11 +123,11 @@ namespace System.Management.Automation { get { - if (provider == null) + if (_provider == null) { - provider = new CmdletProviderManagementIntrinsics(sessionState); + _provider = new CmdletProviderManagementIntrinsics(_sessionState); } - return provider; + return _provider; } // get } // Provider @@ -138,11 +138,11 @@ namespace System.Management.Automation { get { - if (path == null) + if (_path == null) { - path = new PathIntrinsics(sessionState); + _path = new PathIntrinsics(_sessionState); } - return path; + return _path; } // get } // Path @@ -153,11 +153,11 @@ namespace System.Management.Automation { get { - if (variable == null) + if (_variable == null) { - variable = new PSVariableIntrinsics(sessionState); + _variable = new PSVariableIntrinsics(_sessionState); } - return variable; + return _variable; } // get } // PSVariable @@ -168,11 +168,11 @@ namespace System.Management.Automation { get { - return sessionState.LanguageMode; + return _sessionState.LanguageMode; } set { - sessionState.LanguageMode = value; + _sessionState.LanguageMode = value; } } @@ -183,7 +183,7 @@ namespace System.Management.Automation { get { - return sessionState.UseFullLanguageModeInDebugger; + return _sessionState.UseFullLanguageModeInDebugger; } } @@ -193,7 +193,7 @@ namespace System.Management.Automation /// public List Scripts { - get { return sessionState.Scripts; } + get { return _sessionState.Scripts; } } /// @@ -202,7 +202,7 @@ namespace System.Management.Automation /// public List Applications { - get { return sessionState.Applications; } + get { return _sessionState.Applications; } } /// @@ -210,7 +210,7 @@ namespace System.Management.Automation /// public PSModuleInfo Module { - get { return sessionState.Module; } + get { return _sessionState.Module; } } /// @@ -218,7 +218,7 @@ namespace System.Management.Automation /// public ProviderIntrinsics InvokeProvider { - get { return sessionState.InvokeProvider; } + get { return _sessionState.InvokeProvider; } } /// @@ -226,7 +226,7 @@ namespace System.Management.Automation /// public CommandInvocationIntrinsics InvokeCommand { - get { return sessionState.ExecutionContext.EngineIntrinsics.InvokeCommand; } + get { return _sessionState.ExecutionContext.EngineIntrinsics.InvokeCommand; } } /// @@ -239,7 +239,7 @@ namespace System.Management.Automation public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) { SessionStateException exception; - if (! IsVisible(origin, valueToCheck)) + if (!IsVisible(origin, valueToCheck)) { PSVariable sv = valueToCheck as PSVariable; if (sv != null) @@ -380,17 +380,17 @@ namespace System.Management.Automation /// internal SessionStateInternal Internal { - get {return sessionState;} + get { return _sessionState; } } // Internal #endregion Internal methods #region private data - private SessionStateInternal sessionState; - private DriveManagementIntrinsics drive; - private CmdletProviderManagementIntrinsics provider; - private PathIntrinsics path; - private PSVariableIntrinsics variable; + private SessionStateInternal _sessionState; + private DriveManagementIntrinsics _drive; + private CmdletProviderManagementIntrinsics _provider; + private PathIntrinsics _path; + private PSVariableIntrinsics _variable; #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index a2f29be7d..8a53f53db 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -35,11 +35,11 @@ namespace System.Management.Automation if (parentScope != null) { // Now copy the script: scope stack from the parent - this._scriptScope = parentScope.ScriptScope; + _scriptScope = parentScope.ScriptScope; } else { - this._scriptScope = this; + _scriptScope = this; } } // SessionStateScope constructor @@ -506,7 +506,7 @@ namespace System.Management.Automation // Set the variable directly in the table, bypassing all of the checks. This // can only be used for global scope otherwise the slow path is used. - if (fastPath ) + if (fastPath) { if (Parent != null) { @@ -690,7 +690,7 @@ namespace System.Management.Automation "VariableNotWritableRare", SessionStateStrings.VariableNotWritableRare); - throw e; + throw e; } // If the new and old variable are the same then don't bother @@ -812,7 +812,6 @@ namespace System.Management.Automation // Finally mark the variable itself has having been removed so // anyone holding a reference to it can be aware of this. variable.WasRemoved = true; - } // RemoveVariable internal bool TrySetLocalParameterValue(string name, object value) @@ -1270,7 +1269,6 @@ namespace System.Management.Automation } aliasInfos.Remove(name); - } // RemoveAlias #endregion aliases @@ -1646,7 +1644,7 @@ namespace System.Management.Automation else { bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0; - + existingFunction.Update(newValue, applyForce, options, helpFile); result = existingFunction; } @@ -1700,7 +1698,6 @@ namespace System.Management.Automation } } functionInfos.Remove(name); - } // RemoveFunction #endregion functions @@ -1867,7 +1864,6 @@ namespace System.Management.Automation } return _cmdlets[name][0]; - } // AddCmdlet /// @@ -2004,7 +2000,7 @@ namespace System.Management.Automation return (function.Options & options) != 0; } - private static FunctionInfo CreateFunction(string name, ScriptBlock function, FunctionInfo originalFunction, + private static FunctionInfo CreateFunction(string name, ScriptBlock function, FunctionInfo originalFunction, ScopedItemOptions options, ExecutionContext context, string helpFile) { FunctionInfo newValue = null; @@ -2110,9 +2106,9 @@ namespace System.Management.Automation // These variables will automatically propagate to new // scopes since they are marked AllScope. - _variables.Add(_nullVar.Name, _nullVar); - _variables.Add(_falseVar.Name, _falseVar); - _variables.Add(_trueVar.Name, _trueVar); + _variables.Add(s_nullVar.Name, s_nullVar); + _variables.Add(s_falseVar.Name, s_falseVar); + _variables.Add(s_trueVar.Name, s_trueVar); } else { @@ -2331,7 +2327,7 @@ namespace System.Management.Automation /// is ScopedItemOptions.Constant. /// /// - private static readonly PSVariable _trueVar = + private static readonly PSVariable s_trueVar = new PSVariable( StringLiterals.True, true, @@ -2344,7 +2340,7 @@ namespace System.Management.Automation /// is ScopedItemOptions.Constant. /// /// - private static readonly PSVariable _falseVar = + private static readonly PSVariable s_falseVar = new PSVariable( StringLiterals.False, false, @@ -2357,14 +2353,14 @@ namespace System.Management.Automation /// is ScopedItemOptions.Constant. /// /// - private static readonly NullVariable _nullVar = + private static readonly NullVariable s_nullVar = new NullVariable(); #endregion Private members #region Alias mapping - private Dictionary> commandsToAliasesCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); + private Dictionary> _commandsToAliasesCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); /// /// Gets the alises by command name (used by metadata-driven help) @@ -2374,7 +2370,7 @@ namespace System.Management.Automation internal IEnumerable GetAliasesByCommandName(string command) { List commandsToAliases; - if (commandsToAliasesCache.TryGetValue(command, out commandsToAliases)) + if (_commandsToAliasesCache.TryGetValue(command, out commandsToAliases)) { foreach (string str in commandsToAliases) { @@ -2393,11 +2389,11 @@ namespace System.Management.Automation private void AddAliasToCache(string alias, string value) { List existingAliases; - if (!commandsToAliasesCache.TryGetValue(value, out existingAliases)) + if (!_commandsToAliasesCache.TryGetValue(value, out existingAliases)) { List list = new List(); list.Add(alias); - commandsToAliasesCache.Add(value, list); + _commandsToAliasesCache.Add(value, list); } else { @@ -2416,14 +2412,14 @@ namespace System.Management.Automation private void RemoveAliasFromCache(string alias, string value) { List list; - if (!commandsToAliasesCache.TryGetValue(value, out list)) + if (!_commandsToAliasesCache.TryGetValue(value, out list)) { return; } if (list.Count <= 1) { - commandsToAliasesCache.Remove(value); + _commandsToAliasesCache.Remove(value); } else { @@ -2436,7 +2432,6 @@ namespace System.Management.Automation } #endregion - } // class SessionStateScope } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs index 5fe04dd69..e32b554a8 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs @@ -1,10 +1,11 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Threading; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -22,7 +23,7 @@ namespace System.Management.Automation /// scope is implied or can be accessed using $local in /// the shell. /// - private SessionStateScope currentScope; + private SessionStateScope _currentScope; /// /// Given a scope identifier, returns the proper session state scope. @@ -51,7 +52,7 @@ namespace System.Management.Automation /// internal SessionStateScope GetScopeByID(string scopeID) { - SessionStateScope result = currentScope; + SessionStateScope result = _currentScope; if (!string.IsNullOrEmpty(scopeID)) { @@ -67,14 +68,14 @@ namespace System.Management.Automation StringLiterals.Local, StringComparison.OrdinalIgnoreCase)) { - result = currentScope; + result = _currentScope; } else if (String.Equals( scopeID, StringLiterals.Private, StringComparison.OrdinalIgnoreCase)) { - result = currentScope; + result = _currentScope; } else if (String.Equals( scopeID, @@ -82,7 +83,7 @@ namespace System.Management.Automation StringComparison.OrdinalIgnoreCase)) { // Get the current script scope from the stack. - result = currentScope.ScriptScope; + result = _currentScope.ScriptScope; } else { @@ -98,7 +99,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentOutOfRangeException("scopeID", scopeID); } - result = GetScopeByID(scopeNumericID) ?? currentScope; + result = GetScopeByID(scopeNumericID) ?? _currentScope; } catch (FormatException) { @@ -108,7 +109,6 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentOutOfRangeException("scopeID", scopeID); } - } } @@ -135,7 +135,7 @@ namespace System.Management.Automation /// internal SessionStateScope GetScopeByID(int scopeID) { - SessionStateScope processingScope = currentScope; + SessionStateScope processingScope = _currentScope; int originalID = scopeID; while (scopeID > 0 && processingScope != null) @@ -179,7 +179,7 @@ namespace System.Management.Automation { get { - return currentScope; + return _currentScope; } set @@ -188,40 +188,40 @@ namespace System.Management.Automation value != null, "A null scope should never be set"); #if DEBUG - // This code is ifdef'd for DEBUG because it may pose a significant - // performance hit and is only really required to validate our internal - // code. There is no way anyone outside the Monad codebase can cause - // these error conditions to be hit. + // This code is ifdef'd for DEBUG because it may pose a significant + // performance hit and is only really required to validate our internal + // code. There is no way anyone outside the Monad codebase can cause + // these error conditions to be hit. - // Need to make sure the new scope is in the global scope lineage + // Need to make sure the new scope is in the global scope lineage - SessionStateScope scope = value; - bool inGlobalScopeLineage = false; + SessionStateScope scope = value; + bool inGlobalScopeLineage = false; - while (scope != null) + while (scope != null) + { + if (scope == _globalScope) { - if (scope == _globalScope) - { - inGlobalScopeLineage = true; - break; - } - scope = scope.Parent; + inGlobalScopeLineage = true; + break; } + scope = scope.Parent; + } - Diagnostics.Assert( - inGlobalScopeLineage, - "The scope specified to be set in CurrentScope is not in the global scope lineage. All scopes must originate from the global scope."); + Diagnostics.Assert( + inGlobalScopeLineage, + "The scope specified to be set in CurrentScope is not in the global scope lineage. All scopes must originate from the global scope."); #endif - currentScope = value; + _currentScope = value; } } // CurrentScope /// /// Gets the session state current script scope. /// - internal SessionStateScope ScriptScope { get { return currentScope.ScriptScope; } } - + internal SessionStateScope ScriptScope { get { return _currentScope.ScriptScope; } } + /// /// Creates a new scope in the scope tree and assigns the parent /// and child scopes appropriately. @@ -239,12 +239,12 @@ namespace System.Management.Automation internal SessionStateScope NewScope(bool isScriptScope) { Diagnostics.Assert( - currentScope != null, + _currentScope != null, "The currentScope should always be set."); // Create the new child scope. - SessionStateScope newScope = new SessionStateScope(currentScope); + SessionStateScope newScope = new SessionStateScope(_currentScope); if (isScriptScope) { @@ -269,7 +269,7 @@ namespace System.Management.Automation internal void RemoveScope(SessionStateScope scope) { Diagnostics.Assert( - currentScope != null, + _currentScope != null, "The currentScope should always be set."); if (scope == _globalScope) @@ -328,13 +328,12 @@ namespace System.Management.Automation // If the scope being removed is the current scope, // then it must be removed from the tree. - if (scope == currentScope && currentScope.Parent != null) + if (scope == _currentScope && _currentScope.Parent != null) { - currentScope = currentScope.Parent; + _currentScope = _currentScope.Parent; } scope.Parent = null; } // RemoveScope - } // SessionStateInternal class } diff --git a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs index 055f00a30..afe4813f0 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs @@ -79,7 +79,7 @@ namespace System.Management.Automation { get { - return ((IEnumerator) this).Current; + return ((IEnumerator)this).Current; } } @@ -99,7 +99,7 @@ namespace System.Management.Automation { return this; } - + public void Dispose() { Reset(); diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs index 6cb22754a..7ce96538e 100644 --- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs +++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs @@ -45,7 +45,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("providerInstance"); } - ISecurityDescriptorCmdletProvider permissionCmdletProvider = + ISecurityDescriptorCmdletProvider permissionCmdletProvider = providerInstance as ISecurityDescriptorCmdletProvider; if (permissionCmdletProvider == null) @@ -61,7 +61,7 @@ namespace System.Management.Automation #endregion private methods #region GetSecurityDescriptor - + /// /// Gets the security descriptor from the specified item. @@ -94,7 +94,7 @@ namespace System.Management.Automation context.ThrowFirstErrorOrDoNothing(); Collection contextResults = context.GetAccumulatedObjects(); - + if (contextResults == null) { contextResults = new Collection(); @@ -142,7 +142,7 @@ namespace System.Management.Automation ProviderInfo provider = null; CmdletProvider providerInstance = null; - Collection providerPaths = + Collection providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, false, @@ -198,14 +198,13 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "GetSecurityDescriptorProviderException", SessionStateStrings.GetSecurityDescriptorProviderException, providerInstance.ProviderInfo, path, e); } - } // GetSecurityDescriptor #endregion GetSecurityDescriptor @@ -245,7 +244,7 @@ namespace System.Management.Automation SetSecurityDescriptor(path, securityDescriptor, context); context.ThrowFirstErrorOrDoNothing(); - + Collection contextResults = context.GetAccumulatedObjects(); // Return an empty array instead of null @@ -302,29 +301,27 @@ namespace System.Management.Automation ProviderInfo provider = null; CmdletProvider providerInstance = null; - Collection providerPaths = + Collection providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, false, context, out provider, out providerInstance); - + foreach (string providerPath in providerPaths) { - SetSecurityDescriptor( providerInstance, - providerPath, - securityDescriptor, + providerPath, + securityDescriptor, context); } - } // SetSecurityDescriptor private void SetSecurityDescriptor( CmdletProvider providerInstance, - string path, + string path, ObjectSecurity securityDescriptor, CmdletProviderContext context) { @@ -371,7 +368,7 @@ namespace System.Management.Automation // thrown if one tries to set SACL and does not have // SeSecurityPrivilege // - context.WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); + context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (UnauthorizedAccessException e) { @@ -380,7 +377,7 @@ namespace System.Management.Automation // -- owner or pri. group are invalid OR // -- marta returns ERROR_ACCESS_DENIED // - context.WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); + context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (NotSupportedException e) { @@ -390,7 +387,7 @@ namespace System.Management.Automation // // for example, FAT or FAT32 file in case of file system provider // - context.WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.InvalidOperation, path)); + context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path)); } catch (SystemException e) { @@ -399,26 +396,24 @@ namespace System.Management.Automation // thrown if the CLR gets back unexpected error // from OS security or marta // - context.WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.InvalidOperation, path)); + context.WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, path)); } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "SetSecurityDescriptorProviderException", SessionStateStrings.SetSecurityDescriptorProviderException, providerInstance.ProviderInfo, path, e); } - - } // SetSecurityDescriptor #endregion SetSecurityDescriptor #region NewSecurityDescriptor - + /// /// Gets the security descriptor from the specified item. /// @@ -455,7 +450,7 @@ namespace System.Management.Automation ProviderInfo provider = null; CmdletProvider providerInstance = null; - Collection providerPaths = + Collection providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, false, @@ -471,7 +466,6 @@ namespace System.Management.Automation sd = NewSecurityDescriptorFromPath(providerInstance, providerPaths[0], sections); - } else { @@ -482,7 +476,7 @@ namespace System.Management.Automation } // NewSecurityDescriptor private ObjectSecurity NewSecurityDescriptorFromPath( - CmdletProvider providerInstance, + CmdletProvider providerInstance, string path, AccessControlSections sections) { @@ -503,7 +497,7 @@ namespace System.Management.Automation // This just verifies that the provider supports the interface. - ISecurityDescriptorCmdletProvider sdProvider = + ISecurityDescriptorCmdletProvider sdProvider = GetPermissionProviderInstance(providerInstance); try @@ -526,7 +520,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "NewSecurityDescriptorProviderException", SessionStateStrings.GetSecurityDescriptorProviderException, providerInstance.ProviderInfo, @@ -535,7 +529,6 @@ namespace System.Management.Automation } return sd; - } // NewSecurityDescriptor /// @@ -611,7 +604,7 @@ namespace System.Management.Automation // This just verifies that the provider supports the interface. - ISecurityDescriptorCmdletProvider sdProvider = + ISecurityDescriptorCmdletProvider sdProvider = GetPermissionProviderInstance(providerInstance); try @@ -634,7 +627,7 @@ namespace System.Management.Automation catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); - throw NewProviderInvocationException ( + throw NewProviderInvocationException( "NewSecurityDescriptorProviderException", SessionStateStrings.GetSecurityDescriptorProviderException, providerInstance.ProviderInfo, @@ -643,11 +636,9 @@ namespace System.Management.Automation } return sd; - } // NewSecurityDescriptorOfType #endregion NewSecurityDescriptor - } } diff --git a/src/System.Management.Automation/engine/SessionStateStrings.cs b/src/System.Management.Automation/engine/SessionStateStrings.cs index 93e40863c..6e800cb97 100644 --- a/src/System.Management.Automation/engine/SessionStateStrings.cs +++ b/src/System.Management.Automation/engine/SessionStateStrings.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation /// Holds the #defines for any special strings used in session state. /// /// - internal static class StringLiterals + internal static class StringLiterals { // constants @@ -68,7 +68,7 @@ namespace System.Management.Automation /// /// name of the global variable table in Variable scopes of session state. /// - internal const string Global = "GLOBAL"; + internal const string Global = "GLOBAL"; /// /// Name of the current scope variable table of session state. @@ -90,7 +90,7 @@ namespace System.Management.Automation /// /// session state string used as resource name in exceptions /// - internal const string SessionState = "SessionState"; + internal const string SessionState = "SessionState"; #if RELATIONSHIP_SUPPORTED // 2004/11/24-JeffJon - Relationships have been removed from the Exchange release diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index f5c3dad15..465a6775a 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -10,12 +10,12 @@ using System.IO; using System.Management.Automation; using Microsoft.PowerShell.Commands; -namespace System.Management.Automation +namespace System.Management.Automation { /// /// This class holds the integer constants used in Session State /// - internal static class SessionStateConstants + internal static class SessionStateConstants { /// /// The default maximum for the number of variables @@ -108,7 +108,7 @@ namespace System.Management.Automation /// /// This class has static methods that are used in Session State /// - internal static class SessionStateUtilities + internal static class SessionStateUtilities { /// /// Converts the specified array into a collection of the specified type. @@ -167,7 +167,7 @@ namespace System.Management.Automation { throw new ArgumentNullException("collection"); } - + bool result = false; foreach (object item in collection) @@ -226,7 +226,7 @@ namespace System.Management.Automation { result.Add( WildcardPattern.Get( - pattern, + pattern, options)); } } @@ -322,7 +322,6 @@ namespace System.Management.Automation return result; } } - } namespace Microsoft.PowerShell.Commands @@ -349,6 +348,5 @@ namespace Microsoft.PowerShell.Commands /// Overwrite } - } diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index f0b8921d4..1e0bd498a 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -8,7 +9,7 @@ using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 @@ -131,7 +132,6 @@ namespace System.Management.Automation { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); } @@ -143,7 +143,7 @@ namespace System.Management.Automation return resultItem; } // GetVariableValue - + /// /// Get a variable out of session state. This interface supports @@ -267,7 +267,7 @@ namespace System.Management.Automation } else { - result = GetVariableValueFromProvider(variablePath, out context, out scope, currentScope.ScopeOrigin); + result = GetVariableValueFromProvider(variablePath, out context, out scope, _currentScope.ScopeOrigin); } return result; @@ -1222,7 +1222,7 @@ namespace System.Management.Automation /// /// internal object SetVariable( - VariablePath variablePath, + VariablePath variablePath, object newValue, bool asValue, CommandOrigin origin) @@ -1310,11 +1310,11 @@ namespace System.Management.Automation if (variablePath.IsLocal || variablePath.IsUnscopedVariable) { - scope = currentScope; + scope = _currentScope; } else if (variablePath.IsScript) { - scope = currentScope.ScriptScope; + scope = _currentScope.ScriptScope; } else if (variablePath.IsGlobal) { @@ -1322,7 +1322,7 @@ namespace System.Management.Automation } else if (variablePath.IsPrivate) { - scope = currentScope; + scope = _currentScope; } PSVariable varResult = @@ -1638,7 +1638,7 @@ namespace System.Management.Automation force, this); } // NewVariable - + /// /// Creates a new variable in the specified scope /// @@ -1740,7 +1740,7 @@ namespace System.Management.Automation RemoveVariable(name, false); } - /// + /// /// Removes a variable from the variable table. /// /// @@ -2060,14 +2060,14 @@ namespace System.Management.Automation internal IDictionary GetVariableTable() { SessionStateScopeEnumerator scopeEnumerator = - new SessionStateScopeEnumerator(currentScope); + new SessionStateScopeEnumerator(_currentScope); Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (SessionStateScope scope in scopeEnumerator) { - GetScopeVariableTable(scope, result, includePrivate: scope == currentScope); + GetScopeVariableTable(scope, result, includePrivate: scope == _currentScope); } return result; @@ -2143,7 +2143,6 @@ namespace System.Management.Automation #endregion variables } // SessionStateInternal class - } #pragma warning restore 56500 \ No newline at end of file diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 6fe8e00ab..ba09d28f9 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -29,7 +29,7 @@ namespace System.Management.Automation /// /// If is null or empty. /// - public PSVariable(string name) + public PSVariable(string name) : this(name, null, ScopedItemOptions.None, (Collection)null) { } @@ -49,7 +49,7 @@ namespace System.Management.Automation /// /// If is null or empty. /// - public PSVariable(string name, object value) + public PSVariable(string name, object value) : this(name, value, ScopedItemOptions.None, (Collection)null) { } @@ -74,7 +74,7 @@ namespace System.Management.Automation /// /// If is null or empty. /// - public PSVariable(string name, object value, ScopedItemOptions options) + public PSVariable(string name, object value, ScopedItemOptions options) : this(name, value, options, (Collection)null) { } @@ -103,10 +103,10 @@ namespace System.Management.Automation /// /// If is null or empty. /// - internal PSVariable(string name, object value, ScopedItemOptions options, string description) + internal PSVariable(string name, object value, ScopedItemOptions options, string description) : this(name, value, options, (Collection)null) { - this.description = description; + _description = description; } /// @@ -146,7 +146,7 @@ namespace System.Management.Automation string description) : this(name, value, options, attributes) { - this.description = description; + _description = description; } @@ -181,9 +181,9 @@ namespace System.Management.Automation /// throws an exception. /// public PSVariable( - string name, - object value, - ScopedItemOptions options, + string name, + object value, + ScopedItemOptions options, Collection attributes) { if (String.IsNullOrEmpty(name)) @@ -191,9 +191,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("name"); } - this.name = name; + _name = name; - this.attributes = new PSVariableAttributeCollection(this); + _attributes = new PSVariableAttributeCollection(this); // Note, it is OK to set the value before setting the attributes // because each attribute will be validated as it is set. @@ -204,12 +204,12 @@ namespace System.Management.Automation { foreach (Attribute attribute in attributes) { - this.attributes.Add(attribute); + _attributes.Add(attribute); } } - + // Set the options after setting the initial value. - this.options = options; + _options = options; if (IsAllScope) { @@ -223,7 +223,7 @@ namespace System.Management.Automation // the derived class isn't fully constructed yet. internal PSVariable(string name, bool dummy) { - this.name = name; + _name = name; } #endregion ctor @@ -235,10 +235,10 @@ namespace System.Management.Automation { get { - return name; + return _name; } } - private string name = String.Empty; + private string _name = String.Empty; /// /// Gets or sets the description of the variable. @@ -247,14 +247,14 @@ namespace System.Management.Automation { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description = String.Empty; + private string _description = String.Empty; internal void DebuggerCheckVariableRead() @@ -296,7 +296,7 @@ namespace System.Management.Automation get { DebuggerCheckVariableRead(); - return this._value; + return _value; } set @@ -323,7 +323,7 @@ namespace System.Management.Automation { get { return _module; } } - PSModuleInfo _module; + private PSModuleInfo _module; internal void SetModule(PSModuleInfo module) { _module = module; @@ -354,7 +354,7 @@ namespace System.Management.Automation { get { - return options; + return _options; } set @@ -372,7 +372,7 @@ namespace System.Management.Automation { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( - name, + _name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable); @@ -391,7 +391,7 @@ namespace System.Management.Automation SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( - name, + _name, SessionStateCategory.Variable, "VariableCannotBeMadeConstant", SessionStateStrings.VariableCannotBeMadeConstant); @@ -410,7 +410,7 @@ namespace System.Management.Automation SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( - name, + _name, SessionStateCategory.Variable, "VariableAllScopeOptionCannotBeRemoved", SessionStateStrings.VariableAllScopeOptionCannotBeRemoved); @@ -418,9 +418,9 @@ namespace System.Management.Automation throw e; } - options = newOptions; + _options = newOptions; } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// /// Gets the collection that contains the attributes for the variable. @@ -434,14 +434,14 @@ namespace System.Management.Automation { get { - if (attributes == null) + if (_attributes == null) { - attributes = new PSVariableAttributeCollection(this); + _attributes = new PSVariableAttributeCollection(this); } - return attributes; + return _attributes; } } - private PSVariableAttributeCollection attributes; + private PSVariableAttributeCollection _attributes; /// @@ -462,7 +462,7 @@ namespace System.Management.Automation /// public virtual bool IsValidValue(object value) { - return IsValidValue(attributes, value); + return IsValidValue(_attributes, value); } internal static bool IsValidValue(IEnumerable attributes, object value) @@ -565,7 +565,6 @@ namespace System.Management.Automation attribute as ArgumentTransformationAttribute; if (transformationAttribute != null) { - result = transformationAttribute.Transform(engine, result); } } @@ -582,7 +581,7 @@ namespace System.Management.Automation { foreach (Attribute attribute in attributes) { - this.attributes.AddAttributeNoCheck(attribute); + _attributes.AddAttributeNoCheck(attribute); } } @@ -597,7 +596,7 @@ namespace System.Management.Automation { get { - return (options & ScopedItemOptions.Constant) != 0; + return (_options & ScopedItemOptions.Constant) != 0; } } // IsConstant @@ -610,10 +609,10 @@ namespace System.Management.Automation { get { - return (options & ScopedItemOptions.ReadOnly) != 0; + return (_options & ScopedItemOptions.ReadOnly) != 0; } } // IsReadOnly - + /// /// Returns true if the PSVariable is private (only visible in the /// current scope), false otherwise. @@ -623,7 +622,7 @@ namespace System.Management.Automation { get { - return (options & ScopedItemOptions.Private) != 0; + return (_options & ScopedItemOptions.Private) != 0; } } // IsPrivate @@ -636,7 +635,7 @@ namespace System.Management.Automation { get { - return (options & ScopedItemOptions.AllScope) != 0; + return (_options & ScopedItemOptions.AllScope) != 0; } } // IsAllScope @@ -658,14 +657,14 @@ namespace System.Management.Automation // If set to true, clean up the variable... if (value) { - options = ScopedItemOptions.None; + _options = ScopedItemOptions.None; _value = null; _wasRemoved = true; - attributes = null; + _attributes = null; } } } - bool _wasRemoved; + private bool _wasRemoved; internal SessionStateInternal SessionState { @@ -703,11 +702,11 @@ namespace System.Management.Automation { // Check to see if the variable is writable - if ((options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None) + if ((_options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( - name, + _name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable); @@ -717,9 +716,9 @@ namespace System.Management.Automation // Now perform all ArgumentTransformations that are needed object transformedValue = value; - if (attributes != null && attributes.Count > 0) + if (_attributes != null && _attributes.Count > 0) { - transformedValue = TransformValue(this.attributes, value); + transformedValue = TransformValue(_attributes, value); // Next check to make sure the value is valid @@ -729,7 +728,7 @@ namespace System.Management.Automation "ValidateSetFailure", null, Metadata.InvalidValueFailure, - name, + _name, ((transformedValue != null) ? transformedValue.ToString() : "$null")); throw e; @@ -742,7 +741,7 @@ namespace System.Management.Automation } // Set the value before triggering any write breakpoints - this._value = transformedValue; + _value = transformedValue; DebuggerCheckVariableWrite(); } @@ -753,7 +752,7 @@ namespace System.Management.Automation { newValue = CopyMutableValues(newValue); } - this._value = newValue; + _value = newValue; } virtual internal void SetValueRaw(object newValue, bool preserveValueTypeSemantics) @@ -774,9 +773,9 @@ namespace System.Management.Automation { if (!this.IsConstant) { - if (this._value != null) + if (_value != null) { - this._value = PSObject.AsPSObject(_value); + _value = PSObject.AsPSObject(_value); } } } @@ -828,8 +827,8 @@ namespace System.Management.Automation public LocalVariable(string name, MutableTuple tuple, int tupleSlot) : base(name, false) { - this._tuple = tuple; - this._tupleSlot = tupleSlot; + _tuple = tuple; + _tupleSlot = tupleSlot; } public override ScopedItemOptions Options @@ -916,12 +915,12 @@ namespace System.Management.Automation { get { - if (description == null) + if (_description == null) { - description = + _description = SessionStateStrings.DollarNullDescription; } - return description; + return _description; } set @@ -929,7 +928,7 @@ namespace System.Management.Automation // Do nothing } } - private string description; + private string _description; /// /// Gets the scope options for $null which is always None. @@ -958,29 +957,29 @@ namespace System.Management.Automation /// /// There are no constraints on the item. /// - None = 0, + None = 0, /// /// The item is readonly. It can be removed but cannot be changed. /// - ReadOnly = 0x1, + ReadOnly = 0x1, /// /// The item cannot be removed or changed. /// This flag can only be set a variable creation. /// - Constant = 0x2, + Constant = 0x2, /// /// The item is private to the scope it was created in and /// cannot be seen from child scopes. /// - Private = 0x4, + Private = 0x4, /// /// The item is propagated to each new child scope created. /// - AllScope = 0x8, + AllScope = 0x8, /// /// The option is not specified by the user diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index 0fd56301c..ac931fe92 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; @@ -19,7 +20,7 @@ namespace System.Management.Automation // field name. In general, it is preferred to use the VariablePath instead of the string // because we'll end up creating a VariablePath anyway, so doing it once is faster. // - static class SpecialVariables + internal static class SpecialVariables { internal const string HistorySize = "MaximumHistoryCount"; internal static readonly VariablePath HistorySizeVarPath = new VariablePath(HistorySize); @@ -218,7 +219,7 @@ namespace System.Management.Automation #region AllScope variables created in every session internal const string ConsoleFileName = "ConsoleFileName"; - internal const string ExecutionContext = "ExecutionContext"; + internal const string ExecutionContext = "ExecutionContext"; internal const string Home = "HOME"; internal const string Host = "Host"; internal const string PID = "PID"; @@ -232,18 +233,18 @@ namespace System.Management.Automation internal static List AllScopeSessionVariables = new List { - ConsoleFileName, - ExecutionContext, - Home, - Host, - PID, - PSCulture, - PSHome, - PSUICulture, - PSVersionTable, - PSEdition, + ConsoleFileName, + ExecutionContext, + Home, + Host, + PID, + PSCulture, + PSHome, + PSUICulture, + PSVersionTable, + PSEdition, ShellId - } ; + }; #endregion AllScope variables created in every session @@ -312,9 +313,9 @@ namespace System.Management.Automation SpecialVariables.True, }; - private static readonly HashSet ClassMethodsAccessibleVariables = new HashSet + private static readonly HashSet s_classMethodsAccessibleVariables = new HashSet ( - new string[] + new string[] { SpecialVariables.LastExitCode, SpecialVariables.Error, @@ -329,11 +330,11 @@ namespace System.Management.Automation internal static bool IsImplicitVariableAccessibleInClassMethod(VariablePath variablePath) { - return ClassMethodsAccessibleVariables.Contains(variablePath.UserPath); + return s_classMethodsAccessibleVariables.Contains(variablePath.UserPath); } } - enum AutomaticVariable + internal enum AutomaticVariable { Underbar = 0, Args = 1, @@ -347,7 +348,7 @@ namespace System.Management.Automation NumberOfAutomaticVariables // 1 + the last, used to initialize global scope. } - enum PreferenceVariable + internal enum PreferenceVariable { Debug = 9, Verbose = 10, diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index ac74d4fa2..6ecb5878b 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; @@ -14,8 +15,8 @@ namespace System.Management.Automation { internal ThirdPartyAdapter(Type adaptedType, PSPropertyAdapter externalAdapter) { - this.adaptedType = adaptedType; - this.externalAdapter = externalAdapter; + _adaptedType = adaptedType; + _externalAdapter = externalAdapter; } /// @@ -25,7 +26,7 @@ namespace System.Management.Automation { get { - return this.adaptedType; + return _adaptedType; } } @@ -34,9 +35,9 @@ namespace System.Management.Automation /// internal Type ExternalAdapterType { - get - { - return this.externalAdapter.GetType(); + get + { + return _externalAdapter.GetType(); } } @@ -49,7 +50,7 @@ namespace System.Management.Automation try { - typeNameHierarchy = this.externalAdapter.GetTypeNameHierarchy(obj); + typeNameHierarchy = _externalAdapter.GetTypeNameHierarchy(obj); } catch (Exception exception) { @@ -81,7 +82,7 @@ namespace System.Management.Automation try { - properties = this.externalAdapter.GetProperties(obj); + properties = _externalAdapter.GetProperties(obj); } catch (Exception exception) { @@ -104,7 +105,7 @@ namespace System.Management.Automation foreach (PSAdaptedProperty property in properties) { InitializeProperty(property, obj); - + members.Add(property as T); } } @@ -120,7 +121,7 @@ namespace System.Management.Automation try { - property = this.externalAdapter.GetProperty(obj, propertyName); + property = _externalAdapter.GetProperty(obj, propertyName); } catch (Exception exception) { @@ -136,7 +137,7 @@ namespace System.Management.Automation { InitializeProperty(property, obj); } - + return property; } @@ -163,15 +164,15 @@ namespace System.Management.Automation try { - return this.externalAdapter.IsSettable(adaptedProperty); + return _externalAdapter.IsSettable(adaptedProperty); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); throw new ExtendedTypeSystemException( - "PSPropertyAdapter.PropertyIsSettableError", - exception, + "PSPropertyAdapter.PropertyIsSettableError", + exception, ExtendedTypeSystem.PropertyIsSettableError, property.Name); } } @@ -187,15 +188,15 @@ namespace System.Management.Automation try { - return this.externalAdapter.IsGettable(adaptedProperty); + return _externalAdapter.IsGettable(adaptedProperty); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); throw new ExtendedTypeSystemException( - "PSPropertyAdapter.PropertyIsGettableError", - exception, + "PSPropertyAdapter.PropertyIsGettableError", + exception, ExtendedTypeSystem.PropertyIsGettableError, property.Name); } } @@ -211,7 +212,7 @@ namespace System.Management.Automation try { - return this.externalAdapter.GetPropertyValue(adaptedProperty); + return _externalAdapter.GetPropertyValue(adaptedProperty); } catch (Exception exception) { @@ -235,7 +236,7 @@ namespace System.Management.Automation try { - this.externalAdapter.SetPropertyValue(adaptedProperty, setValue); + _externalAdapter.SetPropertyValue(adaptedProperty, setValue); } catch (SetValueException) { throw; } catch (Exception exception) @@ -262,7 +263,7 @@ namespace System.Management.Automation try { - propertyTypeName = this.externalAdapter.GetPropertyTypeName(adaptedProperty); + propertyTypeName = _externalAdapter.GetPropertyTypeName(adaptedProperty); } catch (Exception exception) { @@ -277,8 +278,8 @@ namespace System.Management.Automation return propertyTypeName ?? "System.Object"; } - private Type adaptedType; - private PSPropertyAdapter externalAdapter; + private Type _adaptedType; + private PSPropertyAdapter _externalAdapter; } /// diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index ba4021e8e..562d86f81 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -19,9 +19,9 @@ namespace Microsoft.PowerShell.Commands.Management /// public class TransactedString : IEnlistmentNotification { - StringBuilder m_Value; - StringBuilder m_TemporaryValue; - Transaction enlistedTransaction = null; + private StringBuilder _value; + private StringBuilder _temporaryValue; + private Transaction _enlistedTransaction = null; /// /// Constructor for the TransactedString class. @@ -39,8 +39,8 @@ namespace Microsoft.PowerShell.Commands.Management /// public TransactedString(string value) { - m_Value = new StringBuilder(value); - m_TemporaryValue = null; + _value = new StringBuilder(value); + _temporaryValue = null; } /// @@ -48,9 +48,9 @@ namespace Microsoft.PowerShell.Commands.Management /// void IEnlistmentNotification.Commit(Enlistment enlistment) { - m_Value = new StringBuilder(m_TemporaryValue.ToString()); - m_TemporaryValue = null; - enlistedTransaction = null; + _value = new StringBuilder(_temporaryValue.ToString()); + _temporaryValue = null; + _enlistedTransaction = null; enlistment.Done(); } @@ -59,8 +59,8 @@ namespace Microsoft.PowerShell.Commands.Management /// void IEnlistmentNotification.Rollback(Enlistment enlistment) { - m_TemporaryValue = null; - enlistedTransaction = null; + _temporaryValue = null; + _enlistedTransaction = null; enlistment.Done(); } @@ -87,13 +87,13 @@ namespace Microsoft.PowerShell.Commands.Management { ValidateTransactionOrEnlist(); - if(enlistedTransaction != null) + if (_enlistedTransaction != null) { - m_TemporaryValue.Append(text); + _temporaryValue.Append(text); } else { - m_Value.Append(text); + _value.Append(text); } } @@ -111,13 +111,13 @@ namespace Microsoft.PowerShell.Commands.Management { ValidateTransactionOrEnlist(); - if(enlistedTransaction != null) + if (_enlistedTransaction != null) { - m_TemporaryValue.Remove(startIndex, length); + _temporaryValue.Remove(startIndex, length); } else { - m_Value.Remove(startIndex, length); + _value.Remove(startIndex, length); } } @@ -133,15 +133,15 @@ namespace Microsoft.PowerShell.Commands.Management { // 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( + if ( (Transaction.Current == null) || - (enlistedTransaction != Transaction.Current)) + (_enlistedTransaction != Transaction.Current)) { - return m_Value.Length; + return _value.Length; } else { - return m_TemporaryValue.Length; + return _temporaryValue.Length; } } } @@ -156,37 +156,37 @@ namespace Microsoft.PowerShell.Commands.Management { // 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( + if ( (Transaction.Current == null) || - (enlistedTransaction != Transaction.Current)) + (_enlistedTransaction != Transaction.Current)) { - return m_Value.ToString(); + return _value.ToString(); } else { - return m_TemporaryValue.ToString(); + return _temporaryValue.ToString(); } } private void ValidateTransactionOrEnlist() { // We're in a transaction - if(Transaction.Current != null) + 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) + if (_enlistedTransaction == null) { Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None); - enlistedTransaction = Transaction.Current; + _enlistedTransaction = Transaction.Current; - m_TemporaryValue = new StringBuilder(m_Value.ToString()); + _temporaryValue = new StringBuilder(_value.ToString()); } // We're already enlisted in a transaction else { // And we're in that transaction - if(Transaction.Current != enlistedTransaction) + if (Transaction.Current != _enlistedTransaction) { throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); } @@ -196,7 +196,7 @@ namespace Microsoft.PowerShell.Commands.Management else { // If we're not subscribed to a transaction, modify the underlying value - if(enlistedTransaction != null) + 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 index 87288e653..842d75789 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -31,7 +31,7 @@ namespace System.Management.Automation /// Active = 2 } - + /// /// Represents an active transaction /// @@ -44,9 +44,9 @@ namespace System.Management.Automation /// internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout) { - transaction = new CommittableTransaction(timeout); - this.rollbackPreference = rollbackPreference; - this.subscriberCount = 1; + _transaction = new CommittableTransaction(timeout); + _rollbackPreference = rollbackPreference; + _subscriberCount = 1; } /// @@ -55,12 +55,12 @@ namespace System.Management.Automation /// internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity) { - this.transaction = transaction; - this.rollbackPreference = severity; - this.subscriberCount = 1; + _transaction = transaction; + _rollbackPreference = severity; + _subscriberCount = 1; } - private CommittableTransaction transaction; + private CommittableTransaction _transaction; /// /// Gets the rollback preference for this transaction @@ -68,9 +68,9 @@ namespace System.Management.Automation /// public RollbackSeverity RollbackPreference { - get { return rollbackPreference; } + get { return _rollbackPreference; } } - private RollbackSeverity rollbackPreference; + private RollbackSeverity _rollbackPreference; /// /// Gets the number of subscribers to this transaction @@ -86,11 +86,11 @@ namespace System.Management.Automation this.SubscriberCount = 0; } - return subscriberCount; + return _subscriberCount; } - set { subscriberCount = value; } + set { _subscriberCount = value; } } - private int subscriberCount; + private int _subscriberCount; /// /// Returns the status of this transaction. @@ -100,11 +100,11 @@ namespace System.Management.Automation { get { - if(IsRolledBack) + if (IsRolledBack) { return PSTransactionStatus.RolledBack; } - else if(IsCommitted) + else if (IsCommitted) { return PSTransactionStatus.Committed; } @@ -121,7 +121,7 @@ namespace System.Management.Automation /// internal void Activate() { - Transaction.Current = transaction; + Transaction.Current = _transaction; } /// @@ -130,8 +130,8 @@ namespace System.Management.Automation /// internal void Commit() { - transaction.Commit(); - this.isCommitted = true; + _transaction.Commit(); + _isCommitted = true; } /// @@ -140,8 +140,8 @@ namespace System.Management.Automation /// internal void Rollback() { - transaction.Rollback(); - this.isRolledBack = true; + _transaction.Rollback(); + _isRolledBack = true; } /// @@ -155,21 +155,21 @@ namespace System.Management.Automation { // Check if it's been aborted underneath us if ( - (! isRolledBack) && - (transaction != null) && - (transaction.TransactionInformation.Status == TransactionStatus.Aborted)) + (!_isRolledBack) && + (_transaction != null) && + (_transaction.TransactionInformation.Status == TransactionStatus.Aborted)) { - isRolledBack = true; + _isRolledBack = true; } - return isRolledBack; + return _isRolledBack; } set { - isRolledBack = value; + _isRolledBack = value; } } - private bool isRolledBack = false; + private bool _isRolledBack = false; /// /// Determines whether this PSTransaction @@ -180,14 +180,14 @@ namespace System.Management.Automation { get { - return isCommitted; + return _isCommitted; } set { - isCommitted = value; + _isCommitted = value; } } - private bool isCommitted = false; + private bool _isCommitted = false; /// /// Destructor for the PSTransaction class @@ -219,11 +219,11 @@ namespace System.Management.Automation /// public void Dispose(bool disposing) { - if(disposing) + if (disposing) { - if(transaction != null) + if (_transaction != null) { - transaction.Dispose(); + _transaction.Dispose(); } } } @@ -241,10 +241,10 @@ namespace System.Management.Automation /// internal PSTransactionContext(PSTransactionManager transactionManager) { - this.transactionManager = transactionManager; + _transactionManager = transactionManager; transactionManager.SetActive(); } - private PSTransactionManager transactionManager; + private PSTransactionManager _transactionManager; /// /// Destructor for the PSTransactionManager class @@ -276,9 +276,9 @@ namespace System.Management.Automation /// private void Dispose(bool disposing) { - if(disposing) + if (disposing) { - transactionManager.ResetActive(); + _transactionManager.ResetActive(); } } } @@ -320,8 +320,8 @@ namespace System.Management.Automation.Internal /// internal PSTransactionManager() { - transactionStack = new Stack(); - transactionStack.Push(null); + _transactionStack = new Stack(); + _transactionStack.Push(null); } /// @@ -331,7 +331,7 @@ namespace System.Management.Automation.Internal /// internal static IDisposable GetEngineProtectionScope() { - if(engineProtectionEnabled && (Transaction.Current != null)) + if (s_engineProtectionEnabled && (Transaction.Current != null)) { return new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Suppress); @@ -350,9 +350,9 @@ namespace System.Management.Automation.Internal /// internal static void EnableEngineProtection() { - engineProtectionEnabled = true; + s_engineProtectionEnabled = true; } - private static bool engineProtectionEnabled = false; + private static bool s_engineProtectionEnabled = false; /// /// Gets the rollback preference for the active transaction @@ -362,7 +362,7 @@ namespace System.Management.Automation.Internal { get { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); if (currentTransaction == null) { @@ -370,7 +370,7 @@ namespace System.Management.Automation.Internal // This is not an expected condition, and is just protective // coding. - #pragma warning suppress 56503 +#pragma warning suppress 56503 throw new InvalidOperationException(error); } @@ -395,7 +395,7 @@ namespace System.Management.Automation.Internal /// internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout) { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); // There is a transaction on the stack if (currentTransaction != null) @@ -405,10 +405,10 @@ namespace System.Management.Automation.Internal if (currentTransaction.IsRolledBack || currentTransaction.IsCommitted) { // Clean up the "used" one - transactionStack.Pop().Dispose(); + _transactionStack.Pop().Dispose(); // And add a new one to the stack - transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); + _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); } else { @@ -419,7 +419,7 @@ namespace System.Management.Automation.Internal else { // Add a new transaction to the stack - transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); + _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); } } @@ -440,7 +440,7 @@ namespace System.Management.Automation.Internal /// internal void CreateNew(RollbackSeverity rollbackPreference, TimeSpan timeout) { - transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); + _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); } /// @@ -450,7 +450,7 @@ namespace System.Management.Automation.Internal /// internal void Commit() { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); // Should not be able to commit a transaction that is not active if (currentTransaction == null) @@ -473,7 +473,7 @@ namespace System.Management.Automation.Internal throw new InvalidOperationException(error); } - if(currentTransaction.SubscriberCount == 1) + if (currentTransaction.SubscriberCount == 1) { currentTransaction.Commit(); currentTransaction.SubscriberCount = 0; @@ -484,10 +484,10 @@ namespace System.Management.Automation.Internal } // Now that we've committed, go back to the last available transaction - while((transactionStack.Count > 2) && - (transactionStack.Peek().IsRolledBack || transactionStack.Peek().IsCommitted)) + while ((_transactionStack.Count > 2) && + (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) { - transactionStack.Pop().Dispose(); + _transactionStack.Pop().Dispose(); } } @@ -506,7 +506,7 @@ namespace System.Management.Automation.Internal /// internal void Rollback(bool suppressErrors) { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); // Should not be able to roll back a transaction that is not active if (currentTransaction == null) @@ -518,7 +518,7 @@ namespace System.Management.Automation.Internal // If you are already in a transaction that has been aborted if (currentTransaction.IsRolledBack) { - if(! suppressErrors) + if (!suppressErrors) { // Otherwise, you should not be able to roll it back. string error = TransactionStrings.TransactionRolledBackForRollback; @@ -529,7 +529,7 @@ namespace System.Management.Automation.Internal // See if they've already committed the transaction if (currentTransaction.IsCommitted) { - if(! suppressErrors) + if (!suppressErrors) { string error = TransactionStrings.CommittedTransactionForRollback; throw new InvalidOperationException(error); @@ -541,10 +541,10 @@ namespace System.Management.Automation.Internal 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)) + while ((_transactionStack.Count > 2) && + (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) { - transactionStack.Pop().Dispose(); + _transactionStack.Pop().Dispose(); } } @@ -559,17 +559,17 @@ namespace System.Management.Automation.Internal throw new InvalidOperationException(TransactionStrings.BaseTransactionMustBeFirst); } - PSTransaction currentTransaction = transactionStack.Peek(); + 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)) + while (_transactionStack.Peek() != null && + (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) { - transactionStack.Pop().Dispose(); + _transactionStack.Pop().Dispose(); } - this.baseTransaction = new PSTransaction(transaction, severity); - this.transactionStack.Push(this.baseTransaction); + _baseTransaction = new PSTransaction(transaction, severity); + _transactionStack.Push(_baseTransaction); } /// @@ -578,22 +578,22 @@ namespace System.Management.Automation.Internal /// internal void ClearBaseTransaction() { - if (this.baseTransaction == null) + if (_baseTransaction == null) { throw new InvalidOperationException(TransactionStrings.BaseTransactionNotSet); } - - if (this.transactionStack.Peek() != this.baseTransaction) + + if (_transactionStack.Peek() != _baseTransaction) { throw new InvalidOperationException(TransactionStrings.BaseTransactionNotActive); } - this.transactionStack.Pop().Dispose(); - this.baseTransaction = null; + _transactionStack.Pop().Dispose(); + _baseTransaction = null; } - private Stack transactionStack; - private PSTransaction baseTransaction; + private Stack _transactionStack; + private PSTransaction _baseTransaction; /// /// Returns the current engine transaction @@ -601,7 +601,7 @@ namespace System.Management.Automation.Internal /// internal PSTransaction GetCurrent() { - return transactionStack.Peek(); + return _transactionStack.Peek(); } /// @@ -611,8 +611,8 @@ namespace System.Management.Automation.Internal internal void SetActive() { PSTransactionManager.EnableEngineProtection(); - - PSTransaction currentTransaction = transactionStack.Peek(); + + PSTransaction currentTransaction = _transactionStack.Peek(); // Should not be able to activate a transaction that is not active if (currentTransaction == null) @@ -629,10 +629,10 @@ namespace System.Management.Automation.Internal throw new TransactionAbortedException(error); } - previousActiveTransaction = Transaction.Current; + _previousActiveTransaction = Transaction.Current; currentTransaction.Activate(); } - private Transaction previousActiveTransaction; + private Transaction _previousActiveTransaction; /// /// Deactivates the current transaction in the engine, and restores the @@ -644,8 +644,8 @@ namespace System.Management.Automation.Internal // 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; + Transaction.Current = _previousActiveTransaction; + _previousActiveTransaction = null; } /// @@ -656,7 +656,7 @@ namespace System.Management.Automation.Internal { get { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); if ((currentTransaction != null) && (!currentTransaction.IsCommitted) && @@ -678,7 +678,7 @@ namespace System.Management.Automation.Internal { get { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); if (currentTransaction != null) { @@ -698,7 +698,7 @@ namespace System.Management.Automation.Internal { get { - PSTransaction currentTransaction = transactionStack.Peek(); + PSTransaction currentTransaction = _transactionStack.Peek(); if (currentTransaction != null) { @@ -742,15 +742,15 @@ namespace System.Management.Automation.Internal [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) + if (disposing) { ResetActive(); - while(transactionStack.Peek() != null) + while (_transactionStack.Peek() != null) { - PSTransaction currentTransaction = transactionStack.Pop(); + PSTransaction currentTransaction = _transactionStack.Pop(); - if (currentTransaction != this.baseTransaction) + if (currentTransaction != _baseTransaction) { currentTransaction.Dispose(); } diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index dee63ba9f..dae06f914 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; @@ -19,14 +20,14 @@ namespace System.Management.Automation { #region Private Data - private bool isMandatory; - private int position; - private bool valueFromPipeline; - private bool valueFromPipelineByPropertyName; - private bool valueFromRemainingArguments; - private string helpMessage; - private string helpMessageBaseName; - private string helpMessageResourceId; + private bool _isMandatory; + private int _position; + private bool _valueFromPipeline; + private bool _valueFromPipelineByPropertyName; + private bool _valueFromRemainingArguments; + private string _helpMessage; + private string _helpMessageBaseName; + private string _helpMessageResourceId; #endregion @@ -53,14 +54,14 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("other"); } - this.helpMessage = other.helpMessage; - this.helpMessageBaseName = other.helpMessageBaseName; - this.helpMessageResourceId = other.helpMessageResourceId; - this.isMandatory = other.isMandatory; - this.position = other.position; - this.valueFromPipeline = other.valueFromPipeline; - this.valueFromPipelineByPropertyName = other.valueFromPipelineByPropertyName; - this.valueFromRemainingArguments = other.valueFromRemainingArguments; + _helpMessage = other._helpMessage; + _helpMessageBaseName = other._helpMessageBaseName; + _helpMessageResourceId = other._helpMessageResourceId; + _isMandatory = other._isMandatory; + _position = other._position; + _valueFromPipeline = other._valueFromPipeline; + _valueFromPipelineByPropertyName = other._valueFromPipelineByPropertyName; + _valueFromRemainingArguments = other._valueFromRemainingArguments; } #endregion @@ -75,12 +76,12 @@ namespace System.Management.Automation { get { - return isMandatory; + return _isMandatory; } set { - isMandatory = value; + _isMandatory = value; } } @@ -93,11 +94,11 @@ namespace System.Management.Automation { get { - return position; + return _position; } set { - position = value; + _position = value; } } @@ -108,11 +109,11 @@ namespace System.Management.Automation { get { - return valueFromPipeline; + return _valueFromPipeline; } set { - valueFromPipeline = value; + _valueFromPipeline = value; } } @@ -124,11 +125,11 @@ namespace System.Management.Automation { get { - return valueFromPipelineByPropertyName; + return _valueFromPipelineByPropertyName; } set { - valueFromPipelineByPropertyName = value; + _valueFromPipelineByPropertyName = value; } } @@ -141,11 +142,11 @@ namespace System.Management.Automation { get { - return valueFromRemainingArguments; + return _valueFromRemainingArguments; } set { - valueFromRemainingArguments = value; + _valueFromRemainingArguments = value; } } @@ -156,11 +157,11 @@ namespace System.Management.Automation { get { - return helpMessage; + return _helpMessage; } set { - helpMessage = value; + _helpMessage = value; } } @@ -171,11 +172,11 @@ namespace System.Management.Automation { get { - return helpMessageBaseName; + return _helpMessageBaseName; } set { - helpMessageBaseName = value; + _helpMessageBaseName = value; } } @@ -186,13 +187,13 @@ namespace System.Management.Automation { get { - return helpMessageResourceId; + return _helpMessageResourceId; } set { - helpMessageResourceId = value; + _helpMessageResourceId = value; } - } + } #endregion @@ -204,16 +205,16 @@ namespace System.Management.Automation /// internal void Initialize(ParameterSetSpecificMetadata psMD) { - isMandatory = psMD.IsMandatory; - position = psMD.Position; - valueFromPipeline = psMD.ValueFromPipeline; - valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName; - valueFromRemainingArguments = psMD.ValueFromRemainingArguments; - helpMessage = psMD.HelpMessage; - helpMessageBaseName = psMD.HelpMessageBaseName; - helpMessageResourceId = psMD.HelpMessageResourceId; + _isMandatory = psMD.IsMandatory; + _position = psMD.Position; + _valueFromPipeline = psMD.ValueFromPipeline; + _valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName; + _valueFromRemainingArguments = psMD.ValueFromRemainingArguments; + _helpMessage = psMD.HelpMessage; + _helpMessageBaseName = psMD.HelpMessageBaseName; + _helpMessageResourceId = psMD.HelpMessageResourceId; } - + /// /// Compares this instance with the supplied . /// @@ -225,14 +226,14 @@ namespace System.Management.Automation /// internal bool Equals(ParameterSetMetadata second) { - if ((isMandatory != second.isMandatory) || - (position != second.position) || - (valueFromPipeline != second.valueFromPipeline) || - (valueFromPipelineByPropertyName != second.valueFromPipelineByPropertyName) || - (valueFromRemainingArguments != second.valueFromRemainingArguments) || - (helpMessage != second.helpMessage) || - (helpMessageBaseName != second.helpMessageBaseName) || - (helpMessageResourceId != second.helpMessageResourceId)) + if ((_isMandatory != second._isMandatory) || + (_position != second._position) || + (_valueFromPipeline != second._valueFromPipeline) || + (_valueFromPipelineByPropertyName != second._valueFromPipelineByPropertyName) || + (_valueFromRemainingArguments != second._valueFromRemainingArguments) || + (_helpMessage != second._helpMessage) || + (_helpMessageBaseName != second._helpMessageBaseName) || + (_helpMessageResourceId != second._helpMessageResourceId)) { return false; } @@ -306,43 +307,43 @@ namespace System.Management.Automation Text.StringBuilder result = new System.Text.StringBuilder(); string prefix = ""; - if (isMandatory) + if (_isMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, MandatoryFormat, prefix); prefix = ", "; } - if (position != Int32.MinValue) + if (_position != Int32.MinValue) { - result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, position); + result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, _position); prefix = ", "; } - if (valueFromPipeline) + if (_valueFromPipeline) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineFormat, prefix); prefix = ", "; } - if (valueFromPipelineByPropertyName) + if (_valueFromPipelineByPropertyName) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineByPropertyNameFormat, prefix); prefix = ", "; } - if (valueFromRemainingArguments) + if (_valueFromRemainingArguments) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromRemainingArgumentsFormat, prefix); prefix = ", "; } - if (!string.IsNullOrEmpty(helpMessage)) + if (!string.IsNullOrEmpty(_helpMessage)) { result.AppendFormat( CultureInfo.InvariantCulture, - HelpMessageFormat, - prefix, - CodeGeneration.EscapeSingleQuotedStringContent(helpMessage)); + HelpMessageFormat, + prefix, + CodeGeneration.EscapeSingleQuotedStringContent(_helpMessage)); prefix = ", "; } @@ -359,12 +360,12 @@ namespace System.Management.Automation { #region Private Data - private string name; - private Type parameterType; - private bool isDynamic; - private Dictionary parameterSets; - private Collection aliases; - private Collection attributes; + private string _name; + private Type _parameterType; + private bool _isDynamic; + private Dictionary _parameterSets; + private Collection _aliases; + private Collection _attributes; #endregion @@ -403,12 +404,12 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("name"); } - this.name = name; - this.parameterType = parameterType; + _name = name; + _parameterType = parameterType; - this.attributes = new Collection(); - this.aliases = new Collection(); - this.parameterSets = new Dictionary(); + _attributes = new Collection(); + _aliases = new Collection(); + _parameterSets = new Dictionary(); } /// @@ -423,43 +424,43 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("other"); } - this.isDynamic = other.isDynamic; - this.name = other.name; - this.parameterType = other.parameterType; + _isDynamic = other._isDynamic; + _name = other._name; + _parameterType = other._parameterType; // deep copy - this.aliases = new Collection(new List(other.aliases.Count)); - foreach (string alias in other.aliases) + _aliases = new Collection(new List(other._aliases.Count)); + foreach (string alias in other._aliases) { - this.aliases.Add(alias); + _aliases.Add(alias); } // deep copy of the collection, collection items (Attributes) copied by reference - if (other.attributes == null) + if (other._attributes == null) { - this.attributes = null; + _attributes = null; } else { - this.attributes = new Collection(new List(other.attributes.Count)); - foreach (Attribute attribute in other.attributes) + _attributes = new Collection(new List(other._attributes.Count)); + foreach (Attribute attribute in other._attributes) { - this.attributes.Add(attribute); + _attributes.Add(attribute); } } // deep copy - this.parameterSets = null; - if (other.parameterSets == null) + _parameterSets = null; + if (other._parameterSets == null) { - this.parameterSets = null; + _parameterSets = null; } else { - this.parameterSets = new Dictionary(other.parameterSets.Count); - foreach (KeyValuePair entry in other.parameterSets) + _parameterSets = new Dictionary(other._parameterSets.Count); + foreach (KeyValuePair entry in other._parameterSets) { - this.parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value)); + _parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value)); } } } @@ -490,18 +491,18 @@ namespace System.Management.Automation Dictionary parameterSets, Type parameterType) { - this.aliases = aliases; - this.isDynamic = isDynamic; - this.name = name; - this.parameterSets = parameterSets; - this.parameterType = parameterType; - this.attributes = new Collection(); + _aliases = aliases; + _isDynamic = isDynamic; + _name = name; + _parameterSets = parameterSets; + _parameterType = parameterType; + _attributes = new Collection(); } #endregion #region Public Methods/Properties - + /// /// Gets the name of the parameter /// @@ -510,7 +511,7 @@ namespace System.Management.Automation { get { - return name; + return _name; } set @@ -520,7 +521,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("Name"); } - name = value; + _name = value; } } @@ -531,12 +532,12 @@ namespace System.Management.Automation { get { - return parameterType; + return _parameterType; } set { - parameterType = value; + _parameterType = value; } } @@ -547,26 +548,26 @@ namespace System.Management.Automation { get { - return parameterSets; + return _parameterSets; } } /// /// Specifies if the parameter is Dynamic /// - public bool IsDynamic + public bool IsDynamic { - get { return isDynamic; } - set { isDynamic = value; } + get { return _isDynamic; } + set { _isDynamic = value; } } /// /// Specifies the alias names for this parameter /// - public Collection Aliases + public Collection Aliases { get { - return aliases; + return _aliases; } } @@ -577,26 +578,26 @@ namespace System.Management.Automation { get { - return attributes; + return _attributes; } } /// /// Specifies if the parameter is a SwitchParameter /// - public bool SwitchParameter + public bool SwitchParameter { get { - if (parameterType != null) + if (_parameterType != null) { - return parameterType.Equals(typeof(SwitchParameter)); + return _parameterType.Equals(typeof(SwitchParameter)); } return false; } } - + /// /// Gets a dictionary of parameter metadata for the supplied . /// @@ -634,30 +635,30 @@ namespace System.Management.Automation /// internal void Initialize(CompiledCommandParameter compiledParameterMD) { - name = compiledParameterMD.Name; - parameterType = compiledParameterMD.Type; - isDynamic = compiledParameterMD.IsDynamic; - + _name = compiledParameterMD.Name; + _parameterType = compiledParameterMD.Type; + _isDynamic = compiledParameterMD.IsDynamic; + // Create parameter set metadata - parameterSets = new Dictionary(StringComparer.OrdinalIgnoreCase); + _parameterSets = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string key in compiledParameterMD.ParameterSetData.Keys) { ParameterSetSpecificMetadata pMD = compiledParameterMD.ParameterSetData[key]; - parameterSets.Add(key, new ParameterSetMetadata(pMD)); + _parameterSets.Add(key, new ParameterSetMetadata(pMD)); } // Create aliases for this parameter - aliases = new Collection(); + _aliases = new Collection(); foreach (string alias in compiledParameterMD.Aliases) { - aliases.Add(alias); + _aliases.Add(alias); } // Create attributes for this parameter - attributes = new Collection(); + _attributes = new Collection(); foreach (var attrib in compiledParameterMD.CompiledAttributes) { - attributes.Add(attrib); + _attributes.Add(attrib); } } @@ -672,7 +673,7 @@ namespace System.Management.Automation Dbg.Assert(null != cmdParameterMetadata, "cmdParameterMetadata cannot be null"); Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); - + foreach (var keyValuePair in cmdParameterMetadata.BindableParameters) { var key = keyValuePair.Key; @@ -691,22 +692,22 @@ namespace System.Management.Automation { // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. bool parameterAcceptsObjects = - ((int) (LanguagePrimitives.FigureConversion(typeof (object), this.ParameterType).Rank)) >= - (int) (ConversionRank.AssignableS2A); + ((int)(LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank)) >= + (int)(ConversionRank.AssignableS2A); if (dotNetType.Equals(typeof(object))) { return parameterAcceptsObjects; } if (parameterAcceptsObjects) { - return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof (object))); + return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); } // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. var convertionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType); if (convertionData != null) { - if ((int) (convertionData.Rank) >= (int) (ConversionRank.NumericImplicitS2A)) + if ((int)(convertionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A)) { return true; } @@ -779,9 +780,9 @@ namespace System.Management.Automation { Text.StringBuilder result = new System.Text.StringBuilder(); - if (parameterSets != null && isProxyForCmdlet) + if (_parameterSets != null && isProxyForCmdlet) { - foreach (var pair in parameterSets) + foreach (var pair in _parameterSets) { string parameterSetName = pair.Key; ParameterSetMetadata parameterSet = pair.Value; @@ -795,7 +796,7 @@ namespace System.Management.Automation { result.AppendFormat( CultureInfo.InvariantCulture, - ParameterSetNameFormat, + ParameterSetNameFormat, CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); separator = ", "; } @@ -809,12 +810,12 @@ namespace System.Management.Automation } } - if ((aliases != null) && (aliases.Count > 0)) + if ((_aliases != null) && (_aliases.Count > 0)) { Text.StringBuilder aliasesData = new System.Text.StringBuilder(); string comma = ""; // comma is not need for the first element - foreach (string alias in aliases) + foreach (string alias in _aliases) { aliasesData.AppendFormat( CultureInfo.InvariantCulture, @@ -827,9 +828,9 @@ namespace System.Management.Automation result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString()); } - if ((attributes != null) && (attributes.Count > 0)) + if ((_attributes != null) && (_attributes.Count > 0)) { - foreach (Attribute attrib in attributes) + foreach (Attribute attrib in _attributes) { string attribData = GetProxyAttributeData(attrib, prefix); if (!string.IsNullOrEmpty(attribData)) @@ -843,14 +844,14 @@ namespace System.Management.Automation { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch"); } - else if (parameterType != null) + else if (_parameterType != null) { - result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(parameterType)); + result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType)); } /* 1. CredentialAttribute needs to go after the type * 2. To avoid risk, I don't want to move other attributes to go here / after the type */ - CredentialAttribute credentialAttrib = attributes.OfType().FirstOrDefault(); + CredentialAttribute credentialAttrib = _attributes.OfType().FirstOrDefault(); if (credentialAttrib != null) { string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix); @@ -862,9 +863,9 @@ namespace System.Management.Automation result.AppendFormat( CultureInfo.InvariantCulture, - ParameterNameFormat, + ParameterNameFormat, prefix, - CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? name : paramNameOverride)); + CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? _name : paramNameOverride)); return result.ToString(); } @@ -997,7 +998,7 @@ namespace System.Management.Automation { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = ""; - foreach(string validValue in setAttrib.ValidValues) + foreach (string validValue in setAttrib.ValidValues) { values.AppendFormat( CultureInfo.InvariantCulture, @@ -1029,8 +1030,8 @@ namespace System.Management.Automation { result = string.Format( CultureInfo.InvariantCulture, - PSTypeNameFormat, - prefix, + PSTypeNameFormat, + prefix, CodeGeneration.EscapeSingleQuotedStringContent(psTypeNameAttrib.PSTypeName)); return result; } @@ -1111,7 +1112,7 @@ namespace System.Management.Automation } return new InternalParameterMetadata(runtimeDefinedParameters, processingDynamicParameters, checkNames); - } + } /// /// Gets or constructs an instance of the InternalParameterMetadata for the specified type. @@ -1151,13 +1152,13 @@ namespace System.Management.Automation } InternalParameterMetadata result; - if (context == null || !ParameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) + if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) { result = new InternalParameterMetadata(type, processingDynamicParameters); if (context != null) { - ParameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); + s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } } return result; @@ -1230,8 +1231,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("type"); } - this.type = type; - this.typeName = type.Name; + _type = type; + _typeName = type.Name; ConstructCompiledParametersUsingReflection(processingDynamicParameters); } @@ -1246,10 +1247,10 @@ namespace System.Management.Automation { get { - return typeName; + return _typeName; } } - private string typeName = String.Empty; + private string _typeName = String.Empty; /// /// Gets a dictionary of the compiled parameter metadata for this Type. @@ -1261,10 +1262,10 @@ namespace System.Management.Automation { get { - return bindableParameters; + return _bindableParameters; } } - private Dictionary bindableParameters = + private Dictionary _bindableParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); /// @@ -1276,10 +1277,10 @@ namespace System.Management.Automation { get { - return aliasedParameters; + return _aliasedParameters; } } - private Dictionary aliasedParameters = + private Dictionary _aliasedParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); /// @@ -1287,7 +1288,7 @@ namespace System.Management.Automation /// This member is null in all cases except when constructed with using reflection /// against the Type. /// - private Type type; + private Type _type; /// /// The flags used when reflecting against the object to create the metadata @@ -1322,7 +1323,7 @@ namespace System.Management.Automation bool processingDynamicParameters, bool checkNames) { - Diagnostics.Assert ( + Diagnostics.Assert( runtimeDefinedParameters != null, "This method should only be called when constructed with a valid runtime-defined parameter collection"); @@ -1356,15 +1357,15 @@ namespace System.Management.Automation private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters) { Diagnostics.Assert( - type != null, + _type != null, "This method should only be called when constructed with the Type"); // Get the property and field info - PropertyInfo[] properties = type.GetProperties(metaDataBindingFlags); - FieldInfo[] fields = type.GetFields(metaDataBindingFlags); + PropertyInfo[] properties = _type.GetProperties(metaDataBindingFlags); + FieldInfo[] fields = _type.GetFields(metaDataBindingFlags); - foreach(PropertyInfo property in properties) + foreach (PropertyInfo property in properties) { // Check whether the property is a parameter if (!IsMemberAParameter(property)) @@ -1375,7 +1376,7 @@ namespace System.Management.Automation AddParameter(property, processingDynamicParameters); } - foreach(FieldInfo field in fields) + foreach (FieldInfo field in fields) { // Check whether the field is a parameter if (!IsMemberAParameter(field)) @@ -1417,7 +1418,7 @@ namespace System.Management.Automation do // false loop { CompiledCommandParameter existingParameter; - if (!bindableParameters.TryGetValue(member.Name, out existingParameter)) + if (!_bindableParameters.TryGetValue(member.Name, out existingParameter)) { break; } @@ -1474,14 +1475,14 @@ namespace System.Management.Automation CheckForReservedParameter(parameter.Name); } - bindableParameters.Add(parameter.Name, parameter); + _bindableParameters.Add(parameter.Name, parameter); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { // NTRAID#Windows Out Of Band Releases-917356-JonN - if (aliasedParameters.ContainsKey(alias)) + if (_aliasedParameters.ContainsKey(alias)) { throw new MetadataException( "AliasDeclaredMultipleTimes", @@ -1489,19 +1490,19 @@ namespace System.Management.Automation DiscoveryExceptions.AliasDeclaredMultipleTimes, alias); } - aliasedParameters.Add(alias, parameter); + _aliasedParameters.Add(alias, parameter); } } private void RemoveParameter(CompiledCommandParameter parameter) { - bindableParameters.Remove(parameter.Name); + _bindableParameters.Remove(parameter.Name); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { - aliasedParameters.Remove(alias); + _aliasedParameters.Remove(alias); } } @@ -1537,19 +1538,19 @@ namespace System.Management.Automation catch (MetadataException metadataException) { throw new MetadataException( - "GetCustomAttributesMetadataException", - metadataException, + "GetCustomAttributesMetadataException", + metadataException, Metadata.MetadataMemberInitialization, - member.Name, + member.Name, metadataException.Message); } catch (ArgumentException argumentException) { throw new MetadataException( "GetCustomAttributesArgumentException", - argumentException, + argumentException, Metadata.MetadataMemberInitialization, - member.Name, + member.Name, argumentException.Message); } @@ -1564,7 +1565,7 @@ namespace System.Management.Automation /// The cache of the type metadata. The key for the cache is the Type.FullName. /// Note, this is a case-sensitive dictionary because Type names are case sensitive. /// - private static System.Collections.Concurrent.ConcurrentDictionary ParameterMetadataCache = + private static System.Collections.Concurrent.ConcurrentDictionary s_parameterMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.Ordinal); #endregion Metadata cache diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 0d593667c..0bab1ee05 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -31,13 +31,13 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace System.Management.Automation.Runspaces { // ReSharper disable RedundantCast - class TypesPs1xmlReader + internal class TypesPs1xmlReader { public TypesPs1xmlReader(LoadContext context) { - this._context = context; - this._reader = context.reader; - this._readerLineInfo = (IXmlLineInfo)context.reader; + _context = context; + _reader = context.reader; + _readerLineInfo = (IXmlLineInfo)context.reader; InitIDs(); } @@ -47,16 +47,18 @@ namespace System.Management.Automation.Runspaces #region Helpers - string ReadElementString(string nodeName) + private string ReadElementString(string nodeName) { // This code is based on XmlReader.ReadElementString, which is not available in CoreCLR. string result = string.Empty; - - if (_reader.MoveToContent() != XmlNodeType.Element) { + + if (_reader.MoveToContent() != XmlNodeType.Element) + { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NodeShouldHaveInnerText, nodeName); return null; } - if (!_reader.IsEmptyElement) { + if (!_reader.IsEmptyElement) + { _reader.Read(); while (_reader.NodeType == XmlNodeType.Text) { @@ -66,14 +68,16 @@ namespace System.Management.Automation.Runspaces break; } } - if (_reader.NodeType != XmlNodeType.EndElement) { + if (_reader.NodeType != XmlNodeType.EndElement) + { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NodeShouldHaveInnerText, nodeName); return null; } result = result.Trim(); _reader.Read(); } - else { + else + { _reader.Read(); } if (string.IsNullOrWhiteSpace(result)) @@ -84,7 +88,7 @@ namespace System.Management.Automation.Runspaces return result; } - bool? ReadIsHiddenAttribute() + private bool? ReadIsHiddenAttribute() { bool? isHidden = default(bool?); @@ -100,7 +104,7 @@ namespace System.Management.Automation.Runspaces return isHidden; } - void ReadIsHiddenAttributeNotSupported(string node) + private void ReadIsHiddenAttributeNotSupported(string node) { if (ReadIsHiddenAttribute().HasValue) { @@ -118,7 +122,7 @@ namespace System.Management.Automation.Runspaces _reader.ReadEndElement(); } - void UnknownNode(string node, string expectedNodes) + private void UnknownNode(string node, string expectedNodes) { if (_reader.NodeType == XmlNodeType.Text) { @@ -147,17 +151,17 @@ namespace System.Management.Automation.Runspaces } } - void NotMoreThanOnce(string node, string parent) + private void NotMoreThanOnce(string node, string parent) { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.NotMoreThanOnceOne, node, parent); } - void NodeNotFound(int lineNumber, string node, string parent) + private void NodeNotFound(int lineNumber, string node, string parent) { _context.AddError(lineNumber, TypesXmlStrings.NodeNotFoundOnce, node, parent); } - ScriptBlock GetScriptBlock(string text, int initialLine) + private ScriptBlock GetScriptBlock(string text, int initialLine) { if (text == null) return null; @@ -186,7 +190,7 @@ namespace System.Management.Automation.Runspaces return scriptBlock; } - Type ResolveType(string typeName, int line) + private Type ResolveType(string typeName, int line) { Exception exception; var type = TypeResolver.ResolveType(typeName, out exception); @@ -201,7 +205,7 @@ namespace System.Management.Automation.Runspaces return type; } - bool ToBoolean(string value) + private bool ToBoolean(string value) { value = value.Trim(); if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase)) @@ -212,10 +216,10 @@ namespace System.Management.Automation.Runspaces return false; } - T Converter(object value, string name) + private T Converter(object value, string name) { T result; - + if (!LanguagePrimitives.TryConvertTo(value, out result)) { _context.AddError(TypesXmlStrings.ErrorConvertingNote, name, typeof(T)); @@ -224,7 +228,7 @@ namespace System.Management.Automation.Runspaces return result; } - bool BoolConverter(object value, string name) + private bool BoolConverter(object value, string name) { var s = value as string; if (s != null) @@ -233,7 +237,7 @@ namespace System.Management.Automation.Runspaces return Converter(value, name); } - void CheckStandardNote(TypeMemberData member, TypeData typeData, Action setter, Func converter) + private void CheckStandardNote(TypeMemberData member, TypeData typeData, Action setter, Func converter) { var note = member as NotePropertyData; if (note != null) @@ -255,7 +259,7 @@ namespace System.Management.Automation.Runspaces } } - bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) + private bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) { var propertySet = member as PropertySetData; if (propertySet != null) @@ -283,7 +287,7 @@ namespace System.Management.Automation.Runspaces if (result == null) NodeNotFound(0, _idTypes, "Document"); - + return result; } @@ -427,7 +431,7 @@ namespace System.Management.Automation.Runspaces } else if (m.Name.Equals(TypeTable.DefaultKeyPropertySet, StringComparison.OrdinalIgnoreCase)) { - if (!CheckStandardPropertySet(m, typeData, (t,p) => t.DefaultKeyPropertySet = p)) + if (!CheckStandardPropertySet(m, typeData, (t, p) => t.DefaultKeyPropertySet = p)) { _context.AddError(TypesXmlStrings.MemberShouldHaveType, TypeTable.DefaultKeyPropertySet, _idPropertySet); } @@ -531,7 +535,7 @@ namespace System.Management.Automation.Runspaces return ResolveType(typeName, typeLineNumber); } - Collection Read_Members(out MemberSetData standardMembers) + private Collection Read_Members(out MemberSetData standardMembers) { var errorCount = _context.errors.Count; @@ -1106,7 +1110,7 @@ namespace System.Management.Automation.Runspaces } else if ((object)_reader.LocalName == (object)_idSetScriptBlock) { - if (setScriptBlock != null) NotMoreThanOnce(_idSetScriptBlock, _idScriptProperty); + if (setScriptBlock != null) NotMoreThanOnce(_idSetScriptBlock, _idScriptProperty); setterInitialLine = _readerLineInfo.LineNumber; setScriptBlock = ReadElementString(_idSetScriptBlock); } @@ -1171,17 +1175,17 @@ namespace System.Management.Automation.Runspaces { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) NotMoreThanOnce(_idName, _idAliasProperty); + if (name != null) NotMoreThanOnce(_idName, _idAliasProperty); name = ReadElementString(_idAliasProperty); } else if ((object)_reader.LocalName == (object)_idReferencedMemberName) { - if (referencedMemberName != null) NotMoreThanOnce(_idReferencedMemberName, _idAliasProperty); + if (referencedMemberName != null) NotMoreThanOnce(_idReferencedMemberName, _idAliasProperty); referencedMemberName = ReadElementString(_idReferencedMemberName); } else if ((object)_reader.LocalName == (object)_idTypeName) { - if (typeName != null) NotMoreThanOnce(_idTypeName, _idAliasProperty); + if (typeName != null) NotMoreThanOnce(_idTypeName, _idAliasProperty); typeLineNumber = _readerLineInfo.LineNumber; typeName = ReadElementString(_idTypeName); } @@ -1304,35 +1308,36 @@ namespace System.Management.Automation.Runspaces }; } - string _idTypeName; - string _idSetCodeReference; - string _idScriptMethod; - string _idValue; - string _idScriptProperty; - string _idIsHidden; - string _idScript; - string _idCodeMethod; - string _idMemberSet; - string _idCodeProperty; - string _idMembers; - string _idName; - string _idGetCodeReference; - string _idMethodName; - string _idInheritMembers; - string _idNoteProperty; - string _idTypeAdapter; - string _idSetScriptBlock; - string _idPropertySet; - string _idTypeConverter; - string _idAliasProperty; - string _idType; - string _idCodeReference; - string _idTypes; - string _idReferencedProperties; - string _idGetScriptBlock; - string _idReferencedMemberName; + private string _idTypeName; + private string _idSetCodeReference; + private string _idScriptMethod; + private string _idValue; + private string _idScriptProperty; + private string _idIsHidden; + private string _idScript; + private string _idCodeMethod; + private string _idMemberSet; + private string _idCodeProperty; + private string _idMembers; + private string _idName; + private string _idGetCodeReference; + private string _idMethodName; + private string _idInheritMembers; + private string _idNoteProperty; + private string _idTypeAdapter; + private string _idSetScriptBlock; + private string _idPropertySet; + private string _idTypeConverter; + private string _idAliasProperty; + private string _idType; + private string _idCodeReference; + private string _idTypes; + private string _idReferencedProperties; + private string _idGetScriptBlock; + private string _idReferencedMemberName; - protected void InitIDs() { + protected void InitIDs() + { var xmlNameTable = _reader.NameTable; _idTypeName = xmlNameTable.Add("TypeName"); _idSetCodeReference = xmlNameTable.Add("SetCodeReference"); @@ -1402,7 +1407,7 @@ namespace System.Management.Automation.Runspaces base.RemoveItem(index); UpdateKey(); } - + internal string Key { get; private set; } internal bool IsReadOnly { get { return ((ICollection)this).IsReadOnly; } } @@ -1446,20 +1451,20 @@ namespace System.Management.Automation.Runspaces internal static readonly ConsolidatedString Empty = new ConsolidatedString(Utils.EmptyArray()); - internal static IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); + internal static IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); - private class ConsolidatedStringEqualityComparer : IEqualityComparer - { - bool IEqualityComparer.Equals(ConsolidatedString x, ConsolidatedString y) - { - return x.Key.Equals(y.Key, StringComparison.Ordinal); - } + private class ConsolidatedStringEqualityComparer : IEqualityComparer + { + bool IEqualityComparer.Equals(ConsolidatedString x, ConsolidatedString y) + { + return x.Key.Equals(y.Key, StringComparison.Ordinal); + } - int IEqualityComparer.GetHashCode(ConsolidatedString obj) - { - return obj.Key.GetHashCode(); - } - } + int IEqualityComparer.GetHashCode(ConsolidatedString obj) + { + return obj.Key.GetHashCode(); + } + } } internal class LoadContext @@ -1469,7 +1474,7 @@ namespace System.Management.Automation.Runspaces internal string fileName; internal string PSSnapinName; internal bool isFullyTrusted; - + internal LoadContext(string PSSnapinName, string fileName, ConcurrentBag errors) { this.reader = null; @@ -1497,7 +1502,7 @@ namespace System.Management.Automation.Runspaces internal void AddError(int errorLineNumber, string resourceString, params object[] formatArguments) { string errorMsg = StringUtil.Format(resourceString, formatArguments); - string errorLine = StringUtil.Format(TypesXmlStrings.FileLineError, + string errorLine = StringUtil.Format(TypesXmlStrings.FileLineError, this.PSSnapinName, this.fileName, errorLineNumber, errorMsg); this.errors.Add(errorLine); } @@ -1505,7 +1510,7 @@ namespace System.Management.Automation.Runspaces internal void AddError(string typeName, int errorLineNumber, string resourceString, params object[] formatArguments) { string errorMsg = StringUtil.Format(resourceString, formatArguments); - string errorLine = StringUtil.Format(TypesXmlStrings.FileLineTypeError, + string errorLine = StringUtil.Format(TypesXmlStrings.FileLineTypeError, this.PSSnapinName, this.fileName, errorLineNumber, typeName, errorMsg); this.errors.Add(errorLine); } @@ -1518,7 +1523,7 @@ namespace System.Management.Automation.Runspaces [Serializable] public class TypeTableLoadException : RuntimeException { - private Collection errors; + private Collection _errors; #region Constructors @@ -1568,9 +1573,9 @@ namespace System.Management.Automation.Runspaces /// internal TypeTableLoadException(ConcurrentBag loadErrors) : base(TypesXmlStrings.TypeTableLoadErrors) - + { - errors = new Collection(loadErrors.ToArray()); + _errors = new Collection(loadErrors.ToArray()); SetDefaultErrorRecord(); } @@ -1590,11 +1595,11 @@ namespace System.Management.Automation.Runspaces int errorCount = info.GetInt32("ErrorCount"); if (errorCount > 0) { - errors = new Collection(); + _errors = new Collection(); for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - errors.Add(info.GetString(key)); + _errors.Add(info.GetString(key)); } } } @@ -1617,15 +1622,15 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue - if (null != errors) + if (null != _errors) { - int errorCount = errors.Count; + int errorCount = _errors.Count; info.AddValue("ErrorCount", errorCount); - for(int index = 0; index < errorCount; index++) + for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - info.AddValue(key, errors[index]); + info.AddValue(key, _errors[index]); } } } @@ -1646,7 +1651,7 @@ namespace System.Management.Automation.Runspaces { get { - return errors; + return _errors; } } } @@ -1686,7 +1691,7 @@ namespace System.Management.Automation.Runspaces internal TypeData(string typeName, bool typesXml) : this() { - this.fromTypesXmlFile = typesXml; + this.fromTypesXmlFile = typesXml; this.TypeName = typeName; } @@ -1742,14 +1747,14 @@ namespace System.Management.Automation.Runspaces set { _serializationMethod = value; - if(_serializationMethod == null) + if (_serializationMethod == null) { StandardMembers.Remove(TypeTable.SerializationMethodNode); return; } TypeMemberData typeMemberData; - if(StandardMembers.TryGetValue(TypeTable.SerializationMethodNode, out typeMemberData)) + if (StandardMembers.TryGetValue(TypeTable.SerializationMethodNode, out typeMemberData)) { ((NotePropertyData)typeMemberData).Value = _serializationMethod; } @@ -1770,14 +1775,14 @@ namespace System.Management.Automation.Runspaces set { _targetTypeForDeserialization = value; - if(_targetTypeForDeserialization == null) + if (_targetTypeForDeserialization == null) { StandardMembers.Remove(TypeTable.TargetTypeForDeserialization); return; } TypeMemberData typeMemberData; - if(StandardMembers.TryGetValue(TypeTable.TargetTypeForDeserialization, out typeMemberData)) + if (StandardMembers.TryGetValue(TypeTable.TargetTypeForDeserialization, out typeMemberData)) { ((NotePropertyData)typeMemberData).Value = _targetTypeForDeserialization; } @@ -1800,7 +1805,7 @@ namespace System.Management.Automation.Runspaces _serializationDepth = value; TypeMemberData typeMemberData; - if(StandardMembers.TryGetValue(TypeTable.SerializationDepth, out typeMemberData)) + if (StandardMembers.TryGetValue(TypeTable.SerializationDepth, out typeMemberData)) { ((NotePropertyData)typeMemberData).Value = _serializationDepth; } @@ -1821,7 +1826,7 @@ namespace System.Management.Automation.Runspaces set { _defaultDisplayProperty = value; - if(_defaultDisplayProperty == null) + if (_defaultDisplayProperty == null) { StandardMembers.Remove(TypeTable.DefaultDisplayProperty); return; @@ -1913,7 +1918,7 @@ namespace System.Management.Automation.Runspaces get { return _stringSerializationSourceProperty; } set { - if(value == null) + if (value == null) { // If we set the standard member via StringSerializationSource, we // don't want to remove it, so only remove the member if our previous @@ -1950,7 +1955,7 @@ namespace System.Management.Automation.Runspaces set { _defaultDisplayPropertySet = value; - if(_defaultDisplayPropertySet != null) + if (_defaultDisplayPropertySet != null) { _defaultDisplayPropertySet.Name = TypeTable.DefaultDisplayPropertySet; } @@ -1966,7 +1971,7 @@ namespace System.Management.Automation.Runspaces set { _defaultKeyPropertySet = value; - if(_defaultKeyPropertySet != null) + if (_defaultKeyPropertySet != null) { _defaultKeyPropertySet.Name = TypeTable.DefaultKeyPropertySet; } @@ -1982,14 +1987,14 @@ namespace System.Management.Automation.Runspaces set { _propertySerializationSet = value; - if(_propertySerializationSet != null) + if (_propertySerializationSet != null) { _propertySerializationSet.Name = TypeTable.PropertySerializationSet; } } } - + // They are of NoteProperty private string _serializationMethod; private Type _targetTypeForDeserialization; @@ -2009,7 +2014,7 @@ namespace System.Management.Automation.Runspaces private PropertySetData _propertySerializationSet; #endregion StandardMember - + /// /// Return a TypeData that is a copy of this one /// @@ -2017,7 +2022,7 @@ namespace System.Management.Automation.Runspaces public TypeData Copy() { TypeData newTypeData = new TypeData(this.TypeName); - + foreach (KeyValuePair entry in this.Members) { newTypeData.Members.Add(entry.Key, entry.Value.Copy()); @@ -2143,7 +2148,7 @@ namespace System.Management.Automation.Runspaces /// internal override TypeMemberData Copy() { - NotePropertyData newNote = new NotePropertyData(this.Name, this.Value) {IsHidden = this.IsHidden}; + NotePropertyData newNote = new NotePropertyData(this.Name, this.Value) { IsHidden = this.IsHidden }; return newNote; } @@ -2501,7 +2506,7 @@ namespace System.Management.Automation.Runspaces /// /// The members of the MemberSet /// - public Collection Members { get; private set; } + public Collection Members { get; private set; } /// /// Set true if the member is supposed to be hidden @@ -2564,41 +2569,41 @@ namespace System.Management.Automation.Runspaces /// /// Table from type name list into PSMemberInfoInternalCollection /// - private readonly ConcurrentDictionary> consolidatedMembers = + private readonly ConcurrentDictionary> _consolidatedMembers = new ConcurrentDictionary>( /*concurrency*/1, /*capacity*/256, StringComparer.OrdinalIgnoreCase); /// /// Table from type name list into Collection of strings /// - private readonly ConcurrentDictionary> consolidatedSpecificProperties = + private readonly ConcurrentDictionary> _consolidatedSpecificProperties = new ConcurrentDictionary>( /*concurrency*/1, /*capacity*/10, StringComparer.OrdinalIgnoreCase); /// /// Table from type name into PSMemberInfoInternalCollection /// - private readonly ConcurrentDictionary> extendedMembers = + private readonly ConcurrentDictionary> _extendedMembers = new ConcurrentDictionary>( /*concurrency*/3, /*capacity*/300, StringComparer.OrdinalIgnoreCase); /// /// points to a Hashtable from type name to type converter /// - private readonly ConcurrentDictionary typeConverters + private readonly ConcurrentDictionary _typeConverters = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/5, StringComparer.OrdinalIgnoreCase); /// /// points to a Hashtable from type name to type adapter /// - private readonly ConcurrentDictionary typeAdapters = + private readonly ConcurrentDictionary _typeAdapters = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/5, StringComparer.OrdinalIgnoreCase); // this is used to throw errors when updating a shared TypeTable. internal readonly bool isShared; - private List typeFileList; + private List _typeFileList; // This holds all the type information that is in the typetable // Holds file name if types file was used to update the types @@ -2611,7 +2616,7 @@ namespace System.Management.Automation.Runspaces internal const bool defaultInheritPropertySerializationSet = true; - static readonly string[] standardMembers = new string[] { + private static readonly string[] s_standardMembers = new string[] { DefaultDisplayProperty, DefaultDisplayPropertySet, DefaultKeyPropertySet, @@ -2666,7 +2671,7 @@ namespace System.Management.Automation.Runspaces noteAsMemberInfo = member; } } - + if (noteAsMemberInfo == null) { return true; @@ -2773,9 +2778,9 @@ namespace System.Management.Automation.Runspaces { bool found = false; string memberName = members[i].Name; - for (int j = 0; j < standardMembers.Length; j++) + for (int j = 0; j < s_standardMembers.Length; j++) { - if (String.Equals(memberName, standardMembers[j], StringComparison.OrdinalIgnoreCase)) + if (String.Equals(memberName, s_standardMembers[j], StringComparison.OrdinalIgnoreCase)) { found = true; break; @@ -2865,12 +2870,12 @@ namespace System.Management.Automation.Runspaces } PSMemberInfo otherMember; - if (!GetCheckMemberType(errors, typeName, members, + if (!GetCheckMemberType(errors, typeName, members, DefaultDisplayPropertySet, typeof(PSPropertySet), out otherMember)) { members.Remove(DefaultDisplayPropertySet); } - if (!GetCheckMemberType(errors, typeName, members, + if (!GetCheckMemberType(errors, typeName, members, DefaultKeyPropertySet, typeof(PSPropertySet), out otherMember)) { members.Remove(DefaultKeyPropertySet); @@ -2963,7 +2968,7 @@ namespace System.Management.Automation.Runspaces internal static void ProcessNoteData(ConcurrentBag errors, string typeName, NotePropertyData nodeData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { // value could be null - PSNoteProperty note = new PSNoteProperty(nodeData.Name, nodeData.Value) {IsHidden = nodeData.IsHidden}; + PSNoteProperty note = new PSNoteProperty(nodeData.Name, nodeData.Value) { IsHidden = nodeData.IsHidden }; AddMember(errors, typeName, note, membersCollection, isOverride); } @@ -3026,7 +3031,7 @@ namespace System.Management.Automation.Runspaces internal static void ProcessScriptMethodData(ConcurrentBag errors, string typeName, ScriptMethodData scriptMethodData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if(scriptMethodData.Script == null) + if (scriptMethodData.Script == null) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "ScriptMethodData", "Script"); return; @@ -3038,7 +3043,7 @@ namespace System.Management.Automation.Runspaces internal static void ProcessCodeMethodData(ConcurrentBag errors, string typeName, CodeMethodData codeMethodData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if(codeMethodData.CodeReference == null) + if (codeMethodData.CodeReference == null) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "CodeMethodData", "CodeReference"); return; @@ -3059,7 +3064,7 @@ namespace System.Management.Automation.Runspaces internal static void ProcessPropertySetData(ConcurrentBag errors, string typeName, PropertySetData propertySetData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if(propertySetData.ReferencedProperties == null || propertySetData.ReferencedProperties.Count == 0) + if (propertySetData.ReferencedProperties == null || propertySetData.ReferencedProperties.Count == 0) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "PropertySetData", "ReferencedProperties"); return; @@ -3077,7 +3082,7 @@ namespace System.Management.Automation.Runspaces referencedProperties.Add(name); } - if(referencedProperties.Count == 0) + if (referencedProperties.Count == 0) { return; } @@ -3112,7 +3117,7 @@ namespace System.Management.Automation.Runspaces var memberSetMembers = new PSMemberInfoInternalCollection(); ProcessMembersData(errors, typeName, standardMembers, memberSetMembers, false); - foreach(PropertySetData propertySet in propertySets) + foreach (PropertySetData propertySet in propertySets) { ProcessPropertySetData(errors, typeName, propertySet, memberSetMembers, false); } @@ -3164,7 +3169,7 @@ namespace System.Management.Automation.Runspaces // into the original member collection. Replace the old StandardMembers with the new one foreach (PSMemberInfo member in existingMembers) { - if(oldMembersCopy[member.name] == null) + if (oldMembersCopy[member.name] == null) { oldMembersCopy.Add(member); } @@ -3199,7 +3204,7 @@ namespace System.Management.Automation.Runspaces propertySets.Add(typeData.PropertySerializationSet); } - if(typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 + if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 && typeData.TypeConverter == null && typeData.TypeAdapter == null && propertySets.Count == 0 && !typeData.fromTypesXmlFile) { @@ -3207,10 +3212,10 @@ namespace System.Management.Automation.Runspaces return; } - if(typeData.Members.Count > 0) + if (typeData.Members.Count > 0) { PSMemberInfoInternalCollection typeMembers - = extendedMembers.GetOrAdd(typeName, k => new PSMemberInfoInternalCollection()); + = _extendedMembers.GetOrAdd(typeName, k => new PSMemberInfoInternalCollection()); ProcessMembersData(errors, typeName, typeData.Members.Values, typeMembers, typeData.IsOverride); @@ -3220,15 +3225,15 @@ namespace System.Management.Automation.Runspaces } } - if(typeData.StandardMembers.Count > 0 || propertySets.Count > 0) + if (typeData.StandardMembers.Count > 0 || propertySets.Count > 0) { PSMemberInfoInternalCollection typeMembers - = extendedMembers.GetOrAdd(typeName, k => new PSMemberInfoInternalCollection()); + = _extendedMembers.GetOrAdd(typeName, k => new PSMemberInfoInternalCollection()); ProcessStandardMembers(errors, typeName, typeData.StandardMembers.Values, propertySets, typeMembers, typeData.IsOverride); } - if(typeData.TypeConverter != null) + if (typeData.TypeConverter != null) { object instance = null; if (CreateInstance(errors, typeName, typeData.TypeConverter, TypesXmlStrings.UnableToInstantiateTypeConverter, out instance)) @@ -3243,9 +3248,9 @@ namespace System.Management.Automation.Runspaces } } - if (instance != null && !typeConverters.TryAdd(typeName, instance)) + if (instance != null && !_typeConverters.TryAdd(typeName, instance)) { - if(!typeData.IsOverride) + if (!typeData.IsOverride) { AddError(errors, typeName, TypesXmlStrings.TypeConverterAlreadyPresent); } @@ -3253,7 +3258,7 @@ namespace System.Management.Automation.Runspaces } } - if(typeData.TypeAdapter != null) + if (typeData.TypeAdapter != null) { object instance; PSObject.AdapterSet adapterSet = null; @@ -3279,9 +3284,9 @@ namespace System.Management.Automation.Runspaces } } - if (adapterSet != null && !typeAdapters.TryAdd(typeName, adapterSet)) + if (adapterSet != null && !_typeAdapters.TryAdd(typeName, adapterSet)) { - if(!typeData.IsOverride) + if (!typeData.IsOverride) { AddError(errors, typeName, TypesXmlStrings.TypeAdapterAlreadyPresent); } @@ -3305,7 +3310,7 @@ namespace System.Management.Automation.Runspaces // We always remove the whole type bool typeExist = false; PSMemberInfoInternalCollection memberCollection; - if (extendedMembers.TryRemove(typeName, out memberCollection)) + if (_extendedMembers.TryRemove(typeName, out memberCollection)) { typeExist = true; foreach (var m in memberCollection) @@ -3316,14 +3321,14 @@ namespace System.Management.Automation.Runspaces } object unused1; - if (typeConverters.TryRemove(typeName, out unused1)) + if (_typeConverters.TryRemove(typeName, out unused1)) { typeExist = true; LanguagePrimitives.UpdateTypeConvertFromTypeTable(typeName); } PSObject.AdapterSet unused2; - if (typeAdapters.TryRemove(typeName, out unused2)) + if (_typeAdapters.TryRemove(typeName, out unused2)) { typeExist = true; } @@ -3364,7 +3369,7 @@ namespace System.Management.Automation.Runspaces private void Update(ConcurrentBag errors, TypeData typeData, bool isRemove) { - if(!isRemove) + if (!isRemove) { ProcessTypeDataToAdd(errors, typeData); } @@ -3384,7 +3389,7 @@ namespace System.Management.Automation.Runspaces { // Rather than set these members every time we process the standard members, do it // just once at startup. - foreach (var sm in standardMembers) + foreach (var sm in s_standardMembers) { PSGetMemberBinder.TypeTableMemberAdded(sm); } @@ -3401,7 +3406,7 @@ namespace System.Management.Automation.Runspaces internal TypeTable(bool isShared) { this.isShared = isShared; - typeFileList = new List(); + _typeFileList = new List(); } /// @@ -3480,8 +3485,8 @@ namespace System.Management.Automation.Runspaces } isShared = true; - - typeFileList = new List(); + + _typeFileList = new List(); ConcurrentBag errors = new ConcurrentBag(); foreach (string typefile in typeFiles) { @@ -3492,7 +3497,7 @@ namespace System.Management.Automation.Runspaces bool unused; Initialize(string.Empty, typefile, errors, authorizationManager, host, out unused); - typeFileList.Add(typefile); + _typeFileList.Add(typefile); } if (errors.Count > 0) @@ -3516,13 +3521,13 @@ namespace System.Management.Automation.Runspaces { return new Collection(); } - Collection result = consolidatedSpecificProperties.GetOrAdd(types.Key, key => + Collection result = _consolidatedSpecificProperties.GetOrAdd(types.Key, key => { var retValueTable = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string type in types) { PSMemberInfoInternalCollection typeMembers; - if (!extendedMembers.TryGetValue(type, out typeMembers)) + if (!_extendedMembers.TryGetValue(type, out typeMembers)) continue; PSMemberSet settings = typeMembers[PSStandardMembers] as PSMemberSet; if (settings == null) @@ -3534,7 +3539,7 @@ namespace System.Management.Automation.Runspaces { retValueTable.Add(reference); } - bool inherit = (bool) PSObject.GetNoteSettingValue(settings, InheritPropertySerializationSet, + bool inherit = (bool)PSObject.GetNoteSettingValue(settings, InheritPropertySerializationSet, defaultInheritPropertySerializationSet, typeof(bool), false, null); if (!inherit) { @@ -3559,7 +3564,7 @@ namespace System.Management.Automation.Runspaces /// internal PSMemberInfoInternalCollection GetMembers(ConsolidatedString types) where T : PSMemberInfo { - return PSObject.TransformMemberInfoCollection(GetMembers(types)); + return PSObject.TransformMemberInfoCollection(GetMembers(types)); } @@ -3569,13 +3574,13 @@ namespace System.Management.Automation.Runspaces { return new PSMemberInfoInternalCollection(); } - PSMemberInfoInternalCollection result = consolidatedMembers.GetOrAdd(types.Key, k => + PSMemberInfoInternalCollection result = _consolidatedMembers.GetOrAdd(types.Key, k => { var retValue = new PSMemberInfoInternalCollection(); for (int i = types.Count - 1; i >= 0; i--) { PSMemberInfoInternalCollection typeMembers; - if (!extendedMembers.TryGetValue(types[i], out typeMembers)) + if (!_extendedMembers.TryGetValue(types[i], out typeMembers)) { continue; } @@ -3606,7 +3611,7 @@ namespace System.Management.Automation.Runspaces { if (currentMemberAsMemberSet.Members[typeMemberAsMemberSetMember.Name] == null) { - ((PSMemberInfoIntegratingCollection) currentMemberAsMemberSet.Members) + ((PSMemberInfoIntegratingCollection)currentMemberAsMemberSet.Members) .AddToTypesXmlCache(typeMemberAsMemberSetMember, false); continue; } @@ -3636,7 +3641,7 @@ namespace System.Management.Automation.Runspaces } object result; - typeConverters.TryGetValue(typeName, out result); + _typeConverters.TryGetValue(typeName, out result); return result; } @@ -3664,7 +3669,7 @@ namespace System.Management.Automation.Runspaces */ #if true PSObject.AdapterSet result; - typeAdapters.TryGetValue(type.FullName, out result); + _typeAdapters.TryGetValue(type.FullName, out result); return result; #else foreach (PSObject.AdapterSet adapterSet in this.typeAdapters.Values) @@ -3726,7 +3731,7 @@ namespace System.Management.Automation.Runspaces var memberSet = member as PSMemberSet; if (memberSet != null) { - if(memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) + if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { return null; } @@ -3762,7 +3767,7 @@ namespace System.Management.Automation.Runspaces var memberSet = member as PSMemberSet; if (memberSet != null) { - if(memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) + if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { LoadStandardMembersToTypeData(memberSet, typeData); } @@ -3789,31 +3794,31 @@ namespace System.Management.Automation.Runspaces { PSMemberInfo standardMember = member.Copy(); var memberName = standardMember.Name; - if(memberName.Equals(SerializationMethodNode, StringComparison.OrdinalIgnoreCase)) + if (memberName.Equals(SerializationMethodNode, StringComparison.OrdinalIgnoreCase)) { typeData.SerializationMethod = GetParameterType(((PSNoteProperty)standardMember).Value); } - else if(memberName.Equals(TargetTypeForDeserialization, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(TargetTypeForDeserialization, StringComparison.OrdinalIgnoreCase)) { // Value property of the TargetTypeForDeserialization member is guaranteed to be of System.Type typeData.TargetTypeForDeserialization = GetParameterType(((PSNoteProperty)standardMember).Value); } - else if(memberName.Equals(SerializationDepth, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(SerializationDepth, StringComparison.OrdinalIgnoreCase)) { // Value property of the SerializationDepth member is guaranteed to be of type int typeData.SerializationDepth = GetParameterType(((PSNoteProperty)standardMember).Value); } - else if(memberName.Equals(DefaultDisplayProperty, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(DefaultDisplayProperty, StringComparison.OrdinalIgnoreCase)) { // Value property of the DefaultDisplayProperty is guaranteed to be of type string typeData.DefaultDisplayProperty = GetParameterType(((PSNoteProperty)standardMember).Value); } - else if(memberName.Equals(InheritPropertySerializationSet, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(InheritPropertySerializationSet, StringComparison.OrdinalIgnoreCase)) { // Value property of the InheritPropertySerializationSet is guaranteed to be of type bool typeData.InheritPropertySerializationSet = GetParameterType(((PSNoteProperty)standardMember).Value); } - else if(memberName.Equals(StringSerializationSource, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { var aliasProperty = standardMember as PSAliasProperty; if (aliasProperty != null) @@ -3825,17 +3830,17 @@ namespace System.Management.Automation.Runspaces typeData.StringSerializationSourceProperty = GetTypeMemberDataFromPSMemberInfo(standardMember); } } - else if(memberName.Equals(DefaultDisplayPropertySet, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(DefaultDisplayPropertySet, StringComparison.OrdinalIgnoreCase)) { typeData.DefaultDisplayPropertySet = new PropertySetData(((PSPropertySet)standardMember).ReferencedPropertyNames); } - else if(memberName.Equals(DefaultKeyPropertySet, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(DefaultKeyPropertySet, StringComparison.OrdinalIgnoreCase)) { typeData.DefaultKeyPropertySet = new PropertySetData(((PSPropertySet)standardMember).ReferencedPropertyNames); } - else if(memberName.Equals(PropertySerializationSet, StringComparison.OrdinalIgnoreCase)) + else if (memberName.Equals(PropertySerializationSet, StringComparison.OrdinalIgnoreCase)) { typeData.PropertySerializationSet = new PropertySetData(((PSPropertySet)standardMember).ReferencedPropertyNames); @@ -3850,7 +3855,7 @@ namespace System.Management.Automation.Runspaces internal Dictionary GetAllTypeData() { Dictionary allTypes = new Dictionary(); - foreach (string typeName in extendedMembers.Keys) + foreach (string typeName in _extendedMembers.Keys) { if (allTypes.ContainsKey(typeName)) { @@ -3870,7 +3875,7 @@ namespace System.Management.Automation.Runspaces } } - foreach (string typeName in typeConverters.Keys) + foreach (string typeName in _typeConverters.Keys) { if (allTypes.ContainsKey(typeName)) { @@ -3889,7 +3894,7 @@ namespace System.Management.Automation.Runspaces } } - foreach (string typeName in typeAdapters.Keys) + foreach (string typeName in _typeAdapters.Keys) { if (allTypes.ContainsKey(typeName)) { @@ -3913,7 +3918,7 @@ namespace System.Management.Automation.Runspaces string typeName = typeData.TypeName; PSMemberInfoInternalCollection typeMembers; - if (extendedMembers.TryGetValue(typeName, out typeMembers)) + if (_extendedMembers.TryGetValue(typeName, out typeMembers)) { Dbg.Assert(typeMembers != null, "members should not be null"); foreach (PSMemberInfo member in typeMembers) @@ -3933,7 +3938,7 @@ namespace System.Management.Automation.Runspaces string typeName = typeData.TypeName; object converterResult; - if (typeConverters.TryGetValue(typeName, out converterResult)) + if (_typeConverters.TryGetValue(typeName, out converterResult)) { Dbg.Assert(converterResult != null, "converter should not be null"); typeData.TypeConverter = converterResult.GetType(); @@ -3949,7 +3954,7 @@ namespace System.Management.Automation.Runspaces string typeName = typeData.TypeName; PSObject.AdapterSet adapterResult; - if (typeAdapters.TryGetValue(typeName, out adapterResult)) + if (_typeAdapters.TryGetValue(typeName, out adapterResult)) { Dbg.Assert(adapterResult != null, "adapter should not be null"); typeData.TypeAdapter = ((ThirdPartyAdapter)(adapterResult.OriginalAdapter)).ExternalAdapterType; @@ -3978,7 +3983,7 @@ namespace System.Management.Automation.Runspaces // 2. Shallow copy the 'typesInfo' // copy the type members - foreach (var pair in this.extendedMembers) + foreach (var pair in _extendedMembers) { var resultMembers = new PSMemberInfoInternalCollection(); foreach (var member in pair.Value) @@ -3986,19 +3991,19 @@ namespace System.Management.Automation.Runspaces resultMembers.Add(member.Copy()); } - result.extendedMembers.TryAdd(pair.Key, resultMembers); + result._extendedMembers.TryAdd(pair.Key, resultMembers); } // copy the type adapter members - foreach (var pair in this.typeAdapters) + foreach (var pair in _typeAdapters) { - result.typeAdapters.TryAdd(pair.Key, pair.Value); + result._typeAdapters.TryAdd(pair.Key, pair.Value); } // copy the type converters - foreach (var pair in this.typeConverters) + foreach (var pair in _typeConverters) { - result.typeConverters.TryAdd(pair.Key, pair.Value); + result._typeConverters.TryAdd(pair.Key, pair.Value); } result.typesInfo.Add(this.typesInfo); @@ -4011,24 +4016,24 @@ namespace System.Management.Automation.Runspaces /// internal void Clear() { - foreach (var conv in typeConverters.Keys) + foreach (var conv in _typeConverters.Keys) { LanguagePrimitives.UpdateTypeConvertFromTypeTable(conv); } - typeConverters.Clear(); + _typeConverters.Clear(); - foreach (var ml in extendedMembers.Values) + foreach (var ml in _extendedMembers.Values) { foreach (var m in ml) { PSGetMemberBinder.TypeTableMemberPossiblyUpdated(m.Name); } } - extendedMembers.Clear(); + _extendedMembers.Clear(); StandardMembersUpdated(); - typeAdapters.Clear(); + _typeAdapters.Clear(); typesInfo.Clear(); ClearConsolidatedMembers(); @@ -4036,13 +4041,13 @@ namespace System.Management.Automation.Runspaces internal void ClearConsolidatedMembers() { - consolidatedMembers.Clear(); - consolidatedSpecificProperties.Clear(); + _consolidatedMembers.Clear(); + _consolidatedSpecificProperties.Clear(); } private static void StandardMembersUpdated() { - foreach (var sm in standardMembers) + foreach (var sm in s_standardMembers) { PSGetMemberBinder.TypeTableMemberPossiblyUpdated(sm); } @@ -4065,9 +4070,9 @@ namespace System.Management.Automation.Runspaces /// /// Indicate if the file failed to be loaded internal void Initialize( - string snapinName, + string snapinName, string fileToLoad, - ConcurrentBag errors, + ConcurrentBag errors, AuthorizationManager authorizationManager, PSHost host, out bool failToLoadFile) @@ -4127,7 +4132,7 @@ namespace System.Management.Automation.Runspaces string errorMsg = StringUtil.Format(TypesXmlStrings.Exception, e.Message); string errorLine = StringUtil.Format(TypesXmlStrings.FileError, moduleName, fileToLoad, errorMsg); errors.Add(errorLine); - + failToLoadFile = true; return null; } @@ -4199,9 +4204,9 @@ namespace System.Management.Automation.Runspaces /// internal void Remove(string typeFile) { - lock (typeFileList) + lock (_typeFileList) { - typeFileList.Remove(typeFile); + _typeFileList.Remove(typeFile); typesInfo.Remove(typeFile, null); } } @@ -4275,7 +4280,7 @@ namespace System.Management.Automation.Runspaces /// been created outside of the Runspace. /// internal void Update( - Collection psSnapinTypes, + Collection psSnapinTypes, AuthorizationManager authorizationManager, PSHost host ) @@ -4322,9 +4327,9 @@ namespace System.Management.Automation.Runspaces /// been created outside of the Runspace. /// internal void Update( - string filePath, + string filePath, ConcurrentBag errors, - bool clearTable, + bool clearTable, AuthorizationManager authorizationManager, PSHost host, out bool failToLoadFile) @@ -4368,7 +4373,7 @@ namespace System.Management.Automation.Runspaces throw PSTraceSource.NewInvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); } - var etwEnabled = RunspaceEventSource.Log.IsEnabled(); + var etwEnabled = RunspaceEventSource.Log.IsEnabled(); if (etwEnabled) RunspaceEventSource.Log.ProcessTypeFileStart(filePath); if (!ProcessIsBuiltIn(filePath, errors, out failToLoadFile)) @@ -4434,16 +4439,16 @@ namespace System.Management.Automation.Runspaces /// /// internal void Update( - TypeData type, + TypeData type, ConcurrentBag errors, bool isRemove) { if (type == null) throw new ArgumentNullException("type"); - if(errors == null) + if (errors == null) throw new ArgumentNullException("errors"); - if(isShared) + if (isShared) { throw PSTraceSource.NewInvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); } diff --git a/src/System.Management.Automation/engine/UserFeedbackParameters.cs b/src/System.Management.Automation/engine/UserFeedbackParameters.cs index 24a063006..82c1ae2fd 100644 --- a/src/System.Management.Automation/engine/UserFeedbackParameters.cs +++ b/src/System.Management.Automation/engine/UserFeedbackParameters.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation { if (commandRuntime == null) { - throw PSTraceSource.NewArgumentNullException ("commandRuntime"); + throw PSTraceSource.NewArgumentNullException("commandRuntime"); } commandRuntime.PagingParameters = this; } @@ -48,10 +48,10 @@ namespace System.Management.Automation [Parameter] public UInt64 First { - get { return psFirst; } - set { psFirst = value; } + get { return _psFirst; } + set { _psFirst = value; } } - private ulong psFirst = UInt64.MaxValue; + private ulong _psFirst = UInt64.MaxValue; #endregion parameters @@ -119,13 +119,13 @@ namespace System.Management.Automation.Internal /// user feedback properties on when the parameters get bound. /// /// - internal ShouldProcessParameters (MshCommandRuntime commandRuntime) + internal ShouldProcessParameters(MshCommandRuntime commandRuntime) { if (commandRuntime == null) { - throw PSTraceSource.NewArgumentNullException ("commandRuntime"); + throw PSTraceSource.NewArgumentNullException("commandRuntime"); } - this.commandRuntime = commandRuntime; + _commandRuntime = commandRuntime; } // ctor #endregion ctor @@ -140,11 +140,11 @@ namespace System.Management.Automation.Internal { get { - return this.commandRuntime.WhatIf; + return _commandRuntime.WhatIf; } set { - this.commandRuntime.WhatIf = value; + _commandRuntime.WhatIf = value; } } @@ -157,22 +157,22 @@ namespace System.Management.Automation.Internal { get { - return this.commandRuntime.Confirm; + return _commandRuntime.Confirm; } set { - this.commandRuntime.Confirm = value; + _commandRuntime.Confirm = value; } } #endregion parameters - private MshCommandRuntime commandRuntime; + private MshCommandRuntime _commandRuntime; } /// /// The declaration of parameters for the Transactions mechanisms. -UseTransaction, and -BypassTransaction. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification="These are only exposed by way of the PowerShell core cmdlets that surface them.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "These are only exposed by way of the PowerShell core cmdlets that surface them.")] public sealed class TransactionParameters { #region ctor @@ -186,9 +186,9 @@ namespace System.Management.Automation.Internal /// user feedback properties on when the parameters get bound. /// /// - internal TransactionParameters (MshCommandRuntime commandRuntime) + internal TransactionParameters(MshCommandRuntime commandRuntime) { - this.commandRuntime = commandRuntime; + _commandRuntime = commandRuntime; } // ctor #endregion ctor @@ -204,17 +204,17 @@ namespace System.Management.Automation.Internal { get { - return this.commandRuntime.UseTransaction; + return _commandRuntime.UseTransaction; } set { - this.commandRuntime.UseTransaction = value; + _commandRuntime.UseTransaction = value; } } #endregion parameters - private MshCommandRuntime commandRuntime; - } + private MshCommandRuntime _commandRuntime; + } } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index ea1fbc3c5..0c783d116 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -34,31 +34,38 @@ namespace System.Management.Automation internal static class Utils { // From System.Web.Util.HashCodeCombiner - internal static int CombineHashCodes(int h1, int h2) { + internal static int CombineHashCodes(int h1, int h2) + { return unchecked(((h1 << 5) + h1) ^ h2); } - - internal static int CombineHashCodes(int h1, int h2, int h3) { + + internal static int CombineHashCodes(int h1, int h2, int h3) + { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4) + { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) + { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) + { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) + { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } - - internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { + + internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) + { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } @@ -66,7 +73,7 @@ namespace System.Management.Automation /// The existence of the following registry confirms that the host machine is a WinPE /// HKLM\System\CurrentControlSet\Control\MiniNT /// - internal static string WinPEIdentificationRegKey = @"System\CurrentControlSet\Control\MiniNT"; + internal static string WinPEIdentificationRegKey = @"System\CurrentControlSet\Control\MiniNT"; /// /// Allowed PowerShell Editions @@ -187,20 +194,20 @@ namespace System.Management.Automation { ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (ecFromTLS == null) - { + { return null; } return ecFromTLS.TypeTable; } - private static string _pshome = null; + private static string s_pshome = null; internal static string GetApplicationBaseFromRegistry(string shellId) { - bool wantPsHome = (object) shellId == (object) DefaultPowerShellShellID; - if (wantPsHome && _pshome != null) - return _pshome; + bool wantPsHome = (object)shellId == (object)DefaultPowerShellShellID; + if (wantPsHome && s_pshome != null) + return s_pshome; string engineKeyPath = RegistryStrings.MonadRootKeyPath + "\\" + PSVersionInfo.RegistryVersionKey + "\\" + RegistryStrings.MonadEngineKey; @@ -211,7 +218,7 @@ namespace System.Management.Automation { var result = engineKey.GetValue(RegistryStrings.MonadEngine_ApplicationBase) as string; if (wantPsHome) - Interlocked.CompareExchange(ref _pshome, null, result); + Interlocked.CompareExchange(ref s_pshome, null, result); return result; } @@ -273,11 +280,11 @@ namespace System.Management.Automation #endif } - private static string[] _productFolderDirectories; + private static string[] s_productFolderDirectories; private static string[] GetProductFolderDirectories() { - if (_productFolderDirectories == null) + if (s_productFolderDirectories == null) { List baseDirectories = new List(); @@ -318,10 +325,10 @@ namespace System.Management.Automation baseDirectories.Add(Path.Combine(progFileDir, "Json.Net")); #endif // CORECLR } - Interlocked.CompareExchange(ref _productFolderDirectories, baseDirectories.ToArray(), null); + Interlocked.CompareExchange(ref s_productFolderDirectories, baseDirectories.ToArray(), null); } - return _productFolderDirectories; + return s_productFolderDirectories; } /// @@ -385,7 +392,7 @@ namespace System.Management.Automation } #endif return false; - } + } #region Versioning related methods @@ -475,13 +482,13 @@ namespace System.Management.Automation foreach (Version compatibleVersion in PSVersionInfo.PSCompatibleVersions) { - if(checkVersion.Major == compatibleVersion.Major && checkVersion.Minor <= compatibleVersion.Minor) + if (checkVersion.Major == compatibleVersion.Major && checkVersion.Minor <= compatibleVersion.Minor) return true; } return false; } - + /// /// Checks whether current monad session supports edition specified /// by checkEdition. @@ -521,7 +528,7 @@ namespace System.Management.Automation { return false; } - + // Construct a temporary version number with build number and revision number set to 0. // This is done so as to re-use the version specifications in PSUtils.FrameworkRegistryInstallation Version tempVersion = new Version(checkVersion.Major, checkVersion.Minor, 0, 0); @@ -603,10 +610,10 @@ namespace System.Management.Automation // Retrieves group policy settings based on the preference order provided: // Dictionary settings = GetGroupPolicySetting("Transcription", Registry.LocalMachine, Registry.CurrentUser); - internal static RegistryKey[] RegLocalMachine = new[] {Registry.LocalMachine}; - internal static RegistryKey[] RegCurrentUser = new[] {Registry.CurrentUser}; - internal static RegistryKey[] RegLocalMachineThenCurrentUser = new[] {Registry.LocalMachine, Registry.CurrentUser}; - internal static RegistryKey[] RegCurrentUserThenLocalMachine = new[] {Registry.CurrentUser, Registry.LocalMachine}; + internal static RegistryKey[] RegLocalMachine = new[] { Registry.LocalMachine }; + internal static RegistryKey[] RegCurrentUser = new[] { Registry.CurrentUser }; + internal static RegistryKey[] RegLocalMachineThenCurrentUser = new[] { Registry.LocalMachine, Registry.CurrentUser }; + internal static RegistryKey[] RegCurrentUserThenLocalMachine = new[] { Registry.CurrentUser, Registry.LocalMachine }; internal static Dictionary GetGroupPolicySetting(string settingName, RegistryKey[] preferenceOrder) { @@ -615,18 +622,18 @@ namespace System.Management.Automation } // We use a static to avoid creating "extra garbage." - private static Dictionary _emptyDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static Dictionary s_emptyDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); internal static Dictionary GetGroupPolicySetting(string groupPolicyBase, string settingName, RegistryKey[] preferenceOrder) { #if UNIX - return _emptyDictionary; + return s_emptyDictionary; #else - lock (cachedGroupPolicySettings) + lock (s_cachedGroupPolicySettings) { // Return cached information, if we have it Dictionary settings; - if ((cachedGroupPolicySettings.TryGetValue(settingName, out settings)) && + if ((s_cachedGroupPolicySettings.TryGetValue(settingName, out settings)) && !InternalTestHooks.BypassGroupPolicyCaching) { return settings; @@ -691,14 +698,14 @@ namespace System.Management.Automation // Cache the data if (!InternalTestHooks.BypassGroupPolicyCaching) { - cachedGroupPolicySettings[settingName] = settings; + s_cachedGroupPolicySettings[settingName] = settings; } return settings; } #endif } - static ConcurrentDictionary> cachedGroupPolicySettings = + private static ConcurrentDictionary> s_cachedGroupPolicySettings = new ConcurrentDictionary>(); /// @@ -874,7 +881,7 @@ namespace System.Management.Automation // first look in the loaded modules and then append the modules from gmo -Listavailable // Reason: gmo -li looks only the PSModulepath. There may be cases where a module // is imported directly from a path (that is not in PSModulePath). - List result = context.Modules.GetModules(new[] { fullyQualifiedName }, false); + List result = context.Modules.GetModules(new[] { fullyQualifiedName }, false); CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context); var getModuleCommand = new Runspaces.Command(commandInfo); @@ -1048,8 +1055,8 @@ namespace System.Management.Automation { if ((findData.dwFileAttributes & NativeMethods.FileAttributes.Directory) != 0) { - if ( (! String.Equals(".", findData.cFileName, StringComparison.OrdinalIgnoreCase)) && - (! String.Equals("..", findData.cFileName, StringComparison.OrdinalIgnoreCase))) + if ((!String.Equals(".", findData.cFileName, StringComparison.OrdinalIgnoreCase)) && + (!String.Equals("..", findData.cFileName, StringComparison.OrdinalIgnoreCase))) { directories.Add(directory + "\\" + findData.cFileName); } @@ -1379,7 +1386,7 @@ namespace System.Management.Automation // [System.Text.Encoding]::GetEncodings() | ? { $_.GetEncoding().GetPreamble() } | // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static Dictionary encodingMap = + internal static Dictionary encodingMap = new Dictionary() { { "255-254", FileSystemCmdletProviderEncoding.Unicode }, @@ -1475,14 +1482,14 @@ namespace System.Management.Automation internal static ReadOnlyCollection EmptyReadOnlyCollection() { return EmptyReadOnlyCollectionHolder._instance; - } + } - static class EmptyArrayHolder + private static class EmptyArrayHolder { internal static readonly T[] _instance = new T[0]; } - static class EmptyReadOnlyCollectionHolder + private static class EmptyReadOnlyCollectionHolder { internal static readonly ReadOnlyCollection _instance = new ReadOnlyCollection(EmptyArray()); @@ -1490,29 +1497,29 @@ namespace System.Management.Automation static internal class Separators { - internal static readonly char[] Backslash = new char[] {'\\'}; - internal static readonly char[] Directory = new char[] {'\\', '/'}; - internal static readonly char[] DirectoryOrDrive = new char[] {'\\', '/', ':'}; + internal static readonly char[] Backslash = new char[] { '\\' }; + internal static readonly char[] Directory = new char[] { '\\', '/' }; + internal static readonly char[] DirectoryOrDrive = new char[] { '\\', '/', ':' }; - internal static readonly char[] Colon = new char[] {':'}; - internal static readonly char[] Dot = new char[] {'.'}; - internal static readonly char[] Pipe = new char[] {'|'}; - internal static readonly char[] Comma = new char[] {','}; - internal static readonly char[] Semicolon = new char[] {';'}; - internal static readonly char[] StarOrQuestion = new char[] {'*', '?'}; - internal static readonly char[] ColonOrBackslash = new char[] {'\\', ':'}; + internal static readonly char[] Colon = new char[] { ':' }; + internal static readonly char[] Dot = new char[] { '.' }; + internal static readonly char[] Pipe = new char[] { '|' }; + internal static readonly char[] Comma = new char[] { ',' }; + internal static readonly char[] Semicolon = new char[] { ';' }; + internal static readonly char[] StarOrQuestion = new char[] { '*', '?' }; + internal static readonly char[] ColonOrBackslash = new char[] { '\\', ':' }; - internal static readonly char[] QuoteChars = new char[] {'\'', '"'}; - internal static readonly char[] Space = new char[] {' '}; - internal static readonly char[] QuotesSpaceOrTab = new char[] {' ', '\t', '\'', '"'}; - internal static readonly char[] SpaceOrTab = new char[] {' ', '\t'}; - internal static readonly char[] Newline = new char[] {'\n'}; - internal static readonly char[] CrLf = new char[] {'\r', '\n'}; + internal static readonly char[] QuoteChars = new char[] { '\'', '"' }; + internal static readonly char[] Space = new char[] { ' ' }; + internal static readonly char[] QuotesSpaceOrTab = new char[] { ' ', '\t', '\'', '"' }; + internal static readonly char[] SpaceOrTab = new char[] { ' ', '\t' }; + internal static readonly char[] Newline = new char[] { '\n' }; + internal static readonly char[] CrLf = new char[] { '\r', '\n' }; // (Copied from System.IO.Path so we can call TrimEnd in the same way that Directory.EnumerateFiles would on the search patterns). // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. // String.WhitespaceChars will trim aggressively than what the underlying FS does (for ex, NTFS, FAT). - internal static readonly char[] PathSearchTrimEnd = { (char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x20, (char) 0x85, (char) 0xA0}; + internal static readonly char[] PathSearchTrimEnd = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 }; } } } @@ -1530,14 +1537,14 @@ namespace System.Management.Automation.Internal // It's useful to test that we don't depend on the ScriptBlock and AST objects and can use a re-parsed version. internal static bool IgnoreScriptBlockCache; - /// This member is used for internal test purposes. - public static void SetTestHook(string property, bool value) - { - var fieldInfo = typeof(InternalTestHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); - if (fieldInfo != null) - { - fieldInfo.SetValue(null, value); - } - } + /// This member is used for internal test purposes. + public static void SetTestHook(string property, bool value) + { + var fieldInfo = typeof(InternalTestHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); + if (fieldInfo != null) + { + fieldInfo.SetValue(null, value); + } + } } } diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 7ce5b9c04..ade5a6947 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -3,7 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.ObjectModel; using System.IO; @@ -40,7 +40,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("variable"); } - this.variable = variable; + _variable = variable; } #endregion constructor @@ -74,7 +74,7 @@ namespace System.Management.Automation base.InsertItem(index, item); - variable.SetValueRaw(variableValue, true); + _variable.SetValueRaw(variableValue, true); } /// @@ -100,7 +100,7 @@ namespace System.Management.Automation base.SetItem(index, item); - variable.SetValueRaw(variableValue, true); + _variable.SetValueRaw(variableValue, true); } #endregion Collection overrides @@ -135,7 +135,7 @@ namespace System.Management.Automation /// private object VerifyNewAttribute(Attribute item) { - object variableValue = variable.Value; + object variableValue = _variable.Value; // Perform transformation before validating ArgumentTransformationAttribute argumentTransformation = item as ArgumentTransformationAttribute; @@ -160,8 +160,8 @@ namespace System.Management.Automation "ValidateSetFailure", null, Metadata.InvalidMetadataForCurrentValue, - variable.Name, - ((variable.Value != null) ? variable.Value.ToString() : "")); + _variable.Name, + ((_variable.Value != null) ? _variable.Value.ToString() : "")); throw e; } @@ -173,7 +173,7 @@ namespace System.Management.Automation /// The variable whose value needs to be verified anytime /// the attributes change. /// - private PSVariable variable; + private PSVariable _variable; #endregion private data } } diff --git a/src/System.Management.Automation/engine/VariableInterfaces.cs b/src/System.Management.Automation/engine/VariableInterfaces.cs index 2ecfa84f3..777fa4b85 100644 --- a/src/System.Management.Automation/engine/VariableInterfaces.cs +++ b/src/System.Management.Automation/engine/VariableInterfaces.cs @@ -1,11 +1,12 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Globalization; using System.Management.Automation; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -45,7 +46,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // PSVariableInterfaces internal #endregion Constructors @@ -71,7 +72,7 @@ namespace System.Management.Automation public PSVariable Get(string name) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -87,7 +88,7 @@ namespace System.Management.Automation return null; } - return sessionState.GetVariable(name); + return _sessionState.GetVariable(name); } // Get /// @@ -125,14 +126,14 @@ namespace System.Management.Automation internal PSVariable GetAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetVariableAtScope(name, scope); + return _sessionState.GetVariableAtScope(name, scope); } // GetAtScope - + /// /// Gets the specified variable value from session state. /// @@ -169,12 +170,12 @@ namespace System.Management.Automation public object GetValue(string name) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetVariableValue(name); + return _sessionState.GetVariableValue(name); } // GetValue /// @@ -219,12 +220,12 @@ namespace System.Management.Automation public object GetValue(string name, object defaultValue) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetVariableValue(name) ?? defaultValue; + return _sessionState.GetVariableValue(name) ?? defaultValue; } // GetValue /// @@ -279,12 +280,12 @@ namespace System.Management.Automation internal object GetValueAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - return sessionState.GetVariableValueAtScope(name, scope); + return _sessionState.GetVariableValueAtScope(name, scope); } // GetValueAtScope /// @@ -331,12 +332,12 @@ namespace System.Management.Automation public void Set(string name, object value) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.SetVariableValue(name, value, CommandOrigin.Internal); + _sessionState.SetVariableValue(name, value, CommandOrigin.Internal); } // SetVariable /// @@ -362,12 +363,12 @@ namespace System.Management.Automation public void Set(PSVariable variable) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.SetVariable(variable, false, CommandOrigin.Internal); + _sessionState.SetVariable(variable, false, CommandOrigin.Internal); } // SetVariable /// @@ -406,12 +407,12 @@ namespace System.Management.Automation public void Remove(string name) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveVariable(name); + _sessionState.RemoveVariable(name); } // RemoveVariable /// @@ -432,12 +433,12 @@ namespace System.Management.Automation public void Remove(PSVariable variable) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveVariable(variable); + _sessionState.RemoveVariable(variable); } // RemoveVariable /// @@ -475,12 +476,12 @@ namespace System.Management.Automation internal void RemoveAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveVariableAtScope(name, scope); + _sessionState.RemoveVariableAtScope(name, scope); } /// @@ -513,19 +514,19 @@ namespace System.Management.Automation internal void RemoveAtScope(PSVariable variable, string scope) { Dbg.Diagnostics.Assert( - sessionState != null, + _sessionState != null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object - sessionState.RemoveVariableAtScope(variable, scope); + _sessionState.RemoveVariableAtScope(variable, scope); } #endregion Public methods #region private data - private SessionStateInternal sessionState; + private SessionStateInternal _sessionState; #endregion private data } // PSVariableIntrinsics diff --git a/src/System.Management.Automation/engine/VariablePath.cs b/src/System.Management.Automation/engine/VariablePath.cs index a5afb0a1c..d6c0b00f0 100644 --- a/src/System.Management.Automation/engine/VariablePath.cs +++ b/src/System.Management.Automation/engine/VariablePath.cs @@ -16,15 +16,15 @@ namespace System.Management.Automation [Flags] internal enum VariablePathFlags { - None = 0x00, - Local = 0x01, - Script = 0x02, - Global = 0x04, - Private = 0x08, - Variable = 0x10, - Function = 0x20, + None = 0x00, + Local = 0x01, + Script = 0x02, + Global = 0x04, + Private = 0x08, + Variable = 0x10, + Function = 0x20, DriveQualified = 0x40, - Unqualified = 0x80, + Unqualified = 0x80, // If any of these bits are set, the path does not represent an unscoped variable. UnscopedVariableMask = Local | Script | Global | Private | Function | DriveQualified, @@ -95,8 +95,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("path"); } - this._userPath = path; - this._flags = knownFlags; + _userPath = path; + _flags = knownFlags; string candidateScope = null; string candidateScopeUpper = null; @@ -105,44 +105,44 @@ namespace System.Management.Automation int currentCharIndex = 0; int lastScannedColon = -1; - scanScope: + scanScope: switch (path[0]) { - case 'g': - case 'G': - candidateScope = "lobal"; - candidateScopeUpper = "LOBAL"; - candidateFlags = VariablePathFlags.Global; - break; - case 'l': - case 'L': - candidateScope = "ocal"; - candidateScopeUpper = "OCAL"; - candidateFlags = VariablePathFlags.Local; - break; - case 'p': - case 'P': - candidateScope = "rivate"; - candidateScopeUpper = "RIVATE"; - candidateFlags = VariablePathFlags.Private; - break; - case 's': - case 'S': - candidateScope = "cript"; - candidateScopeUpper = "CRIPT"; - candidateFlags = VariablePathFlags.Script; - break; - case 'v': - case 'V': - if (knownFlags == VariablePathFlags.None) - { - // If we see 'variable:', our namespaceId will be empty, and - // we'll also need to scan for the scope again. - candidateScope = "ariable"; - candidateScopeUpper = "ARIABLE"; - candidateFlags = VariablePathFlags.Variable; - } - break; + case 'g': + case 'G': + candidateScope = "lobal"; + candidateScopeUpper = "LOBAL"; + candidateFlags = VariablePathFlags.Global; + break; + case 'l': + case 'L': + candidateScope = "ocal"; + candidateScopeUpper = "OCAL"; + candidateFlags = VariablePathFlags.Local; + break; + case 'p': + case 'P': + candidateScope = "rivate"; + candidateScopeUpper = "RIVATE"; + candidateFlags = VariablePathFlags.Private; + break; + case 's': + case 'S': + candidateScope = "cript"; + candidateScopeUpper = "CRIPT"; + candidateFlags = VariablePathFlags.Script; + break; + case 'v': + case 'V': + if (knownFlags == VariablePathFlags.None) + { + // If we see 'variable:', our namespaceId will be empty, and + // we'll also need to scan for the scope again. + candidateScope = "ariable"; + candidateScopeUpper = "ARIABLE"; + candidateFlags = VariablePathFlags.Variable; + } + break; } if (candidateScope != null) @@ -157,7 +157,7 @@ namespace System.Management.Automation } } - if (j == candidateScope.Length && + if (j == candidateScope.Length && currentCharIndex < path.Length && path[currentCharIndex] == ':') { @@ -202,7 +202,7 @@ namespace System.Management.Automation if (_flags == VariablePathFlags.None) { - this._flags = VariablePathFlags.Unqualified | VariablePathFlags.Variable; + _flags = VariablePathFlags.Unqualified | VariablePathFlags.Variable; } } @@ -260,7 +260,7 @@ namespace System.Management.Automation /// /// Returns true if the path defines a variable. /// - public bool IsVariable { get { return 0 != (_flags & VariablePathFlags.Variable); } } + public bool IsVariable { get { return 0 != (_flags & VariablePathFlags.Variable); } } /// /// Returns true if the path defines a function. diff --git a/src/System.Management.Automation/engine/WinRT/IInspectable.cs b/src/System.Management.Automation/engine/WinRT/IInspectable.cs index a1f77f580..06159b39f 100644 --- a/src/System.Management.Automation/engine/WinRT/IInspectable.cs +++ b/src/System.Management.Automation/engine/WinRT/IInspectable.cs @@ -1,7 +1,8 @@ // // Copyright (C) Microsoft. All rights reserved. // -using System.Runtime.InteropServices; + +using System.Runtime.InteropServices; using System.Reflection; namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/WorkflowInfo.cs b/src/System.Management.Automation/engine/WorkflowInfo.cs index 48554be43..da83246c2 100644 --- a/src/System.Management.Automation/engine/WorkflowInfo.cs +++ b/src/System.Management.Automation/engine/WorkflowInfo.cs @@ -41,18 +41,18 @@ namespace System.Management.Automation /// If is null. /// public WorkflowInfo(string name, string definition, ScriptBlock workflow, string xamlDefinition, WorkflowInfo[] workflowsCalled) - : this(name, workflow, (ExecutionContext) null) + : this(name, workflow, (ExecutionContext)null) { if (string.IsNullOrEmpty(xamlDefinition)) { throw PSTraceSource.NewArgumentNullException("xamlDefinition"); } - this._definition = definition; + _definition = definition; this.XamlDefinition = xamlDefinition; if (workflowsCalled != null) { - this._workflowsCalled = new ReadOnlyCollection(workflowsCalled); + _workflowsCalled = new ReadOnlyCollection(workflowsCalled); } } @@ -197,7 +197,7 @@ namespace System.Management.Automation internal WorkflowInfo(string name, ScriptBlock workflow, ScopedItemOptions options, ExecutionContext context, string helpFile) : base(name, workflow, options, context, helpFile) { - SetCommandType( CommandTypes.Workflow ); + SetCommandType(CommandTypes.Workflow); } // workflowInfo ctor /// @@ -226,8 +226,8 @@ namespace System.Management.Automation { this.XamlDefinition = other.XamlDefinition; this.NestedXamlDefinition = other.NestedXamlDefinition; - this._workflowsCalled = other.WorkflowsCalled; - this._definition = other.Definition; + _workflowsCalled = other.WorkflowsCalled; + _definition = other.Definition; } /// @@ -307,7 +307,6 @@ namespace System.Management.Automation internal override HelpCategory HelpCategory { get { return HelpCategory.Workflow; } - } - + } } // WorkflowInfo } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index e5138e3dd..330f3bd0b 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -20,7 +20,7 @@ using System.Management.Automation.Internal.Host; using System.Threading; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; - + namespace System.Management.Automation @@ -53,10 +53,10 @@ namespace System.Management.Automation { get { - return commonParameters.Value; + return s_commonParameters.Value; } } - static Lazy> commonParameters = new Lazy>( + private static Lazy> s_commonParameters = new Lazy>( () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { @@ -75,10 +75,10 @@ namespace System.Management.Automation { get { - return optionalCommonParameters.Value; + return s_optionalCommonParameters.Value; } } - static Lazy> optionalCommonParameters = new Lazy>( + private static Lazy> s_optionalCommonParameters = new Lazy>( () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { @@ -104,9 +104,9 @@ namespace System.Management.Automation { get { - using(PSTransactionManager.GetEngineProtectionScope()) + using (PSTransactionManager.GetEngineProtectionScope()) { - return this.IsStopping; + return this.IsStopping; } } } @@ -149,10 +149,10 @@ namespace System.Management.Automation { MshCommandRuntime mshRuntime = this.CommandRuntime as MshCommandRuntime; - if(mshRuntime != null) + if (mshRuntime != null) { - if(mshRuntime.UseTransaction && - (! this.Context.TransactionManager.HasTransaction)) + if (mshRuntime.UseTransaction && + (!this.Context.TransactionManager.HasTransaction)) { string error = TransactionStrings.NoTransactionStarted; @@ -219,7 +219,7 @@ namespace System.Management.Automation #endregion internal_members #region ctor - + /// /// Initializes the new instance of Cmdlet class. /// @@ -303,7 +303,7 @@ namespace System.Management.Automation { using (PSTransactionManager.GetEngineProtectionScope()) { - return commandRuntime; + return commandRuntime; } } set @@ -1577,7 +1577,7 @@ namespace System.Management.Automation if (commandRuntime != null) { ICommandRuntime2 runtime2 = commandRuntime as ICommandRuntime2; - if(runtime2 != null) + if (runtime2 != null) { return runtime2.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); } @@ -1603,7 +1603,7 @@ namespace System.Management.Automation if (this is PSCmdlet) { string msg = CommandBaseStrings.CannotInvokePSCmdletsDirectly; - + throw new System.InvalidOperationException(msg); } @@ -1663,7 +1663,7 @@ namespace System.Management.Automation if (commandRuntime != null) return commandRuntime.TransactionAvailable(); else - #pragma warning suppress 56503 +#pragma warning suppress 56503 throw new System.NotImplementedException("TransactionAvailable"); } } @@ -1677,7 +1677,7 @@ namespace System.Management.Automation { get { - if(commandRuntime != null) + if (commandRuntime != null) return commandRuntime.CurrentPSTransaction; else // We want to throw in this situation, and want to use a @@ -1730,7 +1730,7 @@ namespace System.Management.Automation { using (PSTransactionManager.GetEngineProtectionScope()) { - if(errorRecord == null) + if (errorRecord == null) throw new ArgumentNullException("errorRecord"); if (commandRuntime != null) diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index abb70b206..02fd97198 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -63,7 +63,7 @@ namespace System.Management.Automation { Enabled = true; Script = script; - Id = _lastID++; + Id = s_lastID++; Action = action; HitCount = 0; } @@ -110,7 +110,7 @@ namespace System.Management.Automation } virtual internal void RemoveSelf(ScriptDebugger debugger) - { + { } #endregion methods @@ -127,7 +127,7 @@ namespace System.Management.Automation #region private members - private static int _lastID; + private static int s_lastID; #endregion private members } @@ -267,7 +267,7 @@ namespace System.Management.Automation /// Gets the string representation of this breakpoint /// /// The string representation of this breakpoint - public override string ToString() + public override string ToString() { return IsScriptBreakpoint ? StringUtil.Format(DebuggerStrings.VariableScriptBreakpointString, Script, Variable, AccessMode) diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index ec8532623..0da8a19f5 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -74,8 +74,8 @@ namespace System.Management.Automation /// /// public DebuggerStopEventArgs( - InvocationInfo invocationInfo, - Collection breakpoints, + InvocationInfo invocationInfo, + Collection breakpoints, DebuggerResumeAction resumeAction) { this.InvocationInfo = invocationInfo; @@ -363,7 +363,7 @@ namespace System.Management.Automation /// internal virtual bool IsPendingDebugStopEvent { - get { throw new PSNotImplementedException(); } + get { throw new PSNotImplementedException(); } } /// @@ -371,7 +371,7 @@ namespace System.Management.Automation /// internal virtual bool IsDebuggerSteppingEnabled { - get { throw new PSNotImplementedException(); } + get { throw new PSNotImplementedException(); } } /// @@ -388,7 +388,7 @@ namespace System.Management.Automation internal virtual UnhandledBreakpointProcessingMode UnhandledBreakpointMode { get { throw new PSNotImplementedException(); } - set { throw new PSNotImplementedException(); } + set { throw new PSNotImplementedException(); } } /// @@ -415,7 +415,7 @@ namespace System.Management.Automation /// public virtual Guid InstanceId { - get { return _instanceId; } + get { return s_instanceId; } } /// @@ -516,9 +516,9 @@ namespace System.Management.Automation /// host /// Current path public virtual void SetParent( - Debugger parent, - IEnumerable breakPoints, - DebuggerResumeAction? startAction, + Debugger parent, + IEnumerable breakPoints, + DebuggerResumeAction? startAction, PSHost host, PathInfo path) { @@ -704,7 +704,7 @@ namespace System.Management.Automation { // Raise event on worker thread. Threading.ThreadPool.QueueUserWorkItem( - (state) => + (state) => { try { @@ -725,7 +725,7 @@ namespace System.Management.Automation internal const string CannotEnableDebuggerSteppingInvalidMode = "Debugger:CannotEnableDebuggerSteppingInvalidMode"; - private static readonly Guid _instanceId = new Guid(); + private static readonly Guid s_instanceId = new Guid(); #endregion } @@ -751,7 +751,7 @@ namespace System.Management.Automation _commandBreakpoints = new List(); _variableBreakpoints = new Dictionary>(StringComparer.OrdinalIgnoreCase); _steppingMode = SteppingMode.None; - _callStack = new CallStackList {_callStackList = new List()}; + _callStack = new CallStackList { _callStackList = new List() }; _runningJobs = new Dictionary(); _activeDebuggers = new ConcurrentStack(); @@ -767,7 +767,7 @@ namespace System.Management.Automation /// static ScriptDebugger() { - _processDebugPromptMatch = StringUtil.Format(@"""[{0}:", DebuggerStrings.NestedRunspaceDebuggerPromptProcessName); + s_processDebugPromptMatch = StringUtil.Format(@"""[{0}:", DebuggerStrings.NestedRunspaceDebuggerPromptProcessName); } #endregion constructors @@ -777,9 +777,9 @@ namespace System.Management.Automation /// /// True when debugger is stopped at a breakpoint. /// - public override bool InBreakpoint - { - get + public override bool InBreakpoint + { + get { if (_inBreakpoint) { @@ -791,9 +791,9 @@ namespace System.Management.Automation { return activeDebugger.InBreakpoint; } - - return false; - } + + return false; + } } internal override bool IsPushed @@ -834,8 +834,8 @@ namespace System.Management.Automation if (_isLocalSession == null) { // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. - _isLocalSession = !(((this._context.InternalHost.ExternalHost != null) && - (this._context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); + _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && + (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); } return _isLocalSession.Value; } @@ -862,7 +862,7 @@ namespace System.Management.Automation _boundBreakpoints.Clear(); _commandBreakpoints.Clear(); _variableBreakpoints.Clear(); - _emptyBreakpointList.Clear(); + s_emptyBreakpointList.Clear(); _callStack.Clear(); _overOrOutFrame = null; _commandProcessor = new DebuggerCommandProcessor(); @@ -870,7 +870,7 @@ namespace System.Management.Automation _currentInvocationInfo = null; _inBreakpoint = false; _psDebuggerCommand = null; - savedIgnoreScriptDebug = false; + _savedIgnoreScriptDebug = false; _isLocalSession = null; _nestedDebuggerStop = false; @@ -899,7 +899,7 @@ namespace System.Management.Automation // Called from generated code on entering the script function, called once for each dynamicparam, begin, or end // block, and once for each object written to the pipeline. Also called when entering a trap. - void EnterScriptFunction(FunctionContext functionContext) + internal void EnterScriptFunction(FunctionContext functionContext) { Diagnostics.Assert(functionContext._executionContext == _context, "Wrong debugger is being used."); @@ -943,7 +943,7 @@ namespace System.Management.Automation } } - void SetupBreakpoints(FunctionContext functionContext) + private void SetupBreakpoints(FunctionContext functionContext) { var scriptDebugData = _mapScriptToBreakpoints.GetValue(functionContext._sequencePoints, _ => Tuple.Create(new List(), @@ -1311,7 +1311,7 @@ namespace System.Management.Automation // Ensure that code being processed during breakpoint triggers // act like they are broken into the debugger. _inBreakpoint = true; - if(breakpoint.Trigger() == Breakpoint.BreakpointAction.Break) + if (breakpoint.Trigger() == Breakpoint.BreakpointAction.Break) { breaks.Add(breakpoint); } @@ -1385,7 +1385,7 @@ namespace System.Management.Automation if (!_callStack.Last().IsFrameHidden) { _overOrOutFrame = null; - StopOnSequencePoint(functionContext, _emptyBreakpointList); + StopOnSequencePoint(functionContext, s_emptyBreakpointList); } else if (_overOrOutFrame == null) { @@ -1550,7 +1550,7 @@ namespace System.Management.Automation private SteppingMode _steppingMode; private CallStackInfo _overOrOutFrame; private CallStackList _callStack; - private static readonly List _emptyBreakpointList = new List(); + private static readonly List s_emptyBreakpointList = new List(); private DebuggerCommandProcessor _commandProcessor = new DebuggerCommandProcessor(); private InvocationInfo _currentInvocationInfo; @@ -1582,7 +1582,7 @@ namespace System.Management.Automation private bool _preserveUnhandledDebugStopEvent; private ManualResetEventSlim _preserveDebugStopEvent; - private static readonly string _processDebugPromptMatch; + private static readonly string s_processDebugPromptMatch; #endregion private members @@ -1595,13 +1595,13 @@ namespace System.Management.Automation { Diagnostics.Assert(breakpoints != null, "The list of breakpoints should not be null"); - LocalRunspace localRunspace = this._context.CurrentRunspace as LocalRunspace; + LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; Diagnostics.Assert(localRunspace != null, "Debugging is only supported on local runspaces"); if (localRunspace.PulsePipeline != null && localRunspace.PulsePipeline == localRunspace.GetCurrentlyRunningPipeline()) { - this._context.EngineHostInterface.UI.WriteWarningLine( + _context.EngineHostInterface.UI.WriteWarningLine( breakpoints.Count > 0 ? String.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, breakpoints[0]) @@ -1621,7 +1621,7 @@ namespace System.Management.Automation return; } - this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); + _context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo defaultPromptInfo = null; string originalPromptString = null; @@ -1629,20 +1629,20 @@ namespace System.Management.Automation try { - Collection items = this._context.SessionState.InvokeProvider.Item.Get("function:\\prompt"); - if((items != null) && (items.Count > 0)) + Collection items = _context.SessionState.InvokeProvider.Item.Get("function:\\prompt"); + if ((items != null) && (items.Count > 0)) { defaultPromptInfo = items[0].BaseObject as FunctionInfo; originalPromptString = defaultPromptInfo.Definition as string; if (originalPromptString.Equals(InitialSessionState.DefaultPromptFunctionText, StringComparison.OrdinalIgnoreCase) || - originalPromptString.Trim().StartsWith(_processDebugPromptMatch, StringComparison.OrdinalIgnoreCase)) + originalPromptString.Trim().StartsWith(s_processDebugPromptMatch, StringComparison.OrdinalIgnoreCase)) { hadDefaultPrompt = true; } } } - catch(ItemNotFoundException) + catch (ItemNotFoundException) { // Ignore, it means they don't have the default prompt } @@ -1666,18 +1666,18 @@ namespace System.Management.Automation } PSLanguageMode? originalLanguageMode = null; - if (this._context.UseFullLanguageModeInDebugger && - (this._context.LanguageMode != PSLanguageMode.FullLanguage)) + if (_context.UseFullLanguageModeInDebugger && + (_context.LanguageMode != PSLanguageMode.FullLanguage)) { - originalLanguageMode = this._context.LanguageMode; - this._context.LanguageMode = PSLanguageMode.FullLanguage; + originalLanguageMode = _context.LanguageMode; + _context.LanguageMode = PSLanguageMode.FullLanguage; } else if (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == System.Management.Automation.Security.SystemEnforcementMode.Enforce) { // If there is a system lockdown in place, enforce it - originalLanguageMode = this._context.LanguageMode; - this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + originalLanguageMode = _context.LanguageMode; + _context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } RunspaceAvailability previousAvailability = _context.CurrentRunspace.RunspaceAvailability; @@ -1702,7 +1702,7 @@ namespace System.Management.Automation } // Reset list lines. - this._commandProcessor.Reset(); + _commandProcessor.Reset(); // Save a copy of the stop arguments. DebuggerStopEventArgs copyArgs = new DebuggerStopEventArgs(invocationInfo, breakpoints); @@ -1721,14 +1721,14 @@ namespace System.Management.Automation _callStack.Last().TopFrameAtBreakpoint = false; } - this._context.CurrentRunspace.UpdateRunspaceAvailability(previousAvailability, true); + _context.CurrentRunspace.UpdateRunspaceAvailability(previousAvailability, true); if (originalLanguageMode.HasValue) { - this._context.LanguageMode = originalLanguageMode.Value; + _context.LanguageMode = originalLanguageMode.Value; } - this._context.EngineSessionState.RemoveVariable(SpecialVariables.PSDebugContext); + _context.EngineSessionState.RemoveVariable(SpecialVariables.PSDebugContext); if (hadDefaultPrompt) { @@ -1754,46 +1754,46 @@ namespace System.Management.Automation switch (action) { - case DebuggerResumeAction.StepInto: - _steppingMode = SteppingMode.StepIn; - _overOrOutFrame = null; - break; - - case DebuggerResumeAction.StepOut: - if (_callStack.Count > 1) - { - // When we pop to the parent frame, we'll clear _overOrOutFrame (so OnSequencePointHit - // will stop) and continue with a step. + case DebuggerResumeAction.StepInto: _steppingMode = SteppingMode.StepIn; - _overOrOutFrame = _callStack[_callStack.Count - 2]; - } - else - { - // Stepping out of the top frame is just like continue (allow hitting - // breakpoints in the current frame, but otherwise just go.) - goto case DebuggerResumeAction.Continue; - } - break; + _overOrOutFrame = null; + break; - case DebuggerResumeAction.StepOver: - _steppingMode = SteppingMode.StepIn; - _overOrOutFrame = _callStack.Last(); - break; + case DebuggerResumeAction.StepOut: + if (_callStack.Count > 1) + { + // When we pop to the parent frame, we'll clear _overOrOutFrame (so OnSequencePointHit + // will stop) and continue with a step. + _steppingMode = SteppingMode.StepIn; + _overOrOutFrame = _callStack[_callStack.Count - 2]; + } + else + { + // Stepping out of the top frame is just like continue (allow hitting + // breakpoints in the current frame, but otherwise just go.) + goto case DebuggerResumeAction.Continue; + } + break; - case DebuggerResumeAction.Continue: - // nothing to do, just continue - _steppingMode = SteppingMode.None; - _overOrOutFrame = null; - break; + case DebuggerResumeAction.StepOver: + _steppingMode = SteppingMode.StepIn; + _overOrOutFrame = _callStack.Last(); + break; - case DebuggerResumeAction.Stop: - _steppingMode = SteppingMode.None; - _overOrOutFrame = null; - throw new TerminateException(); + case DebuggerResumeAction.Continue: + // nothing to do, just continue + _steppingMode = SteppingMode.None; + _overOrOutFrame = null; + break; - default: - Debug.Assert(false, "Received an unknown action: " + action); - break; + case DebuggerResumeAction.Stop: + _steppingMode = SteppingMode.None; + _overOrOutFrame = null; + throw new TerminateException(); + + default: + Debug.Assert(false, "Received an unknown action: " + action); + break; } } @@ -1838,7 +1838,7 @@ namespace System.Management.Automation StepIn, None } - + // When a script file changes, we need to rebind all breakpoints in that script. private void UnbindBoundBreakpoints(List boundBreakpoints) { @@ -1913,7 +1913,7 @@ namespace System.Management.Automation _pendingBreakpoints = newPendingBreakpoints; } - void StopOnSequencePoint(FunctionContext functionContext, List breakpoints) + private void StopOnSequencePoint(FunctionContext functionContext, List breakpoints) { if (functionContext._debuggerHidden) { @@ -2134,7 +2134,7 @@ namespace System.Management.Automation // // Otherwise let root script debugger handle it. // - LocalRunspace localRunspace = this._context.CurrentRunspace as LocalRunspace; + LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; if (localRunspace == null) { throw new PSInvalidOperationException( @@ -2683,7 +2683,7 @@ namespace System.Management.Automation Diagnostics.Assert(jobStartedArgs.Job != null, "WF Job to start cannot be null."); Diagnostics.Assert(jobStartedArgs.Debugger != null, "WF Job Started Debugger object cannot be null."); - if (!(jobStartedArgs.Debugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", + if (!(jobStartedArgs.Debugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", StringComparison.OrdinalIgnoreCase))) { // Check to ensure only PS workflow debuggers can be passed in. @@ -2708,7 +2708,7 @@ namespace System.Management.Automation lock (_syncObject) { jobArgs.Job.StateChanged += HandleJobStateChanged; - if (jobArgs.Job.IsPersistentState(jobArgs.Job.JobStateInfo.State)) + if (jobArgs.Job.IsPersistentState(jobArgs.Job.JobStateInfo.State)) { jobArgs.Job.StateChanged -= HandleJobStateChanged; return; @@ -2738,10 +2738,9 @@ namespace System.Management.Automation this, _idToBreakpoint.Values.ToArray(), startAction, - this._context.EngineHostInterface.ExternalHost, - this._context.SessionState.Path.CurrentLocation, + _context.EngineHostInterface.ExternalHost, + _context.SessionState.Path.CurrentLocation, GetFunctionToSourceMap()); - } else { @@ -2797,7 +2796,7 @@ namespace System.Management.Automation Dictionary fnToSource = new Dictionary(); // Get workflow function source information for workflow debugger. - Collection items = this._context.SessionState.InvokeProvider.Item.Get("function:\\*"); + Collection items = _context.SessionState.InvokeProvider.Item.Get("function:\\*"); foreach (var item in items) { var funcItem = item.BaseObject as WorkflowInfo; @@ -2912,7 +2911,7 @@ namespace System.Management.Automation // Save running calling frame. _nestedRunningFrame = _callStack[_callStack.Count - callstackOffset]; - + _commandProcessor.Reset(); // Make active debugger. @@ -2933,7 +2932,7 @@ namespace System.Management.Automation } if (runningJobCount == 0) - { + { // If we are back to the root debugger and are in step mode, ensure // that the root debugger is in step mode to continue stepping. switch (_lastActiveDebuggerAction) @@ -3050,7 +3049,7 @@ namespace System.Management.Automation Debugger activeDebugger = null; if (_activeDebuggers.TryPeek(out activeDebugger)) { - if (activeDebugger.Equals(senderDebugger)) + if (activeDebugger.Equals(senderDebugger)) { HandleActiveJobDebuggerStop(sender, args); return; @@ -3118,14 +3117,14 @@ namespace System.Management.Automation private void HandleJobStateChanged(object sender, JobStateEventArgs args) { Job job = sender as Job; - + if (job.IsPersistentState(args.JobStateInfo.State)) { RemoveFromRunningJobList(job); } } - void HandleOutputProcessingStateChanged(object sender, OutputProcessingStateEventArgs e) + private void HandleOutputProcessingStateChanged(object sender, OutputProcessingStateEventArgs e) { lock (_syncObject) { @@ -3228,7 +3227,7 @@ namespace System.Management.Automation { if (!_writeWFErrorOnce) { - var host = this._context.EngineHostInterface.ExternalHost; + var host = _context.EngineHostInterface.ExternalHost; if (host != null && host.UI != null) { host.UI.WriteErrorLine(DebuggerStrings.WorkflowDebuggingNotSupported); @@ -3434,7 +3433,7 @@ namespace System.Management.Automation } if (remove) - { + { RemoveFromRunningRunspaceList(runspace); } } @@ -3646,8 +3645,8 @@ namespace System.Management.Automation return; } - savedIgnoreScriptDebug = this._context.IgnoreScriptDebug; - this._context.IgnoreScriptDebug = false; + _savedIgnoreScriptDebug = _context.IgnoreScriptDebug; + _context.IgnoreScriptDebug = false; _context.PSDebugTraceLevel = traceLevel; if (step != null) @@ -3660,7 +3659,7 @@ namespace System.Management.Automation internal void DisableTracing() { - this._context.IgnoreScriptDebug = savedIgnoreScriptDebug; + _context.IgnoreScriptDebug = _savedIgnoreScriptDebug; _context.PSDebugTraceLevel = 0; _context.PSDebugTraceStep = false; if (!_idToBreakpoint.Any()) @@ -3669,7 +3668,7 @@ namespace System.Management.Automation SetInternalDebugMode(InternalDebugMode.Disabled); } } - private bool savedIgnoreScriptDebug = false; + private bool _savedIgnoreScriptDebug = false; internal void Trace(string messageId, string resourceString, params object[] args) { @@ -4173,7 +4172,7 @@ namespace System.Management.Automation PowerShell command, Debugger rootDebugger, PSMonitorRunspaceType runspaceType, - Guid parentDebuggerId) + Guid parentDebuggerId) : base(runspace, runspaceType, parentDebuggerId) { if (rootDebugger == null) @@ -4529,22 +4528,22 @@ namespace System.Management.Automation private const int DefaultListLineCount = 16; // table of debugger commands - private Dictionary commandTable; + private Dictionary _commandTable; // the Help command - private DebuggerCommand helpCommand; + private DebuggerCommand _helpCommand; // the List command - private DebuggerCommand listCommand; + private DebuggerCommand _listCommand; // last command processed - private DebuggerCommand lastCommand; + private DebuggerCommand _lastCommand; // the source script split into lines - string[] lines; + private string[] _lines; // last line displayed by the list command - private int lastLineDisplayed; + private int _lastLineDisplayed; private const string Crlf = "\x000D\x000A"; @@ -4553,16 +4552,16 @@ namespace System.Management.Automation /// public DebuggerCommandProcessor() { - this.commandTable = new Dictionary(StringComparer.OrdinalIgnoreCase); - this.commandTable[StepCommand] = commandTable[StepShortcut] = new DebuggerCommand(StepCommand, DebuggerResumeAction.StepInto, true, false); - this.commandTable[StepOutCommand] = commandTable[StepOutShortcut] = new DebuggerCommand(StepOutCommand, DebuggerResumeAction.StepOut, false, false); - this.commandTable[StepOverCommand] = commandTable[StepOverShortcut] = new DebuggerCommand(StepOverCommand, DebuggerResumeAction.StepOver, true, false); - this.commandTable[ContinueCommand] = commandTable[ContinueShortcut] = new DebuggerCommand(ContinueCommand, DebuggerResumeAction.Continue, false, false); - this.commandTable[StopCommand] = commandTable[StopShortcut] = new DebuggerCommand(StopCommand, DebuggerResumeAction.Stop, false, false); - this.commandTable[GetStackTraceShortcut] = new DebuggerCommand("get-pscallstack", null, false, false); - this.commandTable[HelpCommand] = commandTable[HelpShortcut] = this.helpCommand = new DebuggerCommand(HelpCommand, null, false, true); - this.commandTable[ListCommand] = commandTable[ListShortcut] = this.listCommand = new DebuggerCommand(ListCommand, null, true, true); - this.commandTable[string.Empty] = new DebuggerCommand(string.Empty, null, false, true); + _commandTable = new Dictionary(StringComparer.OrdinalIgnoreCase); + _commandTable[StepCommand] = _commandTable[StepShortcut] = new DebuggerCommand(StepCommand, DebuggerResumeAction.StepInto, true, false); + _commandTable[StepOutCommand] = _commandTable[StepOutShortcut] = new DebuggerCommand(StepOutCommand, DebuggerResumeAction.StepOut, false, false); + _commandTable[StepOverCommand] = _commandTable[StepOverShortcut] = new DebuggerCommand(StepOverCommand, DebuggerResumeAction.StepOver, true, false); + _commandTable[ContinueCommand] = _commandTable[ContinueShortcut] = new DebuggerCommand(ContinueCommand, DebuggerResumeAction.Continue, false, false); + _commandTable[StopCommand] = _commandTable[StopShortcut] = new DebuggerCommand(StopCommand, DebuggerResumeAction.Stop, false, false); + _commandTable[GetStackTraceShortcut] = new DebuggerCommand("get-pscallstack", null, false, false); + _commandTable[HelpCommand] = _commandTable[HelpShortcut] = _helpCommand = new DebuggerCommand(HelpCommand, null, false, true); + _commandTable[ListCommand] = _commandTable[ListShortcut] = _listCommand = new DebuggerCommand(ListCommand, null, true, true); + _commandTable[string.Empty] = new DebuggerCommand(string.Empty, null, false, true); } /// @@ -4570,7 +4569,7 @@ namespace System.Management.Automation /// public void Reset() { - this.lines = null; + _lines = null; } /// @@ -4579,7 +4578,7 @@ namespace System.Management.Automation /// public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInfo invocationInfo) { - return this.lastCommand = DoProcessCommand(host, command, invocationInfo, null); + return _lastCommand = DoProcessCommand(host, command, invocationInfo, null); } /// @@ -4593,7 +4592,7 @@ namespace System.Management.Automation public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList output) { DebuggerCommand dbgCommand = DoProcessCommand(host, command, invocationInfo, output); - if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction != null)) { this.lastCommand = dbgCommand; } + if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction != null)) { _lastCommand = dbgCommand; } return dbgCommand; } @@ -4615,15 +4614,15 @@ namespace System.Management.Automation /// DebuggerCommand or null. public DebuggerCommand ProcessBasicCommand(string command) { - if (command.Length == 0 && this.lastCommand != null && this.lastCommand.RepeatOnEnter) + if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) { - return this.lastCommand; + return _lastCommand; } DebuggerCommand debuggerCommand; - if (this.commandTable.TryGetValue(command, out debuggerCommand)) + if (_commandTable.TryGetValue(command, out debuggerCommand)) { - if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction != null)) { this.lastCommand = debuggerCommand; } + if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction != null)) { _lastCommand = debuggerCommand; } return debuggerCommand; } @@ -4636,17 +4635,17 @@ namespace System.Management.Automation private DebuggerCommand DoProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList output) { // check for - if (command.Length == 0 && this.lastCommand != null && this.lastCommand.RepeatOnEnter) + if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) { - if (this.lastCommand == this.listCommand) + if (_lastCommand == _listCommand) { - if (this.lines != null && lastLineDisplayed < this.lines.Length) + if (_lines != null && _lastLineDisplayed < _lines.Length) { - DisplayScript(host, output, invocationInfo, this.lastLineDisplayed + 1, DefaultListLineCount); + DisplayScript(host, output, invocationInfo, _lastLineDisplayed + 1, DefaultListLineCount); } - return this.listCommand; + return _listCommand; } - command = this.lastCommand.Command; + command = _lastCommand.Command; } // Check for the list command using a regular expression @@ -4657,16 +4656,16 @@ namespace System.Management.Automation if (match.Success) { DisplayScript(host, output, invocationInfo, match); - return this.listCommand; + return _listCommand; } // Check for the rest of the debugger commands DebuggerCommand debuggerCommand = null; - if (this.commandTable.TryGetValue(command, out debuggerCommand)) + if (_commandTable.TryGetValue(command, out debuggerCommand)) { // Check for the help command - if (debuggerCommand == this.helpCommand) + if (debuggerCommand == _helpCommand) { DisplayHelp(host, output); } @@ -4717,7 +4716,7 @@ namespace System.Management.Automation // // Get the source code for the script // - if (this.lines == null) + if (_lines == null) { string scriptText = invocationInfo.GetFullScript(); if (string.IsNullOrEmpty(scriptText)) @@ -4726,7 +4725,7 @@ namespace System.Management.Automation return; } - this.lines = scriptText.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); + _lines = scriptText.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); } // @@ -4742,12 +4741,12 @@ namespace System.Management.Automation } catch { - WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, lines.Length), host, output); + WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); return; } - if (start <= 0 || start > lines.Length) + if (start <= 0 || start > _lines.Length) { - WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, lines.Length), host, output); + WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); return; } } @@ -4765,12 +4764,12 @@ namespace System.Management.Automation } catch { - WriteErrorLine(StringUtil.Format(DebuggerStrings.BadCountFormat, lines.Length), host, output); + WriteErrorLine(StringUtil.Format(DebuggerStrings.BadCountFormat, _lines.Length), host, output); return; } // Limit requested line count to maximum number of existing lines - count = (count > lines.Length) ? lines.Length : count; + count = (count > _lines.Length) ? _lines.Length : count; if (count <= 0) { @@ -4792,17 +4791,17 @@ namespace System.Management.Automation { WriteCR(host, output); - for (int lineNumber = start; lineNumber <= lines.Length && lineNumber < start + count; lineNumber++) + for (int lineNumber = start; lineNumber <= _lines.Length && lineNumber < start + count; lineNumber++) { WriteLine( lineNumber == invocationInfo.ScriptLineNumber ? - string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, lines[lineNumber - 1]) + string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) : - string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, lines[lineNumber - 1]), + string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), host, output); - this.lastLineDisplayed = lineNumber; + _lastLineDisplayed = lineNumber; } WriteCR(host, output); @@ -4861,10 +4860,10 @@ namespace System.Management.Automation { public DebuggerCommand(string command, DebuggerResumeAction? action, bool repeatOnEnter, bool executedByDebugger) { - this.resumeAction = action; - this.command = command; - this.repeatOnEnter = repeatOnEnter; - this.executedByDebugger = executedByDebugger; + _resumeAction = action; + _command = command; + _repeatOnEnter = repeatOnEnter; + _executedByDebugger = executedByDebugger; } /// @@ -4875,7 +4874,7 @@ namespace System.Management.Automation /// public DebuggerResumeAction? ResumeAction { - get { return this.resumeAction; } + get { return _resumeAction; } } /// @@ -4884,7 +4883,7 @@ namespace System.Management.Automation /// public string Command { - get { return this.command; } + get { return _command; } } /// @@ -4892,7 +4891,7 @@ namespace System.Management.Automation /// public bool RepeatOnEnter { - get { return this.repeatOnEnter; } + get { return _repeatOnEnter; } } /// @@ -4900,13 +4899,13 @@ namespace System.Management.Automation /// public bool ExecutedByDebugger { - get { return this.executedByDebugger; } + get { return _executedByDebugger; } } - private DebuggerResumeAction? resumeAction; - private string command; - bool repeatOnEnter; - bool executedByDebugger; + private DebuggerResumeAction? _resumeAction; + private string _command; + private bool _repeatOnEnter; + private bool _executedByDebugger; } #endregion @@ -4965,7 +4964,7 @@ namespace System.Management.Automation : this(null, invocationInfo) { } - + /// /// Constructor /// @@ -4981,7 +4980,7 @@ namespace System.Management.Automation if (functionContext != null) { this.InvocationInfo = invocationInfo; - this._functionContext = functionContext; + _functionContext = functionContext; this.Position = functionContext.CurrentPosition; } else @@ -4989,8 +4988,8 @@ namespace System.Management.Automation // WF functions do not have functionContext. Use InvocationInfo. this.InvocationInfo = invocationInfo; this.Position = invocationInfo.ScriptPosition; - this._functionContext = new FunctionContext(); - this._functionContext._functionName = invocationInfo.ScriptName; + _functionContext = new FunctionContext(); + _functionContext._functionName = invocationInfo.ScriptName; } } @@ -5099,7 +5098,7 @@ namespace System.Management.Automation } } -#endregion + #endregion } namespace System.Management.Automation.Internal @@ -5177,7 +5176,7 @@ namespace System.Management.Automation.Internal internal const string SetDebuggerStepMode = "__Set-PSDebuggerStepMode"; internal const string SetPSUnhandledBreakpointMode = "__Set-PSUnhandledBreakpointMode"; - private static SortedSet _noHistoryCommandNames = new SortedSet(StringComparer.OrdinalIgnoreCase) + private static SortedSet s_noHistoryCommandNames = new SortedSet(StringComparer.OrdinalIgnoreCase) { "prompt", "Set-PSDebuggerAction", @@ -5199,9 +5198,9 @@ namespace System.Management.Automation.Internal throw new PSArgumentNullException("command"); } - lock (_noHistoryCommandNames) + lock (s_noHistoryCommandNames) { - return !(_noHistoryCommandNames.Contains(command, StringComparer.OrdinalIgnoreCase)); + return !(s_noHistoryCommandNames.Contains(command, StringComparer.OrdinalIgnoreCase)); } } @@ -5356,7 +5355,7 @@ namespace System.Management.Automation.Internal /// Standalone runspace information for monitoring runspaces for debugging. /// [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed Internal use only")] - public sealed class PSStandaloneMonitorRunspaceInfo: PSMonitorRunspaceInfo + public sealed class PSStandaloneMonitorRunspaceInfo : PSMonitorRunspaceInfo { #region Constructor @@ -5366,7 +5365,7 @@ namespace System.Management.Automation.Internal /// Runspace to monitor public PSStandaloneMonitorRunspaceInfo( Runspace runspace) - : base (runspace, PSMonitorRunspaceType.Standalone) + : base(runspace, PSMonitorRunspaceType.Standalone) { } #endregion @@ -5430,7 +5429,7 @@ namespace System.Management.Automation.Internal PSMonitorRunspaceType runspaceType, PowerShell command, Guid parentDebuggerId) - : base (runspace, runspaceType) + : base(runspace, runspaceType) { Command = command; ParentDebuggerId = parentDebuggerId; diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index 2208316be..8baa4fdec 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -16,20 +16,20 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private Guid ownerId; - private bool isCompleted; - private ManualResetEvent completedWaitHandle; + private Guid _ownerId; + private bool _isCompleted; + private ManualResetEvent _completedWaitHandle; // exception occured in the async thread. - private Exception exception; - private AsyncCallback callback; + private Exception _exception; + private AsyncCallback _callback; // user supplied state object - private object state; - private object syncObject = new object(); + private object _state; + private object _syncObject = new object(); // Invoke on thread (remote debugging support). - private AutoResetEvent invokeOnThreadEvent; - private WaitCallback invokeCallback; - private object invokeCallbackState; + private AutoResetEvent _invokeOnThreadEvent; + private WaitCallback _invokeCallback; + private object _invokeCallbackState; #endregion @@ -50,9 +50,9 @@ namespace System.Management.Automation.Runspaces internal AsyncResult(Guid ownerId, AsyncCallback callback, object state) { Dbg.Assert(Guid.Empty != ownerId, "ownerId cannot be empty"); - this.ownerId = ownerId; - this.callback = callback; - this.state = state; + _ownerId = ownerId; + _callback = callback; + _state = state; } #endregion @@ -78,7 +78,7 @@ namespace System.Management.Automation.Runspaces { get { - return isCompleted; + return _isCompleted; } } @@ -87,7 +87,7 @@ namespace System.Management.Automation.Runspaces /// public object AsyncState { - get { return state; } + get { return _state; } } /// @@ -98,18 +98,18 @@ namespace System.Management.Automation.Runspaces { get { - if (null == completedWaitHandle) + if (null == _completedWaitHandle) { - lock (syncObject) + lock (_syncObject) { - if (null == completedWaitHandle) + if (null == _completedWaitHandle) { - completedWaitHandle = new ManualResetEvent(isCompleted); + _completedWaitHandle = new ManualResetEvent(_isCompleted); } } } - return completedWaitHandle; + return _completedWaitHandle; } } @@ -122,7 +122,7 @@ namespace System.Management.Automation.Runspaces /// internal Guid OwnerId { - get { return ownerId; } + get { return _ownerId; } } /// @@ -131,7 +131,7 @@ namespace System.Management.Automation.Runspaces /// internal Exception Exception { - get { return exception; } + get { return _exception; } } /// @@ -139,7 +139,7 @@ namespace System.Management.Automation.Runspaces /// internal AsyncCallback Callback { - get { return callback; } + get { return _callback; } } /// @@ -147,7 +147,7 @@ namespace System.Management.Automation.Runspaces /// internal object SyncObject { - get { return syncObject; } + get { return _syncObject; } } /// @@ -159,21 +159,21 @@ namespace System.Management.Automation.Runspaces internal void SetAsCompleted(Exception exception) { //Dbg.Assert(!isCompleted, "AsynResult already completed"); - if (isCompleted) + if (_isCompleted) { return; } - lock (syncObject) + lock (_syncObject) { - if (isCompleted) + if (_isCompleted) { return; } else { - this.exception = exception; - isCompleted = true; + _exception = exception; + _isCompleted = true; // release the threads waiting on this operation. SignalWaitHandle(); @@ -181,9 +181,9 @@ namespace System.Management.Automation.Runspaces } // call the user supplied callback - if (null != callback) + if (null != _callback) { - callback(this); + _callback(this); } } @@ -192,9 +192,9 @@ namespace System.Management.Automation.Runspaces /// internal void Release() { - if (!isCompleted) + if (!_isCompleted) { - isCompleted = true; + _isCompleted = true; SignalWaitHandle(); } } @@ -208,11 +208,11 @@ namespace System.Management.Automation.Runspaces /// internal void SignalWaitHandle() { - lock (syncObject) + lock (_syncObject) { - if (null != completedWaitHandle) + if (null != _completedWaitHandle) { - completedWaitHandle.Set(); + _completedWaitHandle.Set(); } } } @@ -222,10 +222,10 @@ namespace System.Management.Automation.Runspaces /// internal void EndInvoke() { - invokeOnThreadEvent = new AutoResetEvent(false); + _invokeOnThreadEvent = new AutoResetEvent(false); // Start the thread wait loop. - WaitHandle[] waitHandles = new WaitHandle[2] { AsyncWaitHandle, invokeOnThreadEvent }; + WaitHandle[] waitHandles = new WaitHandle[2] { AsyncWaitHandle, _invokeOnThreadEvent }; bool waiting = true; while (waiting) { @@ -240,7 +240,7 @@ namespace System.Management.Automation.Runspaces // Invoke callback on thread. try { - invokeCallback(invokeCallbackState); + _invokeCallback(_invokeCallbackState); } catch (Exception e) { @@ -250,15 +250,15 @@ namespace System.Management.Automation.Runspaces } AsyncWaitHandle.Dispose(); - completedWaitHandle = null; // Allow early GC + _completedWaitHandle = null; // Allow early GC - invokeOnThreadEvent.Dispose(); - invokeOnThreadEvent = null; // Allow early GC + _invokeOnThreadEvent.Dispose(); + _invokeOnThreadEvent = null; // Allow early GC // Operation is done: if an exception occured, throw it - if (null != exception) + if (null != _exception) { - throw exception; + throw _exception; } } @@ -274,13 +274,13 @@ namespace System.Management.Automation.Runspaces throw new PSArgumentNullException("callback"); } - invokeCallback = callback; - invokeCallbackState = state; + _invokeCallback = callback; + _invokeCallbackState = state; // Signal thread to run callback. - if (invokeOnThreadEvent != null) + if (_invokeOnThreadEvent != null) { - invokeOnThreadEvent.Set(); + _invokeOnThreadEvent.Set(); return true; } diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index c278c03b9..da3a6d03e 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -37,7 +37,7 @@ namespace System.Management.Automation.Host /// /// - public + public ChoiceDescription(string label) { // the only required parameter is label. @@ -48,7 +48,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("label", DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); } - this.label = label; + _label = label; } /// @@ -77,13 +77,13 @@ namespace System.Management.Automation.Host /// /// - public + public ChoiceDescription(string label, string helpMessage) { // the only required parameter is label. if (String.IsNullOrEmpty(label)) - { + { // "label" is not localizable throw PSTraceSource.NewArgumentException("label", DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); } @@ -94,8 +94,8 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentNullException("helpMessage"); } - this.label = label; - this.helpMessage = helpMessage; + _label = label; + _helpMessage = helpMessage; } /// @@ -121,15 +121,15 @@ namespace System.Management.Automation.Host /// /// - public + public string Label { get { - Dbg.Assert(label != null, "label should not be null"); + Dbg.Assert(_label != null, "label should not be null"); - return label; + return _label; } } @@ -152,15 +152,15 @@ namespace System.Management.Automation.Host /// /// - public - string + public + string HelpMessage { get { - Dbg.Assert(helpMessage != null, "helpMessage should not be null"); + Dbg.Assert(_helpMessage != null, "helpMessage should not be null"); - return helpMessage; + return _helpMessage; } set { @@ -169,12 +169,12 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentNullException("value"); } - helpMessage = value; + _helpMessage = value; } } - private readonly string label = null; - private string helpMessage = ""; + private readonly string _label = null; + private string _helpMessage = ""; } } diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index d19d3d011..1e0b3c3ed 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -11,22 +11,21 @@ using Microsoft.Management.Infrastructure; namespace System.Management.Automation.Runspaces { - /// /// Defines a Command object which can be added to object /// for invocation. /// - public sealed class Command + public sealed class Command { #region constructors - + /// /// Initializes a new instance of Command class using specified command parameter. /// /// Name of the command or script contents /// command is null - public Command (string command) - :this(command,false,null) + public Command(string command) + : this(command, false, null) { } @@ -36,8 +35,8 @@ namespace System.Management.Automation.Runspaces /// The command name or script contents /// True if this command represents a script, otherwise; false. /// command is null - public Command (string command, bool isScript) - :this(command,isScript,null) + public Command(string command, bool isScript) + : this(command, isScript, null) { } @@ -53,7 +52,7 @@ namespace System.Management.Automation.Runspaces IsEndOfStatement = false; if (command == null) { - throw PSTraceSource.NewArgumentNullException ("command"); + throw PSTraceSource.NewArgumentNullException("command"); } _command = command; @@ -84,7 +83,7 @@ namespace System.Management.Automation.Runspaces } internal Command(CommandInfo commandInfo) - :this(commandInfo, false) + : this(commandInfo, false) { } @@ -100,7 +99,7 @@ namespace System.Management.Automation.Runspaces /// Copy constructor for clone operations /// /// The source instance. - internal Command (Command command) + internal Command(Command command) { _isScript = command._isScript; _useLocalScope = command._useLocalScope; @@ -113,7 +112,7 @@ namespace System.Management.Automation.Runspaces foreach (CommandParameter param in command.Parameters) { - Parameters.Add (new CommandParameter (param.Name, param.Value)); + Parameters.Add(new CommandParameter(param.Name, param.Value)); } } @@ -199,14 +198,14 @@ namespace System.Management.Automation.Runspaces #endregion Properties #region Methods - + /// /// Creates a new that is a copy of the current instance. /// /// A new that is a copy of this instance. - internal Command Clone () + internal Command Clone() { - return new Command (this); + return new Command(this); } /// @@ -221,7 +220,7 @@ namespace System.Management.Automation.Runspaces #endregion Methods #region Merge - + private PipelineResultTypes _mergeUnclaimedPreviousCommandResults = PipelineResultTypes.None; /// @@ -257,7 +256,7 @@ namespace System.Management.Automation.Runspaces { throw PSTraceSource.NewNotSupportedException(); } - + _mergeUnclaimedPreviousCommandResults = value; } } @@ -380,7 +379,6 @@ namespace System.Management.Automation.Runspaces { _mergeInstructions[(int)MergeType.Information] = toResult; } - } /// @@ -490,7 +488,7 @@ namespace System.Management.Automation.Runspaces } ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory); - if(origin == Automation.CommandOrigin.Internal) + if (origin == Automation.CommandOrigin.Internal) { scriptBlock.LanguageMode = PSLanguageMode.FullLanguage; } @@ -499,19 +497,19 @@ namespace System.Management.Automation.Runspaces // constructions... switch (scriptBlock.LanguageMode) { - case PSLanguageMode.RestrictedLanguage: - scriptBlock.CheckRestrictedLanguage(null, null, false); - break; - case PSLanguageMode.FullLanguage: - // Interactive script commands are permitted in this mode. - break; - case PSLanguageMode.ConstrainedLanguage: - // Constrained Language is checked at runtime. - break; - default: - // This should never happen... - Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor"); - throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor"); + case PSLanguageMode.RestrictedLanguage: + scriptBlock.CheckRestrictedLanguage(null, null, false); + break; + case PSLanguageMode.FullLanguage: + // Interactive script commands are permitted in this mode. + break; + case PSLanguageMode.ConstrainedLanguage: + // Constrained Language is checked at runtime. + break; + default: + // This should never happen... + Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor"); + throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor"); } if (scriptBlock.UsesCmdletBinding) @@ -531,7 +529,7 @@ namespace System.Management.Automation.Runspaces else { // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace - if (( _useLocalScope.HasValue ) && ( !_useLocalScope.Value )) + if ((_useLocalScope.HasValue) && (!_useLocalScope.Value)) { switch (executionContext.LanguageMode) { @@ -569,8 +567,8 @@ namespace System.Management.Automation.Runspaces if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory)) { commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor( - executionContext, - helpTarget, + executionContext, + helpTarget, helpCategory); } @@ -585,12 +583,12 @@ namespace System.Management.Automation.Runspaces /// /// The collection of paramters that have been added. /// - private readonly CommandParameterCollection _parameters = new CommandParameterCollection (); + private readonly CommandParameterCollection _parameters = new CommandParameterCollection(); /// /// The command string passed in at ctor time. /// - private readonly string _command = string.Empty; + private readonly string _command = string.Empty; /// /// The command info passed in at ctor time. @@ -600,8 +598,8 @@ namespace System.Management.Automation.Runspaces /// /// Does this instance represent a script? /// - private readonly bool _isScript; - + private readonly bool _isScript; + /// /// This is used for script commands (i.e. _isScript is true). If /// _useLocalScope is true, script is run in LocalScope. If @@ -610,7 +608,7 @@ namespace System.Management.Automation.Runspaces /// property is bool, not bool? (from V1), so it should probably /// be deprecated, at least for internal use. /// - private bool? _useLocalScope; + private bool? _useLocalScope; #endregion Private fields @@ -780,12 +778,12 @@ namespace System.Management.Automation.Runspaces internal CimInstance ToCimInstance() { CimInstance c = InternalMISerializer.CreateCimInstance("PS_Command"); - CimProperty commandTextProperty = InternalMISerializer.CreateCimProperty("CommandText", - this.CommandText, + CimProperty commandTextProperty = InternalMISerializer.CreateCimProperty("CommandText", + this.CommandText, Microsoft.Management.Infrastructure.CimType.String); c.CimInstanceProperties.Add(commandTextProperty); - CimProperty isScriptProperty = InternalMISerializer.CreateCimProperty("IsScript", - this.IsScript, + CimProperty isScriptProperty = InternalMISerializer.CreateCimProperty("IsScript", + this.IsScript, Microsoft.Management.Infrastructure.CimType.Boolean); c.CimInstanceProperties.Add(isScriptProperty); @@ -799,7 +797,7 @@ namespace System.Management.Automation.Runspaces if (parameterInstances.Count > 0) { - CimProperty parametersProperty = InternalMISerializer.CreateCimProperty("Parameters", + CimProperty parametersProperty = InternalMISerializer.CreateCimProperty("Parameters", parameterInstances.ToArray(), Microsoft.Management.Infrastructure.CimType.ReferenceArray); c.CimInstanceProperties.Add(parametersProperty); @@ -874,17 +872,17 @@ namespace System.Management.Automation.Runspaces /// /// Make the default constructor internal /// - internal CommandCollection () + internal CommandCollection() { } - + /// /// Adds a new command for given string /// /// /// command is null. /// - public void Add (string command) + public void Add(string command) { if (String.Equals(command, "out-default", StringComparison.OrdinalIgnoreCase)) { @@ -908,9 +906,9 @@ namespace System.Management.Automation.Runspaces /// /// scriptContents is null. /// - public void AddScript (string scriptContents) + public void AddScript(string scriptContents) { - this.Add (new Command (scriptContents, true)); + this.Add(new Command(scriptContents, true)); } /// @@ -921,9 +919,9 @@ namespace System.Management.Automation.Runspaces /// /// scriptContents is null. /// - public void AddScript (string scriptContents, bool useLocalScope) + public void AddScript(string scriptContents, bool useLocalScope) { - this.Add (new Command (scriptContents, true, useLocalScope)); + this.Add(new Command(scriptContents, true, useLocalScope)); } /// diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 97fffe467..d58a57208 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; @@ -30,8 +31,8 @@ namespace System.Management.Automation.Runspaces /// /// Initializes a new instance of InvalidRunspaceStateException /// - public InvalidRunspaceStateException () - :base + public InvalidRunspaceStateException() + : base ( StringUtil.Format(RunspaceStrings.InvalidRunspaceStateGeneral) ) @@ -44,8 +45,8 @@ namespace System.Management.Automation.Runspaces /// /// The message that describes the error. /// - public InvalidRunspaceStateException (string message) - :base(message) + public InvalidRunspaceStateException(string message) + : base(message) { } @@ -60,11 +61,11 @@ namespace System.Management.Automation.Runspaces /// /// The exception that is the cause of the current exception. /// - public InvalidRunspaceStateException (string message, Exception innerException) - :base(message, innerException) + public InvalidRunspaceStateException(string message, Exception innerException) + : base(message, innerException) { } - + /// /// Initializes a new instance of the InvalidRunspaceStateException /// with a specified error message and current and expected state. @@ -72,13 +73,13 @@ namespace System.Management.Automation.Runspaces /// The message that describes the error. /// Current state of runspace /// Expected states of runspace - internal InvalidRunspaceStateException + internal InvalidRunspaceStateException ( - string message, - RunspaceState currentState, + string message, + RunspaceState currentState, RunspaceState expectedState - ) - :base(message) + ) + : base(message) { _expectedState = expectedState; _currentState = currentState; @@ -102,7 +103,7 @@ namespace System.Management.Automation.Runspaces /// The that contains contextual information /// about the source or destination. /// - protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context) + protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } @@ -155,7 +156,7 @@ namespace System.Management.Automation.Runspaces [NonSerialized] private RunspaceState _expectedState = 0; } - + #endregion Exceptions #region Runspace state @@ -246,8 +247,8 @@ namespace System.Management.Automation.Runspaces /// Constructor for state changes not resulting from an error. /// /// The state of the runspace. - internal RunspaceStateInfo (RunspaceState state) - : this (state, null) + internal RunspaceStateInfo(RunspaceState state) + : this(state, null) { } @@ -258,7 +259,7 @@ namespace System.Management.Automation.Runspaces /// A non-null exception if the state change was /// caused by an error, otherwise; null. /// - internal RunspaceStateInfo (RunspaceState state, Exception reason) + internal RunspaceStateInfo(RunspaceState state, Exception reason) : base() { _state = state; @@ -271,7 +272,7 @@ namespace System.Management.Automation.Runspaces /// The source /// RunspaceStateInfo /// - internal RunspaceStateInfo (RunspaceStateInfo runspaceStateInfo) + internal RunspaceStateInfo(RunspaceStateInfo runspaceStateInfo) { _state = runspaceStateInfo.State; _reason = runspaceStateInfo.Reason; @@ -348,7 +349,6 @@ namespace System.Management.Automation.Runspaces /// public sealed class RunspaceStateEventArgs : EventArgs { - #region constructors /// @@ -358,11 +358,11 @@ namespace System.Management.Automation.Runspaces /// current state of the runspace. /// runspaceStateInfo is null /// - internal RunspaceStateEventArgs (RunspaceStateInfo runspaceStateInfo) + internal RunspaceStateEventArgs(RunspaceStateInfo runspaceStateInfo) { if (runspaceStateInfo == null) { - throw PSTraceSource.NewArgumentNullException ("runspaceStateInfo"); + throw PSTraceSource.NewArgumentNullException("runspaceStateInfo"); } _runspaceStateInfo = runspaceStateInfo; } @@ -489,7 +489,7 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private static int _globalId; + private static int s_globalId; private Stack _runningPowerShells; private PowerShell _baseRunningPowerShell; private object _syncObject; @@ -504,7 +504,7 @@ namespace System.Management.Automation.Runspaces internal Runspace() { // Create the default Runspace Id and friendly name. - Id = System.Threading.Interlocked.Increment(ref _globalId); + Id = System.Threading.Interlocked.Increment(ref s_globalId); Name = "Runspace" + Id.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); _runningPowerShells = new Stack(); _syncObject = new object(); @@ -523,7 +523,7 @@ namespace System.Management.Automation.Runspaces { s_syncObject = new object(); s_runspaceDictionary = new SortedDictionary>(); - _globalId = 0; + s_globalId = 0; } #endregion constructor @@ -536,7 +536,7 @@ namespace System.Management.Automation.Runspaces /// etc. /// [ThreadStatic] - private static Runspace ThreadSpecificDefaultRunspace = null; + private static Runspace t_threadSpecificDefaultRunspace = null; /// /// Gets and sets the default Runspace used to evaluate scripts /// @@ -545,13 +545,13 @@ namespace System.Management.Automation.Runspaces { get { - return ThreadSpecificDefaultRunspace; + return t_threadSpecificDefaultRunspace; } set { - if ( value == null || ! value.RunspaceIsRemote ) + if (value == null || !value.RunspaceIsRemote) { - ThreadSpecificDefaultRunspace = value; + t_threadSpecificDefaultRunspace = value; } else { @@ -664,9 +664,9 @@ namespace System.Management.Automation.Runspaces /// public bool RunspaceIsRemote { - get + get { - return ! ( this is LocalRunspace || ConnectionInfo == null); + return !(this is LocalRunspace || ConnectionInfo == null); } } @@ -743,7 +743,7 @@ namespace System.Management.Automation.Runspaces } } - bool _skipUserProfile = false; + private bool _skipUserProfile = false; /// /// Skip user profile on engine initialization /// @@ -762,7 +762,7 @@ namespace System.Management.Automation.Runspaces /// /// Connection information for remote Runspaces, null for local Runspaces /// - public abstract RunspaceConnectionInfo ConnectionInfo {get;} + public abstract RunspaceConnectionInfo ConnectionInfo { get; } /// /// ConnectionInfo originally supplied by the user @@ -853,7 +853,7 @@ namespace System.Management.Automation.Runspaces { lock (s_syncObject) { - return new ReadOnlyDictionary>(new Dictionary>(s_runspaceDictionary)); + return new ReadOnlyDictionary>(new Dictionary>(s_runspaceDictionary)); } } } @@ -940,10 +940,10 @@ namespace System.Management.Automation.Runspaces this.RunspaceAvailability = RunspaceAvailability.Busy; break; - // Otherwise no change. + // Otherwise no change. } break; - + case RunspaceAvailability.Available: switch (pipelineState) { @@ -965,7 +965,7 @@ namespace System.Management.Automation.Runspaces break; case PipelineState.Completed: // a nested pipeline caused the host to exit nested prompt - this.RunspaceAvailability = (this.InNestedPrompt || (this._runningPowerShells.Count > 1)) ? + this.RunspaceAvailability = (this.InNestedPrompt || (_runningPowerShells.Count > 1)) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available; break; @@ -1068,7 +1068,7 @@ namespace System.Management.Automation.Runspaces { this.RunspaceAvailability = Runspaces.RunspaceAvailability.RemoteDebug; } - else if ((currentPipeline.PipelineStateInfo.State == PipelineState.Running) || (this._runningPowerShells.Count > 1)) + else if ((currentPipeline.PipelineStateInfo.State == PipelineState.Running) || (_runningPowerShells.Count > 1)) { // Either the current pipeline is running or there are other nested commands to run in the Runspace. this.RunspaceAvailability = RunspaceAvailability.Busy; @@ -1082,10 +1082,10 @@ namespace System.Management.Automation.Runspaces break; case PipelineState.Running: // this can happen if a nested pipeline is created without entering a nested prompt - break; // no change in the availability + break; // no change in the availability default: - break; // no change in the availability + break; // no change in the availability } break; @@ -1715,7 +1715,7 @@ namespace System.Management.Automation.Runspaces { } - RunspaceBase _runspace; + private RunspaceBase _runspace; internal SessionStateProxy(RunspaceBase runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); @@ -1873,10 +1873,10 @@ namespace System.Management.Automation.Runspaces /// /// Another SessionStateProxy call or another pipeline is in progress. /// - [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification="Shipped this way in V2 before becoming virtual.")] + [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Shipped this way in V2 before becoming virtual.")] public virtual PSModuleInfo Module { - get { return _runspace.Module; } + get { return _runspace.Module; } } /// diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 9b64442d7..7136a61a2 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ + using System; using System.Collections.Generic; using System.Linq; @@ -23,7 +24,7 @@ namespace System.Management.Automation.Runspaces internal abstract class RunspaceBase : Runspace { #region constructors - + /// /// Construct an instance of an Runspace using a custom /// implementation of PSHost. @@ -42,14 +43,14 @@ namespace System.Management.Automation.Runspaces { if (host == null) { - throw PSTraceSource.NewArgumentNullException ("host"); + throw PSTraceSource.NewArgumentNullException("host"); } if (runspaceConfiguration == null) { throw PSTraceSource.NewArgumentNullException("runspaceConfiguration"); } - _host = host; + _host = host; _runspaceConfiguration = runspaceConfiguration; } @@ -67,7 +68,7 @@ namespace System.Management.Automation.Runspaces /// /// configuration information for this runspace instance. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification="OK to call ThreadOptions")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OK to call ThreadOptions")] protected RunspaceBase(PSHost host, InitialSessionState initialSessionState) { if (host == null) @@ -147,7 +148,7 @@ namespace System.Management.Automation.Runspaces } } - RunspaceConfiguration _runspaceConfiguration; + private RunspaceConfiguration _runspaceConfiguration; /// /// runspaceConfiguration information for this runspace /// @@ -164,7 +165,7 @@ namespace System.Management.Automation.Runspaces } } - InitialSessionState _initialSessionState; + private InitialSessionState _initialSessionState; /// /// runspaceConfiguration information for this runspace /// @@ -175,7 +176,7 @@ namespace System.Management.Automation.Runspaces return _initialSessionState; } } - + #endregion constructors #region properties @@ -193,7 +194,7 @@ namespace System.Management.Automation.Runspaces } } - private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo (RunspaceState.BeforeOpen); + private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo(RunspaceState.BeforeOpen); /// /// Retrieve information about current state of the runspace @@ -237,10 +238,10 @@ namespace System.Management.Automation.Runspaces /// public override RunspaceConnectionInfo ConnectionInfo { - get - { + get + { // null refers to local case for path - return null; + return null; } } @@ -253,9 +254,9 @@ namespace System.Management.Automation.Runspaces } #endregion properties - + #region Open - + /// /// Open the runspace synchronously. /// @@ -264,7 +265,7 @@ namespace System.Management.Automation.Runspaces /// override public void Open() { - CoreOpen (true); + CoreOpen(true); } /// @@ -273,9 +274,9 @@ namespace System.Management.Automation.Runspaces /// /// RunspaceState is not BeforeOpen /// - override public void OpenAsync () + override public void OpenAsync() { - CoreOpen (false); + CoreOpen(false); } /// @@ -287,7 +288,7 @@ namespace System.Management.Automation.Runspaces /// /// RunspaceState is not BeforeOpen /// - private void CoreOpen (bool syncCall) + private void CoreOpen(bool syncCall) { bool etwEnabled = RunspaceEventSource.Log.IsEnabled(); if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStart(); @@ -299,7 +300,7 @@ namespace System.Management.Automation.Runspaces InvalidRunspaceStateException e = new InvalidRunspaceStateException ( - StringUtil.Format(RunspaceStrings.CannotOpenAgain,new object[] { RunspaceState.ToString() }), + StringUtil.Format(RunspaceStrings.CannotOpenAgain, new object[] { RunspaceState.ToString() }), RunspaceState, RunspaceState.BeforeOpen ); @@ -332,9 +333,9 @@ namespace System.Management.Automation.Runspaces /// protected abstract void OpenHelper(bool syncCall); - + #endregion open - + #region close /// /// Close the runspace synchronously. @@ -345,9 +346,9 @@ namespace System.Management.Automation.Runspaces /// /// RunspaceState is BeforeOpen or Opening /// - override public void Close () + override public void Close() { - CoreClose (true); + CoreClose(true); } /// @@ -362,7 +363,7 @@ namespace System.Management.Automation.Runspaces /// override public void CloseAsync() { - CoreClose (false); + CoreClose(false); } /// @@ -379,7 +380,7 @@ namespace System.Management.Automation.Runspaces /// /// If SessionStateProxy has some method call in progress /// - private void CoreClose (bool syncCall) + private void CoreClose(bool syncCall) { bool alreadyClosing = false; @@ -571,9 +572,9 @@ namespace System.Management.Automation.Runspaces /// Create an empty pipeline /// /// An empty pipeline - public override Pipeline CreatePipeline () + public override Pipeline CreatePipeline() { - return CoreCreatePipeline (null, false, false); + return CoreCreatePipeline(null, false, false); } /// @@ -590,12 +591,12 @@ namespace System.Management.Automation.Runspaces { if (command == null) { - throw PSTraceSource.NewArgumentNullException ("command"); + throw PSTraceSource.NewArgumentNullException("command"); } - return CoreCreatePipeline (command, false, false); + return CoreCreatePipeline(command, false, false); } - + /// /// Create a pipeline from a command string. /// @@ -607,14 +608,14 @@ namespace System.Management.Automation.Runspaces /// /// command is null /// - public override Pipeline CreatePipeline (string command, bool addToHistory) + public override Pipeline CreatePipeline(string command, bool addToHistory) { if (command == null) { - throw PSTraceSource.NewArgumentNullException ("command"); + throw PSTraceSource.NewArgumentNullException("command"); } - return CoreCreatePipeline (command, addToHistory, false); + return CoreCreatePipeline(command, addToHistory, false); } /// @@ -625,9 +626,9 @@ namespace System.Management.Automation.Runspaces /// prompt requires that we execute new pipelines( child pipelines) /// while current pipeline (lets call it parent pipeline) is blocked. /// - public override Pipeline CreateNestedPipeline () + public override Pipeline CreateNestedPipeline() { - return CoreCreatePipeline (null, false, true); + return CoreCreatePipeline(null, false, true); } /// @@ -645,11 +646,10 @@ namespace System.Management.Automation.Runspaces { if (command == null) { - - throw PSTraceSource.NewArgumentNullException ("command"); + throw PSTraceSource.NewArgumentNullException("command"); } - return CoreCreatePipeline (command, addToHistory, true); + return CoreCreatePipeline(command, addToHistory, true); } /// @@ -662,7 +662,7 @@ namespace System.Management.Automation.Runspaces /// /// A pipline pre-filled with Commands specified in commandString. /// - protected abstract Pipeline CoreCreatePipeline (string command, bool addToHistory, bool isNested); + protected abstract Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested); #endregion CreatePipeline @@ -726,7 +726,7 @@ namespace System.Management.Automation.Runspaces /// Raising event with in a lock introduces chances of deadlock in GUI /// applications. /// - Queue _runspaceEventQueue = new Queue(); + private Queue _runspaceEventQueue = new Queue(); private class RunspaceEventQueueItem { @@ -737,7 +737,7 @@ namespace System.Management.Automation.Runspaces this.NewRunspaceAvailability = newAvailability; } - public RunspaceStateInfo RunspaceStateInfo; + public RunspaceStateInfo RunspaceStateInfo; public RunspaceAvailability CurrentRunspaceAvailability; public RunspaceAvailability NewRunspaceAvailability; } @@ -757,13 +757,13 @@ namespace System.Management.Automation.Runspaces /// adds RunspaceStateInfo to a queue. /// RaiseRunspaceStateEvents raises event for each item in this queue. /// - protected void SetRunspaceState (RunspaceState state, Exception reason) + protected void SetRunspaceState(RunspaceState state, Exception reason) { lock (SyncRoot) { if (state != RunspaceState) { - _runspaceStateInfo = new RunspaceStateInfo (state, reason); + _runspaceStateInfo = new RunspaceStateInfo(state, reason); //Add _runspaceStateInfo to _runspaceEventQueue. //RaiseRunspaceStateEvents will raise event for each item @@ -777,8 +777,8 @@ namespace System.Management.Automation.Runspaces _runspaceEventQueue.Enqueue( new RunspaceEventQueueItem( - _runspaceStateInfo.Clone(), - previousAvailability, + _runspaceStateInfo.Clone(), + previousAvailability, _runspaceAvailability)); } } @@ -788,16 +788,16 @@ namespace System.Management.Automation.Runspaces /// Set the current runspace state - no error /// /// the new state - protected void SetRunspaceState (RunspaceState state) + protected void SetRunspaceState(RunspaceState state) { - this.SetRunspaceState (state, null); + this.SetRunspaceState(state, null); } /// /// Raises events for changes in runspace state. /// - protected void RaiseRunspaceStateEvents () + protected void RaiseRunspaceStateEvents() { Queue tempEventQueue = null; EventHandler stateChanged = null; @@ -818,7 +818,7 @@ namespace System.Management.Automation.Runspaces //Clear the events if there are no EventHandlers. This //ensures that events do not get called for state //changes prior to their registration. - _runspaceEventQueue.Clear (); + _runspaceEventQueue.Clear(); } } @@ -903,7 +903,7 @@ namespace System.Management.Automation.Runspaces /// Thrown if /// is null. /// - internal void AddToRunningPipelineList (PipelineBase pipeline) + internal void AddToRunningPipelineList(PipelineBase pipeline) { Dbg.Assert(pipeline != null, "caller should validate the parameter"); @@ -912,10 +912,10 @@ namespace System.Management.Automation.Runspaces if (_bypassRunspaceStateCheck == false && RunspaceState != RunspaceState.Opened) { InvalidRunspaceStateException e = - new InvalidRunspaceStateException + new InvalidRunspaceStateException ( - StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline,RunspaceState.ToString()), - RunspaceState, + StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, RunspaceState.ToString()), + RunspaceState, RunspaceState.Opened ); throw e; @@ -924,8 +924,8 @@ namespace System.Management.Automation.Runspaces //Add the pipeline to list of Excuting pipeline. //Note:_runningPipelines is always accessed with the lock so //there is no need to create a synchronized version of list - _runningPipelines.Add (pipeline); - currentlyRunningPipeline = pipeline; + _runningPipelines.Add(pipeline); + _currentlyRunningPipeline = pipeline; } } @@ -938,7 +938,7 @@ namespace System.Management.Automation.Runspaces /// /// Thrown if is null. /// - internal void RemoveFromRunningPipelineList (PipelineBase pipeline) + internal void RemoveFromRunningPipelineList(PipelineBase pipeline) { Dbg.Assert(pipeline != null, "caller should validate the parameter"); @@ -950,19 +950,19 @@ namespace System.Management.Automation.Runspaces //Remove the pipeline to list of Excuting pipeline. //Note:_runningPipelines is always accessed with the lock so //there is no need to create a synchronized version of list - _runningPipelines.Remove (pipeline); + _runningPipelines.Remove(pipeline); // Update the running pipeline - if(_runningPipelines.Count == 0) + if (_runningPipelines.Count == 0) { - currentlyRunningPipeline = null; + _currentlyRunningPipeline = null; } else { - currentlyRunningPipeline = _runningPipelines[_runningPipelines.Count - 1]; + _currentlyRunningPipeline = _runningPipelines[_runningPipelines.Count - 1]; } - pipeline.PipelineFinishedEvent.Set (); + pipeline.PipelineFinishedEvent.Set(); } } @@ -970,7 +970,7 @@ namespace System.Management.Automation.Runspaces /// Waits till all the pipelines running in the runspace have /// finished execution. /// - internal bool WaitForFinishofPipelines () + internal bool WaitForFinishofPipelines() { //Take a snapshot of list of active pipelines. //Note:Before we enter to this CloseHelper routine @@ -1001,12 +1001,12 @@ namespace System.Management.Automation.Runspaces { // We use a worker thread to wait for all handles, and the STA thread can just wait on the worker thread -- the worker // threads from the ThreadPool are MTA. - using(ManualResetEvent waitAllIsDone = new ManualResetEvent(false)) + using (ManualResetEvent waitAllIsDone = new ManualResetEvent(false)) { Tuple stateInfo = new Tuple(waitHandles, waitAllIsDone); ThreadPool.QueueUserWorkItem(new WaitCallback( - delegate(object state) + delegate (object state) { var tuple = (Tuple)state; WaitHandle.WaitAll(tuple.Item1); @@ -1028,7 +1028,7 @@ namespace System.Management.Automation.Runspaces /// /// Stops all the running pipelines /// - protected void StopPipelines () + protected void StopPipelines() { PipelineBase[] runningPipelines; @@ -1042,7 +1042,7 @@ namespace System.Management.Automation.Runspaces //Start from the most recent pipeline. for (int i = runningPipelines.Length - 1; i >= 0; i--) { - runningPipelines[i].Stop (); + runningPipelines[i].Stop(); } } } @@ -1056,8 +1056,8 @@ namespace System.Management.Automation.Runspaces // If we have no running pipeline, or if the currently running pipeline is // the same as the current thread, then execute the action. - var pipelineRunning = currentlyRunningPipeline as PipelineBase; - if (pipelineRunning == null || + var pipelineRunning = _currentlyRunningPipeline as PipelineBase; + if (pipelineRunning == null || Thread.CurrentThread.Equals(pipelineRunning.NestedPipelineExecutionThread)) { shouldRunAction = true; @@ -1077,9 +1077,9 @@ namespace System.Management.Automation.Runspaces /// Internal because it is needed by invoke-history internal override Pipeline GetCurrentlyRunningPipeline() { - return currentlyRunningPipeline; + return _currentlyRunningPipeline; } - Pipeline currentlyRunningPipeline = null; + private Pipeline _currentlyRunningPipeline = null; /// /// This method stops all the pipelines which are nested @@ -1087,7 +1087,7 @@ namespace System.Management.Automation.Runspaces /// /// /// - internal void StopNestedPipelines (Pipeline pipeline) + internal void StopNestedPipelines(Pipeline pipeline) { List nestedPipelines = null; @@ -1103,7 +1103,7 @@ namespace System.Management.Automation.Runspaces //If this pipeline is currently running pipeline, //then it does not have nested pipelines - if (GetCurrentlyRunningPipeline () == pipeline) + if (GetCurrentlyRunningPipeline() == pipeline) { return; } @@ -1171,8 +1171,8 @@ namespace System.Management.Automation.Runspaces // (as opposed to ignoring) is 1.6x slower. try { - pulsePipeline = (PipelineBase)CreatePipeline("0"); - pulsePipeline.IsPulsePipeline = true; + _pulsePipeline = (PipelineBase)CreatePipeline("0"); + _pulsePipeline.IsPulsePipeline = true; pipelineCreated = true; } catch (ObjectDisposedException) @@ -1191,7 +1191,7 @@ namespace System.Management.Automation.Runspaces { try { - pulsePipeline.Invoke(); + _pulsePipeline.Invoke(); } catch (PSInvalidOperationException) { @@ -1215,25 +1215,25 @@ namespace System.Management.Automation.Runspaces internal PipelineBase PulsePipeline { - get { return pulsePipeline; } + get { return _pulsePipeline; } } - private PipelineBase pulsePipeline; + private PipelineBase _pulsePipeline; #endregion running pipeline management #region session state proxy - + //Note: When SessionStateProxy calls are in progress, //pipeline cannot be invoked. Also when pipeline is in //progress, SessionStateProxy calls cannot be made. - bool _bSessionStateProxyCallInProgress; + private bool _bSessionStateProxyCallInProgress; /// /// This method ensures that SessionStateProxy call is allowed and if /// allowed it sets a variable to disallow further SessionStateProxy or /// pipeline calls. /// - void DoConcurrentCheckAndMarkSessionStateProxyCallInProgress() + private void DoConcurrentCheckAndMarkSessionStateProxyCallInProgress() { lock (_syncRoot) { @@ -1259,8 +1259,8 @@ namespace System.Management.Automation.Runspaces { // Detect if we're running an engine pulse, or we're running a nested pipeline // from an engine pulse - if (runningPipeline == pulsePipeline || - (runningPipeline.IsNested && pulsePipeline != null)) + if (runningPipeline == _pulsePipeline || + (runningPipeline.IsNested && _pulsePipeline != null)) { // If so, wait and try again // Release the lock before we wait for the pulse pipelines @@ -1662,7 +1662,7 @@ namespace System.Management.Automation.Runspaces /// protected abstract ProviderIntrinsics DoInvokeProvider { get; } - SessionStateProxy _sessionStateProxy; + private SessionStateProxy _sessionStateProxy; /// /// Returns SessionState proxy object. /// diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs index 44dbb1e5a..d2672445b 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Host; @@ -43,7 +44,7 @@ namespace System.Management.Automation.Runspaces { PSHost host = new DefaultHost(CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture); - return CreateRunspace( host ); + return CreateRunspace(host); } /// @@ -68,7 +69,7 @@ namespace System.Management.Automation.Runspaces return CreateRunspace(host, RunspaceConfiguration.Create()); } - + /// /// Creates a runspace using /// @@ -182,7 +183,7 @@ namespace System.Management.Automation.Runspaces /// /// Thrown when initialSessionState is null /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSessionState) { if (host == null) @@ -242,7 +243,7 @@ namespace System.Management.Automation.Runspaces /// public static RunspacePool CreateRunspacePool() { - return CreateRunspacePool(1, 1, + return CreateRunspacePool(1, 1, RunspaceConfiguration.Create(), new DefaultHost ( @@ -271,7 +272,7 @@ namespace System.Management.Automation.Runspaces /// public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces) { - return CreateRunspacePool(minRunspaces, maxRunspaces, + return CreateRunspacePool(minRunspaces, maxRunspaces, RunspaceConfiguration.Create(), new DefaultHost ( @@ -360,7 +361,7 @@ namespace System.Management.Automation.Runspaces /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// - private static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces, + private static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces, RunspaceConfiguration runspaceConfiguration, PSHost host) { return new RunspacePool(minRunspaces, @@ -571,8 +572,8 @@ namespace System.Management.Automation.Runspaces public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) { - if ((!(connectionInfo is WSManConnectionInfo)) && - (!(connectionInfo is NewProcessConnectionInfo)) && + if ((!(connectionInfo is WSManConnectionInfo)) && + (!(connectionInfo is NewProcessConnectionInfo)) && (!(connectionInfo is NamedPipeConnectionInfo)) && (!(connectionInfo is VMConnectionInfo)) && (!(connectionInfo is ContainerConnectionInfo))) @@ -584,7 +585,7 @@ namespace System.Management.Automation.Runspaces { RemotingCommandUtil.CheckHostRemotingPrerequisites(); } - + return new RunspacePool(minRunspaces, maxRunspaces, typeTable, host, applicationArguments, connectionInfo); } @@ -659,8 +660,8 @@ namespace System.Management.Automation.Runspaces /// public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments, string name) { - if ((!(connectionInfo is WSManConnectionInfo)) && - (!(connectionInfo is NewProcessConnectionInfo)) && + if ((!(connectionInfo is WSManConnectionInfo)) && + (!(connectionInfo is NewProcessConnectionInfo)) && (!(connectionInfo is NamedPipeConnectionInfo)) && (!(connectionInfo is VMConnectionInfo)) && (!(connectionInfo is ContainerConnectionInfo))) @@ -710,7 +711,7 @@ namespace System.Management.Automation.Runspaces { NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null); - return CreateRunspace(connectionInfo, null,typeTable); + return CreateRunspace(connectionInfo, null, typeTable); } /// @@ -721,13 +722,12 @@ namespace System.Management.Automation.Runspaces /// public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable, PowerShellProcessInstance processInstance) { - NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null) {Process = processInstance}; + NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null) { Process = processInstance }; return CreateRunspace(connectionInfo, null, typeTable); } #endregion V3 Extensions } - } diff --git a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs index 3685ccff1..3dd201630 100644 --- a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs @@ -13,7 +13,6 @@ using Dbg = System.Diagnostics; namespace Microsoft.PowerShell { - /// /// This is the default host implementing PSHost offering minimal host capabilities. /// Runspace is the primary user of this class. @@ -34,8 +33,8 @@ namespace Microsoft.PowerShell internal DefaultHost(CultureInfo currentCulture, CultureInfo currentUICulture) { - this.currentCulture = currentCulture; - this.currentUICulture = currentUICulture; + _currentCulture = currentCulture; + _currentUICulture = currentUICulture; } #endregion ctor @@ -74,7 +73,7 @@ namespace Microsoft.PowerShell { get { - return ver; + return _ver; } } @@ -92,11 +91,11 @@ namespace Microsoft.PowerShell { get { - return id; + return _id; } } - + /// /// /// See base class @@ -130,7 +129,7 @@ namespace Microsoft.PowerShell { get { - return currentCulture; + return _currentCulture; } } @@ -148,7 +147,7 @@ namespace Microsoft.PowerShell { get { - return currentUICulture; + return _currentUICulture; } } @@ -242,14 +241,12 @@ namespace Microsoft.PowerShell #region private fields - private CultureInfo currentCulture = null; - private CultureInfo currentUICulture = null; - private Guid id = Guid.NewGuid(); - private Version ver = PSVersionInfo.PSVersion; + private CultureInfo _currentCulture = null; + private CultureInfo _currentUICulture = null; + private Guid _id = Guid.NewGuid(); + private Version _ver = PSVersionInfo.PSVersion; #endregion private fields - } - } diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 2662b9edf..83f845547 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -30,7 +30,7 @@ namespace System.Management.Automation.Host /// but there is no established scenario for doing this, nor has it been tested. /// - public class + public class FieldDescription { /// @@ -49,7 +49,7 @@ namespace System.Management.Automation.Host /// /// - public + public FieldDescription(string name) { // the only required parameter is the name. @@ -59,7 +59,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("name", DescriptionsStrings.NullOrEmptyErrorTemplate, "name"); } - this.name = name; + _name = name; } /// @@ -79,7 +79,7 @@ namespace System.Management.Automation.Host { get { - return name; + return _name; } } @@ -136,25 +136,25 @@ namespace System.Management.Automation.Host /// /// - public - string + public + string ParameterTypeName { get { - if (String.IsNullOrEmpty(parameterTypeName)) + if (String.IsNullOrEmpty(_parameterTypeName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } - return parameterTypeName; + return _parameterTypeName; } } - + /// /// /// Gets the full string name of the parameter's type. @@ -169,20 +169,20 @@ namespace System.Management.Automation.Host /// /// - public + public string ParameterTypeFullName { get { - if (String.IsNullOrEmpty(parameterTypeFullName)) + if (String.IsNullOrEmpty(_parameterTypeFullName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } - return parameterTypeFullName; + return _parameterTypeFullName; } } @@ -202,25 +202,25 @@ namespace System.Management.Automation.Host /// /// - public - string + public + string ParameterAssemblyFullName { get { - if (String.IsNullOrEmpty(parameterAssemblyFullName)) + if (String.IsNullOrEmpty(_parameterAssemblyFullName)) { // the default if the type name is not specified is 'string' SetParameterType(typeof(string)); } - return parameterAssemblyFullName; + return _parameterAssemblyFullName; } } - - + + /// /// /// A short, human-presentable message to describe and identify the field. If supplied, a typical implementation of @@ -248,15 +248,15 @@ namespace System.Management.Automation.Host /// /// - public + public string Label { get { - Dbg.Assert(label != null, "label should not be null"); + Dbg.Assert(_label != null, "label should not be null"); - return label; + return _label; } set { @@ -265,12 +265,12 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentNullException("value"); } - label = value; + _label = value; } } - + /// /// /// Gets and sets the help message for this field. @@ -288,15 +288,15 @@ namespace System.Management.Automation.Host /// /// - public - string + public + string HelpMessage { get { - Dbg.Assert(helpMessage != null, "helpMessage should not be null"); + Dbg.Assert(_helpMessage != null, "helpMessage should not be null"); - return helpMessage; + return _helpMessage; } set { @@ -305,7 +305,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentNullException("value"); } - helpMessage = value; + _helpMessage = value; } } @@ -322,11 +322,11 @@ namespace System.Management.Automation.Host { get { - return isMandatory; + return _isMandatory; } set { - isMandatory = value; + _isMandatory = value; } } @@ -350,14 +350,14 @@ namespace System.Management.Automation.Host { get { - return defaultValue; + return _defaultValue; } set { // null is allowed. - defaultValue = value; + _defaultValue = value; } } @@ -377,11 +377,11 @@ namespace System.Management.Automation.Host { get { - if (metadata == null) + if (_metadata == null) { - metadata = new Collection (); + _metadata = new Collection(); } - return metadata; + return _metadata; } } @@ -408,7 +408,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("nameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "nameOfType"); } - parameterTypeName = nameOfType; + _parameterTypeName = nameOfType; } @@ -434,7 +434,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("fullNameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfType"); } - parameterTypeFullName = fullNameOfType; + _parameterTypeFullName = fullNameOfType; } @@ -460,7 +460,7 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("fullNameOfAssembly", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfAssembly"); } - parameterAssemblyFullName = fullNameOfAssembly; + _parameterAssemblyFullName = fullNameOfAssembly; } /// @@ -475,11 +475,11 @@ namespace System.Management.Automation.Host { get { - return modifiedByRemotingProtocol; + return _modifiedByRemotingProtocol; } set { - modifiedByRemotingProtocol = value; + _modifiedByRemotingProtocol = value; } } @@ -495,29 +495,29 @@ namespace System.Management.Automation.Host { get { - return isFromRemoteHost; + return _isFromRemoteHost; } set { - isFromRemoteHost = value; + _isFromRemoteHost = value; } } #region Helper #endregion Helper - - private readonly string name = null; - private string label = ""; - private string parameterTypeName = null; - private string parameterTypeFullName = null; - private string parameterAssemblyFullName = null; - private string helpMessage = ""; - private bool isMandatory = true; - private PSObject defaultValue = null; - private Collection metadata = new Collection(); - private bool modifiedByRemotingProtocol = false; - private bool isFromRemoteHost = false; + private readonly string _name = null; + private string _label = ""; + private string _parameterTypeName = null; + private string _parameterTypeFullName = null; + private string _parameterAssemblyFullName = null; + private string _helpMessage = ""; + private bool _isMandatory = true; + + private PSObject _defaultValue = null; + private Collection _metadata = new Collection(); + private bool _modifiedByRemotingProtocol = false; + private bool _isFromRemoteHost = false; } } diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 65caf987e..28471882d 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -56,7 +57,7 @@ namespace Microsoft.PowerShell.Commands _status = history._status; _startTime = history._startTime; _endTime = history._endTime; - _cleared = history._cleared ; + _cleared = history._cleared; } #endregion constructor @@ -158,7 +159,6 @@ namespace Microsoft.PowerShell.Commands set { _cleared = value; - } } @@ -240,7 +240,7 @@ namespace Microsoft.PowerShell.Commands /// Flag indicating an entry is present/cleared /// - private bool _cleared = false; + private bool _cleared = false; #endregion private @@ -275,7 +275,7 @@ namespace Microsoft.PowerShell.Commands /// /// Constructs history store /// - + internal History(ExecutionContext context) { //Create history size variable. Add ValidateRangeAttribute to @@ -376,8 +376,6 @@ namespace Microsoft.PowerShell.Commands return entry.Clone(); return null; - - } } @@ -463,7 +461,6 @@ namespace Microsoft.PowerShell.Commands } else { //get latest entries - // first id becomes the id +count no of entries from the end of the buffer firstId = baseId + count - 1; // if first id is more than the no of entries in the buffer, first id will be the last entry in the buffer @@ -514,10 +511,10 @@ namespace Microsoft.PowerShell.Commands if (_countEntriesAdded > _capacity) index = SmallestID; } - for (long i = count - 1; i >= 0; ) + for (long i = count - 1; i >= 0;) { if (index > _countEntriesAdded) break; - if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || + if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || (_buffer[GetIndexFromId(index)].Cleared == true)) { index++; continue; @@ -533,7 +530,7 @@ namespace Microsoft.PowerShell.Commands { index = _countEntriesAdded;//SmallestIDinBuffer - for (long i = count - 1; i >= 0; ) + for (long i = count - 1; i >= 0;) { // if an entry is cleared continue to the next entry if (_capacity != DefaultHistorySize) @@ -560,7 +557,6 @@ namespace Microsoft.PowerShell.Commands HistoryInfo[] entries = new HistoryInfo[entriesList.Count]; entriesList.CopyTo(entries); return entries; - }// end lock }// end function @@ -604,7 +600,7 @@ namespace Microsoft.PowerShell.Commands if (_countEntriesAdded > _capacity) id = SmallestID; } - for (long i = 0; i <= count - 1; ) + for (long i = 0; i <= count - 1;) { if (id > _countEntriesAdded) break; if (_buffer[GetIndexFromId(id)].Cleared == false && wildcardpattern.IsMatch(_buffer[GetIndexFromId(id)].CommandLine.Trim())) @@ -617,7 +613,7 @@ namespace Microsoft.PowerShell.Commands else { long id = _countEntriesAdded; - for (long i = 0; i <= count - 1; ) + for (long i = 0; i <= count - 1;) { //if buffersize is changed,we have to loop from max enttry to min entry thats not cleraed if (_capacity != DefaultHistorySize) @@ -646,13 +642,11 @@ namespace Microsoft.PowerShell.Commands cmdlist.Add(_buffer[GetIndexFromId(i)].Clone()); } } - } HistoryInfo[] entries = new HistoryInfo[cmdlist.Count]; cmdlist.CopyTo(entries); return entries; } - } @@ -689,7 +683,6 @@ namespace Microsoft.PowerShell.Commands } return; } - } @@ -865,7 +858,7 @@ namespace Microsoft.PowerShell.Commands _countEntriesInBuffer++; } - + /// /// Get the current history size /// @@ -920,7 +913,7 @@ namespace Microsoft.PowerShell.Commands /// Private object for synchronization /// private object _syncRoot = new object(); - + #endregion private /// @@ -966,7 +959,7 @@ namespace Microsoft.PowerShell.Commands /// /// Is Count parameter specified /// - bool _countParameterSpecified; + private bool _countParameterSpecified; /// /// Count of entries to display. By default, count is the length of the history buffer. /// So "Get-History" returns all history entries. @@ -1011,7 +1004,7 @@ namespace Microsoft.PowerShell.Commands HistoryInfo entry = history.GetEntry(id); - if (entry != null && entry.Id == id ) + if (entry != null && entry.Id == id) { WriteObject(entry); } @@ -1033,7 +1026,6 @@ namespace Microsoft.PowerShell.Commands id ) ); - } } } @@ -1061,7 +1053,7 @@ namespace Microsoft.PowerShell.Commands long id = _id[0]; Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); - WriteObject(history.GetEntries(id, _count,false ), true); + WriteObject(history.GetEntries(id, _count, false), true); } } else @@ -1071,9 +1063,9 @@ namespace Microsoft.PowerShell.Commands { _count = history.Buffercapacity(); } - HistoryInfo[] entries = history.GetEntries(0,_count,true); + HistoryInfo[] entries = history.GetEntries(0, _count, true); for (long i = entries.Length - 1; i >= 0; i--) - WriteObject(entries[i]); + WriteObject(entries[i]); } } } @@ -1090,7 +1082,7 @@ namespace Microsoft.PowerShell.Commands /// Invoke cmd can execute only one history entry. If multiple /// ids are provided, we throw error. /// - bool _multipleIdProvided; + private bool _multipleIdProvided; private string _id; /// /// Accepts a string value indicating a previously executed command to @@ -1212,12 +1204,12 @@ namespace Microsoft.PowerShell.Commands { ps.AddScript(commandToInvoke); - EventHandler debugAdded = delegate(Object sender, DataAddedEventArgs e) { DebugRecord record = (DebugRecord)((PSDataCollection)sender)[e.Index]; WriteDebug(record.Message); }; - EventHandler errorAdded = delegate(Object sender, DataAddedEventArgs e) { ErrorRecord record = (ErrorRecord)((PSDataCollection)sender)[e.Index]; WriteError(record); }; - EventHandler informationAdded = delegate(Object sender, DataAddedEventArgs e) { InformationRecord record = (InformationRecord)((PSDataCollection)sender)[e.Index]; WriteInformation(record); }; - EventHandler progressAdded = delegate(Object sender, DataAddedEventArgs e) { ProgressRecord record = (ProgressRecord)((PSDataCollection)sender)[e.Index]; WriteProgress(record); }; - EventHandler verboseAdded = delegate(Object sender, DataAddedEventArgs e) { VerboseRecord record = (VerboseRecord)((PSDataCollection)sender)[e.Index]; WriteVerbose(record.Message); }; - EventHandler warningAdded = delegate(Object sender, DataAddedEventArgs e) { WarningRecord record = (WarningRecord)((PSDataCollection)sender)[e.Index]; WriteWarning(record.Message); }; + EventHandler debugAdded = delegate (Object sender, DataAddedEventArgs e) { DebugRecord record = (DebugRecord)((PSDataCollection)sender)[e.Index]; WriteDebug(record.Message); }; + EventHandler errorAdded = delegate (Object sender, DataAddedEventArgs e) { ErrorRecord record = (ErrorRecord)((PSDataCollection)sender)[e.Index]; WriteError(record); }; + EventHandler informationAdded = delegate (Object sender, DataAddedEventArgs e) { InformationRecord record = (InformationRecord)((PSDataCollection)sender)[e.Index]; WriteInformation(record); }; + EventHandler progressAdded = delegate (Object sender, DataAddedEventArgs e) { ProgressRecord record = (ProgressRecord)((PSDataCollection)sender)[e.Index]; WriteProgress(record); }; + EventHandler verboseAdded = delegate (Object sender, DataAddedEventArgs e) { VerboseRecord record = (VerboseRecord)((PSDataCollection)sender)[e.Index]; WriteVerbose(record.Message); }; + EventHandler warningAdded = delegate (Object sender, DataAddedEventArgs e) { WarningRecord record = (WarningRecord)((PSDataCollection)sender)[e.Index]; WriteWarning(record.Message); }; ps.Streams.Debug.DataAdded += debugAdded; ps.Streams.Error.DataAdded += errorAdded; @@ -1233,8 +1225,8 @@ namespace Microsoft.PowerShell.Commands { WriteObject(results, true); } - pipeline.RemoveFromInvokeHistoryEntryList(entry); - } + pipeline.RemoveFromInvokeHistoryEntryList(entry); + } finally { ps.Streams.Debug.DataAdded -= debugAdded; @@ -1250,7 +1242,7 @@ namespace Microsoft.PowerShell.Commands /// /// Helper function which gets history entry to invoke /// - [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification="It's ok to use ID in the ArgumentException")] + [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "It's ok to use ID in the ArgumentException")] private HistoryInfo GetHistoryEntryToInvoke(History history) { HistoryInfo entry = null; @@ -1259,7 +1251,7 @@ namespace Microsoft.PowerShell.Commands //entry if (_id == null) { - HistoryInfo[] entries = history.GetEntries(0,1,true ); + HistoryInfo[] entries = history.GetEntries(0, 1, true); if (entries.Length == 1) { @@ -1283,7 +1275,6 @@ namespace Microsoft.PowerShell.Commands null ) ); - } } else @@ -1294,14 +1285,14 @@ namespace Microsoft.PowerShell.Commands //and find latest match if (_commandLine != null) { - HistoryInfo[] entries = history.GetEntries(0,-1,false ); + HistoryInfo[] entries = history.GetEntries(0, -1, false); // and search backwards through the entries for (int i = entries.Length - 1; i >= 0; i--) { if (entries[i].CommandLine.StartsWith(_commandLine, StringComparison.CurrentCulture)) { - entry = entries[i] ; + entry = entries[i]; break; } } @@ -1323,7 +1314,6 @@ namespace Microsoft.PowerShell.Commands _commandLine ) ); - } } else @@ -1347,13 +1337,12 @@ namespace Microsoft.PowerShell.Commands _historyId ) ); - } else { //Retrieve the command at the index we've specified entry = history.GetEntry(_historyId); - if (entry == null || entry.Id != _historyId ) + if (entry == null || entry.Id != _historyId) { Exception ex = new ArgumentException @@ -1371,7 +1360,6 @@ namespace Microsoft.PowerShell.Commands _historyId ) ); - } } } @@ -1393,7 +1381,7 @@ namespace Microsoft.PowerShell.Commands /// /// Parse Id parameter to populate _historyId and _commandLine /// - void PopulateIdAndCommandLine() + private void PopulateIdAndCommandLine() { if (_id == null) return; @@ -1663,7 +1651,6 @@ namespace Microsoft.PowerShell.Commands startExecutionTime, endExecutionTime ); - } while (false); //If we are here, an error has occured. @@ -1707,7 +1694,6 @@ namespace Microsoft.PowerShell.Commands [Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135199")] public class ClearHistoryCommand : PSCmdlet { - #region Command Line Parameters /// @@ -1753,7 +1739,6 @@ namespace Microsoft.PowerShell.Commands { _commandline = value; } - } /// @@ -1779,7 +1764,6 @@ namespace Microsoft.PowerShell.Commands _countParamterSpecified = true; _count = value; } - } /// @@ -1790,7 +1774,7 @@ namespace Microsoft.PowerShell.Commands /// /// a boolean variable to indicate if the count parameter specified /// - bool _countParamterSpecified = false; + private bool _countParamterSpecified = false; /// /// Specifies whether new entries to be cleared or the default old ones. @@ -1807,7 +1791,6 @@ namespace Microsoft.PowerShell.Commands { _newest = value; } - } /// @@ -1824,7 +1807,7 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { - history = ((LocalRunspace)Context.CurrentRunspace).History; + _history = ((LocalRunspace)Context.CurrentRunspace).History; } /// @@ -1865,7 +1848,7 @@ namespace Microsoft.PowerShell.Commands Exception ex = new ArgumentException ( - StringUtil.Format("HistoryStrings","InvalidCountValue") + StringUtil.Format("HistoryStrings", "InvalidCountValue") ); ThrowTerminatingError ( @@ -1888,10 +1871,10 @@ namespace Microsoft.PowerShell.Commands foreach (long id in _id) { Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); - HistoryInfo entry = history.GetEntry(id); - if (entry != null && entry.Id == id ) + HistoryInfo entry = _history.GetEntry(id); + if (entry != null && entry.Id == id) { - history.ClearEntry(entry.Id); + _history.ClearEntry(entry.Id); } else {// throw an exception if an entry for an id is not found @@ -1947,7 +1930,7 @@ namespace Microsoft.PowerShell.Commands if (_countParamterSpecified == false) { string message = StringUtil.Format(HistoryStrings.ClearHistoryWarning, "Warning");// "The command would clear all the entry(s) from the session history,Are you sure you want to continue ?"; - if (!ShouldProcess(message )) + if (!ShouldProcess(message)) { return; } @@ -1987,7 +1970,6 @@ namespace Microsoft.PowerShell.Commands _count ) ); - } // if command line is not present if (_commandline != null) @@ -1997,7 +1979,7 @@ namespace Microsoft.PowerShell.Commands { foreach (string cmd in _commandline) { - ClearHistoryEntries(0,1,cmd, _newest); + ClearHistoryEntries(0, 1, cmd, _newest); } } else if (_commandline.Length > 1) @@ -2021,10 +2003,9 @@ namespace Microsoft.PowerShell.Commands } else { // if commandline,count and newest parameters are present. - ClearHistoryEntries(0,_count,_commandline[0], _newest); + ClearHistoryEntries(0, _count, _commandline[0], _newest); } - } - + } } @@ -2037,7 +2018,7 @@ namespace Microsoft.PowerShell.Commands /// nothing /// - private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) + private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. if (cmdline == null) @@ -2045,8 +2026,8 @@ namespace Microsoft.PowerShell.Commands // if id is present,clears count entries from id if (id > 0) { - HistoryInfo entry = history.GetEntry(id); - if (entry == null || entry.Id != id ) + HistoryInfo entry = _history.GetEntry(id); + if (entry == null || entry.Id != id) { Exception ex = new ArgumentException @@ -2064,12 +2045,12 @@ namespace Microsoft.PowerShell.Commands ) ); } - entries = history.GetEntries(id, count, newest ); + _entries = _history.GetEntries(id, count, newest); } else {// if only count is present - entries = history.GetEntries(0, count, newest ); - } + _entries = _history.GetEntries(0, count, newest); + } } else { @@ -2078,18 +2059,18 @@ namespace Microsoft.PowerShell.Commands //count set to zero if not specified. if (!_countParamterSpecified && WildcardPattern.ContainsWildcardCharacters(cmdline)) { - count = 0; + count = 0; } // Return the matching history entries for the command line parameter // if newest id false...gets the oldest entry - entries = history.GetEntries(wildcardpattern, count, newest); + _entries = _history.GetEntries(wildcardpattern, count, newest); }// end case cmdline //Clear the History value. - foreach (HistoryInfo entry in entries) + foreach (HistoryInfo entry in _entries) { - if (entry != null && entry.Cleared == false) - history.ClearEntry(entry.Id); + if (entry != null && entry.Cleared == false) + _history.ClearEntry(entry.Id); } return; @@ -2099,12 +2080,12 @@ namespace Microsoft.PowerShell.Commands /// /// history obj /// - History history; + private History _history; /// /// array of historyinfo objects /// - HistoryInfo[] entries; + private HistoryInfo[] _entries; #endregion Private } diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 18d3a7a83..76f292241 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -35,10 +35,9 @@ namespace System.Management.Automation /// public static class HostUtilities { - #region Internal Access - private static string checkForCommandInCurrentDirectoryScript = @" + private static string s_checkForCommandInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] param() @@ -54,22 +53,22 @@ namespace System.Management.Automation $foundSuggestion "; - private static string createCommandExistsInCurrentDirectoryScript = @" + private static string s_createCommandExistsInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] param([string] $formatString) $formatString -f $lastError.TargetObject,"".\$($lastError.TargetObject)"" "; - private static ArrayList suggestions = new ArrayList( + private static ArrayList s_suggestions = new ArrayList( new Hashtable[] { NewSuggestion(1, "Transactions", SuggestionMatchType.Command, "^Start-Transaction", SuggestionStrings.Suggestion_StartTransaction, true), NewSuggestion(2, "Transactions", SuggestionMatchType.Command, "^Use-Transaction", SuggestionStrings.Suggestion_UseTransaction, true), NewSuggestion(3, "General", SuggestionMatchType.Dynamic, - ScriptBlock.CreateDelayParsedScriptBlock(checkForCommandInCurrentDirectoryScript, isProductCode: true), - ScriptBlock.CreateDelayParsedScriptBlock(createCommandExistsInCurrentDirectoryScript, isProductCode: true), + ScriptBlock.CreateDelayParsedScriptBlock(s_checkForCommandInCurrentDirectoryScript, isProductCode: true), + ScriptBlock.CreateDelayParsedScriptBlock(s_createCommandExistsInCurrentDirectoryScript, isProductCode: true), new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory) }, true) } @@ -226,7 +225,7 @@ namespace System.Management.Automation return folderPath; } -#endregion GetProfileCommands + #endregion GetProfileCommands /// /// Gets the first lines of . @@ -351,7 +350,7 @@ namespace System.Management.Automation int initialErrorCount = 0; // Go through all of the suggestions - foreach (Hashtable suggestion in suggestions) + foreach (Hashtable suggestion in s_suggestions) { initialErrorCount = errorList.Count; @@ -728,7 +727,7 @@ namespace System.Management.Automation int ulUserNameMaxChars, StringBuilder pszPassword, int ulPasswordMaxChars, ref int pfSave, CREDUI_FLAGS dwFlags); [Flags] - enum CREDUI_FLAGS + private enum CREDUI_FLAGS { INCORRECT_PASSWORD = 0x1, DO_NOT_PERSIST = 0x2, @@ -749,7 +748,7 @@ namespace System.Management.Automation KEEP_USERNAME = 0x100000, } - struct CREDUI_INFO + private struct CREDUI_INFO { public int cbSize; public IntPtr hwndParent; @@ -760,7 +759,7 @@ namespace System.Management.Automation public IntPtr hbmBanner; } - enum CredUIReturnCodes + private enum CredUIReturnCodes { NO_ERROR = 0, ERROR_CANCELLED = 1223, @@ -778,7 +777,7 @@ namespace System.Management.Automation internal static string GetRemotePrompt(RemoteRunspace runspace, string basePrompt, bool configuredSession = false) { if (configuredSession || - runspace.ConnectionInfo is NamedPipeConnectionInfo || + runspace.ConnectionInfo is NamedPipeConnectionInfo || runspace.ConnectionInfo is VMConnectionInfo || runspace.ConnectionInfo is ContainerConnectionInfo) { @@ -862,11 +861,11 @@ namespace System.Management.Automation return remoteRunspace; } -#endregion + #endregion -#region Public Access + #region Public Access -#region PSEdit Support + #region PSEdit Support /// /// PSEditFunction script string. @@ -933,10 +932,10 @@ namespace System.Management.Automation /// public const string RemoteSessionOpenFileEvent = "PSISERemoteSessionOpenFile"; -#endregion + #endregion -#endregion + #endregion } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index 6e70e7ec0..c1109b45e 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -23,10 +23,10 @@ namespace System.Management.Automation /// internal InformationalRecord(string message) { - this.message = message; - this.invocationInfo = null; - this.pipelineIterationInfo = null; - this.serializeExtendedInfo = false; + _message = message; + _invocationInfo = null; + _pipelineIterationInfo = null; + _serializeExtendedInfo = false; } /// @@ -34,20 +34,20 @@ namespace System.Management.Automation /// internal InformationalRecord(PSObject serializedObject) { - this.message = (string) SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_Message"); - this.serializeExtendedInfo = (bool)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_SerializeInvocationInfo"); + _message = (string)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_Message"); + _serializeExtendedInfo = (bool)SerializationUtilities.GetPropertyValue(serializedObject, "InformationalRecord_SerializeInvocationInfo"); - if (this.serializeExtendedInfo) + if (_serializeExtendedInfo) { - this.invocationInfo = new InvocationInfo(serializedObject); + _invocationInfo = new InvocationInfo(serializedObject); - ArrayList pipelineIterationInfo= (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(serializedObject, "InformationalRecord_PipelineIterationInfo"); + ArrayList pipelineIterationInfo = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(serializedObject, "InformationalRecord_PipelineIterationInfo"); - this.pipelineIterationInfo = new ReadOnlyCollection((int[])pipelineIterationInfo.ToArray(typeof(int))); + _pipelineIterationInfo = new ReadOnlyCollection((int[])pipelineIterationInfo.ToArray(typeof(int))); } else { - this.invocationInfo = null; + _invocationInfo = null; } } @@ -58,9 +58,9 @@ namespace System.Management.Automation { get { - return this.message; + return _message; } - set { message = value;} + set { _message = value; } } /// @@ -73,7 +73,7 @@ namespace System.Management.Automation { get { - return this.invocationInfo; + return _invocationInfo; } } @@ -87,7 +87,7 @@ namespace System.Management.Automation { get { - return this.pipelineIterationInfo; + return _pipelineIterationInfo; } } @@ -96,7 +96,7 @@ namespace System.Management.Automation /// internal void SetInvocationInfo(InvocationInfo invocationInfo) { - this.invocationInfo = invocationInfo; + _invocationInfo = invocationInfo; // // Copy a snapshot of the PipelineIterationInfo from the InvocationInfo to this InformationalRecord @@ -105,7 +105,7 @@ namespace System.Management.Automation { int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone(); - this.pipelineIterationInfo = new ReadOnlyCollection(snapshot); + _pipelineIterationInfo = new ReadOnlyCollection(snapshot); } } @@ -116,11 +116,11 @@ namespace System.Management.Automation { get { - return this.serializeExtendedInfo; + return _serializeExtendedInfo; } set { - this.serializeExtendedInfo = value; + _serializeExtendedInfo = value; } } @@ -144,23 +144,23 @@ namespace System.Management.Automation // The invocation info may be null if the record was created via WriteVerbose/Warning/DebugLine instead of WriteVerbose/Warning/Debug, in that case // we set InformationalRecord_SerializeInvocationInfo to false. // - if (!this.SerializeExtendedInfo || this.invocationInfo == null) + if (!this.SerializeExtendedInfo || _invocationInfo == null) { RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => false); } else { RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => true); - this.invocationInfo.ToPSObjectForRemoting(psObject); + _invocationInfo.ToPSObjectForRemoting(psObject); RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_PipelineIterationInfo", () => this.PipelineIterationInfo); } } [DataMember()] - private string message; - private InvocationInfo invocationInfo; - private ReadOnlyCollection pipelineIterationInfo; - private bool serializeExtendedInfo; + private string _message; + private InvocationInfo _invocationInfo; + private ReadOnlyCollection _pipelineIterationInfo; + private bool _serializeExtendedInfo; } /// diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index 055da4d4c..41ca03b21 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -48,14 +48,14 @@ namespace System.Management.Automation.Internal.Host Dbg.Assert(executionContext != null, "must supply an ExecutionContext"); - this.externalHostRef = new ObjectRef(externalHost); - this.executionContext = executionContext; + _externalHostRef = new ObjectRef(externalHost); + _executionContext = executionContext; PSHostUserInterface ui = externalHost.UI; - this.internalUIRef = new ObjectRef(new InternalHostUserInterface(ui, this)); - zeroGuid = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - idResult = zeroGuid; + _internalUIRef = new ObjectRef(new InternalHostUserInterface(ui, this)); + _zeroGuid = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + _idResult = _zeroGuid; } /// @@ -73,19 +73,19 @@ namespace System.Management.Automation.Internal.Host { get { - if (String.IsNullOrEmpty(nameResult)) + if (String.IsNullOrEmpty(_nameResult)) { - nameResult = externalHostRef.Value.Name; + _nameResult = _externalHostRef.Value.Name; #pragma warning disable 56503 - if (String.IsNullOrEmpty(nameResult)) + if (String.IsNullOrEmpty(_nameResult)) { throw PSTraceSource.NewNotImplementedException(); } #pragma warning restore 56503 } - return nameResult; + return _nameResult; } } @@ -104,19 +104,19 @@ namespace System.Management.Automation.Internal.Host { get { - if (versionResult == null) + if (_versionResult == null) { - versionResult = externalHostRef.Value.Version; + _versionResult = _externalHostRef.Value.Version; #pragma warning disable 56503 - if (versionResult == null) + if (_versionResult == null) { throw PSTraceSource.NewNotImplementedException(); } #pragma warning restore 56503 } - return versionResult; + return _versionResult; } } @@ -135,18 +135,18 @@ namespace System.Management.Automation.Internal.Host { get { - if (idResult == zeroGuid) + if (_idResult == _zeroGuid) { - idResult = externalHostRef.Value.InstanceId; + _idResult = _externalHostRef.Value.InstanceId; #pragma warning disable 56503 - if (idResult == zeroGuid) + if (_idResult == _zeroGuid) { throw PSTraceSource.NewNotImplementedException(); } #pragma warning restore 56503 } - return idResult; + return _idResult; } } @@ -161,7 +161,7 @@ namespace System.Management.Automation.Internal.Host { get { - return internalUIRef.Value; + return _internalUIRef.Value; } } @@ -175,7 +175,7 @@ namespace System.Management.Automation.Internal.Host { get { - return internalUIRef.Value; + return _internalUIRef.Value; } } @@ -195,7 +195,7 @@ namespace System.Management.Automation.Internal.Host { get { - CultureInfo ci = externalHostRef.Value.CurrentCulture; + CultureInfo ci = _externalHostRef.Value.CurrentCulture; if (ci == null) { @@ -223,9 +223,9 @@ namespace System.Management.Automation.Internal.Host get { #if CORECLR // No CultureInfo.InstalledUICulture In CoreCLR. Locale cannot be changed On CSS. - CultureInfo ci = externalHostRef.Value.CurrentUICulture ?? CultureInfo.CurrentUICulture; + CultureInfo ci = _externalHostRef.Value.CurrentUICulture ?? CultureInfo.CurrentUICulture; #else - CultureInfo ci = externalHostRef.Value.CurrentUICulture ?? CultureInfo.InstalledUICulture; + CultureInfo ci = _externalHostRef.Value.CurrentUICulture ?? CultureInfo.InstalledUICulture; #endif return ci; } @@ -239,7 +239,7 @@ namespace System.Management.Automation.Internal.Host /// public override void SetShouldExit(int exitCode) { - externalHostRef.Value.SetShouldExit(exitCode); + _externalHostRef.Value.SetShouldExit(exitCode); } /// @@ -291,7 +291,7 @@ namespace System.Management.Automation.Internal.Host // should include setting a bit that indicates that the initialization is complete, and code should be // added here to throw an exception if this function is called before that bit is set. - if (nestedPromptCount < 0) + if (_nestedPromptCount < 0) { Dbg.Assert(false, "nested prompt counter should never be negative."); throw PSTraceSource.NewInvalidOperationException( @@ -302,17 +302,17 @@ namespace System.Management.Automation.Internal.Host // of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or // 2) is a squatter, and we have claim to clobber it. - ++nestedPromptCount; - executionContext.SetVariable(SpecialVariables.NestedPromptCounterVarPath, nestedPromptCount); + ++_nestedPromptCount; + _executionContext.SetVariable(SpecialVariables.NestedPromptCounterVarPath, _nestedPromptCount); // On entering a subshell, save and reset values of certain bits of session state PromptContextData contextData = new PromptContextData(); - contextData.SavedContextData = executionContext.SaveContextData(); - contextData.SavedCurrentlyExecutingCommandVarValue = executionContext.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath); - contextData.SavedPSBoundParametersVarValue = executionContext.GetVariableValue(SpecialVariables.PSBoundParametersVarPath); + contextData.SavedContextData = _executionContext.SaveContextData(); + contextData.SavedCurrentlyExecutingCommandVarValue = _executionContext.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath); + contextData.SavedPSBoundParametersVarValue = _executionContext.GetVariableValue(SpecialVariables.PSBoundParametersVarPath); contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; - contextData.LanguageMode = executionContext.LanguageMode; + contextData.LanguageMode = _executionContext.LanguageMode; PSPropertyInfo commandInfoProperty = null; PSPropertyInfo stackTraceProperty = null; @@ -320,7 +320,7 @@ namespace System.Management.Automation.Internal.Host object oldStackTrace = null; if (callingCommand != null) { - Dbg.Assert(callingCommand.Context == executionContext, "I expect that the contexts should match"); + Dbg.Assert(callingCommand.Context == _executionContext, "I expect that the contexts should match"); // Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want // to expose more and more debug info. We could just populate more and more local variables but that is probably @@ -353,27 +353,27 @@ namespace System.Management.Automation.Internal.Host } #endif - executionContext.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); + _executionContext.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); } - contextStack.Push(contextData); - Dbg.Assert(contextStack.Count == nestedPromptCount, "number of saved contexts should equal nesting count"); + _contextStack.Push(contextData); + Dbg.Assert(_contextStack.Count == _nestedPromptCount, "number of saved contexts should equal nesting count"); - executionContext.PSDebugTraceStep = false; - executionContext.PSDebugTraceLevel = 0; - executionContext.ResetShellFunctionErrorOutputPipe(); + _executionContext.PSDebugTraceStep = false; + _executionContext.PSDebugTraceLevel = 0; + _executionContext.ResetShellFunctionErrorOutputPipe(); // Lock down the language in the nested prompt - if (executionContext.HasRunspaceEverUsedConstrainedLanguageMode) + if (_executionContext.HasRunspaceEverUsedConstrainedLanguageMode) { - executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; + _executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { - externalHostRef.Value.EnterNestedPrompt(); + _externalHostRef.Value.EnterNestedPrompt(); } catch { @@ -398,30 +398,30 @@ namespace System.Management.Automation.Internal.Host } } - Dbg.Assert(nestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); + Dbg.Assert(_nestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); } private void ExitNestedPromptHelper() { - --nestedPromptCount; - executionContext.SetVariable(SpecialVariables.NestedPromptCounterVarPath, nestedPromptCount); + --_nestedPromptCount; + _executionContext.SetVariable(SpecialVariables.NestedPromptCounterVarPath, _nestedPromptCount); // restore the saved context - Dbg.Assert(contextStack.Count > 0, "ExitNestedPrompt: called without any saved context"); + Dbg.Assert(_contextStack.Count > 0, "ExitNestedPrompt: called without any saved context"); - if (contextStack.Count > 0) + if (_contextStack.Count > 0) { - PromptContextData pcd = contextStack.Pop(); + PromptContextData pcd = _contextStack.Pop(); - pcd.SavedContextData.RestoreContextData(executionContext); - executionContext.LanguageMode = pcd.LanguageMode; - executionContext.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, pcd.SavedCurrentlyExecutingCommandVarValue); - executionContext.SetVariable(SpecialVariables.PSBoundParametersVarPath, pcd.SavedPSBoundParametersVarValue); + pcd.SavedContextData.RestoreContextData(_executionContext); + _executionContext.LanguageMode = pcd.LanguageMode; + _executionContext.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, pcd.SavedCurrentlyExecutingCommandVarValue); + _executionContext.SetVariable(SpecialVariables.PSBoundParametersVarPath, pcd.SavedPSBoundParametersVarValue); this.Context.CurrentRunspace.UpdateRunspaceAvailability(pcd.RunspaceAvailability, true); } - Dbg.Assert(contextStack.Count == nestedPromptCount, "number of saved contexts should equal nesting count"); + Dbg.Assert(_contextStack.Count == _nestedPromptCount, "number of saved contexts should equal nesting count"); } /// @@ -432,14 +432,14 @@ namespace System.Management.Automation.Internal.Host /// public override void ExitNestedPrompt() { - Dbg.Assert(nestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); + Dbg.Assert(_nestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); - if (nestedPromptCount == 0) + if (_nestedPromptCount == 0) return; try { - externalHostRef.Value.ExitNestedPrompt(); + _externalHostRef.Value.ExitNestedPrompt(); } finally { @@ -458,7 +458,7 @@ namespace System.Management.Automation.Internal.Host { get { - PSObject result = externalHostRef.Value.PrivateData; + PSObject result = _externalHostRef.Value.PrivateData; return result; } } @@ -471,7 +471,7 @@ namespace System.Management.Automation.Internal.Host /// public override void NotifyBeginApplication() { - externalHostRef.Value.NotifyBeginApplication(); + _externalHostRef.Value.NotifyBeginApplication(); } /// @@ -482,7 +482,7 @@ namespace System.Management.Automation.Internal.Host /// public override void NotifyEndApplication() { - externalHostRef.Value.NotifyEndApplication(); + _externalHostRef.Value.NotifyEndApplication(); } /// @@ -490,8 +490,8 @@ namespace System.Management.Automation.Internal.Host /// public override bool DebuggerEnabled { - get { return this.isDebuggingEnabled; } - set { this.isDebuggingEnabled = value; } + get { return _isDebuggingEnabled; } + set { _isDebuggingEnabled = value; } } /// @@ -500,7 +500,7 @@ namespace System.Management.Automation.Internal.Host /// private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession() { - IHostSupportsInteractiveSession host = this.externalHostRef.Value as IHostSupportsInteractiveSession; + IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession; if (host == null) { throw new PSNotImplementedException(); @@ -559,7 +559,7 @@ namespace System.Management.Automation.Internal.Host /// false, otherwise internal bool HostInNestedPrompt() { - if (nestedPromptCount > 0) + if (_nestedPromptCount > 0) { return true; } @@ -578,8 +578,8 @@ namespace System.Management.Automation.Internal.Host /// and internal void SetHostRef(PSHost psHost) { - this.externalHostRef.Override(psHost); - this.internalUIRef.Override(new InternalHostUserInterface(psHost.UI, this)); + _externalHostRef.Override(psHost); + _internalUIRef.Override(new InternalHostUserInterface(psHost.UI, this)); } /// @@ -590,8 +590,8 @@ namespace System.Management.Automation.Internal.Host { // nothing to revert if Host reference is not set. if (!IsHostRefSet) { return; } - this.externalHostRef.Revert(); - this.internalUIRef.Revert(); + _externalHostRef.Revert(); + _internalUIRef.Revert(); } /// @@ -599,7 +599,7 @@ namespace System.Management.Automation.Internal.Host /// internal bool IsHostRefSet { - get { return this.externalHostRef.IsOverridden; } + get { return _externalHostRef.IsOverridden; } } @@ -607,7 +607,7 @@ namespace System.Management.Automation.Internal.Host { get { - return executionContext; + return _executionContext; } } @@ -615,29 +615,28 @@ namespace System.Management.Automation.Internal.Host { get { - return externalHostRef.Value; + return _externalHostRef.Value; } } internal int NestedPromptCount { - get { return nestedPromptCount; } + get { return _nestedPromptCount; } } // Masked variables. - private ObjectRef externalHostRef; - private ObjectRef internalUIRef; + private ObjectRef _externalHostRef; + private ObjectRef _internalUIRef; // Private variables. - private ExecutionContext executionContext; - private string nameResult; - private Version versionResult; - private Guid idResult; - private int nestedPromptCount; - private Stack contextStack = new Stack(); - private bool isDebuggingEnabled = true; + private ExecutionContext _executionContext; + private string _nameResult; + private Version _versionResult; + private Guid _idResult; + private int _nestedPromptCount; + private Stack _contextStack = new Stack(); + private bool _isDebuggingEnabled = true; - private readonly Guid zeroGuid; + private readonly Guid _zeroGuid; } - } // namespace diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index e447c011e..d30b12b4c 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -21,8 +21,8 @@ namespace System.Management.Automation.Internal.Host InternalHostRawUserInterface(PSHostRawUserInterface externalRawUI, InternalHost parentHost) { // externalRawUI may be null - this.externalRawUI = externalRawUI; - this.parentHost = parentHost; + _externalRawUI = externalRawUI; + _parentHost = parentHost; } @@ -44,7 +44,7 @@ namespace System.Management.Automation.Internal.Host } - + /// /// /// See base class @@ -61,23 +61,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - ConsoleColor result = externalRawUI.ForegroundColor; + ConsoleColor result = _externalRawUI.ForegroundColor; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.ForegroundColor = value; + _externalRawUI.ForegroundColor = value; } } @@ -100,23 +100,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - ConsoleColor result = externalRawUI.BackgroundColor; + ConsoleColor result = _externalRawUI.BackgroundColor; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.BackgroundColor = value; + _externalRawUI.BackgroundColor = value; } } @@ -139,23 +139,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Coordinates result = externalRawUI.CursorPosition; + Coordinates result = _externalRawUI.CursorPosition; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.CursorPosition = value; + _externalRawUI.CursorPosition = value; } } @@ -178,23 +178,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Coordinates result = externalRawUI.WindowPosition; + Coordinates result = _externalRawUI.WindowPosition; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.WindowPosition = value; + _externalRawUI.WindowPosition = value; } } @@ -217,23 +217,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - int result = externalRawUI.CursorSize; + int result = _externalRawUI.CursorSize; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.CursorSize = value; + _externalRawUI.CursorSize = value; } } @@ -256,23 +256,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Size result = externalRawUI.BufferSize; + Size result = _externalRawUI.BufferSize; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.BufferSize = value; + _externalRawUI.BufferSize = value; } } @@ -295,23 +295,23 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Size result = externalRawUI.WindowSize; + Size result = _externalRawUI.WindowSize; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.WindowSize = value; + _externalRawUI.WindowSize = value; } } @@ -334,12 +334,12 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Size result = externalRawUI.MaxWindowSize; + Size result = _externalRawUI.MaxWindowSize; return result; } @@ -364,12 +364,12 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - Size result = externalRawUI.MaxPhysicalWindowSize; + Size result = _externalRawUI.MaxPhysicalWindowSize; return result; } @@ -394,20 +394,20 @@ namespace System.Management.Automation.Internal.Host KeyInfo ReadKey(ReadKeyOptions options) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } KeyInfo result = new KeyInfo(); try { - result = externalRawUI.ReadKey(options); + result = _externalRawUI.ReadKey(options); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)this.parentHost.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parentHost.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -434,12 +434,12 @@ namespace System.Management.Automation.Internal.Host void FlushInputBuffer() { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.FlushInputBuffer(); + _externalRawUI.FlushInputBuffer(); } @@ -461,12 +461,12 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - bool result = externalRawUI.KeyAvailable; + bool result = _externalRawUI.KeyAvailable; return result; } @@ -491,28 +491,28 @@ namespace System.Management.Automation.Internal.Host { get { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - string result = externalRawUI.WindowTitle; + string result = _externalRawUI.WindowTitle; return result; } set { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.WindowTitle = value; + _externalRawUI.WindowTitle = value; } } - + /// /// /// See base class @@ -528,12 +528,12 @@ namespace System.Management.Automation.Internal.Host void SetBufferContents(Coordinates origin, BufferCell[,] contents) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.SetBufferContents(origin, contents); + _externalRawUI.SetBufferContents(origin, contents); } @@ -558,12 +558,12 @@ namespace System.Management.Automation.Internal.Host void SetBufferContents(Rectangle r, BufferCell fill) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.SetBufferContents(r, fill); + _externalRawUI.SetBufferContents(r, fill); } @@ -584,14 +584,14 @@ namespace System.Management.Automation.Internal.Host BufferCell[,] GetBufferContents(Rectangle r) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - return externalRawUI.GetBufferContents(r); + return _externalRawUI.GetBufferContents(r); } - + /// @@ -616,18 +616,18 @@ namespace System.Management.Automation.Internal.Host void ScrollBufferContents ( - Rectangle source, + Rectangle source, Coordinates destination, - Rectangle clip, + Rectangle clip, BufferCell fill ) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - externalRawUI.ScrollBufferContents(source, destination, clip, fill); + _externalRawUI.ScrollBufferContents(source, destination, clip, fill); } /// @@ -641,11 +641,11 @@ namespace System.Management.Automation.Internal.Host /// public override int LengthInBufferCells(string str) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - return externalRawUI.LengthInBufferCells(str); + return _externalRawUI.LengthInBufferCells(str); } /// @@ -663,11 +663,11 @@ namespace System.Management.Automation.Internal.Host Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - return externalRawUI.LengthInBufferCells(str, offset); + return _externalRawUI.LengthInBufferCells(str, offset); } @@ -684,15 +684,14 @@ namespace System.Management.Automation.Internal.Host int LengthInBufferCells(char character) { - if (externalRawUI == null) + if (_externalRawUI == null) { ThrowNotInteractive(); } - return externalRawUI.LengthInBufferCells(character); + return _externalRawUI.LengthInBufferCells(character); } - private PSHostRawUserInterface externalRawUI; - private InternalHost parentHost; + private PSHostRawUserInterface _externalRawUI; + private InternalHost _parentHost; } - } // namespace diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index b2426744b..9eed54fb8 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -23,7 +23,7 @@ namespace System.Management.Automation.Internal.Host { // externalUI may be null - this.externalUI = externalUI; + _externalUI = externalUI; // parent may not be null, however @@ -32,7 +32,7 @@ namespace System.Management.Automation.Internal.Host { throw PSTraceSource.NewArgumentNullException("parentHost"); } - parent = parentHost; + _parent = parentHost; PSHostRawUserInterface rawui = null; @@ -41,14 +41,14 @@ namespace System.Management.Automation.Internal.Host rawui = externalUI.RawUI; } - internalRawUI = new InternalHostRawUserInterface(rawui, parent); + _internalRawUI = new InternalHostRawUserInterface(rawui, _parent); } private void ThrowNotInteractive() { - internalRawUI.ThrowNotInteractive(); + _internalRawUI.ThrowNotInteractive(); } private @@ -78,13 +78,13 @@ namespace System.Management.Automation.Internal.Host { get { - return internalRawUI; + return _internalRawUI; } } public override bool SupportsVirtualTerminal { - get { return externalUI.SupportsVirtualTerminal; } + get { return _externalUI.SupportsVirtualTerminal; } } /// @@ -102,7 +102,7 @@ namespace System.Management.Automation.Internal.Host string ReadLine() { - if (externalUI == null) + if (_externalUI == null) { ThrowNotInteractive(); } @@ -110,13 +110,13 @@ namespace System.Management.Automation.Internal.Host string result = null; try { - result = externalUI.ReadLine(); + result = _externalUI.ReadLine(); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -141,26 +141,26 @@ namespace System.Management.Automation.Internal.Host /// /// - public override - SecureString + public override + SecureString ReadLineAsSecureString() { - if (externalUI == null) + if (_externalUI == null) { ThrowNotInteractive(); } SecureString result = null; - + try { - result = externalUI.ReadLineAsSecureString(); + result = _externalUI.ReadLineAsSecureString(); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -196,12 +196,12 @@ namespace System.Management.Automation.Internal.Host return; } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.Write(value); + _externalUI.Write(value); } @@ -233,12 +233,12 @@ namespace System.Management.Automation.Internal.Host return; } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.Write(foregroundColor, backgroundColor, value); + _externalUI.Write(foregroundColor, backgroundColor, value); } @@ -261,12 +261,12 @@ namespace System.Management.Automation.Internal.Host void WriteLine() { - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteLine(); + _externalUI.WriteLine(); } @@ -294,12 +294,12 @@ namespace System.Management.Automation.Internal.Host return; } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteLine(value); + _externalUI.WriteLine(value); } @@ -313,16 +313,16 @@ namespace System.Management.Automation.Internal.Host return; } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteErrorLine(value); + _externalUI.WriteErrorLine(value); } - - + + /// /// /// See base class @@ -350,12 +350,12 @@ namespace System.Management.Automation.Internal.Host return; } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteLine(foregroundColor, backgroundColor, value); + _externalUI.WriteLine(foregroundColor, backgroundColor, value); } @@ -386,12 +386,12 @@ namespace System.Management.Automation.Internal.Host { WriteDebugInfoBuffers(record); - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteDebugLine(record.Message); + _externalUI.WriteDebugLine(record.Message); } /// @@ -400,9 +400,9 @@ namespace System.Management.Automation.Internal.Host /// DebugRecord internal void WriteDebugInfoBuffers(DebugRecord record) { - if (informationalBuffers != null) + if (_informationalBuffers != null) { - informationalBuffers.AddDebug(record); + _informationalBuffers.AddDebug(record); } } @@ -490,7 +490,7 @@ namespace System.Management.Automation.Internal.Host /// internal void SetInformationalMessageBuffers(PSInformationalBuffers informationalBuffers) { - this.informationalBuffers = informationalBuffers; + _informationalBuffers = informationalBuffers; } /// @@ -499,11 +499,11 @@ namespace System.Management.Automation.Internal.Host /// informational message buffers internal PSInformationalBuffers GetInformationalMessageBuffers() { - return informationalBuffers; + return _informationalBuffers; } - private - void + private + void WriteDebugLineHelper(string message) { if (message == null) @@ -557,9 +557,9 @@ namespace System.Management.Automation.Internal.Host switch ( PromptForChoice( - InternalHostUserInterfaceStrings.ShouldContinuePromptMessage, - message, - choices, + InternalHostUserInterfaceStrings.ShouldContinuePromptMessage, + message, + choices, 0)) { case 0: @@ -587,12 +587,12 @@ namespace System.Management.Automation.Internal.Host case 4: // This call returns when the user exits the nested prompt. - parent.EnterNestedPrompt(); + _parent.EnterNestedPrompt(); endLoop = false; break; }//switch } while (endLoop != true); - + return shouldContinue; } @@ -620,17 +620,17 @@ namespace System.Management.Automation.Internal.Host } // Write to Information Buffers - if (null != informationalBuffers) + if (null != _informationalBuffers) { - informationalBuffers.AddProgress(record); + _informationalBuffers.AddProgress(record); } - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteProgress(sourceId, record); + _externalUI.WriteProgress(sourceId, record); } @@ -666,12 +666,12 @@ namespace System.Management.Automation.Internal.Host { WriteVerboseInfoBuffers(record); - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteVerboseLine(record.Message); + _externalUI.WriteVerboseLine(record.Message); } /// @@ -680,9 +680,9 @@ namespace System.Management.Automation.Internal.Host /// VerboseRecord internal void WriteVerboseInfoBuffers(VerboseRecord record) { - if (informationalBuffers != null) + if (_informationalBuffers != null) { - informationalBuffers.AddVerbose(record); + _informationalBuffers.AddVerbose(record); } } @@ -715,12 +715,12 @@ namespace System.Management.Automation.Internal.Host { WriteWarningInfoBuffers(record); - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteWarningLine(record.Message); + _externalUI.WriteWarningLine(record.Message); } /// @@ -729,9 +729,9 @@ namespace System.Management.Automation.Internal.Host /// WarningRecord internal void WriteWarningInfoBuffers(WarningRecord record) { - if (informationalBuffers != null) + if (_informationalBuffers != null) { - informationalBuffers.AddWarning(record); + _informationalBuffers.AddWarning(record); } } @@ -742,12 +742,12 @@ namespace System.Management.Automation.Internal.Host { WriteInformationInfoBuffers(record); - if (externalUI == null) + if (_externalUI == null) { return; } - externalUI.WriteInformation(record); + _externalUI.WriteInformation(record); } /// @@ -756,9 +756,9 @@ namespace System.Management.Automation.Internal.Host /// WarningRecord internal void WriteInformationInfoBuffers(InformationRecord record) { - if (informationalBuffers != null) + if (_informationalBuffers != null) { - informationalBuffers.AddInformation(record); + _informationalBuffers.AddInformation(record); } } @@ -818,7 +818,7 @@ namespace System.Management.Automation.Internal.Host /// public override - Dictionary + Dictionary Prompt(string caption, string message, Collection descriptions) { if (descriptions == null) @@ -831,22 +831,22 @@ namespace System.Management.Automation.Internal.Host throw PSTraceSource.NewArgumentException("descriptions", InternalHostUserInterfaceStrings.PromptEmptyDescriptionsError, "descriptions"); } - if (externalUI == null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } - Dictionary result = null; + Dictionary result = null; try { - result = externalUI.Prompt(caption, message, descriptions); + result = _externalUI.Prompt(caption, message, descriptions); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline) ((RunspaceBase) this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -881,7 +881,7 @@ namespace System.Management.Automation.Internal.Host int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) { - if (externalUI == null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -889,13 +889,13 @@ namespace System.Management.Automation.Internal.Host int result = -1; try { - result = externalUI.PromptForChoice(caption, message, choices, defaultChoice); + result = _externalUI.PromptForChoice(caption, message, choices, defaultChoice); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline) ((RunspaceBase) this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -931,13 +931,13 @@ namespace System.Management.Automation.Internal.Host Collection choices, IEnumerable defaultChoices) { - if (externalUI == null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } IHostUISupportsMultipleChoiceSelection hostForMultipleChoices = - externalUI as IHostUISupportsMultipleChoiceSelection; + _externalUI as IHostUISupportsMultipleChoiceSelection; Collection result = null; try @@ -959,7 +959,7 @@ namespace System.Management.Automation.Internal.Host { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline)((RunspaceBase)this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -989,7 +989,7 @@ namespace System.Management.Automation.Internal.Host Collection choices, IEnumerable defaultChoices) { - Dbg.Assert(null != externalUI, "externalUI cannot be null."); + Dbg.Assert(null != _externalUI, "externalUI cannot be null."); if (choices == null) { @@ -1094,8 +1094,8 @@ namespace System.Management.Automation.Internal.Host { string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected); messageToBeDisplayed += choiceMsg; - externalUI.WriteLine(messageToBeDisplayed); - string response = externalUI.ReadLine(); + _externalUI.WriteLine(messageToBeDisplayed); + string response = _externalUI.ReadLine(); // they just hit enter if (response.Length == 0) @@ -1131,11 +1131,10 @@ namespace System.Management.Automation.Internal.Host return result; } - private PSHostUserInterface externalUI = null; - private InternalHostRawUserInterface internalRawUI = null; - private InternalHost parent = null; - private PSInformationalBuffers informationalBuffers = null; + private PSHostUserInterface _externalUI = null; + private InternalHostRawUserInterface _internalRawUI = null; + private InternalHost _parent = null; + private PSInformationalBuffers _informationalBuffers = null; } - } // namespace diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 6aa2ec512..2f2eb27ee 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -26,11 +26,11 @@ namespace System.Management.Automation /// /// Create a new PSListModifier with empty lists for Add/Remove. /// - public PSListModifier() + public PSListModifier() { - this._itemsToAdd = new Collection(); - this._itemsToRemove = new Collection(); - this._replacementItems = new Collection(); + _itemsToAdd = new Collection(); + _itemsToRemove = new Collection(); + _replacementItems = new Collection(); } /// @@ -40,9 +40,9 @@ namespace System.Management.Automation /// The items to add public PSListModifier(Collection removeItems, Collection addItems) { - this._itemsToAdd = (addItems != null) ? addItems : new Collection(); - this._itemsToRemove = (removeItems != null) ? removeItems : new Collection(); - this._replacementItems = new Collection(); + _itemsToAdd = (addItems != null) ? addItems : new Collection(); + _itemsToRemove = (removeItems != null) ? removeItems : new Collection(); + _replacementItems = new Collection(); } /// @@ -51,32 +51,32 @@ namespace System.Management.Automation /// The item(s) to replace an existing list with public PSListModifier(object replacementItems) { - this._itemsToAdd = new Collection(); - this._itemsToRemove = new Collection(); + _itemsToAdd = new Collection(); + _itemsToRemove = new Collection(); if (replacementItems == null) { - this._replacementItems = new Collection(); + _replacementItems = new Collection(); } else if (replacementItems is Collection) { - this._replacementItems = (Collection)replacementItems; + _replacementItems = (Collection)replacementItems; } else if (replacementItems is IList) { - this._replacementItems = new Collection((IList)replacementItems); + _replacementItems = new Collection((IList)replacementItems); } else if (replacementItems is IList) { - this._replacementItems = new Collection(); + _replacementItems = new Collection(); foreach (object item in (IList)replacementItems) { - this._replacementItems.Add(item); + _replacementItems.Add(item); } } else { - this._replacementItems = new Collection(); - this._replacementItems.Add(replacementItems); + _replacementItems = new Collection(); + _replacementItems.Add(replacementItems); } } @@ -92,9 +92,9 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("hash"); } - this._itemsToAdd = new Collection(); - this._itemsToRemove = new Collection(); - this._replacementItems = new Collection(); + _itemsToAdd = new Collection(); + _itemsToRemove = new Collection(); + _replacementItems = new Collection(); foreach (DictionaryEntry entry in hash) { @@ -113,15 +113,15 @@ namespace System.Management.Automation Collection collection; if (isRemove) { - collection = this._itemsToRemove; + collection = _itemsToRemove; } else if (isAdd) { - collection = this._itemsToAdd; + collection = _itemsToAdd; } else { - collection = this._replacementItems; + collection = _replacementItems; } IEnumerable enumerable = LanguagePrimitives.GetEnumerable(entry.Value); @@ -151,7 +151,7 @@ namespace System.Management.Automation { get { return _itemsToAdd; } } - Collection _itemsToAdd; + private Collection _itemsToAdd; /// /// The list of items to remove when AppyTo is called. @@ -160,7 +160,7 @@ namespace System.Management.Automation { get { return _itemsToRemove; } } - Collection _itemsToRemove; + private Collection _itemsToRemove; /// /// The list of items to replace an existing list with. @@ -169,7 +169,7 @@ namespace System.Management.Automation { get { return _replacementItems; } } - Collection _replacementItems; + private Collection _replacementItems; /// /// Update the given collection with the items in Add and Remove. diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 25ec05acc..2d6183500 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -46,8 +46,8 @@ namespace System.Management.Automation.Runspaces /// configuration information for this minshell. /// [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] - internal LocalRunspace (PSHost host, RunspaceConfiguration runspaceConfig) - : base( host,runspaceConfig) + internal LocalRunspace(PSHost host, RunspaceConfiguration runspaceConfig) + : base(host, runspaceConfig) { } @@ -99,18 +99,18 @@ namespace System.Management.Automation.Runspaces // if we didn't get applicationPrivateData from a runspace pool, // then we create a new one - if (applicationPrivateData == null) + if (_applicationPrivateData == null) { lock (this.SyncRoot) { - if (applicationPrivateData == null) + if (_applicationPrivateData == null) { - applicationPrivateData = new PSPrimitiveDictionary(); + _applicationPrivateData = new PSPrimitiveDictionary(); } } } - return applicationPrivateData; + return _applicationPrivateData; } /// @@ -119,10 +119,10 @@ namespace System.Management.Automation.Runspaces /// internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { - this.applicationPrivateData = applicationPrivateData; + _applicationPrivateData = applicationPrivateData; } - private PSPrimitiveDictionary applicationPrivateData; + private PSPrimitiveDictionary _applicationPrivateData; /// /// Gets the event manager @@ -158,14 +158,14 @@ namespace System.Management.Automation.Runspaces { get { - return this.createThreadOptions; + return _createThreadOptions; } set { lock (this.SyncRoot) { - if (value != this.createThreadOptions) + if (value != _createThreadOptions) { if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen) { @@ -185,12 +185,12 @@ namespace System.Management.Automation.Runspaces } } - this.createThreadOptions = value; + _createThreadOptions = value; } } } } - private PSThreadOptions createThreadOptions = PSThreadOptions.Default; + private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// /// Resets the runspace state to allow for fast reuse. Not all of the runspace @@ -204,7 +204,6 @@ namespace System.Management.Automation.Runspaces if (this.InitialSessionState == null) { invalidOperation = PSTraceSource.NewInvalidOperationException(); - } else if (this.RunspaceState != Runspaces.RunspaceState.Opened) { @@ -241,7 +240,7 @@ namespace System.Management.Automation.Runspaces /// /// A pipeline pre-filled with Commands specified in commandString. /// - protected override Pipeline CoreCreatePipeline (string command, bool addToHistory, bool isNested) + protected override Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -325,10 +324,10 @@ namespace System.Management.Automation.Runspaces return _transcriptionData; } } - TranscriptionData _transcriptionData = null; + private TranscriptionData _transcriptionData = null; - JobRepository _jobRepository; + private JobRepository _jobRepository; /// /// List of jobs in this runspace /// @@ -340,12 +339,12 @@ namespace System.Management.Automation.Runspaces } } - JobManager _jobManager; + private JobManager _jobManager; /// /// Manager for JobSourceAdapters registered in this runspace. /// - public override JobManager JobManager + public override JobManager JobManager { get { @@ -353,7 +352,7 @@ namespace System.Management.Automation.Runspaces } } - RunspaceRepository _runspaceRepository; + private RunspaceRepository _runspaceRepository; /// /// List of remote runspaces in this runspace @@ -381,8 +380,8 @@ namespace System.Management.Automation.Runspaces } } - private static string DebugPreferenceCachePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); - private static object DebugPreferenceLockObject = new object(); + private static string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); + private static object s_debugPreferenceLockObject = new object(); /// /// DebugPreference serves as a property bag to keep @@ -413,7 +412,7 @@ namespace System.Management.Automation.Runspaces /// Indicates if the debug preference has to be enabled or disabled. internal static void SetDebugPreference(string processName, List appDomainName, bool enable) { - lock(DebugPreferenceLockObject) + lock (s_debugPreferenceLockObject) { bool iscacheUpdated = false; Hashtable debugPreferenceCache = null; @@ -424,7 +423,7 @@ namespace System.Management.Automation.Runspaces appDomainNames = appDomainName.ToArray(); } - if (!File.Exists(LocalRunspace.DebugPreferenceCachePath)) + if (!File.Exists(LocalRunspace.s_debugPreferenceCachePath)) { if (enable) { @@ -440,7 +439,7 @@ namespace System.Management.Automation.Runspaces if (debugPreferenceCache != null) { if (enable) - { + { // Debug preference is set to enable. // If the cache does not contain the process name, then we just update the cache. if (!debugPreferenceCache.ContainsKey(processName)) @@ -525,7 +524,6 @@ namespace System.Management.Automation.Runspaces } } } - } } } @@ -546,7 +544,7 @@ namespace System.Management.Automation.Runspaces { using (PowerShell ps = PowerShell.Create()) { - ps.AddCommand("Export-Clixml").AddParameter("Path", LocalRunspace.DebugPreferenceCachePath).AddParameter("InputObject", debugPreferenceCache); + ps.AddCommand("Export-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath).AddParameter("InputObject", debugPreferenceCache); ps.Invoke(); } } @@ -570,7 +568,7 @@ namespace System.Management.Automation.Runspaces ps.Runspace = runspace; } - ps.AddCommand("Import-Clixml").AddParameter("Path", LocalRunspace.DebugPreferenceCachePath); + ps.AddCommand("Import-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath); Collection psObjects = ps.Invoke(); if (psObjects != null && psObjects.Count == 1) @@ -589,13 +587,13 @@ namespace System.Management.Automation.Runspaces private static DebugPreference GetProcessSpecificDebugPreference(object debugPreference) { DebugPreference processDebugPreference = null; - if(debugPreference != null) + if (debugPreference != null) { PSObject debugPreferencePsObject = debugPreference as PSObject; if (debugPreferencePsObject != null) { processDebugPreference = LanguagePrimitives.ConvertTo(debugPreferencePsObject); - } + } } return processDebugPreference; } @@ -646,7 +644,7 @@ namespace System.Management.Automation.Runspaces /// /// Helper function used for opening a runspace /// - void DoOpenHelper () + private void DoOpenHelper() { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -655,7 +653,7 @@ namespace System.Management.Automation.Runspaces } bool startLifeCycleEventWritten = false; - runspaceInitTracer.WriteLine("begin open runspace"); + s_runspaceInitTracer.WriteLine("begin open runspace"); try { _transcriptionData = new TranscriptionData(); @@ -683,13 +681,13 @@ namespace System.Management.Automation.Runspaces _jobManager = new JobManager(); _runspaceRepository = new RunspaceRepository(); - runspaceInitTracer.WriteLine("initializing built-in aliases and variable information"); + s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information"); InitializeDefaults(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); - runspaceInitTracer.WriteLine("Runspace open failed"); + s_runspaceInitTracer.WriteLine("Runspace open failed"); //Log engine health event LogEngineHealthEvent(exception); @@ -702,29 +700,29 @@ namespace System.Management.Automation.Runspaces } //Open failed. Set the RunspaceState to Broken. - SetRunspaceState (RunspaceState.Broken, exception); + SetRunspaceState(RunspaceState.Broken, exception); //Raise the event - RaiseRunspaceStateEvents (); + RaiseRunspaceStateEvents(); //Rethrow the exception. For asynchronous execution, //OpenThreadProc will catch it. For synchronous execution //caller of open will catch it. - throw ; + throw; } - SetRunspaceState (RunspaceState.Opened); + SetRunspaceState(RunspaceState.Opened); RunspaceOpening.Set(); //Raise the event - RaiseRunspaceStateEvents() ; - runspaceInitTracer.WriteLine("runspace opened successfully"); + RaiseRunspaceStateEvents(); + s_runspaceInitTracer.WriteLine("runspace opened successfully"); // Now do initial state configuration that requires an active runspace if (InitialSessionState != null) { - Exception initError = InitialSessionState.BindRunspace(this, runspaceInitTracer); - if(initError != null) + Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer); + if (initError != null) { // Log engine health event LogEngineHealthEvent(initError); @@ -802,45 +800,45 @@ namespace System.Management.Automation.Runspaces /// internal PipelineThread GetPipelineThread() { - if (this.pipelineThread == null) + if (_pipelineThread == null) { #if CORECLR // No ApartmentState In CoreCLR - this.pipelineThread = new PipelineThread(); + _pipelineThread = new PipelineThread(); #else - this.pipelineThread = new PipelineThread(this.ApartmentState); + _pipelineThread = new PipelineThread(this.ApartmentState); #endif } - return this.pipelineThread; + return _pipelineThread; } - private PipelineThread pipelineThread = null; + private PipelineThread _pipelineThread = null; override protected void CloseHelper(bool syncCall) { if (syncCall) { //Do close synchronously - DoCloseHelper (); + DoCloseHelper(); } else { //Do close asynchronously - Thread asyncThread = new Thread (new ThreadStart(this.CloseThreadProc)); + Thread asyncThread = new Thread(new ThreadStart(this.CloseThreadProc)); - asyncThread.Start (); + asyncThread.Start(); } } /// /// Start method for asynchronous close /// - private void CloseThreadProc () + private void CloseThreadProc() { #pragma warning disable 56500 try { - DoCloseHelper (); + DoCloseHelper(); } catch (Exception exception) // ignore non-severe exceptions { @@ -856,7 +854,7 @@ namespace System.Management.Automation.Runspaces /// Attempts to create/execute pipelines after a call to /// close will fail. /// - void DoCloseHelper () + private void DoCloseHelper() { // Stop any transcription if we're the last runspace to exit ExecutionContext executionContext = this.GetExecutionContext; @@ -932,10 +930,10 @@ namespace System.Management.Automation.Runspaces _engine = null; _commandFactory = null; - SetRunspaceState (RunspaceState.Closed); + SetRunspaceState(RunspaceState.Closed); //Raise Event - RaiseRunspaceStateEvents (); + RaiseRunspaceStateEvents(); // Report telemetry if we have no more open runspaces. bool allRunspacesClosed = true; @@ -974,7 +972,7 @@ namespace System.Management.Automation.Runspaces using (ManualResetEvent remoteRunspaceCloseCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); - throttleManager.ThrottleComplete += delegate(object sender, EventArgs e) + throttleManager.ThrottleComplete += delegate (object sender, EventArgs e) { remoteRunspaceCloseCompleted.Set(); }; @@ -1001,7 +999,7 @@ namespace System.Management.Automation.Runspaces using (ManualResetEvent jobsStopCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); - throttleManager.ThrottleComplete += delegate(object sender, EventArgs e) + throttleManager.ThrottleComplete += delegate (object sender, EventArgs e) { jobsStopCompleted.Set(); }; @@ -1035,7 +1033,6 @@ namespace System.Management.Automation.Runspaces // Stop jobs. throttleManager.EndSubmitOperations(); jobsStopCompleted.WaitOne(); - } // using jobsStopCompleted // Disconnect all disconnectable job runspaces found. @@ -1233,7 +1230,7 @@ namespace System.Management.Automation.Runspaces /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// Protected dispose which can be overridden by derived classes. @@ -1304,9 +1301,9 @@ namespace System.Management.Automation.Runspaces base.Close(); // call base.Close() first to make it stop the pipeline - if (this.pipelineThread != null) + if (_pipelineThread != null) { - this.pipelineThread.Close(); + _pipelineThread.Close(); } } @@ -1335,17 +1332,17 @@ namespace System.Management.Automation.Runspaces /// /// Manages history for this runspace /// - History _history; + private History _history; [TraceSource("RunspaceInit", "Initialization code for Runspace")] private static - PSTraceSource runspaceInitTracer = + PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); /// /// This ensures all processes have a server/listener. /// - private static RemoteSessionNamedPipeServer IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; + private static RemoteSessionNamedPipeServer s_IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; #endregion private fields } @@ -1357,7 +1354,7 @@ namespace System.Management.Automation.Runspaces /// internal sealed class StopJobOperationHelper : IThrottleOperation { - private Job job; + private Job _job; /// /// Internal constructor @@ -1365,8 +1362,8 @@ namespace System.Management.Automation.Runspaces /// Job object to stop. internal StopJobOperationHelper(Job job) { - this.job = job; - this.job.StateChanged += new EventHandler(HandleJobStateChanged); + _job = job; + _job.StateChanged += new EventHandler(HandleJobStateChanged); } /// @@ -1376,7 +1373,7 @@ namespace System.Management.Automation.Runspaces /// Event arguments containing Job state. private void HandleJobStateChanged(object sender, JobStateEventArgs eventArgs) { - if (job.IsFinishedState(job.JobStateInfo.State)) + if (_job.IsFinishedState(_job.JobStateInfo.State)) { // We are done when the job is in the finished state. RaiseOperationCompleteEvent(); @@ -1388,7 +1385,7 @@ namespace System.Management.Automation.Runspaces /// internal override void StartOperation() { - if (job.IsFinishedState(job.JobStateInfo.State)) + if (_job.IsFinishedState(_job.JobStateInfo.State)) { // The job is already in the finished state and so cannot be stopped. RaiseOperationCompleteEvent(); @@ -1396,7 +1393,7 @@ namespace System.Management.Automation.Runspaces else { // Otherwise stop the job. - job.StopJob(); + _job.StopJob(); } } @@ -1418,7 +1415,7 @@ namespace System.Management.Automation.Runspaces /// private void RaiseOperationCompleteEvent() { - this.job.StateChanged -= new EventHandler(HandleJobStateChanged); + _job.StateChanged -= new EventHandler(HandleJobStateChanged); OperationStateEventArgs operationStateArgs = new OperationStateEventArgs(); operationStateArgs.OperationState = OperationState.StartComplete; @@ -1427,14 +1424,14 @@ namespace System.Management.Automation.Runspaces OperationComplete.SafeInvoke(this, operationStateArgs); } } - + /// /// Helper class to disconnect a runspace if the runspace supports disconnect /// semantics or otherwise close the runspace. /// internal sealed class CloseOrDisconnectRunspaceOperationHelper : IThrottleOperation { - private RemoteRunspace remoteRunspace; + private RemoteRunspace _remoteRunspace; /// /// Internal constructor @@ -1442,8 +1439,8 @@ namespace System.Management.Automation.Runspaces /// internal CloseOrDisconnectRunspaceOperationHelper(RemoteRunspace remoteRunspace) { - this.remoteRunspace = remoteRunspace; - this.remoteRunspace.StateChanged += new EventHandler(HandleRunspaceStateChanged); + _remoteRunspace = remoteRunspace; + _remoteRunspace.StateChanged += new EventHandler(HandleRunspaceStateChanged); } /// @@ -1473,9 +1470,9 @@ namespace System.Management.Automation.Runspaces /// internal override void StartOperation() { - if (remoteRunspace.RunspaceStateInfo.State == RunspaceState.Closed || - remoteRunspace.RunspaceStateInfo.State == RunspaceState.Broken || - remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected) + if (_remoteRunspace.RunspaceStateInfo.State == RunspaceState.Closed || + _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Broken || + _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { // If the runspace is currently in a disconnected state then leave it // as is. @@ -1490,14 +1487,14 @@ namespace System.Management.Automation.Runspaces { // If the runspace supports disconnect semantics and is running a command, // then disconnect it rather than closing it. - if (remoteRunspace.CanDisconnect && - remoteRunspace.GetCurrentlyRunningPipeline() != null) + if (_remoteRunspace.CanDisconnect && + _remoteRunspace.GetCurrentlyRunningPipeline() != null) { - remoteRunspace.DisconnectAsync(); + _remoteRunspace.DisconnectAsync(); } else { - remoteRunspace.CloseAsync(); + _remoteRunspace.CloseAsync(); } } } @@ -1508,7 +1505,6 @@ namespace System.Management.Automation.Runspaces /// internal override void StopOperation() { - } /// @@ -1521,7 +1517,7 @@ namespace System.Management.Automation.Runspaces /// private void RaiseOperationCompleteEvent() { - this.remoteRunspace.StateChanged -= new EventHandler(HandleRunspaceStateChanged); + _remoteRunspace.StateChanged -= new EventHandler(HandleRunspaceStateChanged); OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); @@ -1595,7 +1591,7 @@ namespace System.Management.Automation.Runspaces { get { return _errors; } } - PSDataCollection _errors; + private PSDataCollection _errors; #region Serialization /// @@ -1626,9 +1622,6 @@ namespace System.Management.Automation.Runspaces } #endregion Serialization - - - } // RunspaceOpenException #endregion Helper Class diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index a6c406403..4b3943a87 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -1,6 +1,7 @@ /********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ + using System; using System.Diagnostics; using System.Collections.Generic; @@ -32,11 +33,11 @@ namespace System.Management.Automation.Runspaces /// The command string to parse. /// if true, add pipeline to history /// True for nested pipeline - internal LocalPipeline (LocalRunspace runspace, string command, bool addToHistory, bool isNested) - :base((Runspace)runspace, command, addToHistory,isNested) + internal LocalPipeline(LocalRunspace runspace, string command, bool addToHistory, bool isNested) + : base((Runspace)runspace, command, addToHistory, isNested) { _stopper = new PipelineStopper(this); - InitStreams (); + InitStreams(); } /// @@ -68,13 +69,13 @@ namespace System.Management.Automation.Runspaces /// Buffers used to write progress, verbose, debug, warning, information /// information of an invocation. /// - internal LocalPipeline(LocalRunspace runspace, - CommandCollection command, + internal LocalPipeline(LocalRunspace runspace, + CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, - ObjectStreamBase outputStream, - ObjectStreamBase errorStream, + ObjectStreamBase outputStream, + ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command, addToHistory, isNested, inputStream, outputStream, errorStream, infoBuffers) { @@ -87,22 +88,22 @@ namespace System.Management.Automation.Runspaces /// Copy constructor to support cloning /// /// The source pipeline - internal LocalPipeline (LocalPipeline pipeline) - : base ((PipelineBase)(pipeline)) + internal LocalPipeline(LocalPipeline pipeline) + : base((PipelineBase)(pipeline)) { _stopper = new PipelineStopper(this); InitStreams(); } #endregion constructors - + #region public_methods - + /// /// Creates a new that is a copy of the current instance. /// /// A new that is a copy of this instance. - public override Pipeline Copy () + public override Pipeline Copy() { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -116,14 +117,14 @@ namespace System.Management.Automation.Runspaces #endregion public_methods #region private_methods - + /// /// Invoke the pipeline asynchronously with input. /// /// /// Results are returned through the reader. /// - override protected void StartPipelineExecution () + override protected void StartPipelineExecution() { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -142,7 +143,7 @@ namespace System.Management.Automation.Runspaces // NTRAID#Windows Out Of Band Releases-925566-2005/12/09-JonN // Remember this here, in the synchronous thread, // to avoid timing dependencies in the pipeline thread. - useExternalInput = (InputStream.IsOpen || InputStream.Count > 0); + _useExternalInput = (InputStream.IsOpen || InputStream.Count > 0); PSThreadOptions memberOptions = this.IsNested ? PSThreadOptions.UseCurrentThread : this.LocalRunspace.ThreadOptions; @@ -150,78 +151,78 @@ namespace System.Management.Automation.Runspaces { case PSThreadOptions.Default: case PSThreadOptions.UseNewThread: - { + { #if CORECLR - //Start execution of pipeline in another thread - // No ApartmentState/ThreadStackSize In CoreCLR - Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc)); - SetupInvokeThread(invokeThread, true); + //Start execution of pipeline in another thread + // No ApartmentState/ThreadStackSize In CoreCLR + Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc)); + SetupInvokeThread(invokeThread, true); #else - //Start execution of pipeline in another thread - // 2004/05/02-JonN Specify maxStack parameter - Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc), MaxStack); - SetupInvokeThread(invokeThread, true); + //Start execution of pipeline in another thread + // 2004/05/02-JonN Specify maxStack parameter + Thread invokeThread = new Thread(new ThreadStart(this.InvokeThreadProc), MaxStack); + SetupInvokeThread(invokeThread, true); - ApartmentState apartmentState; + ApartmentState apartmentState; - if (InvocationSettings != null && InvocationSettings.ApartmentState != ApartmentState.Unknown) - { - apartmentState = InvocationSettings.ApartmentState; // set the user-defined apartmentstate. - } - else - { - apartmentState = this.LocalRunspace.ApartmentState; // use the Runspace apartmet state - } + if (InvocationSettings != null && InvocationSettings.ApartmentState != ApartmentState.Unknown) + { + apartmentState = InvocationSettings.ApartmentState; // set the user-defined apartmentstate. + } + else + { + apartmentState = this.LocalRunspace.ApartmentState; // use the Runspace apartmet state + } - if (apartmentState != ApartmentState.Unknown) - { - invokeThread.SetApartmentState(apartmentState); - } + if (apartmentState != ApartmentState.Unknown) + { + invokeThread.SetApartmentState(apartmentState); + } #endif - invokeThread.Start(); + invokeThread.Start(); - break; - } + break; + } case PSThreadOptions.ReuseThread: - { - if (this.IsNested) { - // if this a nested pipeline we are already in the appropriate thread so we just execute the pipeline here - SetupInvokeThread(Thread.CurrentThread, true); - this.InvokeThreadProc(); + if (this.IsNested) + { + // if this a nested pipeline we are already in the appropriate thread so we just execute the pipeline here + SetupInvokeThread(Thread.CurrentThread, true); + this.InvokeThreadProc(); + } + else + { + // otherwise we execute the pipeline in the Runspace's thread + PipelineThread invokeThread = this.LocalRunspace.GetPipelineThread(); + SetupInvokeThread(invokeThread.Worker, true); + invokeThread.Start(this.InvokeThreadProc); + } + break; } - else - { - // otherwise we execute the pipeline in the Runspace's thread - PipelineThread invokeThread = this.LocalRunspace.GetPipelineThread(); - SetupInvokeThread(invokeThread.Worker, true); - invokeThread.Start(this.InvokeThreadProc); - } - break; - } case PSThreadOptions.UseCurrentThread: - { - Thread oldNestedPipelineThread = NestedPipelineExecutionThread; - - CultureInfo oldCurrentCulture = CultureInfo.CurrentCulture; - CultureInfo oldCurrentUICulture = CultureInfo.CurrentUICulture; - - try { - // prepare invoke thread - SetupInvokeThread(Thread.CurrentThread, false); - this.InvokeThreadProc(); + Thread oldNestedPipelineThread = NestedPipelineExecutionThread; + + CultureInfo oldCurrentCulture = CultureInfo.CurrentCulture; + CultureInfo oldCurrentUICulture = CultureInfo.CurrentUICulture; + + try + { + // prepare invoke thread + SetupInvokeThread(Thread.CurrentThread, false); + this.InvokeThreadProc(); + } + finally + { + NestedPipelineExecutionThread = oldNestedPipelineThread; + ClrFacade.SetCurrentThreadCulture(oldCurrentCulture); + ClrFacade.SetCurrentThreadUiCulture(oldCurrentUICulture); + } + break; } - finally - { - NestedPipelineExecutionThread = oldNestedPipelineThread; - ClrFacade.SetCurrentThreadCulture(oldCurrentCulture); - ClrFacade.SetCurrentThreadUiCulture(oldCurrentUICulture); - } - break; - } default: Debug.Assert(false); @@ -295,7 +296,7 @@ namespace System.Management.Automation.Runspaces foreach (Command command in this.Commands) { - if (command.IsScript && (! this.IsPulsePipeline)) + if (command.IsScript && (!this.IsPulsePipeline)) { // Transcribe scripts, unless they are the pulse pipeline. this.Runspace.GetExecutionContext.EngineHostInterface.UI.TranscribeCommand(command.CommandText, null); @@ -344,7 +345,7 @@ namespace System.Management.Automation.Runspaces //Supply input stream to PipelineProcessor // NTRAID#Windows Out Of Band Releases-925566-2005/12/09-JonN - if (useExternalInput) + if (_useExternalInput) { pipelineProcessor.ExternalInput = InputStream.ObjectReader; } @@ -523,7 +524,7 @@ namespace System.Management.Automation.Runspaces // 2004/02/26-JonN added IDisposable to PipelineProcessor if (null != pipelineProcessor) { - pipelineProcessor.Dispose (); + pipelineProcessor.Dispose(); pipelineProcessor = null; } } @@ -583,55 +584,55 @@ namespace System.Management.Automation.Runspaces try { if ((null != InvocationSettings) && (InvocationSettings.FlowImpersonationPolicy)) - { + { // we have a valid identity to impersonate. System.Security.Principal.WindowsIdentity identityToImPersonate = new System.Security.Principal.WindowsIdentity(InvocationSettings.WindowsIdentityToImpersonate.Token); oldImpersonationCtxt = identityToImPersonate.Impersonate(); } #endif - // Set up pipeline internal host if it is available. - if (InvocationSettings != null && InvocationSettings.Host != null) + // Set up pipeline internal host if it is available. + if (InvocationSettings != null && InvocationSettings.Host != null) + { + InternalHost internalHost = InvocationSettings.Host as InternalHost; + + if (internalHost != null) // if we are given an internal host, use the external host { - InternalHost internalHost = InvocationSettings.Host as InternalHost; - - if (internalHost != null) // if we are given an internal host, use the external host - { - LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost); - } - else - { - LocalRunspace.ExecutionContext.InternalHost.SetHostRef(InvocationSettings.Host); - } - } - - if (LocalRunspace.ExecutionContext.InternalHost.ExternalHost.ShouldSetThreadUILanguageToZero) - { - // BUG: 610329. Pipeline execution happens in a new thread. For - // Console applications SetThreadUILanguage(0) must be called - // inorder for the native MUI loader to load the resources correctly. - // ConsoleHost already does this in its entry point..but the same - // call is not performed in the Pipeline execution threads causing - // cmdlets that load native resources show unreadable messages on - // the console. - Microsoft.PowerShell.NativeCultureResolver.SetThreadUILanguage(0); - } - - //Put Execution Context In TLS - Runspace.DefaultRunspace = this.LocalRunspace; - - FlowControlException flowControlException = InvokeHelper(); - - if (flowControlException != null) - { - // Let pipeline propagate the BreakException. - SetPipelineState(Runspaces.PipelineState.Failed, flowControlException); + LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost); } else { - // Invoke finished successfully. Set state to Completed. - SetPipelineState(PipelineState.Completed); + LocalRunspace.ExecutionContext.InternalHost.SetHostRef(InvocationSettings.Host); } + } + + if (LocalRunspace.ExecutionContext.InternalHost.ExternalHost.ShouldSetThreadUILanguageToZero) + { + // BUG: 610329. Pipeline execution happens in a new thread. For + // Console applications SetThreadUILanguage(0) must be called + // inorder for the native MUI loader to load the resources correctly. + // ConsoleHost already does this in its entry point..but the same + // call is not performed in the Pipeline execution threads causing + // cmdlets that load native resources show unreadable messages on + // the console. + Microsoft.PowerShell.NativeCultureResolver.SetThreadUILanguage(0); + } + + //Put Execution Context In TLS + Runspace.DefaultRunspace = this.LocalRunspace; + + FlowControlException flowControlException = InvokeHelper(); + + if (flowControlException != null) + { + // Let pipeline propagate the BreakException. + SetPipelineState(Runspaces.PipelineState.Failed, flowControlException); + } + else + { + // Invoke finished successfully. Set state to Completed. + SetPipelineState(PipelineState.Completed); + } #if !CORECLR } finally @@ -695,7 +696,7 @@ namespace System.Management.Automation.Runspaces // Remove pipeline specific host if it was set. // Win8:464422 Revert the host only if this pipeline invocation changed it // with 464422 a nested pipeline reverts the host, although the nested pipeline did not set it. - if ((InvocationSettings != null && InvocationSettings.Host != null) && + if ((InvocationSettings != null && InvocationSettings.Host != null) && (LocalRunspace.ExecutionContext.InternalHost.IsHostRefSet)) { LocalRunspace.ExecutionContext.InternalHost.RevertHostRef(); @@ -738,7 +739,7 @@ namespace System.Management.Automation.Runspaces { try { - OutputStream.Close (); + OutputStream.Close(); } catch (ObjectDisposedException) { @@ -750,7 +751,7 @@ namespace System.Management.Automation.Runspaces { try { - ErrorStream.Close (); + ErrorStream.Close(); } catch (ObjectDisposedException) { @@ -775,7 +776,7 @@ namespace System.Management.Automation.Runspaces //Runspace object maintains a list of pipelines in execution. //Remove this pipeline from the list. This method also calls the //pipeline finished event. - LocalRunspace.RemoveFromRunningPipelineList (this); + LocalRunspace.RemoveFromRunningPipelineList(this); //If async call raise the event here. For sync invoke call, //thread on which invoke is called will raise the event. @@ -785,7 +786,7 @@ namespace System.Management.Automation.Runspaces //RemoveFromRunningPipelineList. If it is done before, and in the //Event, Runspace.Close is called which waits for pipeline to close. //We will have deadlock - RaisePipelineStateEvents (); + RaisePipelineStateEvents(); } } } @@ -797,28 +798,28 @@ namespace System.Management.Automation.Runspaces /// /// If true pipeline is stoped synchronously /// else asynchronously. - override protected void ImplementStop (bool syncCall) + override protected void ImplementStop(bool syncCall) { if (syncCall) { - StopHelper (); + StopHelper(); } else { - Thread stopThread = new Thread (new ThreadStart (this.StopThreadProc)); - stopThread.Start (); + Thread stopThread = new Thread(new ThreadStart(this.StopThreadProc)); + stopThread.Start(); } } /// /// Start method for asynchronous Stop /// - private void StopThreadProc () + private void StopThreadProc() { - StopHelper (); + StopHelper(); } - PipelineStopper _stopper; + private PipelineStopper _stopper; /// /// Gets PipelineStopper object which maitains stack of PipelineProcessor @@ -835,14 +836,14 @@ namespace System.Management.Automation.Runspaces /// /// Helper method for Stop functionality /// - private void StopHelper () + private void StopHelper() { // Ensure that any saved debugger stop is released LocalRunspace.ReleaseDebugger(); //first stop all child pipelines of this pipeline - LocalRunspace.StopNestedPipelines (this); - + LocalRunspace.StopNestedPipelines(this); + //close the input pipe if it hasn't been closed. //This would release the pipeline thread if it is //waiting for input. @@ -879,7 +880,7 @@ namespace System.Management.Automation.Runspaces /// Creates a PipelineProcessor object from LocalPipeline object. /// /// Created PipelineProcessor object - private PipelineProcessor CreatePipelineProcessor () + private PipelineProcessor CreatePipelineProcessor() { CommandCollection commands = Commands; @@ -888,7 +889,7 @@ namespace System.Management.Automation.Runspaces throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoCommandInPipeline); } - PipelineProcessor pipelineProcessor = new PipelineProcessor (); + PipelineProcessor pipelineProcessor = new PipelineProcessor(); pipelineProcessor.TopLevel = true; bool failed = false; @@ -904,7 +905,7 @@ namespace System.Management.Automation.Runspaces try { CommandOrigin commandOrigin = command.CommandOrigin; - if(IsNested) + if (IsNested) { commandOrigin = CommandOrigin.Internal; } @@ -931,7 +932,7 @@ namespace System.Management.Automation.Runspaces this.Runspace.ExecutionContext.InternalHost.UI.TranscribeCommand(command.CommandText, null); } } - + throw; } } @@ -997,7 +998,7 @@ namespace System.Management.Automation.Runspaces { return new CommandProcessor(cmdletInfo, LocalRunspace.ExecutionContext); } - + IScriptCommandInfo functionInfo = commandInfo as IScriptCommandInfo; if (functionInfo != null) { @@ -1018,12 +1019,12 @@ namespace System.Management.Automation.Runspaces /// This method initializes streams and backs up their original states. /// This should be only called from constructors. /// - private void InitStreams () + private void InitStreams() { if (LocalRunspace.ExecutionContext != null) { - oldExternalErrorOutput = LocalRunspace.ExecutionContext.ExternalErrorOutput; - oldExternalSuccessOutput = LocalRunspace.ExecutionContext.ExternalSuccessOutput; + _oldExternalErrorOutput = LocalRunspace.ExecutionContext.ExternalErrorOutput; + _oldExternalSuccessOutput = LocalRunspace.ExecutionContext.ExternalSuccessOutput; LocalRunspace.ExecutionContext.ExternalErrorOutput = ErrorStream.ObjectWriter; LocalRunspace.ExecutionContext.ExternalSuccessOutput = OutputStream.ObjectWriter; } @@ -1037,18 +1038,18 @@ namespace System.Management.Automation.Runspaces { if (LocalRunspace.ExecutionContext != null) { - LocalRunspace.ExecutionContext.ExternalErrorOutput = oldExternalErrorOutput; - LocalRunspace.ExecutionContext.ExternalSuccessOutput = oldExternalSuccessOutput; + LocalRunspace.ExecutionContext.ExternalErrorOutput = _oldExternalErrorOutput; + LocalRunspace.ExecutionContext.ExternalSuccessOutput = _oldExternalSuccessOutput; } } //History object for this pipeline - DateTime _pipelineStartTime; + private DateTime _pipelineStartTime; /// /// Adds an entry in history for this pipeline /// - private void RecordPipelineStartTime () + private void RecordPipelineStartTime() { _pipelineStartTime = DateTime.Now; } @@ -1057,17 +1058,17 @@ namespace System.Management.Automation.Runspaces /// Add HistoryEntry for this pipeline. Use this function when writing /// history at the end of pipeline. /// - private void AddHistoryEntry (bool skipIfLocked) + private void AddHistoryEntry(bool skipIfLocked) { //History id is greater than zero if entry was added to history if (AddToHistory) { - LocalRunspace.History.AddEntry(InstanceId, HistoryString, PipelineState,_pipelineStartTime, DateTime.Now, skipIfLocked); + LocalRunspace.History.AddEntry(InstanceId, HistoryString, PipelineState, _pipelineStartTime, DateTime.Now, skipIfLocked); } } - long _historyIdForThisPipeline = -1; + private long _historyIdForThisPipeline = -1; /// /// This method is called Add-History cmdlet to add history entry. /// @@ -1160,10 +1161,10 @@ namespace System.Management.Automation.Runspaces } // NTRAID#Windows Out Of Band Releases-925566-2005/12/09-JonN - bool useExternalInput; + private bool _useExternalInput; - PipelineWriter oldExternalErrorOutput; - PipelineWriter oldExternalSuccessOutput; + private PipelineWriter _oldExternalErrorOutput; + private PipelineWriter _oldExternalSuccessOutput; #endregion private_fields @@ -1175,19 +1176,19 @@ namespace System.Management.Automation.Runspaces /// private List _invokeHistoryIds = new List(); - internal bool PresentInInvokeHistoryEntryList (HistoryInfo entry) + internal bool PresentInInvokeHistoryEntryList(HistoryInfo entry) { - return _invokeHistoryIds.Contains (entry.Id); + return _invokeHistoryIds.Contains(entry.Id); } - internal void AddToInvokeHistoryEntryList (HistoryInfo entry) + internal void AddToInvokeHistoryEntryList(HistoryInfo entry) { - _invokeHistoryIds.Add (entry.Id); + _invokeHistoryIds.Add(entry.Id); } - internal void RemoveFromInvokeHistoryEntryList (HistoryInfo entry) + internal void RemoveFromInvokeHistoryEntryList(HistoryInfo entry) { - _invokeHistoryIds.Remove (entry.Id); + _invokeHistoryIds.Remove(entry.Id); } #endregion invoke_loop_detection @@ -1197,7 +1198,7 @@ namespace System.Management.Automation.Runspaces /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// Protected dispose which can be overridden by derived classes. @@ -1238,22 +1239,22 @@ namespace System.Management.Automation.Runspaces #if CORECLR internal PipelineThread() { - this.worker = new Thread(WorkerProc); - this.workItem = null; - this.workItemReady = new AutoResetEvent(false); - this.closed = false; + _worker = new Thread(WorkerProc); + _workItem = null; + _workItemReady = new AutoResetEvent(false); + _closed = false; } #else internal PipelineThread(ApartmentState apartmentState) { - this.worker = new Thread(WorkerProc, LocalPipeline.MaxStack); - this.workItem = null; - this.workItemReady = new AutoResetEvent(false); - this.closed = false; + _worker = new Thread(WorkerProc, LocalPipeline.MaxStack); + _workItem = null; + _workItemReady = new AutoResetEvent(false); + _closed = false; if (apartmentState != ApartmentState.Unknown) { - this.worker.SetApartmentState(apartmentState); + _worker.SetApartmentState(apartmentState); } } #endif @@ -1265,7 +1266,7 @@ namespace System.Management.Automation.Runspaces { get { - return this.worker; + return _worker; } } @@ -1274,17 +1275,17 @@ namespace System.Management.Automation.Runspaces /// internal void Start(ThreadStart workItem) { - if (this.closed) + if (_closed) { return; } - this.workItem = workItem; - this.workItemReady.Set(); - - if (this.worker.ThreadState == System.Threading.ThreadState.Unstarted) + _workItem = workItem; + _workItemReady.Set(); + + if (_worker.ThreadState == System.Threading.ThreadState.Unstarted) { - this.worker.Start(); + _worker.Start(); } } @@ -1301,13 +1302,13 @@ namespace System.Management.Automation.Runspaces /// private void WorkerProc() { - while (!closed) + while (!_closed) { - this.workItemReady.WaitOne(); + _workItemReady.WaitOne(); - if (!this.closed) + if (!_closed) { - this.workItem(); + _workItem(); } } } @@ -1317,21 +1318,21 @@ namespace System.Management.Automation.Runspaces /// public void Dispose() { - if (this.closed) + if (_closed) { return; } - this.closed = true; + _closed = true; - this.workItemReady.Set(); + _workItemReady.Set(); - if (this.worker.ThreadState != System.Threading.ThreadState.Unstarted && Thread.CurrentThread != this.worker) + if (_worker.ThreadState != System.Threading.ThreadState.Unstarted && Thread.CurrentThread != _worker) { - this.worker.Join(); + _worker.Join(); } - this.workItemReady.Dispose(); + _workItemReady.Dispose(); GC.SuppressFinalize(this); } @@ -1344,10 +1345,10 @@ namespace System.Management.Automation.Runspaces Dispose(); } - Thread worker; - ThreadStart workItem; - AutoResetEvent workItemReady; - bool closed; + private Thread _worker; + private ThreadStart _workItem; + private AutoResetEvent _workItemReady; + private bool _closed; } /// @@ -1361,7 +1362,7 @@ namespace System.Management.Automation.Runspaces /// /// stack of current executing pipeline processor /// - private Stack _stack = new Stack (); + private Stack _stack = new Stack(); /// /// Object used for synchronization @@ -1372,7 +1373,7 @@ namespace System.Management.Automation.Runspaces /// /// Default constructor /// - internal PipelineStopper (LocalPipeline localPipeline) + internal PipelineStopper(LocalPipeline localPipeline) { _localPipeline = localPipeline; } @@ -1380,7 +1381,7 @@ namespace System.Management.Automation.Runspaces /// /// This is set true when stop is called /// - bool _stopping; + private bool _stopping; internal bool IsStopping { get @@ -1401,16 +1402,16 @@ namespace System.Management.Automation.Runspaces { if (item == null) { - throw PSTraceSource.NewArgumentNullException ("item"); + throw PSTraceSource.NewArgumentNullException("item"); } lock (_syncRoot) { if (_stopping) { - PipelineStoppedException e = new PipelineStoppedException (); + PipelineStoppedException e = new PipelineStoppedException(); throw e; } - _stack.Push (item); + _stack.Push(item); } item.LocalPipeline = _localPipeline; } @@ -1418,7 +1419,7 @@ namespace System.Management.Automation.Runspaces /// /// Pop top item from PipelineProcessor stack /// - internal void Pop (bool fromSteppablePipeline) + internal void Pop(bool fromSteppablePipeline) { lock (_syncRoot) { @@ -1429,7 +1430,7 @@ namespace System.Management.Automation.Runspaces { return; } - + if (_stack.Count > 0) { PipelineProcessor oldPipe = _stack.Pop(); @@ -1446,7 +1447,7 @@ namespace System.Management.Automation.Runspaces } } - internal void Stop () + internal void Stop() { PipelineProcessor[] copyStack; lock (_syncRoot) @@ -1463,7 +1464,7 @@ namespace System.Management.Automation.Runspaces // Propigate error from the toplevel operation through to enclosing the LocalPipeline. if (copyStack.Length > 0) { - PipelineProcessor topLevel = copyStack[copyStack.Length-1]; + PipelineProcessor topLevel = copyStack[copyStack.Length - 1]; if (topLevel != null && _localPipeline != null) { _localPipeline.SetHadErrors(topLevel.ExecutionFailed); @@ -1480,7 +1481,7 @@ namespace System.Management.Automation.Runspaces //in the finally block though. foreach (PipelineProcessor pp in copyStack) { - pp.Stop (); + pp.Stop(); } } } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 767d7c605..f3d0bacf3 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -373,10 +373,10 @@ namespace System.Management.Automation.Host /// internal bool ShouldSetThreadUILanguageToZero { - get { return shouldSetThreadUILanguageToZero; } - set { shouldSetThreadUILanguageToZero = value; } + get { return _shouldSetThreadUILanguageToZero; } + set { _shouldSetThreadUILanguageToZero = value; } } - private bool shouldSetThreadUILanguageToZero; + private bool _shouldSetThreadUILanguageToZero; /// /// This property enables and disables the host debugger if debugging is supported. diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 2204732cd..f21906b38 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -12,7 +12,6 @@ using System.Globalization; namespace System.Management.Automation.Host { - #region Ancillary types. // I would have preferred to make these nested types within PSHostRawUserInterface, but that @@ -26,7 +25,7 @@ namespace System.Management.Automation.Host /// /// - public + public struct Coordinates { /// @@ -37,10 +36,10 @@ namespace System.Management.Automation.Host public int X { - get { return x; } - set { x = value; } + get { return _x; } + set { _x = value; } } - private int x; + private int _x; /// /// @@ -50,11 +49,11 @@ namespace System.Management.Automation.Host public int Y { - get { return y; } - set { y = value; } + get { return _y; } + set { _y = value; } } - private int y; + private int _y; /// @@ -73,11 +72,11 @@ namespace System.Management.Automation.Host /// /// - public + public Coordinates(int x, int y) { - this.x = x; - this.y = y; + _x = x; + _y = y; } @@ -127,7 +126,7 @@ namespace System.Management.Automation.Host if (obj is Coordinates) { - result = this == ((Coordinates) obj); + result = this == ((Coordinates)obj); } return result; @@ -160,16 +159,16 @@ namespace System.Management.Automation.Host { // add one and invert to avoid an overflow. - i64 = (UInt64) (-1 * (X + 1)); + i64 = (UInt64)(-1 * (X + 1)); } else { - i64 = (UInt64) (-X); + i64 = (UInt64)(-X); } } else { - i64 = (UInt64) X; + i64 = (UInt64)X; } // rotate 32 bits to the left. @@ -182,16 +181,16 @@ namespace System.Management.Automation.Host { if (Y == Int32.MinValue) { - i64 += (UInt64) (-1 * (Y + 1)); + i64 += (UInt64)(-1 * (Y + 1)); } else { - i64 += (UInt64) (-Y); + i64 += (UInt64)(-Y); } } else { - i64 += (UInt64) Y; + i64 += (UInt64)Y; } int result = i64.GetHashCode(); @@ -270,7 +269,7 @@ namespace System.Management.Automation.Host /// /// - public + public struct Size { /// @@ -281,11 +280,11 @@ namespace System.Management.Automation.Host public int Width { - get { return width; } - set { width = value; } + get { return _width; } + set { _width = value; } } - private int width; - + private int _width; + /// /// /// Gets and sets the Height @@ -294,10 +293,10 @@ namespace System.Management.Automation.Host public int Height { - get { return height; } - set { height = value; } + get { return _height; } + set { _height = value; } } - private int height; + private int _height; /// @@ -316,11 +315,11 @@ namespace System.Management.Automation.Host /// /// - public + public Size(int width, int height) { - this.width = width; - this.height = height; + _width = width; + _height = height; } @@ -498,7 +497,6 @@ namespace System.Management.Automation.Host { return !(first == second); } - } @@ -522,7 +520,7 @@ namespace System.Management.Automation.Host /// AllowCtrlC = 0x0001, - + /// /// /// Do not display the character for the key in the window when pressed. @@ -538,7 +536,7 @@ namespace System.Management.Automation.Host /// IncludeKeyDown = 0x0004, - + /// /// /// Include key up events. Either one of IncludeKeyDown and IncludeKeyUp or both must be specified. @@ -575,43 +573,43 @@ namespace System.Management.Automation.Host /// /// The right ctrl key is pressed. /// - + RightCtrlPressed = 0x0004, /// /// The left ctrl key is pressed. /// - + LeftCtrlPressed = 0x0008, /// /// The shift key is pressed. /// - + ShiftPressed = 0x0010, /// /// The numlock light is on. /// - + NumLockOn = 0x0020, /// /// The scrolllock light is on. /// - + ScrollLockOn = 0x0040, /// /// The capslock light is on. /// - + CapsLockOn = 0x0080, /// /// The key is enhanced. /// - + EnhancedKey = 0x0100 } @@ -622,8 +620,8 @@ namespace System.Management.Automation.Host /// Represents information of a keystroke /// /// - - public + + public struct KeyInfo { /// @@ -634,47 +632,47 @@ namespace System.Management.Automation.Host public int VirtualKeyCode { - get { return virtualKeyCode; } - set { virtualKeyCode = value; } + get { return _virtualKeyCode; } + set { _virtualKeyCode = value; } } - private int virtualKeyCode; + private int _virtualKeyCode; + - /// /// Gets and set unicode Character of the key /// public char Character { - get { return character; } - set { character = value; } + get { return _character; } + set { _character = value; } } - private char character; + private char _character; + - /// /// State of the control keys. /// - + public ControlKeyStates ControlKeyState { - get { return controlKeyState; } - set { controlKeyState = value; } + get { return _controlKeyState; } + set { _controlKeyState = value; } } - - private ControlKeyStates controlKeyState; + + private ControlKeyStates _controlKeyState; /// /// Gets and set the status of whether this instance is generated by a key pressed or released /// - + public bool KeyDown { - get { return keyDown; } - set { keyDown = value; } + get { return _keyDown; } + set { _keyDown = value; } } - private bool keyDown; + private bool _keyDown; /// /// @@ -712,10 +710,10 @@ namespace System.Management.Automation.Host bool keyDown ) { - this.virtualKeyCode = virtualKeyCode; - this.character = ch; - this.controlKeyState = controlKeyState; - this.keyDown = keyDown; + _virtualKeyCode = virtualKeyCode; + _character = ch; + _controlKeyState = controlKeyState; + _keyDown = keyDown; } /// @@ -793,10 +791,10 @@ namespace System.Management.Automation.Host UInt32 i32 = KeyDown ? 0x10000000U : 0; // mask in ControlKeyState - i32 |= ((uint) ControlKeyState) << 16; + i32 |= ((uint)ControlKeyState) << 16; // mask in the VirtualKeyCode - i32 |= (UInt32) VirtualKeyCode; + i32 |= (UInt32)VirtualKeyCode; return i32.GetHashCode(); } @@ -877,7 +875,7 @@ namespace System.Management.Automation.Host /// /// - public + public struct Rectangle { /// @@ -888,12 +886,12 @@ namespace System.Management.Automation.Host public int Left { - get { return left; } - set { left = value; } + get { return _left; } + set { _left = value; } } - private int left; + private int _left; + - /// /// /// Gets and sets the top of the rectangle @@ -902,12 +900,12 @@ namespace System.Management.Automation.Host public int Top { - get { return top; } - set { top = value; } + get { return _top; } + set { _top = value; } } - private int top; - - + private int _top; + + /// /// /// Gets and sets the right side of the rectangle @@ -916,13 +914,13 @@ namespace System.Management.Automation.Host public int Right { - get { return right; } - set { right = value; } + get { return _right; } + set { _right = value; } } - private int right; + private int _right; + + - - /// /// /// Gets and sets the bottom of the rectanngle @@ -931,10 +929,10 @@ namespace System.Management.Automation.Host public int Bottom { - get { return bottom; } - set { bottom = value; } + get { return _bottom; } + set { _bottom = value; } } - private int bottom; + private int _bottom; /// @@ -983,10 +981,10 @@ namespace System.Management.Automation.Host throw PSTraceSource.NewArgumentException("bottom", MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "bottom", "top"); } - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; + _left = left; + _top = top; + _right = right; + _bottom = bottom; } @@ -1208,7 +1206,7 @@ namespace System.Management.Automation.Host /// /// - public + public struct BufferCell { /// @@ -1219,11 +1217,11 @@ namespace System.Management.Automation.Host public char Character { - get { return character; } - set { character = value; } + get { return _character; } + set { _character = value; } } - private char character; - + private char _character; + // we reuse System.ConsoleColor - it's in the core assembly, and I think it would be confusing to create another // essentially identical enum @@ -1236,11 +1234,11 @@ namespace System.Management.Automation.Host public ConsoleColor ForegroundColor { - get { return foregroundColor; } - set { foregroundColor = value; } + get { return _foregroundColor; } + set { _foregroundColor = value; } } - private ConsoleColor foregroundColor; - + private ConsoleColor _foregroundColor; + /// /// /// Gets and sets the background color @@ -1249,10 +1247,10 @@ namespace System.Management.Automation.Host public ConsoleColor BackgroundColor { - get { return backgroundColor; } - set { backgroundColor = value; } + get { return _backgroundColor; } + set { _backgroundColor = value; } } - private ConsoleColor backgroundColor; + private ConsoleColor _backgroundColor; /// /// @@ -1262,11 +1260,11 @@ namespace System.Management.Automation.Host public BufferCellType BufferCellType { - get { return bufferCellType; } - set { bufferCellType = value; } + get { return _bufferCellType; } + set { _bufferCellType = value; } } - private BufferCellType bufferCellType; + private BufferCellType _bufferCellType; @@ -1300,10 +1298,10 @@ namespace System.Management.Automation.Host public BufferCell(char character, ConsoleColor foreground, ConsoleColor background, BufferCellType bufferCellType) { - this.character = character; - this.foregroundColor = foreground; - this.backgroundColor = background; - this.bufferCellType = bufferCellType; + _character = character; + _foregroundColor = foreground; + _backgroundColor = background; + _bufferCellType = bufferCellType; } @@ -1509,7 +1507,7 @@ namespace System.Management.Automation.Host /// /// - public abstract + public abstract class PSHostRawUserInterface { /// @@ -1517,7 +1515,7 @@ namespace System.Management.Automation.Host /// Protected constructor which does nothing. Provided per .Net design guidelines section 4.3.1 /// /// - + protected PSHostRawUserInterface() { @@ -1759,7 +1757,7 @@ namespace System.Management.Automation.Host /// /// - public + public KeyInfo ReadKey() { @@ -1861,7 +1859,7 @@ namespace System.Management.Automation.Host } - + /// /// /// Copies the array into the screen buffer at the @@ -1888,7 +1886,7 @@ namespace System.Management.Automation.Host /// /// - public abstract + public abstract void SetBufferContents(Coordinates origin, BufferCell[,] contents); @@ -1995,7 +1993,7 @@ namespace System.Management.Automation.Host public abstract BufferCell[,] GetBufferContents(Rectangle rectangle); - + /// @@ -2039,9 +2037,9 @@ namespace System.Management.Automation.Host void ScrollBufferContents ( - Rectangle source, + Rectangle source, Coordinates destination, - Rectangle clip, + Rectangle clip, BufferCell fill ); @@ -2234,7 +2232,7 @@ namespace System.Management.Automation.Host BufferCell[,] NewBufferCellArray(string[] contents, ConsoleColor foregroundColor, ConsoleColor backgroundColor) { - #pragma warning disable 56506 +#pragma warning disable 56506 if (contents == null) { @@ -2291,7 +2289,7 @@ namespace System.Management.Automation.Host } } return results; - #pragma warning restore 56506 +#pragma warning restore 56506 } #pragma warning restore 56506 diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 1f22a655a..6fc29050d 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1,4 +1,4 @@ - /********************************************************************++ +/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ @@ -42,7 +42,7 @@ namespace System.Management.Automation.Host { get; } - + /// /// Returns true for hosts that support VT100 like virtual terminals. /// @@ -159,7 +159,7 @@ namespace System.Management.Automation.Host // expressly not checking for value == null so that attempts to write a null cause an exception - if ( (value !=null) && (value.Length != 0)) + if ((value != null) && (value.Length != 0)) { Write(foregroundColor, backgroundColor, value); } @@ -232,7 +232,7 @@ namespace System.Management.Automation.Host /// informational messages. These should not be displayed to the user by default, but may be useful to display in /// a separate area of the user interface. /// - public virtual void WriteInformation(InformationRecord record) {} + public virtual void WriteInformation(InformationRecord record) { } // Gets the state associated with PowerShell transcription. // @@ -250,25 +250,25 @@ namespace System.Management.Automation.Host LocalRunspace localRunspace = Runspace.DefaultRunspace as LocalRunspace; if (localRunspace != null) { - volatileTranscriptionData = localRunspace.TranscriptionData; - if (volatileTranscriptionData != null) - { - return volatileTranscriptionData; + _volatileTranscriptionData = localRunspace.TranscriptionData; + if (_volatileTranscriptionData != null) + { + return _volatileTranscriptionData; } } - + // Otherwise, use the last stored transcription data. This will let us transcribe // errors where the runspace has gone away. - if(volatileTranscriptionData != null) + if (_volatileTranscriptionData != null) { - return volatileTranscriptionData; + return _volatileTranscriptionData; } TranscriptionData temporaryTranscriptionData = new TranscriptionData(); return temporaryTranscriptionData; } } - private TranscriptionData volatileTranscriptionData; + private TranscriptionData _volatileTranscriptionData; /// /// Transcribes a command being invoked @@ -354,7 +354,7 @@ namespace System.Management.Automation.Host if (String.Equals(helperCommand, commandName, StringComparison.OrdinalIgnoreCase)) { IgnoreCommand(logElement, invocation); - + // Record that this is a helper command. In this case, we ignore even the results // from Out-Default TranscriptionData.IsHelperCommand = true; @@ -443,7 +443,7 @@ namespace System.Management.Automation.Host // Add bits from PSVersionTable StringBuilder psVersionInfo = new StringBuilder(); Hashtable versionInfo = PSVersionInfo.GetPSVersionTable(); - foreach(string versionKey in versionInfo.Keys) + foreach (string versionKey in versionInfo.Keys) { Object value = versionInfo[versionKey]; @@ -489,7 +489,7 @@ namespace System.Management.Automation.Host LogTranscriptFooter(stoppedTranscript); stoppedTranscript.Dispose(); TranscriptionData.Transcripts.Remove(stoppedTranscript); - + return stoppedTranscript.Path; } @@ -532,8 +532,8 @@ namespace System.Management.Automation.Host LogTranscriptFooter(TranscriptionData.SystemTranscript); TranscriptionData.SystemTranscript.Dispose(); TranscriptionData.SystemTranscript = null; - - lock(systemTranscriptLock) + + lock (s_systemTranscriptLock) { systemTranscript = null; } @@ -548,12 +548,12 @@ namespace System.Management.Automation.Host /// The text to be transcribed. internal void TranscribeResult(Runspace sourceRunspace, string resultText) { - if(IsTranscribing) + if (IsTranscribing) { // If the runspace that this result applies to is not the current runspace, update Runspace.DefaultRunspace // so that the transcript paths / etc. will be available to the TranscriptionData accessor. Runspace originalDefaultRunspace = null; - if(sourceRunspace != null) + if (sourceRunspace != null) { originalDefaultRunspace = Runspace.DefaultRunspace; Runspace.DefaultRunspace = sourceRunspace; @@ -587,7 +587,7 @@ namespace System.Management.Automation.Host } finally { - if(originalDefaultRunspace != null) + if (originalDefaultRunspace != null) { Runspace.DefaultRunspace = originalDefaultRunspace; } @@ -650,7 +650,7 @@ namespace System.Management.Automation.Host { lock (transcript.OutputToLog) { - if(transcript.OutputToLog.Count == 0) + if (transcript.OutputToLog.Count == 0) { continue; } @@ -773,7 +773,7 @@ namespace System.Management.Automation.Host /// /// /// - public abstract PSCredential PromptForCredential( string caption, string message, + public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName ); @@ -807,7 +807,7 @@ namespace System.Management.Automation.Host /// /// /// - public abstract PSCredential PromptForCredential( string caption, string message, + public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options ); @@ -876,7 +876,7 @@ namespace System.Management.Automation.Host // Otherwise, populate the static variable with the result of the group policy setting. // // This way, multiple runspaces opened by the same process will share the same transcript. - lock (systemTranscriptLock) + lock (s_systemTranscriptLock) { if (systemTranscript == null) { @@ -888,14 +888,14 @@ namespace System.Management.Automation.Host return systemTranscript; } internal static TranscriptionOption systemTranscript = null; - private static Object systemTranscriptLock = new Object(); + private static Object s_systemTranscriptLock = new Object(); private static TranscriptionOption GetTranscriptOptionFromSettings(Dictionary settings, TranscriptionOption currentTranscript) { TranscriptionOption transcript = null; object keyValue = null; - if(settings.TryGetValue("EnableTranscripting", out keyValue)) + if (settings.TryGetValue("EnableTranscripting", out keyValue)) { if (String.Equals(keyValue.ToString(), "1", StringComparison.OrdinalIgnoreCase)) { @@ -908,7 +908,7 @@ namespace System.Management.Automation.Host // Pull out the transcript path object outputDirectoryValue = null; - if(settings.TryGetValue("OutputDirectory", out outputDirectoryValue)) + if (settings.TryGetValue("OutputDirectory", out outputDirectoryValue)) { string outputDirectoryString = outputDirectoryValue as string; transcript.Path = GetTranscriptPath(outputDirectoryString, true); @@ -922,7 +922,7 @@ namespace System.Management.Automation.Host object enableInvocationHeaderValue = null; if (settings.TryGetValue("EnableInvocationHeader", out enableInvocationHeaderValue)) { - if(String.Equals("1", enableInvocationHeaderValue.ToString(), StringComparison.OrdinalIgnoreCase)) + if (String.Equals("1", enableInvocationHeaderValue.ToString(), StringComparison.OrdinalIgnoreCase)) { transcript.IncludeInvocationHeader = true; } @@ -941,13 +941,13 @@ namespace System.Management.Automation.Host internal static string GetTranscriptPath(string baseDirectory, bool includeDate) { - if(String.IsNullOrEmpty(baseDirectory)) + if (String.IsNullOrEmpty(baseDirectory)) { baseDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } else { - if(! Path.IsPathRooted(baseDirectory)) + if (!Path.IsPathRooted(baseDirectory)) { baseDirectory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @@ -955,7 +955,7 @@ namespace System.Management.Automation.Host } } - if(includeDate) + if (includeDate) { baseDirectory = Path.Combine(baseDirectory, DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); } @@ -1021,12 +1021,12 @@ namespace System.Management.Automation.Host { get { - return path; + return _path; } set { - path = value; + _path = value; Encoding = Encoding.UTF8; FileSystemCmdletProviderEncoding fileEncoding = Utils.GetEncoding(value); @@ -1035,9 +1035,9 @@ namespace System.Management.Automation.Host { Encoding = Utils.GetEncodingFromEnum(fileEncoding); } - } + } } - private string path; + private string _path; /// /// Any output to log for this transcript. @@ -1070,53 +1070,52 @@ namespace System.Management.Automation.Host { lock (OutputBeingLogged) { - if (!disposed) + if (!_disposed) { - if (contentWriter == null) + if (_contentWriter == null) { try { // Try to first open the file with permissions that will allow us to read from it // later. - contentWriter = new StreamWriter( + _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read), this.Encoding); - contentWriter.BaseStream.Seek(0, SeekOrigin.End); + _contentWriter.BaseStream.Seek(0, SeekOrigin.End); } - catch(IOException) + catch (IOException) { // If that doesn't work (i.e.: logging to a tightly-ACL'd share), request fewer // file permissions. - contentWriter = new StreamWriter( + _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), this.Encoding); - } - contentWriter.AutoFlush = true; + _contentWriter.AutoFlush = true; } foreach (string line in this.OutputBeingLogged) { - contentWriter.WriteLine(line); + _contentWriter.WriteLine(line); } } OutputBeingLogged.Clear(); } } - StreamWriter contentWriter = null; + private StreamWriter _contentWriter = null; /// /// Disposes this runspace instance. Dispose will close the runspace if not closed already. /// public void Dispose() { - if (disposed) { return; } + if (_disposed) { return; } // Wait for any pending output to be flushed to disk so that Stop-Transcript // can be trusted to immediately have all content from that session in the file) int outputWait = 0; - while( + while ( (outputWait < 1000) && ((OutputToLog.Count > 0) || (OutputBeingLogged.Count > 0))) { @@ -1124,16 +1123,16 @@ namespace System.Management.Automation.Host outputWait += 100; } - if (contentWriter != null) + if (_contentWriter != null) { - contentWriter.Flush(); - contentWriter.Dispose(); - contentWriter = null; + _contentWriter.Flush(); + _contentWriter.Dispose(); + _contentWriter = null; } - disposed = true; + _disposed = true; } - bool disposed = false; + private bool _disposed = false; } /// @@ -1183,7 +1182,7 @@ namespace System.Management.Automation.Host /// /// 1. Cannot process the hot key because a question mark ("?") cannot be used as a hot key. /// - internal static void BuildHotkeysAndPlainLabels(Collection choices, + internal static void BuildHotkeysAndPlainLabels(Collection choices, out string[,] hotkeysAndPlainLabels) { // we will allocate the result array @@ -1270,7 +1269,6 @@ namespace System.Management.Automation.Host return result; } } - } // namespace System.Management.Automation.Host diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs index 74b4f0519..004ffcc73 100644 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs @@ -39,10 +39,10 @@ namespace Microsoft.PowerShell /// internal class VistaCultureInfo : CultureInfo { - private string[] m_fallbacks; + private string[] _fallbacks; // Cache the immediate parent and immediate fallback - private VistaCultureInfo parentCI = null; - private object syncObject = new object(); + private VistaCultureInfo _parentCI = null; + private object _syncObject = new object(); /// /// Constructs a CultureInfo that keeps track of fallbacks @@ -55,7 +55,7 @@ namespace Microsoft.PowerShell string[] fallbacks) : base(name) { - m_fallbacks = fallbacks; + _fallbacks = fallbacks; } /// @@ -76,21 +76,21 @@ namespace Microsoft.PowerShell return ImmediateParent; } - + // Check whether we have any fallback specified // MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK // returns fallback cultures (specified by the user) // and also adds neutral culture where appropriate. // Ex: ja-jp ja en-us en - while((null != m_fallbacks) && (m_fallbacks.Length > 0)) + while ((null != _fallbacks) && (_fallbacks.Length > 0)) { - string fallback = m_fallbacks[0]; + string fallback = _fallbacks[0]; string[] fallbacksForParent = null; - if (m_fallbacks.Length > 1) + if (_fallbacks.Length > 1) { - fallbacksForParent = new string[m_fallbacks.Length - 1]; - Array.Copy(m_fallbacks, 1, fallbacksForParent, 0, m_fallbacks.Length - 1); + fallbacksForParent = new string[_fallbacks.Length - 1]; + Array.Copy(_fallbacks, 1, fallbacksForParent, 0, _fallbacks.Length - 1); } try @@ -101,9 +101,9 @@ namespace Microsoft.PowerShell // the next culture in the list. catch (ArgumentException) { - m_fallbacks = fallbacksForParent; + _fallbacks = fallbacksForParent; } - } + } //no fallbacks..just return base parent return base.Parent; @@ -118,21 +118,21 @@ namespace Microsoft.PowerShell { get { - if (null == parentCI) + if (null == _parentCI) { - lock (syncObject) + lock (_syncObject) { - if (null == parentCI) + if (null == _parentCI) { string parentCulture = base.Parent.Name; // remove the parentCulture from the m_fallbacks list. // ie., remove duplicates from the parent heirarchy. string[] fallbacksForTheParent = null; - if (null != m_fallbacks) + if (null != _fallbacks) { - fallbacksForTheParent = new string[m_fallbacks.Length]; + fallbacksForTheParent = new string[_fallbacks.Length]; int currentIndex = 0; - foreach (string culture in m_fallbacks) + foreach (string culture in _fallbacks) { if (!parentCulture.Equals(culture, StringComparison.OrdinalIgnoreCase)) { @@ -143,17 +143,17 @@ namespace Microsoft.PowerShell // There is atlease 1 duplicate in m_fallbacks which was not added to // fallbacksForTheParent array. Resize the array to take care of this. - if (m_fallbacks.Length != currentIndex) + if (_fallbacks.Length != currentIndex) { Array.Resize(ref fallbacksForTheParent, currentIndex); } } - parentCI = new VistaCultureInfo(parentCulture, fallbacksForTheParent); + _parentCI = new VistaCultureInfo(parentCulture, fallbacksForTheParent); } } } - return parentCI; + return _parentCI; } } @@ -163,7 +163,7 @@ namespace Microsoft.PowerShell /// Cloned custom CultureInfo public override object Clone() { - return new VistaCultureInfo(base.Name, m_fallbacks); + return new VistaCultureInfo(base.Name, _fallbacks); } } @@ -172,9 +172,9 @@ namespace Microsoft.PowerShell /// internal static class NativeCultureResolver { - private static CultureInfo m_uiCulture = null; - private static CultureInfo m_Culture = null; - private static object m_syncObject = new object(); + private static CultureInfo s_uiCulture = null; + private static CultureInfo s_culture = null; + private static object s_syncObject = new object(); /// /// Gets the UICulture to be used by console host @@ -183,18 +183,18 @@ namespace Microsoft.PowerShell { get { - if (null == m_uiCulture) + if (null == s_uiCulture) { - lock (m_syncObject) + lock (s_syncObject) { - if (null == m_uiCulture) + if (null == s_uiCulture) { - m_uiCulture = GetUICulture(); + s_uiCulture = GetUICulture(); } } } - return (CultureInfo)m_uiCulture.Clone(); + return (CultureInfo)s_uiCulture.Clone(); } } @@ -202,18 +202,18 @@ namespace Microsoft.PowerShell { get { - if (null == m_Culture) + if (null == s_culture) { - lock (m_syncObject) + lock (s_syncObject) { - if (null == m_Culture) + if (null == s_culture) { - m_Culture = GetCulture(); + s_culture = GetCulture(); } } } - return m_Culture; + return s_culture; } } @@ -231,8 +231,8 @@ namespace Microsoft.PowerShell { if (!IsVistaAndLater()) { - m_uiCulture = EmulateDownLevel(); - return m_uiCulture; + s_uiCulture = EmulateDownLevel(); + return s_uiCulture; } // We are running on Vista @@ -252,16 +252,16 @@ namespace Microsoft.PowerShell Array.Copy(fallbacks, 1, fallbacksForParent, 0, fallbacks.Length - 1); } - m_uiCulture = new VistaCultureInfo(fallback, fallbacksForParent); - return m_uiCulture; + s_uiCulture = new VistaCultureInfo(fallback, fallbacksForParent); + return s_uiCulture; } catch (ArgumentException) { } } - m_uiCulture = EmulateDownLevel(); - return m_uiCulture; + s_uiCulture = EmulateDownLevel(); + return s_uiCulture; } [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "In XP and below GetUserDefaultLocaleName is not available")] @@ -301,7 +301,6 @@ namespace Microsoft.PowerShell returnValue = CultureInfo.CreateSpecificCulture( returnValue.GetConsoleFallbackUICulture().Name); } - } catch (ArgumentException) { @@ -378,7 +377,7 @@ namespace Microsoft.PowerShell // set Console CodePage filter. // The MSDN documentation does not call this out explicitly. Opened // Bug 950 (Windows Developer Content) to track this. - if (!SetThreadPreferredUILanguages(MUI_CONSOLE_FILTER, null, IntPtr.Zero)) + if (!SetThreadPreferredUILanguages(s_MUI_CONSOLE_FILTER, null, IntPtr.Zero)) { return returnval; } @@ -390,7 +389,7 @@ namespace Microsoft.PowerShell // and also adds neutral culture where appropriate. // Ex: ja-jp ja en-us en if (!GetThreadPreferredUILanguages( - MUI_LANGUAGE_NAME | MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK, + s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK, out numberLangs, null, out bufferSize)) @@ -406,7 +405,7 @@ namespace Microsoft.PowerShell // Now get the actual value if (!GetThreadPreferredUILanguages( - MUI_LANGUAGE_NAME | MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK, + s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK, out numberLangs, langBufferPtr, // Pointer to a buffer in which this function retrieves an ordered, null-delimited list. out bufferSize)) @@ -487,10 +486,10 @@ namespace Microsoft.PowerShell internal static extern Int16 SetThreadUILanguage(Int16 langId); //private static int MUI_LANGUAGE_ID = 0x4; - private static int MUI_LANGUAGE_NAME = 0x8; - private static int MUI_CONSOLE_FILTER = 0x100; - private static int MUI_MERGE_USER_FALLBACK = 0x20; - private static int MUI_MERGE_SYSTEM_FALLBACK = 0x10; + private static int s_MUI_LANGUAGE_NAME = 0x8; + private static int s_MUI_CONSOLE_FILTER = 0x100; + private static int s_MUI_MERGE_USER_FALLBACK = 0x20; + private static int s_MUI_MERGE_SYSTEM_FALLBACK = 0x10; #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 405b63ffd..942989567 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -8,7 +8,6 @@ using System.Collections.ObjectModel; namespace System.Management.Automation { - /// /// Defines a PowerShell command / script object which can be used with /// object. @@ -17,9 +16,9 @@ namespace System.Management.Automation { #region Private Fields - private PowerShell owner; - private CommandCollection commands; - private Command currentCommand; + private PowerShell _owner; + private CommandCollection _commands; + private Command _currentCommand; #endregion @@ -39,13 +38,13 @@ namespace System.Management.Automation /// internal PSCommand(PSCommand commandToClone) { - commands = new CommandCollection(); + _commands = new CommandCollection(); foreach (Command command in commandToClone.Commands) { - Command clone = command.Clone () ; + Command clone = command.Clone(); // Attach the cloned Command to this instance. - commands.Add(clone); - currentCommand = clone; + _commands.Add(clone); + _currentCommand = clone; } } @@ -55,9 +54,9 @@ namespace System.Management.Automation /// Command object to use internal PSCommand(Command command) { - currentCommand = command; - commands = new CommandCollection(); - commands.Add(currentCommand); + _currentCommand = command; + _commands = new CommandCollection(); + _commands.Add(_currentCommand); } #endregion @@ -93,13 +92,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("cmdlet"); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand = new Command(command, false); - commands.Add(currentCommand); + _currentCommand = new Command(command, false); + _commands.Add(_currentCommand); return this; } @@ -136,13 +135,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("cmdlet"); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand = new Command(cmdlet, false, useLocalScope); - commands.Add(currentCommand); + _currentCommand = new Command(cmdlet, false, useLocalScope); + _commands.Add(_currentCommand); return this; } @@ -177,13 +176,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("script"); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand = new Command(script, true); - commands.Add(currentCommand); + _currentCommand = new Command(script, true); + _commands.Add(_currentCommand); return this; } @@ -221,13 +220,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("script"); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand = new Command(script, true, useLocalScope); - commands.Add(currentCommand); + _currentCommand = new Command(script, true, useLocalScope); + _commands.Add(_currentCommand); return this; } @@ -258,13 +257,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("command"); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand = command; - commands.Add(currentCommand); + _currentCommand = command; + _commands.Add(_currentCommand); return this; } @@ -299,16 +298,16 @@ namespace System.Management.Automation /// public PSCommand AddParameter(string parameterName, object value) { - if (null == currentCommand) + if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, - new object[] {"PSCommand"}); + new object[] { "PSCommand" }); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand.Parameters.Add(parameterName, value); + _currentCommand.Parameters.Add(parameterName, value); return this; } @@ -339,16 +338,16 @@ namespace System.Management.Automation /// public PSCommand AddParameter(string parameterName) { - if (null == currentCommand) + if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, - new object[] {"PSCommand"}); + new object[] { "PSCommand" }); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand.Parameters.Add(parameterName, true); + _currentCommand.Parameters.Add(parameterName, true); return this; } @@ -380,16 +379,16 @@ namespace System.Management.Automation /// public PSCommand AddArgument(object value) { - if (null == currentCommand) + if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, - new object[] {"PSCommand"}); + new object[] { "PSCommand" }); } - if (owner != null) + if (_owner != null) { - owner.AssertChangesAreAccepted(); + _owner.AssertChangesAreAccepted(); } - currentCommand.Parameters.Add(null, value); + _currentCommand.Parameters.Add(null, value); return this; } @@ -413,12 +412,12 @@ namespace System.Management.Automation /// public PSCommand AddStatement() { - if (commands.Count == 0) + if (_commands.Count == 0) { return this; } - commands[commands.Count - 1].IsEndOfStatement = true; + _commands[_commands.Count - 1].IsEndOfStatement = true; return this; } @@ -434,7 +433,7 @@ namespace System.Management.Automation { get { - return commands; + return _commands; } } @@ -445,11 +444,11 @@ namespace System.Management.Automation { get { - return owner; + return _owner; } set { - owner = value; + _owner = value; } } @@ -458,8 +457,8 @@ namespace System.Management.Automation /// public void Clear() { - commands.Clear(); - currentCommand = null; + _commands.Clear(); + _currentCommand = null; } /// @@ -498,12 +497,12 @@ namespace System.Management.Automation /// private void Initialize(string command, bool isScript, bool? useLocalScope) { - commands = new CommandCollection(); + _commands = new CommandCollection(); if (command != null) { - currentCommand = new Command(command, isScript, useLocalScope); - commands.Add(currentCommand); + _currentCommand = new Command(command, isScript, useLocalScope); + _commands.Add(_currentCommand); } } diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 6200984c8..3d120d02d 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -28,9 +28,9 @@ namespace System.Management.Automation { #region Private Data - private int index; - private Guid psInstanceId; - + private int _index; + private Guid _psInstanceId; + #endregion #region Constructor @@ -48,8 +48,8 @@ namespace System.Management.Automation /// internal DataAddedEventArgs(Guid psInstanceId, int index) { - this.psInstanceId = psInstanceId; - this.index = index; + _psInstanceId = psInstanceId; + _index = index; } #endregion @@ -59,14 +59,14 @@ namespace System.Management.Automation /// /// Index at which the data is added. /// - public int Index { get { return this.index; } } + public int Index { get { return _index; } } /// /// PowerShell InstanceId which added this data. /// Guid.Empty, if the data is not added by a PowerShell /// instance. /// - public Guid PowerShellInstanceId { get { return this.psInstanceId; } } + public Guid PowerShellInstanceId { get { return _psInstanceId; } } #endregion } @@ -80,9 +80,9 @@ namespace System.Management.Automation { #region Private Data - private Guid psInstanceId; - private Object itemAdded; - + private Guid _psInstanceId; + private Object _itemAdded; + #endregion #region Constructor @@ -100,8 +100,8 @@ namespace System.Management.Automation /// internal DataAddingEventArgs(Guid psInstanceId, object itemAdded) { - this.psInstanceId = psInstanceId; - this.itemAdded = itemAdded; + _psInstanceId = psInstanceId; + _itemAdded = itemAdded; } #endregion @@ -111,14 +111,14 @@ namespace System.Management.Automation /// /// The item about to be added. /// - public Object ItemAdded { get { return this.itemAdded; } } + public Object ItemAdded { get { return _itemAdded; } } /// /// PowerShell InstanceId which added this data. /// Guid.Empty, if the data is not added by a PowerShell /// instance. /// - public Guid PowerShellInstanceId { get { return this.psInstanceId; } } + public Guid PowerShellInstanceId { get { return _psInstanceId; } } #endregion } @@ -133,17 +133,17 @@ namespace System.Management.Automation { #region Private Data - private IList data; - private ManualResetEvent readWaitHandle; - private bool isOpen = true; - private bool releaseOnEnumeration; - private bool isEnumerated; + private IList _data; + private ManualResetEvent _readWaitHandle; + private bool _isOpen = true; + private bool _releaseOnEnumeration; + private bool _isEnumerated; // a counter to keep track of active PowerShell instances // using this buffer. - private int refCount; + private int _refCount; - private object syncObject = new object(); - private bool isDisposed = false; + private object _syncObject = new object(); + private bool _isDisposed = false; /// /// Whether the enumerator needs to be blocking @@ -270,7 +270,7 @@ namespace System.Management.Automation /// The value to convert /// New collection of value, marked as Complete [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", - Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] + Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] public static implicit operator PSDataCollection(Hashtable valueToConvert) { PSDataCollection psdc = new PSDataCollection(); @@ -285,7 +285,7 @@ namespace System.Management.Automation /// The value to convert /// New collection of value, marked as Complete [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", - Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] + Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] public static implicit operator PSDataCollection(T valueToConvert) { PSDataCollection psdc = new PSDataCollection(); @@ -300,7 +300,7 @@ namespace System.Management.Automation /// The value to convert /// New collection of value, marked as Complete [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", - Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] + Justification = "There are already alternates to the implicit casts, ToXXX and FromXXX methods are unnecessary and redundant")] public static implicit operator PSDataCollection(object[] arrayToConvert) { PSDataCollection psdc = new PSDataCollection(); @@ -333,7 +333,7 @@ namespace System.Management.Automation /// internal PSDataCollection(IList listToUse) { - data = listToUse; + _data = listToUse; } /// @@ -355,12 +355,12 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("info"); } - data = listToUse; + _data = listToUse; _blockingEnumerator = info.GetBoolean("BlockingEnumerator"); _dataAddedFrequency = info.GetInt32("DataAddedCount"); EnumeratorNeverBlocks = info.GetBoolean("EnumeratorNeverBlocks"); - isOpen = info.GetBoolean("IsOpen"); + _isOpen = info.GetBoolean("IsOpen"); } #endregion @@ -389,9 +389,9 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { - return isOpen; + return _isOpen; } } } @@ -408,7 +408,7 @@ namespace System.Management.Automation set { bool raiseDataAdded = false; - lock (syncObject) + lock (_syncObject) { _dataAddedFrequency = value; if (_countNewData >= _dataAddedFrequency) @@ -435,7 +435,7 @@ namespace System.Management.Automation { get { - return serializeInput; + return _serializeInput; } set @@ -446,10 +446,10 @@ namespace System.Management.Automation throw new NotSupportedException(PSDataBufferStrings.SerializationNotSupported); } - serializeInput = value; + _serializeInput = value; } } - private bool serializeInput = false; + private bool _serializeInput = false; /// /// Determines whether this PSDataCollection was created implicitly in support of @@ -468,14 +468,14 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { return _sourceGuid; } } set { - lock (syncObject) + lock (_syncObject) { _sourceGuid = value; } @@ -490,16 +490,16 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { - return this.releaseOnEnumeration; + return _releaseOnEnumeration; } } set { - lock (syncObject) + lock (_syncObject) { - this.releaseOnEnumeration = value; + _releaseOnEnumeration = value; } } } @@ -511,16 +511,16 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { - return this.isEnumerated; + return _isEnumerated; } } set { - lock (syncObject) + lock (_syncObject) { - this.isEnumerated = value; + _isEnumerated = value; } } } @@ -536,15 +536,15 @@ namespace System.Management.Automation try { // Close the buffer - lock (syncObject) + lock (_syncObject) { - if (isOpen) + if (_isOpen) { - isOpen = false; + _isOpen = false; raiseEvents = true; // release any threads to notify an event. Enumertor // blocks on this syncObject. - Monitor.PulseAll(syncObject); + Monitor.PulseAll(_syncObject); if (_countNewData > 0) { @@ -559,10 +559,10 @@ namespace System.Management.Automation // raise the events outside of the lock. if (raiseEvents) { - if (null != readWaitHandle) + if (null != _readWaitHandle) { // unblock any readers waiting on the handle - readWaitHandle.Set(); + _readWaitHandle.Set(); } // A temporary variable is used as the Completed may @@ -570,7 +570,7 @@ namespace System.Management.Automation EventHandler tempCompleted = Completed; if (null != tempCompleted) { - tempCompleted(this, EventArgs.Empty); + tempCompleted(this, EventArgs.Empty); } } if (raiseDataAdded) @@ -593,14 +593,14 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { return _blockingEnumerator; } } set { - lock(syncObject) + lock (_syncObject) { _blockingEnumerator = value; @@ -617,7 +617,7 @@ namespace System.Management.Automation // TODO: false doesn't always leading to non-blocking // behavior in an intuitive way. Need to follow up // and fix this - if(_refCountIncrementedForBlockingEnumerator) + if (_refCountIncrementedForBlockingEnumerator) { _refCountIncrementedForBlockingEnumerator = false; DecrementRef(); @@ -625,7 +625,6 @@ namespace System.Management.Automation } } } - } /// @@ -654,30 +653,30 @@ namespace System.Management.Automation /// (or) /// index is equal to or greater than Count. /// - public T this[int index] + public T this[int index] { get { - lock (syncObject) + lock (_syncObject) { - return data[index]; + return _data[index]; } } set { - lock (syncObject) + lock (_syncObject) { - if ((index < 0) || (index >= data.Count)) + if ((index < 0) || (index >= _data.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index, - PSDataBufferStrings.IndexOutOfRange, 0, data.Count - 1); + PSDataBufferStrings.IndexOutOfRange, 0, _data.Count - 1); } - if (serializeInput) + if (_serializeInput) { value = (T)(Object)GetSerializedObject(value); } - data[index] = value; + _data[index] = value; } } } @@ -693,7 +692,7 @@ namespace System.Management.Automation /// public int IndexOf(T item) { - lock (syncObject) + lock (_syncObject) { return InternalIndexOf(item); } @@ -719,7 +718,7 @@ namespace System.Management.Automation /// public void Insert(int index, T item) { - lock (syncObject) + lock (_syncObject) { InternalInsertItem(Guid.Empty, index, item); } @@ -738,12 +737,12 @@ namespace System.Management.Automation /// public void RemoveAt(int index) { - lock (syncObject) + lock (_syncObject) { - if ((index < 0) || (index >= data.Count)) + if ((index < 0) || (index >= _data.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("index", index, - PSDataBufferStrings.IndexOutOfRange, 0, data.Count - 1); + PSDataBufferStrings.IndexOutOfRange, 0, _data.Count - 1); } RemoveItem(index); } @@ -756,16 +755,16 @@ namespace System.Management.Automation /// /// Gets the number of elements contained in the buffer /// - public int Count + public int Count { get { - lock (syncObject) + lock (_syncObject) { - if (data == null) + if (_data == null) return 0; else - return data.Count; + return _data.Count; } } } @@ -773,7 +772,7 @@ namespace System.Management.Automation /// /// Gets a value indicating whether the buffer is read-only. /// - public bool IsReadOnly + public bool IsReadOnly { get { @@ -794,7 +793,7 @@ namespace System.Management.Automation /// public void Add(T item) { - InternalAdd(Guid.Empty, item); + InternalAdd(Guid.Empty, item); } /// @@ -802,11 +801,11 @@ namespace System.Management.Automation /// public void Clear() { - lock (this.syncObject) + lock (_syncObject) { - if (data != null) + if (_data != null) { - data.Clear(); + _data.Clear(); } } } @@ -822,14 +821,14 @@ namespace System.Management.Automation /// public bool Contains(T item) { - lock (this.syncObject) + lock (_syncObject) { - if (serializeInput) + if (_serializeInput) { item = (T)(Object)GetSerializedObject(item); } - return data.Contains(item); + return _data.Contains(item); } } @@ -860,9 +859,9 @@ namespace System.Management.Automation /// public void CopyTo(T[] array, int arrayIndex) { - lock (syncObject) + lock (_syncObject) { - data.CopyTo(array, arrayIndex); + _data.CopyTo(array, arrayIndex); } } @@ -877,7 +876,7 @@ namespace System.Management.Automation /// public bool Remove(T item) { - lock (syncObject) + lock (_syncObject) { int index = InternalIndexOf(item); if (index < 0) @@ -932,11 +931,11 @@ namespace System.Management.Automation int IList.Add(object value) { PSDataCollection.VerifyValueType(value); - int index = data.Count; + int index = _data.Count; InternalAdd(Guid.Empty, (T)value); RaiseEvents(Guid.Empty, index); - return index; + return index; } /// @@ -1095,7 +1094,7 @@ namespace System.Management.Automation { get { - return syncObject; + return _syncObject; } } @@ -1126,9 +1125,9 @@ namespace System.Management.Automation /// void ICollection.CopyTo(Array array, int index) { - lock (this.syncObject) + lock (_syncObject) { - data.CopyTo((T[])array, index); + _data.CopyTo((T[])array, index); } } @@ -1179,24 +1178,24 @@ namespace System.Management.Automation /// maximum number of elements to read internal Collection ReadAndRemove(int readCount) { - Dbg.Assert(null != data, "Collection cannot be null"); + Dbg.Assert(null != _data, "Collection cannot be null"); Dbg.Assert(readCount >= 0, "ReadCount cannot be negative"); int resolvedReadCount = (readCount > 0 ? readCount : Int32.MaxValue); - lock (syncObject) + lock (_syncObject) { // Copy the elements into a new collection // and clear. Collection result = new Collection(); - for(int i = 0; i < resolvedReadCount; i++) + for (int i = 0; i < resolvedReadCount; i++) { - if (data.Count > 0) + if (_data.Count > 0) { - result.Add(data[0]); - data.RemoveAt(0); + result.Add(_data[0]); + _data.RemoveAt(0); } else { @@ -1204,18 +1203,18 @@ namespace System.Management.Automation } } - if (null != readWaitHandle) + if (null != _readWaitHandle) { - if (data.Count > 0 || !isOpen) + if (_data.Count > 0 || !_isOpen) { // release all the waiting threads. - readWaitHandle.Set(); + _readWaitHandle.Set(); } else { // reset the handle so that future // threads will block - readWaitHandle.Reset(); + _readWaitHandle.Reset(); } } @@ -1227,12 +1226,12 @@ namespace System.Management.Automation { T value = default(T); - lock (syncObject) + lock (_syncObject) { - if (data != null && data.Count > 0) + if (_data != null && _data.Count > 0) { - value = data[0]; - data.RemoveAt(0); + value = _data[0]; + _data.RemoveAt(0); } } @@ -1265,12 +1264,12 @@ namespace System.Management.Automation { RaiseDataAddingEvent(psInstanceId, item); - if (serializeInput) + if (_serializeInput) { item = (T)(Object)GetSerializedObject(item); } - data.Insert(index, item); + _data.Insert(index, item); } /// @@ -1285,7 +1284,7 @@ namespace System.Management.Automation /// protected virtual void RemoveItem(int index) { - data.RemoveAt(index); + _data.RemoveAt(index); } #endregion @@ -1304,11 +1303,11 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("info"); } - info.AddValue("Data", data); + info.AddValue("Data", _data); info.AddValue("BlockingEnumerator", _blockingEnumerator); info.AddValue("DataAddedCount", _dataAddedFrequency); info.AddValue("EnumeratorNeverBlocks", EnumeratorNeverBlocks); - info.AddValue("IsOpen", isOpen); + info.AddValue("IsOpen", _isOpen); } #endregion @@ -1323,21 +1322,21 @@ namespace System.Management.Automation { get { - if (null == readWaitHandle) + if (null == _readWaitHandle) { - lock (syncObject) + lock (_syncObject) { - if (null == readWaitHandle) + if (null == _readWaitHandle) { // Create the handle signaled if there are objects in the buffer // or the buffer has been closed. - readWaitHandle = new ManualResetEvent(data.Count > 0 || !isOpen); + _readWaitHandle = new ManualResetEvent(_data.Count > 0 || !_isOpen); } } } - return readWaitHandle; + return _readWaitHandle; } - } + } /// /// Utility method to signal handles and raise events @@ -1354,30 +1353,30 @@ namespace System.Management.Automation private void RaiseEvents(Guid psInstanceId, int index) { bool raiseDataAdded = false; - lock (syncObject) + lock (_syncObject) { - if (null != readWaitHandle) + if (null != _readWaitHandle) { // TODO: Should ObjectDisposedException be caught. - if (data.Count > 0 || !isOpen) + if (_data.Count > 0 || !_isOpen) { // release all the waiting threads. - readWaitHandle.Set(); + _readWaitHandle.Set(); } else { // reset the handle so that future // threads will block - readWaitHandle.Reset(); + _readWaitHandle.Reset(); } } // release any threads to notify an event. Enumertor // blocks on this syncObject. - Monitor.PulseAll(syncObject); + Monitor.PulseAll(_syncObject); _countNewData++; - if (_countNewData >= _dataAddedFrequency || (_countNewData > 0 &&!isOpen)) + if (_countNewData >= _dataAddedFrequency || (_countNewData > 0 && !_isOpen)) { raiseDataAdded = true; _countNewData = 0; @@ -1387,7 +1386,7 @@ namespace System.Management.Automation // store information in case _dataAddedFrequency is updated or collection completes // so that event may be raised using last added data. _lastPsInstanceId = psInstanceId; - _lastIndex = index; + _lastIndex = index; } } @@ -1421,7 +1420,7 @@ namespace System.Management.Automation if (null != tempDataAdded) { tempDataAdded(this, new DataAddedEventArgs(psInstanceId, index)); - } + } } /// @@ -1451,7 +1450,7 @@ namespace System.Management.Automation /// private void InternalInsertItem(Guid psInstanceId, int index, T item) { - if (!isOpen) + if (!_isOpen) { throw PSTraceSource.NewInvalidOperationException(PSDataBufferStrings.WriteToClosedBuffer); } @@ -1480,12 +1479,12 @@ namespace System.Management.Automation // as another thread might add data int index = -1; - lock (syncObject) + lock (_syncObject) { // Add the item and set to raise events // so that events are raised outside of // lock. - index = data.Count; + index = _data.Count; InternalInsertItem(psInstanceId, index, item); } @@ -1521,18 +1520,18 @@ namespace System.Management.Automation int index = -1; bool raiseEvents = false; - lock (syncObject) + lock (_syncObject) { - if (!isOpen) + if (!_isOpen) { throw PSTraceSource.NewInvalidOperationException(PSDataBufferStrings.WriteToClosedBuffer); } - index = data.Count; + index = _data.Count; foreach (object o in collection) { - InsertItem(psInstanceId, data.Count, (T)o); + InsertItem(psInstanceId, _data.Count, (T)o); // set raise events if atlease one item is // added. @@ -1552,9 +1551,9 @@ namespace System.Management.Automation /// internal void AddRef() { - lock (syncObject) + lock (_syncObject) { - refCount++; + _refCount++; } } @@ -1564,23 +1563,23 @@ namespace System.Management.Automation /// internal void DecrementRef() { - lock (syncObject) + lock (_syncObject) { - Dbg.Assert(refCount > 0, "RefCount cannot be <= 0"); + Dbg.Assert(_refCount > 0, "RefCount cannot be <= 0"); - refCount--; - if (refCount != 0 && (!_blockingEnumerator || refCount != 1)) return; + _refCount--; + if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) return; // release threads blocked on waithandle - if (null != readWaitHandle) + if (null != _readWaitHandle) { - readWaitHandle.Set(); + _readWaitHandle.Set(); } // release any threads to notify refCount is 0. Enumertor // blocks on this syncObject and it needs to be notified // when the count becomes 0. - Monitor.PulseAll(syncObject); + Monitor.PulseAll(_syncObject); } } @@ -1598,15 +1597,15 @@ namespace System.Management.Automation /// private int InternalIndexOf(T item) { - if (serializeInput) + if (_serializeInput) { item = (T)(Object)GetSerializedObject(item); } - int count = data.Count; + int count = _data.Count; for (int index = 0; index < count; index++) { - if (object.Equals(data[index], item)) + if (object.Equals(_data[index], item)) { return index; } @@ -1638,7 +1637,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("value", PSDataBufferStrings.CannotConvertToGenericType, value.GetType().FullName, - typeof (T).FullName); + typeof(T).FullName); } } @@ -1657,9 +1656,9 @@ namespace System.Management.Automation else { Object deserialized = PSSerializer.Deserialize(PSSerializer.Serialize(value)); - if(deserialized == null) + if (deserialized == null) { - return (PSObject) deserialized; + return (PSObject)deserialized; } else { @@ -1670,31 +1669,31 @@ namespace System.Management.Automation private bool SerializationWouldHaveNoEffect(PSObject result) { - if(result == null) + if (result == null) { return true; } Object baseObject = PSObject.Base(result); - if(baseObject == null) + if (baseObject == null) { return true; } // Check if it's a primitive known type - if(InternalSerializer.IsPrimitiveKnownType(baseObject.GetType())) + if (InternalSerializer.IsPrimitiveKnownType(baseObject.GetType())) { return true; } // Check if it's a CIM type - if(baseObject is Microsoft.Management.Infrastructure.CimInstance) + if (baseObject is Microsoft.Management.Infrastructure.CimInstance) { return true; } - + // Check if it's got "Deserialized" in its type name - if(result.TypeNames[0].StartsWith("Deserialized", StringComparison.OrdinalIgnoreCase)) + if (result.TypeNames[0].StartsWith("Deserialized", StringComparison.OrdinalIgnoreCase)) { return true; } @@ -1709,7 +1708,7 @@ namespace System.Management.Automation { get { - return syncObject; + return _syncObject; } } @@ -1720,13 +1719,13 @@ namespace System.Management.Automation { get { - return refCount; + return _refCount; } set { - lock (syncObject) + lock (_syncObject) { - refCount = value; + _refCount = value; } } } @@ -1758,9 +1757,9 @@ namespace System.Management.Automation /// internal void Pulse() { - lock (syncObject) + lock (_syncObject) { - Monitor.PulseAll(syncObject); + Monitor.PulseAll(_syncObject); } } @@ -1786,33 +1785,33 @@ namespace System.Management.Automation { if (disposing) { - if (isDisposed) + if (_isDisposed) { return; } - lock (syncObject) + lock (_syncObject) { - if (isDisposed) + if (_isDisposed) { return; } - isDisposed = true; + _isDisposed = true; } Complete(); - lock (this.syncObject) + lock (_syncObject) { - if (readWaitHandle != null) + if (_readWaitHandle != null) { - readWaitHandle.Dispose(); - readWaitHandle = null; + _readWaitHandle.Dispose(); + _readWaitHandle = null; } - if (data != null) + if (_data != null) { - data.Clear(); + _data.Clear(); } } } @@ -1845,9 +1844,9 @@ namespace System.Management.Automation { #region Private Data - private W currentElement; - private int index; - private PSDataCollection collToEnumerate; + private W _currentElement; + private int _index; + private PSDataCollection _collToEnumerate; private bool _neverBlock; #endregion @@ -1865,15 +1864,15 @@ namespace System.Management.Automation /// internal PSDataCollectionEnumerator(PSDataCollection collection, bool neverBlock) { - Dbg.Assert(null != collection, + Dbg.Assert(null != collection, "Collection cannot be null"); - Dbg.Assert(!collection.ReleaseOnEnumeration || !collection.IsEnumerated, + Dbg.Assert(!collection.ReleaseOnEnumeration || !collection.IsEnumerated, "shouldn't enumerate more than once if ReleaseOnEnumeration is true"); - collToEnumerate = collection; - index = 0; - currentElement = default(W); - collToEnumerate.IsEnumerated = true; + _collToEnumerate = collection; + _index = 0; + _currentElement = default(W); + _collToEnumerate.IsEnumerated = true; _neverBlock = neverBlock; } @@ -1894,7 +1893,7 @@ namespace System.Management.Automation { get { - return currentElement; + return _currentElement; } } @@ -1911,7 +1910,7 @@ namespace System.Management.Automation { get { - return currentElement; + return _currentElement; } } @@ -1942,40 +1941,40 @@ namespace System.Management.Automation /// true - to block when no elements are available public bool MoveNext(bool block) { - lock (collToEnumerate.SyncObject) + lock (_collToEnumerate.SyncObject) { do { - if (index < collToEnumerate.Count) + if (_index < _collToEnumerate.Count) { - currentElement = collToEnumerate[index]; - if (collToEnumerate.ReleaseOnEnumeration) + _currentElement = _collToEnumerate[_index]; + if (_collToEnumerate.ReleaseOnEnumeration) { - collToEnumerate[index] = default(W); + _collToEnumerate[_index] = default(W); } - index++; + _index++; return true; } // we have reached the end if either the collection is closed // or no powershell instance is bound to this collection. - if ((0 == collToEnumerate.RefCount) || (!collToEnumerate.IsOpen)) + if ((0 == _collToEnumerate.RefCount) || (!_collToEnumerate.IsOpen)) { return false; } if (block) { - if (collToEnumerate.PulseIdleEvent) + if (_collToEnumerate.PulseIdleEvent) { - collToEnumerate.FireIdleEvent(); - Monitor.Wait(collToEnumerate.SyncObject); + _collToEnumerate.FireIdleEvent(); + Monitor.Wait(_collToEnumerate.SyncObject); } else { // using light-weight monitor to block the current thread instead // of AutoResetEvent. This saves using Kernel objects. - Monitor.Wait(collToEnumerate.SyncObject); + Monitor.Wait(_collToEnumerate.SyncObject); } } else @@ -1992,8 +1991,8 @@ namespace System.Management.Automation /// public void Reset() { - currentElement = default(W); - index = 0; + _currentElement = default(W); + _index = 0; } /// @@ -2014,7 +2013,7 @@ namespace System.Management.Automation /// internal sealed class PSInformationalBuffers { - private Guid psInstanceId; + private Guid _psInstanceId; /// /// Default constructor. @@ -2030,12 +2029,12 @@ namespace System.Management.Automation Dbg.Assert(psInstanceId != Guid.Empty, "PowerShell instance id cannot be Guid.Empty"); - this.psInstanceId = psInstanceId; + _psInstanceId = psInstanceId; progress = new PSDataCollection(); verbose = new PSDataCollection(); debug = new PSDataCollection(); - warning = new PSDataCollection(); - information = new PSDataCollection(); + _warning = new PSDataCollection(); + _information = new PSDataCollection(); } #region Internal Methods / Properties @@ -2088,13 +2087,13 @@ namespace System.Management.Automation /// internal PSDataCollection Warning { - get { return warning; } + get { return _warning; } set { - warning = value; + _warning = value; } } - private PSDataCollection warning; + private PSDataCollection _warning; /// /// A buffer representing Information objects of a PowerShell command invocation. @@ -2102,13 +2101,13 @@ namespace System.Management.Automation /// internal PSDataCollection Information { - get { return information; } + get { return _information; } set { - information = value; + _information = value; } } - private PSDataCollection information; + private PSDataCollection _information; /// /// Adds item to the progress buffer. @@ -2119,7 +2118,7 @@ namespace System.Management.Automation { if (null != progress) { - progress.InternalAdd(psInstanceId, item); + progress.InternalAdd(_psInstanceId, item); } } @@ -2132,7 +2131,7 @@ namespace System.Management.Automation { if (null != verbose) { - verbose.InternalAdd(psInstanceId, item); + verbose.InternalAdd(_psInstanceId, item); } } @@ -2145,7 +2144,7 @@ namespace System.Management.Automation { if (null != debug) { - debug.InternalAdd(psInstanceId, item); + debug.InternalAdd(_psInstanceId, item); } } @@ -2156,9 +2155,9 @@ namespace System.Management.Automation /// internal void AddWarning(WarningRecord item) { - if (null != warning) + if (null != _warning) { - warning.InternalAdd(psInstanceId, item); + _warning.InternalAdd(_psInstanceId, item); } } @@ -2169,9 +2168,9 @@ namespace System.Management.Automation /// internal void AddInformation(InformationRecord item) { - if (null != information) + if (null != _information) { - information.InternalAdd(psInstanceId, item); + _information.InternalAdd(_psInstanceId, item); } } diff --git a/src/System.Management.Automation/engine/hostifaces/Parameter.cs b/src/System.Management.Automation/engine/hostifaces/Parameter.cs index db944bf85..bced50d86 100644 --- a/src/System.Management.Automation/engine/hostifaces/Parameter.cs +++ b/src/System.Management.Automation/engine/hostifaces/Parameter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Management.Automation.Language; using Microsoft.Management.Infrastructure; @@ -27,8 +28,8 @@ namespace System.Management.Automation.Runspaces /// /// Name length is zero after trimming whitespace. /// - public CommandParameter (string name) - : this (name, null) + public CommandParameter(string name) + : this(name, null) { if (name == null) { @@ -96,11 +97,11 @@ namespace System.Management.Automation.Runspaces /// /// The parameter name /// - private string _name; + private string _name; /// /// The parameter value. /// - private object _value; + private object _value; #endregion Private Fields @@ -122,7 +123,7 @@ namespace System.Management.Automation.Runspaces { name = name + " "; } - + Diagnostics.Assert(name != null, "'name' variable should be initialized at this point"); Diagnostics.Assert(name[0].IsDash(), "first character in parameter name must be a dash"); Diagnostics.Assert(name.Trim().Length != 0, "Parameter name has to have some non-whitespace characters in it"); @@ -150,7 +151,7 @@ namespace System.Management.Automation.Runspaces string name = publicParameter.Name; object value = publicParameter.Value; - Debug.Assert( (name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); + Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); if (name == null) { @@ -259,21 +260,21 @@ namespace System.Management.Automation.Runspaces internal CimInstance ToCimInstance() { CimInstance c = InternalMISerializer.CreateCimInstance("PS_Parameter"); - CimProperty nameProperty = InternalMISerializer.CreateCimProperty("Name", this.Name, + CimProperty nameProperty = InternalMISerializer.CreateCimProperty("Name", this.Name, Microsoft.Management.Infrastructure.CimType.String); c.CimInstanceProperties.Add(nameProperty); Microsoft.Management.Infrastructure.CimType cimType = CimConverter.GetCimType(this.Value.GetType()); CimProperty valueProperty; if (cimType == Microsoft.Management.Infrastructure.CimType.Unknown) { - valueProperty = InternalMISerializer.CreateCimProperty("Value", (object) PSMISerializer.Serialize(this.Value), + valueProperty = InternalMISerializer.CreateCimProperty("Value", (object)PSMISerializer.Serialize(this.Value), Microsoft.Management.Infrastructure.CimType.Instance); } else { valueProperty = InternalMISerializer.CreateCimProperty("Value", this.Value, cimType); } - + c.CimInstanceProperties.Add(valueProperty); return c; } @@ -292,7 +293,7 @@ namespace System.Management.Automation.Runspaces /// /// Create a new empty instance of this collection type /// - public CommandParameterCollection () + public CommandParameterCollection() { } @@ -306,9 +307,9 @@ namespace System.Management.Automation.Runspaces /// /// Name length is zero after trimming whitespace. /// - public void Add (string name) + public void Add(string name) { - Add (new CommandParameter (name)); + Add(new CommandParameter(name)); } /// @@ -322,9 +323,9 @@ namespace System.Management.Automation.Runspaces /// /// Name is non null and name length is zero after trimming whitespace. /// - public void Add (string name, object value) + public void Add(string name, object value) { - Add (new CommandParameter (name, value)); + Add(new CommandParameter(name, value)); } } } diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index f11251997..e2f84bf61 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -22,13 +22,13 @@ namespace System.Management.Automation.Runspaces /// from expected state. /// [Serializable] - public class InvalidPipelineStateException : SystemException + public class InvalidPipelineStateException : SystemException { /// /// Initializes a new instance of the InvalidPipelineStateException class /// - public InvalidPipelineStateException () - :base (StringUtil.Format(RunspaceStrings.InvalidPipelineStateStateGeneral)) + public InvalidPipelineStateException() + : base(StringUtil.Format(RunspaceStrings.InvalidPipelineStateStateGeneral)) { } @@ -39,8 +39,8 @@ namespace System.Management.Automation.Runspaces /// /// The error message that explains the reason for the exception. /// - public InvalidPipelineStateException (string message) - :base(message) + public InvalidPipelineStateException(string message) + : base(message) { } @@ -54,8 +54,8 @@ namespace System.Management.Automation.Runspaces /// /// The exception that is the cause of the current exception. /// - public InvalidPipelineStateException (string message, Exception innerException) - :base(message, innerException) + public InvalidPipelineStateException(string message, Exception innerException) + : base(message, innerException) { } @@ -67,7 +67,7 @@ namespace System.Management.Automation.Runspaces /// /// Current state of pipeline /// Expected state of pipeline - internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState) + internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState) : base(message) { _expectedState = expectedState; @@ -91,7 +91,7 @@ namespace System.Management.Automation.Runspaces /// The that contains contextual information /// about the source or destination. /// - private InvalidPipelineStateException (SerializationInfo info, StreamingContext context) + private InvalidPipelineStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } @@ -178,8 +178,8 @@ namespace System.Management.Automation.Runspaces /// Constructor for state changes not resulting from an error. /// /// Execution state - internal PipelineStateInfo (PipelineState state) - :this(state, null) + internal PipelineStateInfo(PipelineState state) + : this(state, null) { } @@ -190,7 +190,7 @@ namespace System.Management.Automation.Runspaces /// A non-null exception if the state change was /// caused by an error,otherwise; null. /// - internal PipelineStateInfo (PipelineState state, Exception reason) + internal PipelineStateInfo(PipelineState state, Exception reason) { _state = state; _reason = reason; @@ -203,7 +203,7 @@ namespace System.Management.Automation.Runspaces /// /// ArgumentNullException when is null. /// - internal PipelineStateInfo (PipelineStateInfo pipelineStateInfo) + internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); @@ -246,9 +246,9 @@ namespace System.Management.Automation.Runspaces /// Clones this object /// /// Cloned object - internal PipelineStateInfo Clone () + internal PipelineStateInfo Clone() { - return new PipelineStateInfo (this); + return new PipelineStateInfo(this); } #region private_fields @@ -272,7 +272,6 @@ namespace System.Management.Automation.Runspaces /// public sealed class PipelineStateEventArgs : EventArgs { - #region constructors /// @@ -283,7 +282,7 @@ namespace System.Management.Automation.Runspaces /// /// ArgumentNullException when is null. /// - internal PipelineStateEventArgs (PipelineStateInfo pipelineStateInfo) + internal PipelineStateEventArgs(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); _pipelineStateInfo = pipelineStateInfo; @@ -316,15 +315,15 @@ namespace System.Management.Automation.Runspaces /// /// Defines a class which can be used to invoke a pipeline of commands. /// - public abstract class Pipeline :IDisposable + public abstract class Pipeline : IDisposable { #region constructor - + /// /// Explicit default constructor /// internal Pipeline(Runspace runspace) - :this(runspace, new CommandCollection()) + : this(runspace, new CommandCollection()) { } @@ -463,7 +462,7 @@ namespace System.Management.Automation.Runspaces return _hadErrors; } } - bool _hadErrors; + private bool _hadErrors; internal void SetHadErrors(bool status) { @@ -492,7 +491,7 @@ namespace System.Management.Automation.Runspaces } } - bool _setPipelineSessionState = true; + private bool _setPipelineSessionState = true; /// /// If this property is true, SessionState is updated for this /// pipeline state. @@ -532,8 +531,8 @@ namespace System.Management.Automation.Runspaces /// internal bool RedirectShellErrorOutputPipe { - get { return this._redirectShellErrorOutputPipe; } - set { this._redirectShellErrorOutputPipe = value; } + get { return _redirectShellErrorOutputPipe; } + set { _redirectShellErrorOutputPipe = value; } } private bool _redirectShellErrorOutputPipe = false; @@ -617,7 +616,7 @@ namespace System.Management.Automation.Runspaces /// public Collection Invoke() { - return Invoke (null); + return Invoke(null); } /// @@ -728,18 +727,18 @@ namespace System.Management.Automation.Runspaces /// /// Synchronous call to stop the running pipeline. /// - public abstract void Stop (); + public abstract void Stop(); /// /// Asynchronous call to stop the running pipeline. /// - public abstract void StopAsync (); + public abstract void StopAsync(); /// /// Creates a new that is a copy of the current instance. /// /// A new that is a copy of this instance. - public abstract Pipeline Copy (); + public abstract Pipeline Copy(); /// /// Connects synchronously to a running command on a remote server. diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index aafe12632..e14402827 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -64,7 +64,7 @@ namespace System.Management.Automation /// The exception that is the cause of the current exception. /// public InvalidPowerShellStateException(string message, Exception innerException) - :base(message, innerException) + : base(message, innerException) { } @@ -77,7 +77,7 @@ namespace System.Management.Automation : base (StringUtil.Format(PowerShellStrings.InvalidPowerShellStateGeneral)) { - currState = currentState; + _currState = currentState; } #region ISerializable Members @@ -98,7 +98,7 @@ namespace System.Management.Automation /// about the source or destination. /// protected - InvalidPowerShellStateException(SerializationInfo info, StreamingContext context) + InvalidPowerShellStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } @@ -112,7 +112,7 @@ namespace System.Management.Automation { get { - return currState; + return _currState; } } @@ -120,7 +120,7 @@ namespace System.Management.Automation /// State of powershell when exception was thrown. /// [NonSerialized] - private PSInvocationState currState = 0; + private PSInvocationState _currState = 0; } #endregion @@ -193,10 +193,10 @@ namespace System.Management.Automation /// A non-null exception if the state change was /// caused by an error,otherwise; null. /// - internal PSInvocationStateInfo (PSInvocationState state, Exception reason) + internal PSInvocationStateInfo(PSInvocationState state, Exception reason) { - executionState = state; - exceptionReason = reason; + _executionState = state; + _exceptionReason = reason; } /// @@ -205,8 +205,8 @@ namespace System.Management.Automation /// internal PSInvocationStateInfo(PipelineStateInfo pipelineStateInfo) { - executionState = (PSInvocationState)((int)pipelineStateInfo.State); - exceptionReason = pipelineStateInfo.Reason; + _executionState = (PSInvocationState)((int)pipelineStateInfo.State); + _exceptionReason = pipelineStateInfo.Reason; } #endregion @@ -222,7 +222,7 @@ namespace System.Management.Automation { get { - return executionState; + return _executionState; } } @@ -238,7 +238,7 @@ namespace System.Management.Automation { get { - return exceptionReason; + return _exceptionReason; } } @@ -253,8 +253,8 @@ namespace System.Management.Automation internal PSInvocationStateInfo Clone() { return new PSInvocationStateInfo( - this.executionState, - this.exceptionReason + _executionState, + _exceptionReason ); } @@ -263,12 +263,12 @@ namespace System.Management.Automation /// /// The current execution state /// - private PSInvocationState executionState; + private PSInvocationState _executionState; /// /// Non-null exception if the execution state change was due to an error. /// - private Exception exceptionReason; + private Exception _exceptionReason; #endregion } @@ -290,7 +290,7 @@ namespace System.Management.Automation internal PSInvocationStateChangedEventArgs(PSInvocationStateInfo psStateInfo) { Dbg.Assert(psStateInfo != null, "caller should validate the parameter"); - executionStateInfo = psStateInfo; + _executionStateInfo = psStateInfo; } #endregion @@ -304,7 +304,7 @@ namespace System.Management.Automation { get { - return executionStateInfo; + return _executionStateInfo; } } @@ -313,7 +313,7 @@ namespace System.Management.Automation /// /// Information about current state of a PowerShell Instance. /// - private PSInvocationStateInfo executionStateInfo; + private PSInvocationStateInfo _executionStateInfo; } #endregion @@ -325,21 +325,21 @@ namespace System.Management.Automation { #region Private Fields - private PSHost host; - private RemoteStreamOptions remoteStreamOptions; - private ActionPreference? errorActionPreference; - private bool addToHistory; + private PSHost _host; + private RemoteStreamOptions _remoteStreamOptions; + private ActionPreference? _errorActionPreference; + private bool _addToHistory; #if !CORECLR // No ApartmentState In CoreCLR private ApartmentState apartmentState; #endif // the following are used to flow the identity to pipeline execution thread - private bool flowImpersonationPolicy; - private System.Security.Principal.WindowsIdentity windowsIdentityToImpersonate; + private bool _flowImpersonationPolicy; + private System.Security.Principal.WindowsIdentity _windowsIdentityToImpersonate; // Invokes a remote command and immediately disconnects, if transport layer // supports this operation. - private bool invokeAndDisconnect; + private bool _invokeAndDisconnect; #endregion @@ -353,10 +353,10 @@ namespace System.Management.Automation #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = ApartmentState.Unknown; #endif - this.host = null; - this.remoteStreamOptions = 0; - this.addToHistory = false; - this.errorActionPreference = null; + _host = null; + _remoteStreamOptions = 0; + _addToHistory = false; + _errorActionPreference = null; } #endregion @@ -366,7 +366,7 @@ namespace System.Management.Automation /// ApartmentState of the thread in which the command /// is executed. /// - public ApartmentState ApartmentState + public ApartmentState ApartmentState { get { @@ -384,11 +384,11 @@ namespace System.Management.Automation /// Host to use with the Runspace when the command is /// executed. /// - public PSHost Host + public PSHost Host { get { - return host; + return _host; } set { @@ -396,7 +396,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Host"); } - host = value; + _host = value; } } @@ -407,11 +407,11 @@ namespace System.Management.Automation { get { - return this.remoteStreamOptions; + return _remoteStreamOptions; } set { - this.remoteStreamOptions = value; + _remoteStreamOptions = value; } } @@ -421,8 +421,8 @@ namespace System.Management.Automation /// public bool AddToHistory { - get { return addToHistory; } - set { addToHistory = value; } + get { return _addToHistory; } + set { _addToHistory = value; } } /// @@ -430,10 +430,10 @@ namespace System.Management.Automation /// public ActionPreference? ErrorActionPreference { - get { return errorActionPreference; } - set { errorActionPreference = value; } + get { return _errorActionPreference; } + set { _errorActionPreference = value; } } - + /// /// Used by Powershell remoting infrastructure to flow identity from calling thread to /// Pipeline Execution Thread. @@ -448,18 +448,18 @@ namespace System.Management.Automation { get { - return flowImpersonationPolicy; + return _flowImpersonationPolicy; } set { - flowImpersonationPolicy = value; + _flowImpersonationPolicy = value; } } internal System.Security.Principal.WindowsIdentity WindowsIdentityToImpersonate { - get { return windowsIdentityToImpersonate; } - set { windowsIdentityToImpersonate = value; } + get { return _windowsIdentityToImpersonate; } + set { _windowsIdentityToImpersonate = value; } } /// @@ -478,8 +478,8 @@ namespace System.Management.Automation /// internal bool InvokeAndDisconnect { - get { return this.invokeAndDisconnect; } - set { this.invokeAndDisconnect = value; } + get { return _invokeAndDisconnect; } + set { _invokeAndDisconnect = value; } } } @@ -488,9 +488,9 @@ namespace System.Management.Automation /// internal class BatchInvocationContext { - private PSCommand command; - private PSDataCollection output; - private AutoResetEvent completionEvent; + private PSCommand _command; + private PSDataCollection _output; + private AutoResetEvent _completionEvent; /// /// Class constructor @@ -499,9 +499,9 @@ namespace System.Management.Automation /// internal BatchInvocationContext(PSCommand command, PSDataCollection output) { - this.command = command; - this.output = output; - completionEvent = new AutoResetEvent(false); + _command = command; + _output = output; + _completionEvent = new AutoResetEvent(false); } /// @@ -509,7 +509,7 @@ namespace System.Management.Automation /// internal PSDataCollection Output { - get { return output; } + get { return _output; } } /// @@ -517,7 +517,7 @@ namespace System.Management.Automation /// internal PSCommand Command { - get { return command; } + get { return _command; } } /// @@ -525,7 +525,7 @@ namespace System.Management.Automation /// internal void Wait() { - completionEvent.WaitOne(); + _completionEvent.WaitOne(); } /// @@ -533,7 +533,7 @@ namespace System.Management.Automation /// internal void Signal() { - completionEvent.Set(); + _completionEvent.Set(); } } @@ -541,7 +541,8 @@ namespace System.Management.Automation /// These flags control whether InvocationInfo is added to items in the Error, Warning, Verbose and Debug /// streams during remote calls /// - [Flags] public enum RemoteStreamOptions + [Flags] + public enum RemoteStreamOptions { /// /// If this flag is set, ErrorRecord will include an instance of InvocationInfo on remote calls @@ -566,7 +567,7 @@ namespace System.Management.Automation /// /// If this flag is set, ErrorRecord, WarningRecord, DebugRecord, and VerboseRecord will include an instance of InvocationInfo on remote calls /// - AddInvocationInfo = AddInvocationInfoToErrorRecord + AddInvocationInfo = AddInvocationInfoToErrorRecord | AddInvocationInfoToWarningRecord | AddInvocationInfoToDebugRecord | AddInvocationInfoToVerboseRecord @@ -580,10 +581,10 @@ namespace System.Management.Automation internal sealed class PowerShellAsyncResult : AsyncResult { #region Private Data / Properties - + // used to track if this AsyncResult is created by a BeginInvoke operation or // a BeginStop operation. - private bool isAssociatedWithAsyncInvoke; + private bool _isAssociatedWithAsyncInvoke; /// /// true if AsyncResult monitors Async BeginInvoke(). @@ -591,7 +592,7 @@ namespace System.Management.Automation /// internal bool IsAssociatedWithAsyncInvoke { - get { return isAssociatedWithAsyncInvoke; } + get { return _isAssociatedWithAsyncInvoke; } } /// @@ -599,10 +600,10 @@ namespace System.Management.Automation /// internal PSDataCollection Output { - get { return output; } + get { return _output; } } - private PSDataCollection output; + private PSDataCollection _output; #endregion @@ -631,8 +632,8 @@ namespace System.Management.Automation bool isCalledFromBeginInvoke) : base(ownerId, callback, state) { - this.isAssociatedWithAsyncInvoke = isCalledFromBeginInvoke; - this.output = output; + _isAssociatedWithAsyncInvoke = isCalledFromBeginInvoke; + _output = output; } #endregion @@ -661,42 +662,42 @@ namespace System.Management.Automation { #region Private Fields - private bool isGetCommandMetadataSpecialPipeline; - private PSCommand psCommand; - private Collection extraCommands; - private bool runningExtraCommands; + private bool _isGetCommandMetadataSpecialPipeline; + private PSCommand _psCommand; + private Collection _extraCommands; + private bool _runningExtraCommands; // worker object which does the invoke - private Worker worker; - private PSInvocationStateInfo invocationStateInfo; - private PowerShellAsyncResult invokeAsyncResult; - private PowerShellAsyncResult stopAsyncResult; - private PowerShellAsyncResult batchAsyncResult; - private PSInvocationSettings batchInvocationSettings; - private PSCommand backupPSCommand; - private bool isNested; - private bool isChild = false; - private object rsConnection; + private Worker _worker; + private PSInvocationStateInfo _invocationStateInfo; + private PowerShellAsyncResult _invokeAsyncResult; + private PowerShellAsyncResult _stopAsyncResult; + private PowerShellAsyncResult _batchAsyncResult; + private PSInvocationSettings _batchInvocationSettings; + private PSCommand _backupPSCommand; + private bool _isNested; + private bool _isChild = false; + private object _rsConnection; - private PSDataCollection outputBuffer; - private bool outputBufferOwner = true; - private PSDataCollection errorBuffer; - private bool errorBufferOwner = true; - private PSInformationalBuffers informationalBuffers; - private PSDataStreams dataStreams; + private PSDataCollection _outputBuffer; + private bool _outputBufferOwner = true; + private PSDataCollection _errorBuffer; + private bool _errorBufferOwner = true; + private PSInformationalBuffers _informationalBuffers; + private PSDataStreams _dataStreams; - private bool isDisposed; - private Guid instanceId; - private object syncObject = new object(); + private bool _isDisposed; + private Guid _instanceId; + private object _syncObject = new object(); - private ClientRemotePowerShell remotePowerShell; - // client remote powershell if the powershell - // is executed with a remote runspace pool - private String historyString; + private ClientRemotePowerShell _remotePowerShell; + // client remote powershell if the powershell + // is executed with a remote runspace pool + private String _historyString; - private ConnectCommandInfo connectCmdInfo; - private bool commandInvokedSynchronously = false; - private bool isBatching = false; - private bool stopBatchExecution = false; + private ConnectCommandInfo _connectCmdInfo; + private bool _commandInvokedSynchronously = false; + private bool _isBatching = false; + private bool _stopBatchExecution = false; #endregion @@ -719,20 +720,20 @@ namespace System.Management.Automation private PowerShell(PSCommand command, Collection extraCommands, object rsConnection) { Dbg.Assert(command != null, "command must not be null"); - this.extraCommands = (extraCommands == null) ? new Collection() : extraCommands; - this.runningExtraCommands = false; - psCommand = command; - psCommand.Owner = this; + _extraCommands = (extraCommands == null) ? new Collection() : extraCommands; + _runningExtraCommands = false; + _psCommand = command; + _psCommand.Owner = this; RemoteRunspace remoteRunspace = rsConnection as RemoteRunspace; - this.rsConnection = remoteRunspace != null ? remoteRunspace.RunspacePool : rsConnection; - instanceId = Guid.NewGuid(); - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.NotStarted, null); - outputBuffer = null; - outputBufferOwner = true; - errorBuffer = new PSDataCollection(); - errorBufferOwner = true; - informationalBuffers = new PSInformationalBuffers(instanceId); - dataStreams = new PSDataStreams(this); + _rsConnection = remoteRunspace != null ? remoteRunspace.RunspacePool : rsConnection; + _instanceId = Guid.NewGuid(); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.NotStarted, null); + _outputBuffer = null; + _outputBufferOwner = true; + _errorBuffer = new PSDataCollection(); + _errorBufferOwner = true; + _informationalBuffers = new PSInformationalBuffers(_instanceId); + _dataStreams = new PSDataStreams(this); } /// @@ -744,27 +745,27 @@ namespace System.Management.Automation internal PowerShell(ConnectCommandInfo connectCmdInfo, object rsConnection) : this(new PSCommand(), null, rsConnection) { - this.extraCommands = new Collection(); - this.runningExtraCommands = false; + _extraCommands = new Collection(); + _runningExtraCommands = false; AddCommand(connectCmdInfo.Command); - this.connectCmdInfo = connectCmdInfo; + _connectCmdInfo = connectCmdInfo; // The command ID is passed to the PSRP layer through the PowerShell instanceID. - this.instanceId = this.connectCmdInfo.CommandId; + _instanceId = _connectCmdInfo.CommandId; - this.invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, null); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, null); if (rsConnection is RemoteRunspace) { - this.runspace = rsConnection as Runspace; - this.runspacePool = ((RemoteRunspace)rsConnection).RunspacePool; + _runspace = rsConnection as Runspace; + _runspacePool = ((RemoteRunspace)rsConnection).RunspacePool; } else if (rsConnection is RunspacePool) { - this.runspacePool = (RunspacePool)rsConnection; + _runspacePool = (RunspacePool)rsConnection; } - Dbg.Assert(this.runspacePool != null, "Invalid rsConnection parameter>"); - this.remotePowerShell = new ClientRemotePowerShell(this, this.runspacePool.RemoteRunspacePoolInternal); + Dbg.Assert(_runspacePool != null, "Invalid rsConnection parameter>"); + _remotePowerShell = new ClientRemotePowerShell(this, _runspacePool.RemoteRunspacePoolInternal); } /// @@ -777,23 +778,23 @@ namespace System.Management.Automation internal PowerShell(ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, RunspacePool runspacePool) { - this.extraCommands = new Collection(); - this.runningExtraCommands = false; - rsConnection = runspacePool; - instanceId = Guid.NewGuid(); - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.NotStarted, null); - informationalBuffers = new PSInformationalBuffers(instanceId); - dataStreams = new PSDataStreams(this); - + _extraCommands = new Collection(); + _runningExtraCommands = false; + _rsConnection = runspacePool; + _instanceId = Guid.NewGuid(); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.NotStarted, null); + _informationalBuffers = new PSInformationalBuffers(_instanceId); + _dataStreams = new PSDataStreams(this); + PSDataCollectionStream outputdatastream = (PSDataCollectionStream)outputstream; - outputBuffer = outputdatastream.ObjectStore; + _outputBuffer = outputdatastream.ObjectStore; PSDataCollectionStream errordatastream = (PSDataCollectionStream)errorstream; - errorBuffer = errordatastream.ObjectStore; + _errorBuffer = errordatastream.ObjectStore; if (runspacePool != null && runspacePool.RemoteRunspacePoolInternal != null) { - remotePowerShell = new ClientRemotePowerShell(this, runspacePool.RemoteRunspacePoolInternal); + _remotePowerShell = new ClientRemotePowerShell(this, runspacePool.RemoteRunspacePoolInternal); } } @@ -810,21 +811,21 @@ namespace System.Management.Automation ObjectStreamBase errorstream, RunspacePool runspacePool) : this(inputstream, outputstream, errorstream, runspacePool) { - this.extraCommands = new Collection(); - this.runningExtraCommands = false; - this.psCommand = new PSCommand(); - psCommand.Owner = this; - this.runspacePool = runspacePool; + _extraCommands = new Collection(); + _runningExtraCommands = false; + _psCommand = new PSCommand(); + _psCommand.Owner = this; + _runspacePool = runspacePool; AddCommand(connectCmdInfo.Command); - this.connectCmdInfo = connectCmdInfo; + _connectCmdInfo = connectCmdInfo; // The command ID is passed to the PSRP layer through the PowerShell instanceID. - this.instanceId = this.connectCmdInfo.CommandId; + _instanceId = _connectCmdInfo.CommandId; - this.invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, null); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, null); - this.remotePowerShell = new ClientRemotePowerShell(this, runspacePool.RemoteRunspacePoolInternal); + _remotePowerShell = new ClientRemotePowerShell(this, runspacePool.RemoteRunspacePoolInternal); } /// @@ -839,21 +840,21 @@ namespace System.Management.Automation { Dbg.Assert(command != null, "A command collection need to be specified"); - psCommand = new PSCommand(command[0]); - psCommand.Owner = this; + _psCommand = new PSCommand(command[0]); + _psCommand.Owner = this; for (int i = 1; i < command.Count; i++) { AddCommand(command[i]); } - this.redirectShellErrorOutputPipe = redirectShellErrorOutputPipe; + _redirectShellErrorOutputPipe = redirectShellErrorOutputPipe; // create the client remote powershell for remoting // communications - if (remotePowerShell == null) + if (_remotePowerShell == null) { - remotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)rsConnection).RemoteRunspacePoolInternal); + _remotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); } // If we get here, we don't call 'Invoke' or any of it's friends on 'this', instead we serialize 'this' in PowerShell.ToPSObjectForRemoting. @@ -862,13 +863,13 @@ namespace System.Management.Automation // in the call to ClientRemotePowerShell.Initialize (which happens just below.) DetermineIsBatching(); - if (isBatching) + if (_isBatching) { SetupAsyncBatchExecution(); } - remotePowerShell.Initialize(inputstream, outputstream, - errorstream, this.informationalBuffers, settings); + _remotePowerShell.Initialize(inputstream, outputstream, + errorstream, _informationalBuffers, settings); } /// @@ -886,21 +887,21 @@ namespace System.Management.Automation // Make sure the associated runspace is valid and connected. CheckRunspacePoolAndConnect(); - if (this.invocationStateInfo.State != PSInvocationState.Disconnected) + if (_invocationStateInfo.State != PSInvocationState.Disconnected) { - throw new InvalidPowerShellStateException(this.invocationStateInfo.State); + throw new InvalidPowerShellStateException(_invocationStateInfo.State); } - this.redirectShellErrorOutputPipe = redirectShellErrorOutputPipe; + _redirectShellErrorOutputPipe = redirectShellErrorOutputPipe; - if (this.remotePowerShell == null) + if (_remotePowerShell == null) { - this.remotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)rsConnection).RemoteRunspacePoolInternal); + _remotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); } - if (!this.remotePowerShell.Initialized) + if (!_remotePowerShell.Initialized) { - this.remotePowerShell.Initialize(inputstream, outputstream, errorstream, this.informationalBuffers, settings); + _remotePowerShell.Initialize(inputstream, outputstream, errorstream, _informationalBuffers, settings); } } @@ -936,10 +937,10 @@ namespace System.Management.Automation throw new InvalidOperationException(PowerShellStrings.NoDefaultRunspaceForPSCreate); } result = new PowerShell(new PSCommand(), null, Runspace.DefaultRunspace); - result.isChild = true; - result.isNested = true; + result._isChild = true; + result._isNested = true; result.IsRunspaceOwner = false; - result.runspace = Runspace.DefaultRunspace; + result._runspace = Runspace.DefaultRunspace; break; case RunspaceMode.NewRunspace: result = new PowerShell(new PSCommand(), null, null); @@ -957,10 +958,10 @@ namespace System.Management.Automation public static PowerShell Create(InitialSessionState initialSessionState) { PowerShell result = Create(); - + result.Runspace = RunspaceFactory.CreateRunspace(initialSessionState); result.Runspace.Open(); - + return result; } @@ -984,11 +985,11 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ps", Justification = "ps represents PowerShell and is used at many places.")] public PowerShell CreateNestedPowerShell() { - if ((null != this.worker) && (null != this.worker.CurrentlyRunningPipeline)) + if ((null != _worker) && (null != _worker.CurrentlyRunningPipeline)) { - PowerShell result = new PowerShell(new PSCommand(), - null, this.worker.CurrentlyRunningPipeline.Runspace); - result.isNested = true; + PowerShell result = new PowerShell(new PSCommand(), + null, _worker.CurrentlyRunningPipeline.Runspace); + result._isNested = true; return result; } @@ -1004,7 +1005,7 @@ namespace System.Management.Automation private static PowerShell Create(bool isNested, PSCommand psCommand, Collection extraCommands) { PowerShell powerShell = new PowerShell(psCommand, extraCommands, null); - powerShell.isNested = isNested; + powerShell._isNested = isNested; return powerShell; } @@ -1040,11 +1041,11 @@ namespace System.Management.Automation /// public PowerShell AddCommand(string cmdlet) { - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand.AddCommand(cmdlet); + _psCommand.AddCommand(cmdlet); return this; } @@ -1081,11 +1082,11 @@ namespace System.Management.Automation /// public PowerShell AddCommand(string cmdlet, bool useLocalScope) { - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand.AddCommand(cmdlet, useLocalScope); + _psCommand.AddCommand(cmdlet, useLocalScope); return this; } @@ -1120,11 +1121,11 @@ namespace System.Management.Automation /// public PowerShell AddScript(string script) { - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand.AddScript(script); + _psCommand.AddScript(script); return this; } @@ -1162,11 +1163,11 @@ namespace System.Management.Automation /// public PowerShell AddScript(string script, bool useLocalScope) { - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand.AddScript(script, useLocalScope); + _psCommand.AddScript(script, useLocalScope); return this; } @@ -1197,11 +1198,11 @@ namespace System.Management.Automation /// internal PowerShell AddCommand(Command command) { - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand.AddCommand(command); + _psCommand.AddCommand(command); return this; } @@ -1234,7 +1235,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("commandInfo"); } Command cmd = new Command(commandInfo); - psCommand.AddCommand(cmd); + _psCommand.AddCommand(cmd); return this; } @@ -1272,15 +1273,15 @@ namespace System.Management.Automation /// public PowerShell AddParameter(string parameterName, object value) { - lock (syncObject) + lock (_syncObject) { - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.ParameterRequiresCommand); } AssertChangesAreAccepted(); - psCommand.AddParameter(parameterName, value); + _psCommand.AddParameter(parameterName, value); return this; } } @@ -1315,15 +1316,15 @@ namespace System.Management.Automation /// public PowerShell AddParameter(string parameterName) { - lock (syncObject) + lock (_syncObject) { - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.ParameterRequiresCommand); } AssertChangesAreAccepted(); - psCommand.AddParameter(parameterName); + _psCommand.AddParameter(parameterName); return this; } } @@ -1350,14 +1351,14 @@ namespace System.Management.Automation /// public PowerShell AddParameters(IList parameters) { - lock (syncObject) + lock (_syncObject) { if (parameters == null) { throw PSTraceSource.NewArgumentNullException("parameters"); } - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.ParameterRequiresCommand); } @@ -1366,7 +1367,7 @@ namespace System.Management.Automation foreach (object p in parameters) { - psCommand.AddParameter(null, p); + _psCommand.AddParameter(null, p); } return this; @@ -1398,14 +1399,14 @@ namespace System.Management.Automation /// public PowerShell AddParameters(IDictionary parameters) { - lock (syncObject) + lock (_syncObject) { if (parameters == null) { throw PSTraceSource.NewArgumentNullException("parameters"); } - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.ParameterRequiresCommand); } @@ -1421,7 +1422,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("parameters", PowerShellStrings.KeyMustBeString); } - psCommand.AddParameter(parameterName, entry.Value); + _psCommand.AddParameter(parameterName, entry.Value); } return this; @@ -1452,15 +1453,15 @@ namespace System.Management.Automation /// public PowerShell AddArgument(object value) { - lock (syncObject) + lock (_syncObject) { - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.ParameterRequiresCommand); } AssertChangesAreAccepted(); - psCommand.AddArgument(value); + _psCommand.AddArgument(value); return this; } } @@ -1485,18 +1486,18 @@ namespace System.Management.Automation /// public PowerShell AddStatement() { - lock (syncObject) + lock (_syncObject) { // for PowerShell.Create().AddStatement().AddCommand("Get-Process"); // we reduce it to PowerShell.Create().AddCommand("Get-Process"); - if (psCommand.Commands.Count == 0) + if (_psCommand.Commands.Count == 0) { return this; } AssertChangesAreAccepted(); - psCommand.Commands[psCommand.Commands.Count - 1].IsEndOfStatement = true; + _psCommand.Commands[_psCommand.Commands.Count - 1].IsEndOfStatement = true; return this; } @@ -1523,7 +1524,7 @@ namespace System.Management.Automation { get { - return psCommand; + return _psCommand; } set @@ -1532,11 +1533,11 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Command"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - psCommand = value.Clone(); - psCommand.Owner = this; + _psCommand = value.Clone(); + _psCommand.Owner = this; } } } @@ -1548,7 +1549,7 @@ namespace System.Management.Automation { get { - return this.dataStreams; + return _dataStreams; } } @@ -1571,7 +1572,7 @@ namespace System.Management.Automation { get { - return errorBuffer; + return _errorBuffer; } set @@ -1580,11 +1581,11 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Error"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - errorBuffer = value; - errorBufferOwner = false; + _errorBuffer = value; + _errorBufferOwner = false; } } } @@ -1605,7 +1606,7 @@ namespace System.Management.Automation { get { - return informationalBuffers.Progress; + return _informationalBuffers.Progress; } set @@ -1614,10 +1615,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Progress"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - informationalBuffers.Progress = value; + _informationalBuffers.Progress = value; } } } @@ -1638,7 +1639,7 @@ namespace System.Management.Automation { get { - return informationalBuffers.Verbose; + return _informationalBuffers.Verbose; } set @@ -1647,10 +1648,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Verbose"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - informationalBuffers.Verbose = value; + _informationalBuffers.Verbose = value; } } } @@ -1671,7 +1672,7 @@ namespace System.Management.Automation { get { - return informationalBuffers.Debug; + return _informationalBuffers.Debug; } set @@ -1680,10 +1681,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Debug"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - informationalBuffers.Debug = value; + _informationalBuffers.Debug = value; } } } @@ -1707,7 +1708,7 @@ namespace System.Management.Automation { get { - return informationalBuffers.Warning; + return _informationalBuffers.Warning; } set @@ -1716,10 +1717,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Warning"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - informationalBuffers.Warning = value; + _informationalBuffers.Warning = value; } } } @@ -1743,7 +1744,7 @@ namespace System.Management.Automation { get { - return informationalBuffers.Information; + return _informationalBuffers.Information; } set @@ -1752,10 +1753,10 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("Information"); } - lock (syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - informationalBuffers.Information = value; + _informationalBuffers.Information = value; } } } @@ -1765,7 +1766,7 @@ namespace System.Management.Automation /// internal PSInformationalBuffers InformationalBuffers { - get { return informationalBuffers; } + get { return _informationalBuffers; } } /// @@ -1777,10 +1778,10 @@ namespace System.Management.Automation /// internal bool RedirectShellErrorOutputPipe { - get { return this.redirectShellErrorOutputPipe; } - set { this.redirectShellErrorOutputPipe = value; } + get { return _redirectShellErrorOutputPipe; } + set { _redirectShellErrorOutputPipe = value; } } - private bool redirectShellErrorOutputPipe = true; + private bool _redirectShellErrorOutputPipe = true; /// /// Get unqiue id for this instance of runspace pool. It is primarily used @@ -1790,7 +1791,7 @@ namespace System.Management.Automation { get { - return instanceId; + return _instanceId; } } @@ -1801,7 +1802,7 @@ namespace System.Management.Automation { get { - return invocationStateInfo; + return _invocationStateInfo; } } @@ -1813,7 +1814,7 @@ namespace System.Management.Automation { get { - return isNested; + return _isNested; } } @@ -1830,7 +1831,7 @@ namespace System.Management.Automation { get { - return isChild; + return _isChild; } } @@ -1845,7 +1846,7 @@ namespace System.Management.Automation { _hadErrors = status; } - bool _hadErrors; + private bool _hadErrors; /// /// Access to the EndInvoke AysncResult object. Used by remote @@ -1892,11 +1893,11 @@ namespace System.Management.Automation { get { - if (this.runspace == null && this.runspacePool == null) // create a runspace only if neither a runspace nor a runspace pool have been set + if (_runspace == null && _runspacePool == null) // create a runspace only if neither a runspace nor a runspace pool have been set { - lock (this.syncObject) + lock (_syncObject) { - if (this.runspace == null && this.runspacePool == null) + if (_runspace == null && _runspacePool == null) { AssertChangesAreAccepted(); SetRunspace(RunspaceFactory.CreateRunspace(), true); @@ -1905,26 +1906,26 @@ namespace System.Management.Automation } } - return runspace; + return _runspace; } set { - lock (this.syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - if (this.runspace != null && this.runspaceOwner) + if (_runspace != null && _runspaceOwner) { - this.runspace.Dispose(); - this.runspace = null; - this.runspaceOwner = false; + _runspace.Dispose(); + _runspace = null; + _runspaceOwner = false; } SetRunspace(value, false); } } - } + } /// /// Internal method to set the Runspace property @@ -1935,27 +1936,27 @@ namespace System.Management.Automation if (remoteRunspace == null) { - this.rsConnection = runspace; + _rsConnection = runspace; } else { - this.rsConnection = remoteRunspace.RunspacePool; + _rsConnection = remoteRunspace.RunspacePool; - if (remotePowerShell != null) + if (_remotePowerShell != null) { - remotePowerShell.Clear(); - remotePowerShell.Dispose(); + _remotePowerShell.Clear(); + _remotePowerShell.Dispose(); } - remotePowerShell = new ClientRemotePowerShell(this, remoteRunspace.RunspacePool.RemoteRunspacePoolInternal); + _remotePowerShell = new ClientRemotePowerShell(this, remoteRunspace.RunspacePool.RemoteRunspacePoolInternal); } - this.runspace = runspace; - this.runspaceOwner = owner; - this.runspacePool = null; + _runspace = runspace; + _runspaceOwner = owner; + _runspacePool = null; } - private Runspace runspace = null; - private bool runspaceOwner = false; // If true, runspace was created by this instance; otherwise it was set by the user and we should not dispose it + private Runspace _runspace = null; + private bool _runspaceOwner = false; // If true, runspace was created by this instance; otherwise it was set by the user and we should not dispose it /// /// Sets an associated RunspacePool for this PowerShell instance. @@ -1980,44 +1981,44 @@ namespace System.Management.Automation { get { - return this.runspacePool; + return _runspacePool; } set { if (value != null) { - lock (this.syncObject) + lock (_syncObject) { AssertChangesAreAccepted(); - if (this.runspace != null && this.runspaceOwner) + if (_runspace != null && _runspaceOwner) { - this.runspace.Dispose(); - this.runspace = null; - this.runspaceOwner = false; + _runspace.Dispose(); + _runspace = null; + _runspaceOwner = false; } - this.rsConnection = value; - this.runspacePool = value; + _rsConnection = value; + _runspacePool = value; - if (this.runspacePool.IsRemote) + if (_runspacePool.IsRemote) { - if (this.remotePowerShell != null) + if (_remotePowerShell != null) { - this.remotePowerShell.Clear(); - this.remotePowerShell.Dispose(); + _remotePowerShell.Clear(); + _remotePowerShell.Dispose(); } - this.remotePowerShell = new - ClientRemotePowerShell(this, this.runspacePool.RemoteRunspacePoolInternal); + _remotePowerShell = new + ClientRemotePowerShell(this, _runspacePool.RemoteRunspacePoolInternal); } - this.runspace = null; + _runspace = null; } } } } - private RunspacePool runspacePool = null; + private RunspacePool _runspacePool = null; /// /// Gets the associated Runspace or RunspacePool for this PowerShell @@ -2026,7 +2027,7 @@ namespace System.Management.Automation /// internal object GetRunspaceConnection() { - return rsConnection; + return _rsConnection; } #endregion @@ -2041,7 +2042,7 @@ namespace System.Management.Automation { // Regardless of how the command was originally invoked, set this member // variable to indicate the command is now running synchronously. - this.commandInvokedSynchronously = true; + _commandInvokedSynchronously = true; IAsyncResult asyncResult = ConnectAsync(); PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; @@ -2092,25 +2093,25 @@ namespace System.Management.Automation AsyncCallback invocationCallback, object state) { - if (this.invocationStateInfo.State != PSInvocationState.Disconnected) + if (_invocationStateInfo.State != PSInvocationState.Disconnected) { - throw new InvalidPowerShellStateException(this.invocationStateInfo.State); + throw new InvalidPowerShellStateException(_invocationStateInfo.State); } // Ensure this is a command invoked on a remote runspace(pool) and connect the // runspace if it is currently disconnected. CheckRunspacePoolAndConnect(); - if (this.connectCmdInfo != null) + if (_connectCmdInfo != null) { // // This is a reconstruct/connect scenario and we create new state. // - PSDataCollection streamToUse = this.outputBuffer; + PSDataCollection streamToUse = _outputBuffer; // The remotePowerShell may have been initialized by InitForRemotePipelineConnect() - if (!this.remotePowerShell.Initialized) + if (!_remotePowerShell.Initialized) { // Empty input stream. ObjectStreamBase inputStream = new ObjectStream(); @@ -2120,63 +2121,63 @@ namespace System.Management.Automation if (output != null) { // Use the supplied output buffer. - this.outputBuffer = output; - this.outputBufferOwner = false; + _outputBuffer = output; + _outputBufferOwner = false; } - else if (this.outputBuffer == null) + else if (_outputBuffer == null) { - this.outputBuffer = new PSDataCollection(); - this.outputBufferOwner = true; + _outputBuffer = new PSDataCollection(); + _outputBufferOwner = true; } - streamToUse = this.outputBuffer; + streamToUse = _outputBuffer; - ObjectStreamBase outputStream = new PSDataCollectionStream(this.instanceId, streamToUse); + ObjectStreamBase outputStream = new PSDataCollectionStream(_instanceId, streamToUse); - this.remotePowerShell.Initialize(inputStream, outputStream, - new PSDataCollectionStream(this.instanceId, this.errorBuffer), - this.informationalBuffers, null); + _remotePowerShell.Initialize(inputStream, outputStream, + new PSDataCollectionStream(_instanceId, _errorBuffer), + _informationalBuffers, null); } - Dbg.Assert((this.invokeAsyncResult == null), "Async result should be null in the reconstruct scenario."); - this.invokeAsyncResult = new PowerShellAsyncResult(this.instanceId, invocationCallback, state, streamToUse, true); + Dbg.Assert((_invokeAsyncResult == null), "Async result should be null in the reconstruct scenario."); + _invokeAsyncResult = new PowerShellAsyncResult(_instanceId, invocationCallback, state, streamToUse, true); } else { // If this is not a reconstruct scenario then this must be a PowerShell object that was // previously disconnected, and all state should be valid. - Dbg.Assert((this.invokeAsyncResult != null && this.remotePowerShell.Initialized), + Dbg.Assert((_invokeAsyncResult != null && _remotePowerShell.Initialized), "AsyncResult and RemotePowerShell objects must be valid here."); if (output != null || invocationCallback != null || - invokeAsyncResult.IsCompleted) + _invokeAsyncResult.IsCompleted) { // A new async object is needed. PSDataCollection streamToUse; if (output != null) { streamToUse = output; - this.outputBuffer = output; - this.outputBufferOwner = false; + _outputBuffer = output; + _outputBufferOwner = false; } - else if (invokeAsyncResult.Output == null || - !invokeAsyncResult.Output.IsOpen) + else if (_invokeAsyncResult.Output == null || + !_invokeAsyncResult.Output.IsOpen) { - this.outputBuffer = new PSDataCollection(); - this.outputBufferOwner = true; - streamToUse = this.outputBuffer; + _outputBuffer = new PSDataCollection(); + _outputBufferOwner = true; + streamToUse = _outputBuffer; } else { - streamToUse = invokeAsyncResult.Output; - this.outputBuffer = streamToUse; - this.outputBufferOwner = false; + streamToUse = _invokeAsyncResult.Output; + _outputBuffer = streamToUse; + _outputBufferOwner = false; } - this.invokeAsyncResult = new PowerShellAsyncResult( - this.instanceId, - invocationCallback ?? this.invokeAsyncResult.Callback, - (invocationCallback != null) ? state : this.invokeAsyncResult.AsyncState, + _invokeAsyncResult = new PowerShellAsyncResult( + _instanceId, + invocationCallback ?? _invokeAsyncResult.Callback, + (invocationCallback != null) ? state : _invokeAsyncResult.AsyncState, streamToUse, true); } @@ -2187,24 +2188,24 @@ namespace System.Management.Automation // Perform the connect operation to the remote server through the PSRP layer. // If this.connectCmdInfo is null then a connection will be attempted using current state. // If this.connectCmdInfo is non-null then a connection will be attempted with this info. - this.remotePowerShell.ConnectAsync(this.connectCmdInfo); + _remotePowerShell.ConnectAsync(_connectCmdInfo); } catch (Exception exception) { // allow GC collection - invokeAsyncResult = null; + _invokeAsyncResult = null; SetStateChanged(new PSInvocationStateInfo(PSInvocationState.Failed, exception)); // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && this.runspace != null) // the pool exception was actually thrown by a runspace + if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } throw; } - return this.invokeAsyncResult; + return _invokeAsyncResult; } /// @@ -2214,13 +2215,13 @@ namespace System.Management.Automation private void CheckRunspacePoolAndConnect() { RemoteRunspacePoolInternal remoteRunspacePoolInternal = null; - if (this.rsConnection is RemoteRunspace) + if (_rsConnection is RemoteRunspace) { - remoteRunspacePoolInternal = (this.rsConnection as RemoteRunspace).RunspacePool.RemoteRunspacePoolInternal; + remoteRunspacePoolInternal = (_rsConnection as RemoteRunspace).RunspacePool.RemoteRunspacePoolInternal; } - else if (this.rsConnection is RunspacePool) + else if (_rsConnection is RunspacePool) { - remoteRunspacePoolInternal = (this.rsConnection as RunspacePool).RemoteRunspacePoolInternal; + remoteRunspacePoolInternal = (_rsConnection as RunspacePool).RemoteRunspacePoolInternal; } if (remoteRunspacePoolInternal == null) @@ -2237,7 +2238,7 @@ namespace System.Management.Automation // Make sure runspace is in valid state for connection. if (remoteRunspacePoolInternal.RunspacePoolStateInfo.State != RunspacePoolState.Opened) { - throw new InvalidRunspacePoolStateException(RunspacePoolStrings.InvalidRunspacePoolState, + throw new InvalidRunspacePoolStateException(RunspacePoolStrings.InvalidRunspacePoolState, remoteRunspacePoolInternal.RunspacePoolStateInfo.State, RunspacePoolState.Opened); } } @@ -2261,12 +2262,12 @@ namespace System.Management.Automation /// /// DebuggerCommandResults internal void InvokeWithDebugger( - IEnumerable input, - IList output, + IEnumerable input, + IList output, PSInvocationSettings settings, bool invokeMustRun) { - Debugger debugger = this.runspace.Debugger; + Debugger debugger = _runspace.Debugger; bool addToHistory = true; if (debugger != null && @@ -2779,7 +2780,7 @@ namespace System.Management.Automation Invoke(input, output, null); } - + /// /// Invoke the synchronously and collect /// output data into the buffer @@ -2914,7 +2915,7 @@ namespace System.Management.Automation /// /// If there is an error generating the metadata for dynamic parameters. /// - public void Invoke(PSDataCollectioninput, PSDataCollection output, PSInvocationSettings settings) + public void Invoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings) { if (null == output) { @@ -3026,26 +3027,26 @@ namespace System.Management.Automation { DetermineIsBatching(); - if (this.outputBuffer != null) + if (_outputBuffer != null) { - if (isBatching || extraCommands.Count != 0) + if (_isBatching || _extraCommands.Count != 0) { - return BeginBatchInvoke(input, this.outputBuffer, settings, callback, state); + return BeginBatchInvoke(input, _outputBuffer, settings, callback, state); } - return CoreInvokeAsync(input, this.outputBuffer, settings, callback, state, null); + return CoreInvokeAsync(input, _outputBuffer, settings, callback, state, null); } else { - this.outputBuffer = new PSDataCollection(); - outputBufferOwner = true; + _outputBuffer = new PSDataCollection(); + _outputBufferOwner = true; - if (isBatching || extraCommands.Count != 0) + if (_isBatching || _extraCommands.Count != 0) { - return BeginBatchInvoke(input, this.outputBuffer, settings, callback, state); + return BeginBatchInvoke(input, _outputBuffer, settings, callback, state); } - return CoreInvokeAsync(input, this.outputBuffer, settings, callback, state, this.outputBuffer); + return CoreInvokeAsync(input, _outputBuffer, settings, callback, state, _outputBuffer); } } @@ -3088,9 +3089,9 @@ namespace System.Management.Automation /// /// Object is disposed. /// - public IAsyncResult BeginInvoke(PSDataCollection input, PSDataCollection output) + public IAsyncResult BeginInvoke(PSDataCollection input, PSDataCollection output) { - return BeginInvoke(input, output, null, null, null); + return BeginInvoke(input, output, null, null, null); } /// @@ -3143,7 +3144,7 @@ namespace System.Management.Automation /// /// Object is disposed. /// - public IAsyncResult BeginInvoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state) + public IAsyncResult BeginInvoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state) { if (null == output) { @@ -3152,12 +3153,12 @@ namespace System.Management.Automation DetermineIsBatching(); - if (isBatching || extraCommands.Count != 0) + if (_isBatching || _extraCommands.Count != 0) { return BeginBatchInvoke(input, output, settings, callback, state); } - return CoreInvokeAsync(input, output, settings, callback, state, null); + return CoreInvokeAsync(input, output, settings, callback, state, null); } /// @@ -3203,12 +3204,12 @@ namespace System.Management.Automation throw PSTraceSource.NewInvalidOperationException(); } - if (isBatching) + if (_isBatching) { SetupAsyncBatchExecution(); } - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; if ((null != pool) && (pool.IsRemote)) { // Server supports batch invocation, in this case, we just send everything to the server and return immediately @@ -3220,7 +3221,7 @@ namespace System.Management.Automation } finally { - if (isBatching) + if (_isBatching) { EndAsyncBatchExecution(); } @@ -3231,14 +3232,14 @@ namespace System.Management.Automation // Non-remoting case or server does not support batching // In this case we execute the cmdlets one by one - runningExtraCommands = true; - batchInvocationSettings = settings; + _runningExtraCommands = true; + _batchInvocationSettings = settings; - batchAsyncResult = new PowerShellAsyncResult(instanceId, callback, state, asyncOutput, true); + _batchAsyncResult = new PowerShellAsyncResult(_instanceId, callback, state, asyncOutput, true); CoreInvokeAsync(input, output, settings, new AsyncCallback(BatchInvocationCallback), state, asyncOutput); - return batchAsyncResult; + return _batchAsyncResult; } @@ -3248,35 +3249,35 @@ namespace System.Management.Automation /// private void BatchInvocationWorkItem(object state) { - Debug.Assert(extraCommands.Count != 0, "This callback is for batch invocation only"); + Debug.Assert(_extraCommands.Count != 0, "This callback is for batch invocation only"); BatchInvocationContext context = state as BatchInvocationContext; Debug.Assert(context != null, "Context should never be null"); - PSCommand backupCommand = psCommand; + PSCommand backupCommand = _psCommand; try { - psCommand = context.Command; + _psCommand = context.Command; // Last element - if (psCommand == extraCommands[extraCommands.Count - 1]) + if (_psCommand == _extraCommands[_extraCommands.Count - 1]) { - runningExtraCommands = false; + _runningExtraCommands = false; } try { - IAsyncResult cmdResult = CoreInvokeAsync(null, context.Output, batchInvocationSettings, - null, batchAsyncResult.AsyncState, context.Output); + IAsyncResult cmdResult = CoreInvokeAsync(null, context.Output, _batchInvocationSettings, + null, _batchAsyncResult.AsyncState, context.Output); EndInvoke(cmdResult); } catch (ActionPreferenceStopException e) { // We need to honor the current error action preference here - stopBatchExecution = true; - batchAsyncResult.SetAsCompleted(e); + _stopBatchExecution = true; + _batchAsyncResult.SetAsCompleted(e); return; } catch (Exception e) @@ -3286,17 +3287,17 @@ namespace System.Management.Automation SetHadErrors(true); // Stop if necessarily - if ((null != batchInvocationSettings) && batchInvocationSettings.ErrorActionPreference == ActionPreference.Stop) + if ((null != _batchInvocationSettings) && _batchInvocationSettings.ErrorActionPreference == ActionPreference.Stop) { - stopBatchExecution = true; + _stopBatchExecution = true; AppendExceptionToErrorStream(e); - batchAsyncResult.SetAsCompleted(null); + _batchAsyncResult.SetAsCompleted(null); return; } // If we get here, then ErrorActionPreference is either Continue, // SilentlyContinue, or Inquire (Continue), so we just continue.... - if (batchInvocationSettings == null) + if (_batchInvocationSettings == null) { ActionPreference preference = (ActionPreference)Runspace.SessionStateProxy.GetVariable("ErrorActionPreference"); @@ -3307,14 +3308,14 @@ namespace System.Management.Automation AppendExceptionToErrorStream(e); break; case ActionPreference.Stop: - batchAsyncResult.SetAsCompleted(e); + _batchAsyncResult.SetAsCompleted(e); return; case ActionPreference.Inquire: case ActionPreference.Ignore: break; } } - else if (batchInvocationSettings.ErrorActionPreference != ActionPreference.Ignore) + else if (_batchInvocationSettings.ErrorActionPreference != ActionPreference.Ignore) { AppendExceptionToErrorStream(e); } @@ -3322,14 +3323,14 @@ namespace System.Management.Automation // Let it continue } - if (psCommand == extraCommands[extraCommands.Count - 1]) + if (_psCommand == _extraCommands[_extraCommands.Count - 1]) { - batchAsyncResult.SetAsCompleted(null); + _batchAsyncResult.SetAsCompleted(null); } } finally { - psCommand = backupCommand; + _psCommand = backupCommand; context.Signal(); } } @@ -3340,18 +3341,17 @@ namespace System.Management.Automation /// private void BatchInvocationCallback(IAsyncResult result) { - Debug.Assert(extraCommands.Count != 0, "This callback is for batch invocation only"); + Debug.Assert(_extraCommands.Count != 0, "This callback is for batch invocation only"); PSDataCollection objs = null; try { - objs = EndInvoke(result); if (objs == null) { - objs = batchAsyncResult.Output; + objs = _batchAsyncResult.Output; } DoRemainingBatchCommands(objs); @@ -3359,27 +3359,27 @@ namespace System.Management.Automation catch (PipelineStoppedException e) { // PowerShell throws the pipeline stopped exception. - batchAsyncResult.SetAsCompleted(e); + _batchAsyncResult.SetAsCompleted(e); return; } catch (ActionPreferenceStopException e) { // We need to honor the current error action preference here - batchAsyncResult.SetAsCompleted(e); + _batchAsyncResult.SetAsCompleted(e); return; } catch (Exception e) { - runningExtraCommands = false; + _runningExtraCommands = false; CommandProcessorBase.CheckForSevereException(e); SetHadErrors(true); ActionPreference preference; - if (batchInvocationSettings != null) + if (_batchInvocationSettings != null) { - preference = (batchInvocationSettings.ErrorActionPreference.HasValue) ? - batchInvocationSettings.ErrorActionPreference.Value + preference = (_batchInvocationSettings.ErrorActionPreference.HasValue) ? + _batchInvocationSettings.ErrorActionPreference.Value : ActionPreference.Continue; } else @@ -3396,7 +3396,7 @@ namespace System.Management.Automation AppendExceptionToErrorStream(e); break; case ActionPreference.Stop: - batchAsyncResult.SetAsCompleted(e); + _batchAsyncResult.SetAsCompleted(e); return; case ActionPreference.Inquire: case ActionPreference.Ignore: @@ -3405,14 +3405,14 @@ namespace System.Management.Automation if (objs == null) { - objs = batchAsyncResult.Output; + objs = _batchAsyncResult.Output; } DoRemainingBatchCommands(objs); } finally { - if (isBatching) + if (_isBatching) { EndAsyncBatchExecution(); } @@ -3424,16 +3424,16 @@ namespace System.Management.Automation /// private void DoRemainingBatchCommands(PSDataCollection objs) { - if (extraCommands.Count > 1) + if (_extraCommands.Count > 1) { - for (int i = 1; i < extraCommands.Count; i++) + for (int i = 1; i < _extraCommands.Count; i++) { - if (stopBatchExecution) + if (_stopBatchExecution) { break; } - BatchInvocationContext context = new BatchInvocationContext(extraCommands[i], objs); + BatchInvocationContext context = new BatchInvocationContext(_extraCommands[i], objs); // Queue a batch work item here. // Calling CoreInvokeAsync / CoreInvoke here directly doesn't work and causes the thread to hang. @@ -3441,7 +3441,6 @@ namespace System.Management.Automation context.Wait(); } } - } /// @@ -3449,16 +3448,16 @@ namespace System.Management.Automation /// private void DetermineIsBatching() { - foreach (Command command in psCommand.Commands) + foreach (Command command in _psCommand.Commands) { if (command.IsEndOfStatement) { - isBatching = true; + _isBatching = true; return; } } - isBatching = false; + _isBatching = false; } /// @@ -3466,20 +3465,20 @@ namespace System.Management.Automation /// private void SetupAsyncBatchExecution() { - Debug.Assert(isBatching); + Debug.Assert(_isBatching); - backupPSCommand = psCommand.Clone(); - extraCommands.Clear(); + _backupPSCommand = _psCommand.Clone(); + _extraCommands.Clear(); PSCommand currentPipe = new PSCommand(); currentPipe.Owner = this; - foreach (Command command in psCommand.Commands) + foreach (Command command in _psCommand.Commands) { if (command.IsEndOfStatement) { currentPipe.Commands.Add(command); - extraCommands.Add(currentPipe); + _extraCommands.Add(currentPipe); currentPipe = new PSCommand(); currentPipe.Owner = this; } @@ -3491,10 +3490,10 @@ namespace System.Management.Automation if (currentPipe.Commands.Count != 0) { - extraCommands.Add(currentPipe); + _extraCommands.Add(currentPipe); } - psCommand = extraCommands[0]; + _psCommand = _extraCommands[0]; } /// @@ -3502,9 +3501,9 @@ namespace System.Management.Automation /// private void EndAsyncBatchExecution() { - Debug.Assert(isBatching); + Debug.Assert(_isBatching); - psCommand = backupPSCommand; + _psCommand = _backupPSCommand; } /// @@ -3546,7 +3545,7 @@ namespace System.Management.Automation { try { - this.commandInvokedSynchronously = true; + _commandInvokedSynchronously = true; if (null == asyncResult) { @@ -3556,7 +3555,7 @@ namespace System.Management.Automation PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; if ((null == psAsyncResult) || - (psAsyncResult.OwnerId != instanceId) || + (psAsyncResult.OwnerId != _instanceId) || (psAsyncResult.IsAssociatedWithAsyncInvoke != true)) { throw PSTraceSource.NewArgumentException("asyncResult", @@ -3567,11 +3566,11 @@ namespace System.Management.Automation psAsyncResult.EndInvoke(); EndInvokeAsyncResult = null; - if (this.outputBufferOwner) + if (_outputBufferOwner) { // PowerShell no longer owns the output buffer when it is passed back to the caller. - this.outputBufferOwner = false; - this.outputBuffer = null; + _outputBufferOwner = false; + _outputBuffer = null; } return psAsyncResult.Output; @@ -3579,7 +3578,7 @@ namespace System.Management.Automation catch (InvalidRunspacePoolStateException exception) { SetHadErrors(true); - if (this.runspace != null) // the pool exception was actually thrown by a runspace + if (_runspace != null) // the pool exception was actually thrown by a runspace { throw exception.ToInvalidRunspaceStateException(); } @@ -3656,8 +3655,8 @@ namespace System.Management.Automation PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; - if ((null == psAsyncResult) || - (psAsyncResult.OwnerId != instanceId) || + if ((null == psAsyncResult) || + (psAsyncResult.OwnerId != _instanceId) || (psAsyncResult.IsAssociatedWithAsyncInvoke != false)) { throw PSTraceSource.NewArgumentException("asyncResult", @@ -3713,20 +3712,20 @@ namespace System.Management.Automation /// public bool IsRunspaceOwner { - get { return runspaceOwner; } - internal set { runspaceOwner = value; } + get { return _runspaceOwner; } + internal set { _runspaceOwner = value; } } internal bool ErrorBufferOwner { - get { return errorBufferOwner; } - set { errorBufferOwner = value; } + get { return _errorBufferOwner; } + set { _errorBufferOwner = value; } } internal bool OutputBufferOwner { - get { return outputBufferOwner; } - set { outputBufferOwner = value; } + get { return _outputBufferOwner; } + set { _outputBufferOwner = value; } } /// @@ -3734,7 +3733,7 @@ namespace System.Management.Automation /// internal PSDataCollection OutputBuffer { - get { return this.outputBuffer; } + get { return _outputBuffer; } } /// @@ -3757,7 +3756,7 @@ namespace System.Management.Automation /// internal void GenerateNewInstanceId() { - instanceId = Guid.NewGuid(); + _instanceId = Guid.NewGuid(); } /// @@ -3833,10 +3832,10 @@ namespace System.Management.Automation Runspace.DefaultRunspace.ExecutionContext, ((LocalRunspace)Runspace.DefaultRunspace).CommandFactory, false, - isNested == true ? CommandOrigin.Internal : CommandOrigin.Runspace + _isNested == true ? CommandOrigin.Internal : CommandOrigin.Runspace ); - commandProcessorBase.RedirectShellErrorOutputPipe = this.redirectShellErrorOutputPipe; + commandProcessorBase.RedirectShellErrorOutputPipe = _redirectShellErrorOutputPipe; pipelineProcessor.Add(commandProcessorBase); } @@ -3865,8 +3864,8 @@ namespace System.Management.Automation internal bool IsGetCommandMetadataSpecialPipeline { - get { return this.isGetCommandMetadataSpecialPipeline; } - set { this.isGetCommandMetadataSpecialPipeline = value; } + get { return _isGetCommandMetadataSpecialPipeline; } + set { _isGetCommandMetadataSpecialPipeline = value; } } /// @@ -3891,7 +3890,7 @@ namespace System.Management.Automation { return (InvocationStateInfo.State == PSInvocationState.Disconnected); } - + /// /// Checks if the command is already running. /// If the command is already running, throws an @@ -3919,7 +3918,7 @@ namespace System.Management.Automation throw new InvalidOperationException(message); } - if (invocationStateInfo.State == PSInvocationState.Stopping) + if (_invocationStateInfo.State == PSInvocationState.Stopping) { string message = StringUtil.Format(PowerShellStrings.ExecutionStopping); throw new InvalidOperationException(message); @@ -3940,7 +3939,7 @@ namespace System.Management.Automation /// internal void AssertChangesAreAccepted() { - lock (syncObject) + lock (_syncObject) { AssertNotDisposed(); if (IsCommandRunning() || IsDisconnected()) @@ -3959,7 +3958,7 @@ namespace System.Management.Automation /// private void AssertNotDisposed() { - if (isDisposed) + if (_isDisposed) { throw PSTraceSource.NewObjectDisposedException("PowerShell"); } @@ -3975,49 +3974,49 @@ namespace System.Management.Automation { if (disposing) { - lock (syncObject) + lock (_syncObject) { // if already disposed return - if (isDisposed) + if (_isDisposed) { return; } } // Stop the currently running command outside of the lock - if (invocationStateInfo.State == PSInvocationState.Running || - invocationStateInfo.State == PSInvocationState.Stopping) + if (_invocationStateInfo.State == PSInvocationState.Running || + _invocationStateInfo.State == PSInvocationState.Stopping) { Stop(); } - lock (syncObject) + lock (_syncObject) { - isDisposed = true; + _isDisposed = true; } - if (outputBuffer != null && outputBufferOwner) + if (_outputBuffer != null && _outputBufferOwner) { - outputBuffer.Dispose(); + _outputBuffer.Dispose(); } - if (errorBuffer != null && errorBufferOwner) + if (_errorBuffer != null && _errorBufferOwner) { - errorBuffer.Dispose(); + _errorBuffer.Dispose(); } - if (runspaceOwner) + if (_runspaceOwner) { - runspace.Dispose(); + _runspace.Dispose(); } - if (remotePowerShell != null) + if (_remotePowerShell != null) { - remotePowerShell.Dispose(); + _remotePowerShell.Dispose(); } - invokeAsyncResult = null; - stopAsyncResult = null; + _invokeAsyncResult = null; + _stopAsyncResult = null; } } @@ -4026,11 +4025,11 @@ namespace System.Management.Automation /// private void InternalClearSuppressExceptions() { - lock (syncObject) + lock (_syncObject) { - if (null != worker) + if (null != _worker) { - worker.InternalClearSuppressExceptions(); + _worker.InternalClearSuppressExceptions(); } } } @@ -4047,10 +4046,10 @@ namespace System.Management.Automation // The Pipeline class takes care of updating local runspaces. // Don't update for RemoteRunspace and nested PowerShell since this is used // only internally by the remote debugger. - RemoteRunspace remoteRunspace = this.runspace as RemoteRunspace; + RemoteRunspace remoteRunspace = _runspace as RemoteRunspace; if (remoteRunspace != null && !this.IsNested) { - this.runspace.UpdateRunspaceAvailability(invocationStateInfo.State, true, instanceId); + _runspace.UpdateRunspaceAvailability(_invocationStateInfo.State, true, _instanceId); } if (stateInfo.State == PSInvocationState.Running) @@ -4063,7 +4062,7 @@ namespace System.Management.Automation RemoveFromRemoteRunspaceRunningList(); } - InvocationStateChanged.SafeInvoke(this, new PSInvocationStateChangedEventArgs(stateInfo)); + InvocationStateChanged.SafeInvoke(this, new PSInvocationStateChangedEventArgs(stateInfo)); } /// @@ -4076,9 +4075,9 @@ namespace System.Management.Automation PSInvocationState previousState; // copy pipeline HasdErrors property to PowerShell instance... - if (worker != null && worker.CurrentlyRunningPipeline != null) + if (_worker != null && _worker.CurrentlyRunningPipeline != null) { - SetHadErrors(worker.CurrentlyRunningPipeline.HadErrors); + SetHadErrors(_worker.CurrentlyRunningPipeline.HadErrors); } // win281312: Usig temporary variables to avoid thread @@ -4087,12 +4086,12 @@ namespace System.Management.Automation PowerShellAsyncResult tempInvokeAsyncResult; PowerShellAsyncResult tempStopAsyncResult; - lock (syncObject) + lock (_syncObject) { - previousState = invocationStateInfo.State; + previousState = _invocationStateInfo.State; // Check the current state and see if we need to process this pipeline event. - switch (invocationStateInfo.State) + switch (_invocationStateInfo.State) { case PSInvocationState.Completed: case PSInvocationState.Failed: @@ -4124,20 +4123,20 @@ namespace System.Management.Automation break; } - tempInvokeAsyncResult = invokeAsyncResult; - tempStopAsyncResult = stopAsyncResult; - invocationStateInfo = copyStateInfo; + tempInvokeAsyncResult = _invokeAsyncResult; + tempStopAsyncResult = _stopAsyncResult; + _invocationStateInfo = copyStateInfo; } bool isExceptionOccured = false; - switch (invocationStateInfo.State) + switch (_invocationStateInfo.State) { case PSInvocationState.Running: CloseInputBufferOnReconnection(previousState); - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); break; case PSInvocationState.Stopping: - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); break; case PSInvocationState.Completed: case PSInvocationState.Failed: @@ -4146,29 +4145,29 @@ namespace System.Management.Automation InternalClearSuppressExceptions(); // Ensure remote receive queue is not blocked. - if (remotePowerShell != null) + if (_remotePowerShell != null) { ResumeIncomingData(); } try { - if (runningExtraCommands) + if (_runningExtraCommands) { if (null != tempInvokeAsyncResult) { - tempInvokeAsyncResult.SetAsCompleted(invocationStateInfo.Reason); + tempInvokeAsyncResult.SetAsCompleted(_invocationStateInfo.Reason); } - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); } else { - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); if (null != tempInvokeAsyncResult) { - tempInvokeAsyncResult.SetAsCompleted(invocationStateInfo.Reason); + tempInvokeAsyncResult.SetAsCompleted(_invocationStateInfo.Reason); } } @@ -4198,14 +4197,14 @@ namespace System.Management.Automation try { // Ensure remote receive queue is not blocked. - if (remotePowerShell != null) + if (_remotePowerShell != null) { ResumeIncomingData(); } // If this command was disconnected and was also invoked synchronously then // we throw an exception on the calling thread. - if (this.commandInvokedSynchronously && (tempInvokeAsyncResult != null)) + if (_commandInvokedSynchronously && (tempInvokeAsyncResult != null)) { tempInvokeAsyncResult.SetAsCompleted(new RuntimeException(PowerShellStrings.DiscOnSyncCommand)); } @@ -4224,7 +4223,7 @@ namespace System.Management.Automation // times with the command remaining in Disconnected state. if (previousState != PSInvocationState.Disconnected) { - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); } } catch (Exception) @@ -4247,7 +4246,7 @@ namespace System.Management.Automation // Make sure the connect command information is null when going to Disconnected state. // This parameter is used to determine reconnect/reconstruct scenarios. Setting to null // means we have a reconnect scenario. - this.connectCmdInfo = null; + _connectCmdInfo = null; break; default: @@ -4266,12 +4265,12 @@ namespace System.Management.Automation // the input buffer to allow the remote command to complete. Otherwise the // synchronous Connect() method will wait indefinitely for the command to complete. if (previousState == PSInvocationState.Disconnected && - this.commandInvokedSynchronously && - this.remotePowerShell.InputStream != null && - this.remotePowerShell.InputStream.IsOpen && - this.remotePowerShell.InputStream.Count > 0) + _commandInvokedSynchronously && + _remotePowerShell.InputStream != null && + _remotePowerShell.InputStream.IsOpen && + _remotePowerShell.InputStream.Count > 0) { - this.remotePowerShell.InputStream.Close(); + _remotePowerShell.InputStream.Close(); } } @@ -4280,11 +4279,11 @@ namespace System.Management.Automation /// internal void ClearRemotePowerShell() { - lock (syncObject) + lock (_syncObject) { - if (null != remotePowerShell) + if (null != _remotePowerShell) { - remotePowerShell.Clear(); + _remotePowerShell.Clear(); } } } @@ -4297,7 +4296,7 @@ namespace System.Management.Automation { AssertChangesAreAccepted(); - this.isNested = isNested; + _isNested = isNested; } /// @@ -4359,18 +4358,17 @@ namespace System.Management.Automation /// private void CoreInvoke(IEnumerable input, PSDataCollection output, PSInvocationSettings settings) { - PSDataCollection inputBuffer = null; if (null != input) { - inputBuffer = new PSDataCollection(); + inputBuffer = new PSDataCollection(); foreach (object o in input) { inputBuffer.Add(o); } inputBuffer.Complete(); } - CoreInvoke(inputBuffer, output, settings); + CoreInvoke(inputBuffer, output, settings); } /// @@ -4383,7 +4381,7 @@ namespace System.Management.Automation /// invocation settings private void CoreInvokeHelper(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings) { - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; // Prepare the environment...non-remoting case. Prepare(input, output, settings, true); @@ -4392,7 +4390,7 @@ namespace System.Management.Automation { // Invoke in the same thread as the calling thread. Runspace rsToUse = null; - if (!isNested) + if (!_isNested) { if (null != pool) { @@ -4401,13 +4399,13 @@ namespace System.Management.Automation #endif // getting the runspace asynchronously so that Stop can be supported from a different // thread. - worker.GetRunspaceAsyncResult = pool.BeginGetRunspace(null, null); - worker.GetRunspaceAsyncResult.AsyncWaitHandle.WaitOne(); - rsToUse = pool.EndGetRunspace(worker.GetRunspaceAsyncResult); + _worker.GetRunspaceAsyncResult = pool.BeginGetRunspace(null, null); + _worker.GetRunspaceAsyncResult.AsyncWaitHandle.WaitOne(); + rsToUse = pool.EndGetRunspace(_worker.GetRunspaceAsyncResult); } else { - rsToUse = rsConnection as Runspace; + rsToUse = _rsConnection as Runspace; if (null != rsToUse) { #if !CORECLR // No ApartmentState In CoreCLR @@ -4428,11 +4426,11 @@ namespace System.Management.Automation } // perform the work in the current thread - worker.CreateRunspaceIfNeededAndDoWork(rsToUse, true); + _worker.CreateRunspaceIfNeededAndDoWork(rsToUse, true); } else { - rsToUse = rsConnection as Runspace; + rsToUse = _rsConnection as Runspace; Dbg.Assert(null != rsToUse, "Nested PowerShell can only work on a Runspace"); @@ -4440,7 +4438,7 @@ namespace System.Management.Automation // Peform work on the current thread. Nested Pipeline // should be invoked from the same thread that the parent // pipeline is executing in. - worker.ConstructPipelineAndDoWork(rsToUse, true); + _worker.ConstructPipelineAndDoWork(rsToUse, true); } } catch (Exception exception) @@ -4450,7 +4448,7 @@ namespace System.Management.Automation // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && this.runspace != null) // the pool exception was actually thrown by a runspace + if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } @@ -4468,12 +4466,12 @@ namespace System.Management.Automation /// invocation settings private void CoreInvokeRemoteHelper(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings) { - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; // For remote calls..use the infrastructure built in CoreInvokeAsync.. IAsyncResult asyncResult = CoreInvokeAsync(input, output, settings, null, null, null); - this.commandInvokedSynchronously = true; + _commandInvokedSynchronously = true; PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; // Wait for command to complete. If an exception was thrown during command @@ -4483,10 +4481,10 @@ namespace System.Management.Automation psAsyncResult.EndInvoke(); EndInvokeAsyncResult = null; - if ((PSInvocationState.Failed == invocationStateInfo.State) && - (null != invocationStateInfo.Reason)) + if ((PSInvocationState.Failed == _invocationStateInfo.State) && + (null != _invocationStateInfo.Reason)) { - throw invocationStateInfo.Reason; + throw _invocationStateInfo.Reason; } return; @@ -4506,13 +4504,13 @@ namespace System.Management.Automation DetermineIsBatching(); - if (isBatching) + if (_isBatching) { SetupAsyncBatchExecution(); } SetHadErrors(false); - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; if ((null != pool) && (pool.IsRemote)) { if (ServerSupportsBatchInvocation()) @@ -4523,7 +4521,7 @@ namespace System.Management.Automation } finally { - if (isBatching) + if (_isBatching) { EndAsyncBatchExecution(); } @@ -4535,25 +4533,25 @@ namespace System.Management.Automation isRemote = true; } - if (isBatching) + if (_isBatching) { try { - foreach (PSCommand command in extraCommands) + foreach (PSCommand command in _extraCommands) { // Last element - if (psCommand != extraCommands[extraCommands.Count - 1]) + if (_psCommand != _extraCommands[_extraCommands.Count - 1]) { - runningExtraCommands = true; + _runningExtraCommands = true; } else { - runningExtraCommands = false; + _runningExtraCommands = false; } try { - psCommand = command; + _psCommand = command; if (isRemote) { @@ -4608,9 +4606,9 @@ namespace System.Management.Automation } finally { - runningExtraCommands = false; + _runningExtraCommands = false; - if (isBatching) + if (_isBatching) { EndAsyncBatchExecution(); } @@ -4618,7 +4616,7 @@ namespace System.Management.Automation } else { - runningExtraCommands = false; + _runningExtraCommands = false; if (isRemote) { @@ -4664,21 +4662,21 @@ namespace System.Management.Automation /// Object is disposed. /// [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] - private IAsyncResult CoreInvokeAsync(PSDataCollection input, + private IAsyncResult CoreInvokeAsync(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state, PSDataCollection asyncResultOutput) { - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; // We dont need to create worker if pool is remote - Prepare(input, output, settings, (pool == null || !pool.IsRemote)); + Prepare(input, output, settings, (pool == null || !pool.IsRemote)); - invokeAsyncResult = new PowerShellAsyncResult(instanceId, callback, state, asyncResultOutput, true); + _invokeAsyncResult = new PowerShellAsyncResult(_instanceId, callback, state, asyncResultOutput, true); try { // IsNested is true for the icm | % { icm } scenario - if (!isNested || (pool != null && pool.IsRemote)) + if (!_isNested || (pool != null && pool.IsRemote)) { if (null != pool) { @@ -4690,9 +4688,9 @@ namespace System.Management.Automation // for executing in a remote runspace pool case if (pool.IsRemote) { - worker = null; + _worker = null; - lock (syncObject) + lock (_syncObject) { // for remoting case, when the state is set to // Running, the message should have been sent @@ -4708,55 +4706,54 @@ namespace System.Management.Automation // are blocked. AssertExecutionNotStarted(); - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Running, null); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Running, null); ObjectStreamBase inputStream = null; if (input != null) { - inputStream = new PSDataCollectionStream(instanceId, input); + inputStream = new PSDataCollectionStream(_instanceId, input); } - if (!remotePowerShell.Initialized) + if (!_remotePowerShell.Initialized) { if (inputStream == null) { inputStream = new ObjectStream(); inputStream.Close(); } - remotePowerShell.Initialize( - inputStream, new PSDataCollectionStream(instanceId, output), - new PSDataCollectionStream(instanceId, errorBuffer), - informationalBuffers, settings); + _remotePowerShell.Initialize( + inputStream, new PSDataCollectionStream(_instanceId, output), + new PSDataCollectionStream(_instanceId, _errorBuffer), + _informationalBuffers, settings); } else { if (inputStream != null) { - remotePowerShell.InputStream = inputStream; + _remotePowerShell.InputStream = inputStream; } if (output != null) { - remotePowerShell.OutputStream = - new PSDataCollectionStream(instanceId, output); + _remotePowerShell.OutputStream = + new PSDataCollectionStream(_instanceId, output); } } - pool.RemoteRunspacePoolInternal.CreatePowerShellOnServerAndInvoke(remotePowerShell); - + pool.RemoteRunspacePoolInternal.CreatePowerShellOnServerAndInvoke(_remotePowerShell); } // lock - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); } else { - worker.GetRunspaceAsyncResult = pool.BeginGetRunspace( - new AsyncCallback(worker.RunspaceAvailableCallback), null); + _worker.GetRunspaceAsyncResult = pool.BeginGetRunspace( + new AsyncCallback(_worker.RunspaceAvailableCallback), null); } } else { - LocalRunspace rs = rsConnection as LocalRunspace; + LocalRunspace rs = _rsConnection as LocalRunspace; if (null != rs) { #if !CORECLR // No ApartmentState In CoreCLR @@ -4773,14 +4770,14 @@ namespace System.Management.Automation throw e; } - worker.CreateRunspaceIfNeededAndDoWork(rs, false); + _worker.CreateRunspaceIfNeededAndDoWork(rs, false); } else { // create a new runspace and perform invoke.. ThreadPool.QueueUserWorkItem( - new WaitCallback(worker.CreateRunspaceIfNeededAndDoWork), - rsConnection); + new WaitCallback(_worker.CreateRunspaceIfNeededAndDoWork), + _rsConnection); } } } @@ -4793,19 +4790,19 @@ namespace System.Management.Automation catch (Exception exception) { // allow GC collection - invokeAsyncResult = null; + _invokeAsyncResult = null; SetStateChanged(new PSInvocationStateInfo(PSInvocationState.Failed, exception)); // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && this.runspace != null) // the pool exception was actually thrown by a runspace + if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } throw; } - return invokeAsyncResult; + return _invokeAsyncResult; } #if !CORECLR // No ApartmentState In CoreCLR @@ -4861,13 +4858,13 @@ namespace System.Management.Automation /// /// Object is disposed. /// - private void Prepare(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, bool shouldCreateWorker) + private void Prepare(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, bool shouldCreateWorker) { Dbg.Assert(null != output, "Output cannot be null"); - - lock (syncObject) + + lock (_syncObject) { - if ((null == psCommand) || (null == psCommand.Commands) || (0 == psCommand.Commands.Count)) + if ((null == _psCommand) || (null == _psCommand.Commands) || (0 == _psCommand.Commands.Count)) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.NoCommandToInvoke); } @@ -4879,7 +4876,7 @@ namespace System.Management.Automation // set the execution state to running.. so changes // to the current instance of powershell // are blocked. - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Running, null); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Running, null); // update settings for impersonation policy if ((null != settings) && (settings.FlowImpersonationPolicy)) @@ -4898,7 +4895,7 @@ namespace System.Management.Automation ObjectStreamBase inputStream; if (null != input) { - inputStream = new PSDataCollectionStream(instanceId, input); + inputStream = new PSDataCollectionStream(_instanceId, input); } else { @@ -4906,8 +4903,8 @@ namespace System.Management.Automation inputStream.Close(); } - ObjectStreamBase outputStream = new PSDataCollectionStream(instanceId, output); - worker = new Worker(inputStream, outputStream, settings, this); + ObjectStreamBase outputStream = new PSDataCollectionStream(_instanceId, output); + _worker = new Worker(inputStream, outputStream, settings, this); } } @@ -4919,7 +4916,7 @@ namespace System.Management.Automation // Raise the state change events outside of the lock // send a cloned copy..this way the handler will // not see changes happening to the instance's execution state. - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); } } @@ -4945,17 +4942,17 @@ namespace System.Management.Automation Queue events = new Queue(); // Acquire lock as we are going to change state here.. - lock (syncObject) + lock (_syncObject) { //BUGBUG: remote powershell appears to handle state change's differently //Need to speak with remoting dev and resolve this. - switch (invocationStateInfo.State) + switch (_invocationStateInfo.State) { case PSInvocationState.NotStarted: // Stopped is called before operation started..we need to change // state to stopping and then to stopped... so that future stops // dont affect the state. - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Stopping, + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Stopping, null); events.Enqueue(new PSInvocationStateInfo(PSInvocationState.Stopped, @@ -4965,33 +4962,33 @@ namespace System.Management.Automation case PSInvocationState.Completed: case PSInvocationState.Failed: case PSInvocationState.Stopped: - stopAsyncResult = new PowerShellAsyncResult(instanceId, callback, state, null, false); - stopAsyncResult.SetAsCompleted(null); - return stopAsyncResult; + _stopAsyncResult = new PowerShellAsyncResult(_instanceId, callback, state, null, false); + _stopAsyncResult.SetAsCompleted(null); + return _stopAsyncResult; case PSInvocationState.Stopping: // Create new stop sync object if none exists. Otherwise return existing. - if (stopAsyncResult == null) + if (_stopAsyncResult == null) { - stopAsyncResult = new PowerShellAsyncResult(instanceId, callback, state, null, false); - stopAsyncResult.SetAsCompleted(null); + _stopAsyncResult = new PowerShellAsyncResult(_instanceId, callback, state, null, false); + _stopAsyncResult.SetAsCompleted(null); } - return stopAsyncResult; + return _stopAsyncResult; case PSInvocationState.Running: - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Stopping, + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Stopping, null); isRunning = true; break; case PSInvocationState.Disconnected: // Stopping a disconnected command results in a failed state. - invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Failed, null); + _invocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Failed, null); isDisconnected = true; break; } - stopAsyncResult = new PowerShellAsyncResult(instanceId, callback, state, null, false); + _stopAsyncResult = new PowerShellAsyncResult(_instanceId, callback, state, null, false); } // If in the Disconnected state then stopping simply cuts loose the PowerShell object @@ -4999,36 +4996,36 @@ namespace System.Management.Automation // cannot complete with this object. if (isDisconnected) { - if (invokeAsyncResult != null) + if (_invokeAsyncResult != null) { // Since object is stopped, allow result wait to end. - invokeAsyncResult.SetAsCompleted(null); + _invokeAsyncResult.SetAsCompleted(null); } - stopAsyncResult.SetAsCompleted(null); + _stopAsyncResult.SetAsCompleted(null); // Raise event for failed state change. - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); - return stopAsyncResult; + return _stopAsyncResult; } // Ensure the runspace is not blocking in a debug stop. ReleaseDebugger(); - RaiseStateChangeEvent(invocationStateInfo.Clone()); + RaiseStateChangeEvent(_invocationStateInfo.Clone()); bool shouldRunStopHelper = false; - RunspacePool pool = rsConnection as RunspacePool; + RunspacePool pool = _rsConnection as RunspacePool; if (pool != null && pool.IsRemote) { - if ((remotePowerShell != null) && remotePowerShell.Initialized) - { - remotePowerShell.StopAsync(); + if ((_remotePowerShell != null) && _remotePowerShell.Initialized) + { + _remotePowerShell.StopAsync(); if (isSyncCall) { - stopAsyncResult.AsyncWaitHandle.WaitOne(); + _stopAsyncResult.AsyncWaitHandle.WaitOne(); } } else @@ -5038,13 +5035,13 @@ namespace System.Management.Automation } else if (isRunning) { - worker.Stop(isSyncCall); - } + _worker.Stop(isSyncCall); + } else { shouldRunStopHelper = true; } - + if (shouldRunStopHelper) { if (isSyncCall) @@ -5054,15 +5051,15 @@ namespace System.Management.Automation else { ThreadPool.QueueUserWorkItem(new WaitCallback(StopThreadProc), events); - } + } } - return stopAsyncResult; + return _stopAsyncResult; } private void ReleaseDebugger() { - LocalRunspace localRunspace = this.runspace as LocalRunspace; + LocalRunspace localRunspace = _runspace as LocalRunspace; if (localRunspace != null) { localRunspace.ReleaseDebugger(); @@ -5120,7 +5117,7 @@ namespace System.Management.Automation { get { - return remotePowerShell; + return _remotePowerShell; } } @@ -5132,11 +5129,11 @@ namespace System.Management.Automation { get { - return historyString; + return _historyString; } set { - historyString = value; + _historyString = value; } } @@ -5145,7 +5142,7 @@ namespace System.Management.Automation /// internal Collection ExtraCommands { - get { return extraCommands; } + get { return _extraCommands; } } /// @@ -5153,25 +5150,25 @@ namespace System.Management.Automation /// internal bool RunningExtraCommands { - get { return runningExtraCommands; } + get { return _runningExtraCommands; } } private bool ServerSupportsBatchInvocation() { - if (runspace != null) + if (_runspace != null) { - return runspace.RunspaceStateInfo.State != RunspaceState.BeforeOpen && - runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersionWin8RTM; + return _runspace.RunspaceStateInfo.State != RunspaceState.BeforeOpen && + _runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersionWin8RTM; } RemoteRunspacePoolInternal remoteRunspacePoolInternal = null; - if (this.rsConnection is RemoteRunspace) + if (_rsConnection is RemoteRunspace) { - remoteRunspacePoolInternal = (this.rsConnection as RemoteRunspace).RunspacePool.RemoteRunspacePoolInternal; + remoteRunspacePoolInternal = (_rsConnection as RemoteRunspace).RunspacePool.RemoteRunspacePoolInternal; } - else if (this.rsConnection is RunspacePool) + else if (_rsConnection is RunspacePool) { - remoteRunspacePoolInternal = (this.rsConnection as RunspacePool).RemoteRunspacePoolInternal; + remoteRunspacePoolInternal = (_rsConnection as RunspacePool).RemoteRunspacePoolInternal; } return remoteRunspacePoolInternal != null && @@ -5183,9 +5180,9 @@ namespace System.Management.Automation /// private void AddToRemoteRunspaceRunningList() { - if (this.runspace != null) + if (_runspace != null) { - this.runspace.PushRunningPowerShell(this); + _runspace.PushRunningPowerShell(this); } else { @@ -5202,9 +5199,9 @@ namespace System.Management.Automation /// private void RemoveFromRemoteRunspaceRunningList() { - if (this.runspace != null) + if (_runspace != null) { - this.runspace.PopRunningPowerShell(); + _runspace.PopRunningPowerShell(); } else { @@ -5218,7 +5215,7 @@ namespace System.Management.Automation private RemoteRunspacePoolInternal GetRemoteRunspacePoolInternal() { - RunspacePool runspacePool = this.rsConnection as RunspacePool; + RunspacePool runspacePool = _rsConnection as RunspacePool; return (runspacePool != null) ? (runspacePool.RemoteRunspacePoolInternal) : null; } @@ -5232,15 +5229,15 @@ namespace System.Management.Automation /// private sealed class Worker { - private ObjectStreamBase inputStream; - private ObjectStreamBase outputStream; - private ObjectStreamBase errorStream; - private PSInvocationSettings settings; - private IAsyncResult getRunspaceAsyncResult; - private Pipeline currentlyRunningPipeline; - private bool isNotActive; - private PowerShell shell; - private object syncObject = new object(); + private ObjectStreamBase _inputStream; + private ObjectStreamBase _outputStream; + private ObjectStreamBase _errorStream; + private PSInvocationSettings _settings; + private IAsyncResult _getRunspaceAsyncResult; + private Pipeline _currentlyRunningPipeline; + private bool _isNotActive; + private PowerShell _shell; + private object _syncObject = new object(); /// /// @@ -5254,11 +5251,11 @@ namespace System.Management.Automation PSInvocationSettings settings, PowerShell shell) { - this.inputStream = inputStream; - this.outputStream = outputStream; - this.errorStream = new PSDataCollectionStream(shell.instanceId, shell.errorBuffer); - this.settings = settings; - this.shell = shell; + _inputStream = inputStream; + _outputStream = outputStream; + _errorStream = new PSDataCollectionStream(shell._instanceId, shell._errorBuffer); + _settings = settings; + _shell = shell; } /// @@ -5268,8 +5265,8 @@ namespace System.Management.Automation /// internal IAsyncResult GetRunspaceAsyncResult { - get { return getRunspaceAsyncResult; } - set { getRunspaceAsyncResult = value; } + get { return _getRunspaceAsyncResult; } + set { _getRunspaceAsyncResult = value; } } /// @@ -5277,7 +5274,7 @@ namespace System.Management.Automation /// internal Pipeline CurrentlyRunningPipeline { - get { return currentlyRunningPipeline; } + get { return _currentlyRunningPipeline; } } /// @@ -5287,7 +5284,7 @@ namespace System.Management.Automation internal void CreateRunspaceIfNeededAndDoWork(object state) { Runspace rsToUse = state as Runspace; - CreateRunspaceIfNeededAndDoWork(rsToUse, false); + CreateRunspaceIfNeededAndDoWork(rsToUse, false); } /// @@ -5314,26 +5311,26 @@ namespace System.Management.Automation LocalRunspace rs = rsToUse as LocalRunspace; if (null == rs) { - lock (this.shell.syncObject) + lock (_shell._syncObject) { - if (this.shell.runspace != null) + if (_shell._runspace != null) { - rsToUse = this.shell.runspace; + rsToUse = _shell._runspace; } else { Runspace runspace = null; - if ((null != settings) && (null != settings.Host)) + if ((null != _settings) && (null != _settings.Host)) { - runspace = RunspaceFactory.CreateRunspace(settings.Host); + runspace = RunspaceFactory.CreateRunspace(_settings.Host); } else { runspace = RunspaceFactory.CreateRunspace(); } - this.shell.SetRunspace(runspace, true); + _shell.SetRunspace(runspace, true); rsToUse = (LocalRunspace)runspace; rsToUse.Open(); @@ -5348,14 +5345,14 @@ namespace System.Management.Automation // PipelineStateChangedEvent is not raised // if there is an exception calling BeginInvoke // So raise the event here and notify the caller. - lock (syncObject) + lock (_syncObject) { - if (isNotActive) + if (_isNotActive) return; - isNotActive = true; + _isNotActive = true; } - shell.PipelineStateChanged(this, + _shell.PipelineStateChanged(this, new PipelineStateEventArgs( new PipelineStateInfo(PipelineState.Failed, e))); @@ -5391,7 +5388,7 @@ namespace System.Management.Automation #pragma warning disable 56500 try { - RunspacePool pool = shell.rsConnection as RunspacePool; + RunspacePool pool = _shell._rsConnection as RunspacePool; Dbg.Assert(pool != null, "RunspaceConnection must be a runspace pool"); // get the runspace..this will throw if there is an exception @@ -5410,17 +5407,16 @@ namespace System.Management.Automation // PipelineStateChangedEvent is not raised // if there is an exception calling BeginInvoke // So raise the event here and notify the caller. - lock (syncObject) + lock (_syncObject) { - if (isNotActive) + if (_isNotActive) return; - isNotActive = true; + _isNotActive = true; } - shell.PipelineStateChanged(this, + _shell.PipelineStateChanged(this, new PipelineStateEventArgs( new PipelineStateInfo(PipelineState.Failed, e))); - } #pragma warning restore 56500 } @@ -5448,15 +5444,15 @@ namespace System.Management.Automation internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) { Dbg.Assert(rs != null, "Runspace cannot be null in ConstructPipelineAndDoWork"); - shell.RunspaceAssigned.SafeInvoke(this, new PSEventArgs(rs)); + _shell.RunspaceAssigned.SafeInvoke(this, new PSEventArgs(rs)); // lock is needed until a pipeline is created to // make stop() cleanly release resources. LocalRunspace lrs = rs as LocalRunspace; - - lock (syncObject) + + lock (_syncObject) { - if (isNotActive) + if (_isNotActive) { return false; } @@ -5465,28 +5461,28 @@ namespace System.Management.Automation { LocalPipeline localPipeline = new LocalPipeline( lrs, - shell.Commands.Commands, - ((null != settings) && (settings.AddToHistory)) ? true : false, - shell.IsNested, - inputStream, - outputStream, - errorStream, - shell.informationalBuffers); + _shell.Commands.Commands, + ((null != _settings) && (_settings.AddToHistory)) ? true : false, + _shell.IsNested, + _inputStream, + _outputStream, + _errorStream, + _shell._informationalBuffers); - localPipeline.IsChild = shell.IsChild; + localPipeline.IsChild = _shell.IsChild; - if (!String.IsNullOrEmpty(shell.HistoryString)) + if (!String.IsNullOrEmpty(_shell.HistoryString)) { - localPipeline.SetHistoryString(shell.HistoryString); + localPipeline.SetHistoryString(_shell.HistoryString); } - localPipeline.RedirectShellErrorOutputPipe = this.shell.RedirectShellErrorOutputPipe; + localPipeline.RedirectShellErrorOutputPipe = _shell.RedirectShellErrorOutputPipe; - currentlyRunningPipeline = localPipeline; + _currentlyRunningPipeline = localPipeline; // register for pipeline state changed events within a lock...so that if // stop is called before invoke, we can listen to state transition and // take appropriate action. - currentlyRunningPipeline.StateChanged += shell.PipelineStateChanged; + _currentlyRunningPipeline.StateChanged += _shell.PipelineStateChanged; } else { @@ -5495,17 +5491,17 @@ namespace System.Management.Automation } // Set pipeline specific settings - currentlyRunningPipeline.InvocationSettings = settings; - + _currentlyRunningPipeline.InvocationSettings = _settings; + Dbg.Assert(lrs != null, "LocalRunspace cannot be null here"); if (performSyncInvoke) { - currentlyRunningPipeline.Invoke(); + _currentlyRunningPipeline.Invoke(); } else { - currentlyRunningPipeline.InvokeAsync(); + _currentlyRunningPipeline.InvokeAsync(); } return true; @@ -5517,32 +5513,32 @@ namespace System.Management.Automation /// internal void Stop(bool isSyncCall) { - lock (syncObject) + lock (_syncObject) { - if (isNotActive) + if (_isNotActive) { return; } - isNotActive = true; - if (null != currentlyRunningPipeline) + _isNotActive = true; + if (null != _currentlyRunningPipeline) { if (isSyncCall) { - currentlyRunningPipeline.Stop(); + _currentlyRunningPipeline.Stop(); } else { - currentlyRunningPipeline.StopAsync(); + _currentlyRunningPipeline.StopAsync(); } return; } - - if (null != getRunspaceAsyncResult) + + if (null != _getRunspaceAsyncResult) { - RunspacePool pool = shell.rsConnection as RunspacePool; + RunspacePool pool = _shell._rsConnection as RunspacePool; Dbg.Assert(pool != null, "RunspaceConnection must be a runspace pool"); - pool.CancelGetRunspace(getRunspaceAsyncResult); + pool.CancelGetRunspace(_getRunspaceAsyncResult); } } @@ -5553,11 +5549,11 @@ namespace System.Management.Automation if (isSyncCall) { - shell.StopHelper(events); + _shell.StopHelper(events); } else { - ThreadPool.QueueUserWorkItem(new WaitCallback(shell.StopThreadProc), events); + ThreadPool.QueueUserWorkItem(new WaitCallback(_shell.StopThreadProc), events); } } @@ -5569,41 +5565,41 @@ namespace System.Management.Automation { try { - if ((null != settings) && (null != settings.WindowsIdentityToImpersonate)) + if ((null != _settings) && (null != _settings.WindowsIdentityToImpersonate)) { - settings.WindowsIdentityToImpersonate.Dispose(); - settings.WindowsIdentityToImpersonate = null; + _settings.WindowsIdentityToImpersonate.Dispose(); + _settings.WindowsIdentityToImpersonate = null; } - inputStream.Close(); - outputStream.Close(); - errorStream.Close(); + _inputStream.Close(); + _outputStream.Close(); + _errorStream.Close(); - if (null == currentlyRunningPipeline) + if (null == _currentlyRunningPipeline) { return; } // Detach state changed handler so that runspace.close // and pipeline.dispose will not change powershell instances state - currentlyRunningPipeline.StateChanged -= shell.PipelineStateChanged; + _currentlyRunningPipeline.StateChanged -= _shell.PipelineStateChanged; - if ((null == getRunspaceAsyncResult) && (null == shell.rsConnection)) + if ((null == _getRunspaceAsyncResult) && (null == _shell._rsConnection)) { // user did not supply a runspace..Invoke* method created // a new runspace..so close it. - currentlyRunningPipeline.Runspace.Close(); + _currentlyRunningPipeline.Runspace.Close(); } else { - RunspacePool pool = shell.rsConnection as RunspacePool; + RunspacePool pool = _shell._rsConnection as RunspacePool; if (null != pool) { - pool.ReleaseRunspace(currentlyRunningPipeline.Runspace); + pool.ReleaseRunspace(_currentlyRunningPipeline.Runspace); } } - currentlyRunningPipeline.Dispose(); + _currentlyRunningPipeline.Dispose(); } catch (ArgumentException) { @@ -5618,15 +5614,15 @@ namespace System.Management.Automation { } - currentlyRunningPipeline = null; + _currentlyRunningPipeline = null; } #if !CORECLR // PSMI Not Supported On CSS internal void GetSettings(out bool addToHistory, out bool noInput, out uint apartmentState) { - addToHistory = this.settings.AddToHistory; + addToHistory = _settings.AddToHistory; noInput = false; - apartmentState = (uint)this.settings.ApartmentState; + apartmentState = (uint)_settings.ApartmentState; } #endif } @@ -5658,8 +5654,8 @@ namespace System.Management.Automation Collection extraCommands = null; ReadOnlyPSMemberInfoCollection properties = powerShellAsPSObject.Properties.Match(RemoteDataNameStrings.ExtraCommands); - - if(properties.Count > 0) + + if (properties.Count > 0) { extraCommands = new Collection(); @@ -5688,7 +5684,7 @@ namespace System.Management.Automation PSCommand psCommand = null; foreach (PSObject commandAsPSObject in RemotingDecoder.EnumerateListProperty(powerShellAsPSObject, RemoteDataNameStrings.Commands)) { - System.Management.Automation.Runspaces.Command command = + System.Management.Automation.Runspaces.Command command = System.Management.Automation.Runspaces.Command.FromPSObjectForRemoting(commandAsPSObject); if (psCommand == null) @@ -5716,15 +5712,15 @@ namespace System.Management.Automation internal PSObject ToPSObjectForRemoting() { PSObject powerShellAsPSObject = RemotingEncoder.CreateEmptyPSObject(); - Version psRPVersion = RemotingEncoder.GetPSRemotingProtocolVersion(rsConnection as RunspacePool); + Version psRPVersion = RemotingEncoder.GetPSRemotingProtocolVersion(_rsConnection as RunspacePool); // Check if the server supports batch invocation if (ServerSupportsBatchInvocation()) { - if (extraCommands.Count > 0) + if (_extraCommands.Count > 0) { - List extraCommandsAsListOfPSObjects = new List(this.extraCommands.Count); - foreach (PSCommand extraCommand in extraCommands) + List extraCommandsAsListOfPSObjects = new List(_extraCommands.Count); + foreach (PSCommand extraCommand in _extraCommands) { PSObject obj = RemotingEncoder.CreateEmptyPSObject(); @@ -5741,7 +5737,7 @@ namespace System.Management.Automation powerShellAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.Commands, commandsAsListOfPSObjects)); powerShellAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.IsNested, this.IsNested)); - powerShellAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.HistoryString, this.historyString)); + powerShellAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.HistoryString, _historyString)); powerShellAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.RedirectShellErrorOutputPipe, this.RedirectShellErrorOutputPipe)); return powerShellAsPSObject; } @@ -5766,14 +5762,14 @@ namespace System.Management.Automation /// internal void SuspendIncomingData() { - if (remotePowerShell == null) + if (_remotePowerShell == null) { throw new PSNotSupportedException(); } - if (remotePowerShell.DataStructureHandler != null) + if (_remotePowerShell.DataStructureHandler != null) { - remotePowerShell.DataStructureHandler.TransportManager.SuspendQueue(true); + _remotePowerShell.DataStructureHandler.TransportManager.SuspendQueue(true); } } @@ -5782,14 +5778,14 @@ namespace System.Management.Automation /// internal void ResumeIncomingData() { - if (remotePowerShell == null) + if (_remotePowerShell == null) { throw new PSNotSupportedException(); } - if (remotePowerShell.DataStructureHandler != null) + if (_remotePowerShell.DataStructureHandler != null) { - remotePowerShell.DataStructureHandler.TransportManager.ResumeQueue(); + _remotePowerShell.DataStructureHandler.TransportManager.ResumeQueue(); } } @@ -5800,16 +5796,16 @@ namespace System.Management.Automation /// internal void WaitForServicingComplete() { - if (remotePowerShell == null) + if (_remotePowerShell == null) { throw new PSNotSupportedException(); } - if (remotePowerShell.DataStructureHandler != null) + if (_remotePowerShell.DataStructureHandler != null) { int count = 0; while (++count < 2 && - remotePowerShell.DataStructureHandler.TransportManager.IsServicing) + _remotePowerShell.DataStructureHandler.TransportManager.IsServicing) { // Try waiting for 50 ms, then continue. Threading.Thread.Sleep(50); @@ -5846,14 +5842,14 @@ namespace System.Management.Automation // check if the AsJob parameter has already // been added. If not, add the same bool found = false; - foreach(CommandParameter parameter in this.Commands.Commands[0].Parameters) + foreach (CommandParameter parameter in this.Commands.Commands[0].Parameters) { if (string.Compare(parameter.Name, "AsJob", StringComparison.OrdinalIgnoreCase) == 0) { found = true; } } - + if (!found) { AddParameter("AsJob"); @@ -5874,31 +5870,31 @@ namespace System.Management.Automation internal CimInstance AsPSPowerShellPipeline() { CimInstance c = InternalMISerializer.CreateCimInstance("PS_PowerShellPipeline"); - CimProperty instanceIdProperty = InternalMISerializer.CreateCimProperty("InstanceId", - this.InstanceId.ToString(), + CimProperty instanceIdProperty = InternalMISerializer.CreateCimProperty("InstanceId", + this.InstanceId.ToString(), Microsoft.Management.Infrastructure.CimType.String); c.CimInstanceProperties.Add(instanceIdProperty); - CimProperty isNestedProperty = InternalMISerializer.CreateCimProperty("IsNested", - this.IsNested, - Microsoft.Management.Infrastructure.CimType.Boolean); + CimProperty isNestedProperty = InternalMISerializer.CreateCimProperty("IsNested", + this.IsNested, + Microsoft.Management.Infrastructure.CimType.Boolean); c.CimInstanceProperties.Add(isNestedProperty); - bool addToHistoryValue=false, noInputValue=false; + bool addToHistoryValue = false, noInputValue = false; uint apartmentStateValue = 0; - if (this.worker != null) + if (_worker != null) { - this.worker.GetSettings(out addToHistoryValue, out noInputValue, out apartmentStateValue); + _worker.GetSettings(out addToHistoryValue, out noInputValue, out apartmentStateValue); } - CimProperty addToHistoryProperty = InternalMISerializer.CreateCimProperty("AddToHistory", - addToHistoryValue, + CimProperty addToHistoryProperty = InternalMISerializer.CreateCimProperty("AddToHistory", + addToHistoryValue, Microsoft.Management.Infrastructure.CimType.Boolean); c.CimInstanceProperties.Add(addToHistoryProperty); - CimProperty noInputProperty = InternalMISerializer.CreateCimProperty("NoInput", - noInputValue, + CimProperty noInputProperty = InternalMISerializer.CreateCimProperty("NoInput", + noInputValue, Microsoft.Management.Infrastructure.CimType.Boolean); c.CimInstanceProperties.Add(noInputProperty); - CimProperty apartmentStateProperty = InternalMISerializer.CreateCimProperty("ApartmentState", - apartmentStateValue, + CimProperty apartmentStateProperty = InternalMISerializer.CreateCimProperty("ApartmentState", + apartmentStateValue, Microsoft.Management.Infrastructure.CimType.UInt32); c.CimInstanceProperties.Add(apartmentStateProperty); @@ -5932,7 +5928,7 @@ namespace System.Management.Automation /// internal PSDataStreams(PowerShell powershell) { - this.powershell = powershell; + _powershell = powershell; } /// @@ -5950,16 +5946,16 @@ namespace System.Management.Automation /// Object is disposed. /// [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "We want to allow callers to change the backing store.")] - public PSDataCollection Error + public PSDataCollection Error { get { - return this.powershell.ErrorBuffer; + return _powershell.ErrorBuffer; } set { - this.powershell.ErrorBuffer = value; + _powershell.ErrorBuffer = value; } } @@ -5979,12 +5975,12 @@ namespace System.Management.Automation { get { - return this.powershell.ProgressBuffer; + return _powershell.ProgressBuffer; } set { - this.powershell.ProgressBuffer = value; + _powershell.ProgressBuffer = value; } } @@ -6004,12 +6000,12 @@ namespace System.Management.Automation { get { - return this.powershell.VerboseBuffer; + return _powershell.VerboseBuffer; } set { - this.powershell.VerboseBuffer = value; + _powershell.VerboseBuffer = value; } } @@ -6029,12 +6025,12 @@ namespace System.Management.Automation { get { - return this.powershell.DebugBuffer; + return _powershell.DebugBuffer; } set { - this.powershell.DebugBuffer = value; + _powershell.DebugBuffer = value; } } @@ -6053,16 +6049,16 @@ namespace System.Management.Automation /// Object is disposed. /// [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "We want to allow callers to change the backing store.")] - public PSDataCollection Warning + public PSDataCollection Warning { get { - return this.powershell.WarningBuffer; + return _powershell.WarningBuffer; } set { - this.powershell.WarningBuffer = value; + _powershell.WarningBuffer = value; } } @@ -6085,12 +6081,12 @@ namespace System.Management.Automation { get { - return this.powershell.InformationBuffer; + return _powershell.InformationBuffer; } set { - this.powershell.InformationBuffer = value; + _powershell.InformationBuffer = value; } } @@ -6106,8 +6102,8 @@ namespace System.Management.Automation this.Debug.Clear(); this.Warning.Clear(); } - - private PowerShell powershell; + + private PowerShell _powershell; } /// @@ -6126,9 +6122,9 @@ namespace System.Management.Automation /// internal class PowerShellStopper : IDisposable { - private PipelineBase pipeline; - private PowerShell powerShell; - private EventHandler eventHandler; + private PipelineBase _pipeline; + private PowerShell _powerShell; + private EventHandler _eventHandler; internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { @@ -6141,44 +6137,43 @@ namespace System.Management.Automation throw new ArgumentNullException("powerShell"); } - this.powerShell = powerShell; - + _powerShell = powerShell; + if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null) && (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline != null)) { - this.eventHandler = new EventHandler(LocalPipeline_StateChanged); - this.pipeline = context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline; - this.pipeline.StateChanged += eventHandler; + _eventHandler = new EventHandler(LocalPipeline_StateChanged); + _pipeline = context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline; + _pipeline.StateChanged += _eventHandler; } } private void LocalPipeline_StateChanged(object sender, PipelineStateEventArgs e) { if ((e.PipelineStateInfo.State == PipelineState.Stopping) && - (this.powerShell.InvocationStateInfo.State == PSInvocationState.Running)) + (_powerShell.InvocationStateInfo.State == PSInvocationState.Running)) { - this.powerShell.Stop(); + _powerShell.Stop(); } } - private bool isDisposed; - - public void Dispose() + private bool _isDisposed; + + public void Dispose() { - if (!isDisposed) + if (!_isDisposed) { - if (this.eventHandler != null) + if (_eventHandler != null) { - pipeline.StateChanged -= this.eventHandler; - this.eventHandler = null; + _pipeline.StateChanged -= _eventHandler; + _eventHandler = null; } GC.SuppressFinalize(this); - isDisposed = true; + _isDisposed = true; } } } - } diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 85ca58779..cb00b9d6d 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -1,12 +1,13 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.ComponentModel; using System.Globalization; using System.IO; using System.Management.Automation.Remoting; using System.Text; -using System.Diagnostics; +using System.Diagnostics; namespace System.Management.Automation.Runspaces @@ -20,7 +21,7 @@ namespace System.Management.Automation.Runspaces private readonly ProcessStartInfo _startInfo; private Process _process; - private static readonly string PSExePath; + private static readonly string s_PSExePath; private RunspacePool _runspacePool; private readonly object _syncObject = new object(); private OutOfProcessTextWriter _textWriter; @@ -37,7 +38,7 @@ namespace System.Management.Automation.Runspaces /// static PowerShellProcessInstance() { - PSExePath = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), + s_PSExePath = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "powershell.exe"); } @@ -50,7 +51,7 @@ namespace System.Management.Automation.Runspaces /// public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64) { - string psWow64Path = PSExePath; + string psWow64Path = s_PSExePath; if (useWow64) { @@ -59,7 +60,7 @@ namespace System.Management.Automation.Runspaces if ((!string.IsNullOrEmpty(procArch)) && (procArch.Equals("amd64", StringComparison.OrdinalIgnoreCase) || procArch.Equals("ia64", StringComparison.OrdinalIgnoreCase))) { - psWow64Path = PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\"); + psWow64Path = s_PSExePath.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\"); if (!File.Exists(psWow64Path)) { @@ -104,16 +105,16 @@ namespace System.Management.Automation.Runspaces // 'WindowStyle' is used only if 'UseShellExecute' is 'true'. Since 'UseShellExecute' is set // to 'false' in our use, we can ignore the 'WindowStyle' setting in the initialization below. _startInfo = new ProcessStartInfo - { - FileName = useWow64 ? psWow64Path : PSExePath, - Arguments = processArguments, - UseShellExecute = false, - RedirectStandardInput = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true, - LoadUserProfile = true, - }; + { + FileName = useWow64 ? psWow64Path : s_PSExePath, + Arguments = processArguments, + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + LoadUserProfile = true, + }; if (credential != null) { @@ -128,13 +129,13 @@ namespace System.Management.Automation.Runspaces #endif } - _process = new Process {StartInfo = _startInfo, EnableRaisingEvents = true}; + _process = new Process { StartInfo = _startInfo, EnableRaisingEvents = true }; } /// /// /// - public PowerShellProcessInstance(): this(null, null, null, false) + public PowerShellProcessInstance() : this(null, null, null, false) { } @@ -170,8 +171,8 @@ namespace System.Management.Automation.Runspaces /// private void Dispose(bool disposing) { - if(_isDisposed) return; - lock(_syncObject) + if (_isDisposed) return; + lock (_syncObject) { if (_isDisposed) return; _isDisposed = true; @@ -254,10 +255,10 @@ namespace System.Management.Automation.Runspaces _started = true; _process.Exited += ProcessExited; } - _process.Start(); + _process.Start(); } - void ProcessExited(object sender, EventArgs e) + private void ProcessExited(object sender, EventArgs e) { lock (_syncObject) { diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs index cae64d4b0..b85959d42 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs @@ -30,10 +30,9 @@ namespace System.Management.Automation.Runspaces /// Runspace class for local runspace /// - internal sealed partial + internal sealed partial class LocalRunspace : RunspaceBase { - /// /// initialize default values of preference vars /// diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs index f0d6d4c77..d11aa891e 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation { using System; @@ -11,14 +12,14 @@ namespace System.Management.Automation /// /// Defines a class which allows simple execution of commands from CLR languages /// - public class RunspaceInvoke: IDisposable + public class RunspaceInvoke : IDisposable { #region constructors /// /// Runspace on which commands are invoked /// - Runspace _runspace; + private Runspace _runspace; /// /// Create a RunspaceInvoke for invoking commands. This uses @@ -97,7 +98,7 @@ namespace System.Management.Automation /// /// /// Runspace must be opened state - public RunspaceInvoke (Runspace runspace) + public RunspaceInvoke(Runspace runspace) { if (runspace == null) { @@ -119,7 +120,7 @@ namespace System.Management.Automation /// /// msh script to invoke /// Output of invocation - public Collection Invoke (string script) + public Collection Invoke(string script) { return Invoke(script, null); } @@ -130,7 +131,7 @@ namespace System.Management.Automation /// msh script to invoke /// input to script /// Output of invocation - public Collection Invoke (string script, IEnumerable input) + public Collection Invoke(string script, IEnumerable input) { if (_disposed == true) { @@ -139,10 +140,10 @@ namespace System.Management.Automation if (script == null) { - throw PSTraceSource.NewArgumentNullException ("script"); + throw PSTraceSource.NewArgumentNullException("script"); } - Pipeline p = _runspace.CreatePipeline (script); - return p.Invoke (input); + Pipeline p = _runspace.CreatePipeline(script); + return p.Invoke(input); } /// @@ -158,7 +159,7 @@ namespace System.Management.Automation /// In this release, the objects read from this PipelineReader /// are PSObjects wrapping ErrorRecords. /// - public Collection Invoke (string script, IEnumerable input, out IList errors) + public Collection Invoke(string script, IEnumerable input, out IList errors) { if (_disposed == true) { @@ -167,12 +168,12 @@ namespace System.Management.Automation if (script == null) { - throw PSTraceSource.NewArgumentNullException ("script"); + throw PSTraceSource.NewArgumentNullException("script"); } - Pipeline p = _runspace.CreatePipeline (script); - Collection output = p.Invoke (input); + Pipeline p = _runspace.CreatePipeline(script); + Collection output = p.Invoke(input); // 2004/06/30-JonN was ReadAll() which was non-blocking - errors = p.Error.NonBlockingRead (); + errors = p.Error.NonBlockingRead(); return output; } @@ -183,7 +184,7 @@ namespace System.Management.Automation /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// Dispose underlying Runspace diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 85a1f828f..d869292f8 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -57,7 +57,7 @@ namespace System.Management.Automation.Runspaces /// The exception that is the cause of the current exception. /// public InvalidRunspacePoolStateException(string message, Exception innerException) - :base(message, innerException) + : base(message, innerException) { } @@ -76,8 +76,8 @@ namespace System.Management.Automation.Runspaces ) : base(message) { - this.expectedState = expectedState; - this.currentState = currentState; + _expectedState = expectedState; + _currentState = currentState; } @@ -116,7 +116,7 @@ namespace System.Management.Automation.Runspaces { get { - return currentState; + return _currentState; } } @@ -128,7 +128,7 @@ namespace System.Management.Automation.Runspaces { get { - return expectedState; + return _expectedState; } } @@ -138,7 +138,7 @@ namespace System.Management.Automation.Runspaces internal InvalidRunspaceStateException ToInvalidRunspaceStateException() { InvalidRunspaceStateException exception = new InvalidRunspaceStateException( - RunspaceStrings.InvalidRunspaceStateGeneral, + RunspaceStrings.InvalidRunspaceStateGeneral, this); exception.CurrentState = RunspacePoolStateToRunspaceState(this.CurrentState); exception.ExpectedState = RunspacePoolStateToRunspaceState(this.ExpectedState); @@ -189,13 +189,13 @@ namespace System.Management.Automation.Runspaces /// State of the runspace pool when exception was thrown. /// [NonSerialized] - private RunspacePoolState currentState = 0; + private RunspacePoolState _currentState = 0; /// /// State of the runspace pool expected in method which throws this exception. /// [NonSerialized] - private RunspacePoolState expectedState = 0; + private RunspacePoolState _expectedState = 0; } #endregion @@ -262,7 +262,7 @@ namespace System.Management.Automation.Runspaces /// internal RunspacePoolStateChangedEventArgs(RunspacePoolState state) { - stateInfo = new RunspacePoolStateInfo(state, null); + _stateInfo = new RunspacePoolStateInfo(state, null); } /// @@ -271,7 +271,7 @@ namespace System.Management.Automation.Runspaces /// internal RunspacePoolStateChangedEventArgs(RunspacePoolStateInfo stateInfo) { - this.stateInfo = stateInfo; + _stateInfo = stateInfo; } #endregion @@ -285,7 +285,7 @@ namespace System.Management.Automation.Runspaces { get { - return stateInfo; + return _stateInfo; } } @@ -293,7 +293,7 @@ namespace System.Management.Automation.Runspaces #region Private Data - private RunspacePoolStateInfo stateInfo; + private RunspacePoolStateInfo _stateInfo; #endregion } @@ -305,7 +305,7 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private Runspace runspace; + private Runspace _runspace; #endregion @@ -316,7 +316,7 @@ namespace System.Management.Automation.Runspaces /// internal RunspaceCreatedEventArgs(Runspace runspace) { - this.runspace = runspace; + _runspace = runspace; } #endregion @@ -325,7 +325,7 @@ namespace System.Management.Automation.Runspaces internal Runspace Runspace { - get { return runspace; } + get { return _runspace; } } #endregion @@ -389,7 +389,7 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private bool isAssociatedWithAsyncOpen; + private bool _isAssociatedWithAsyncOpen; #endregion @@ -415,7 +415,7 @@ namespace System.Management.Automation.Runspaces bool isCalledFromOpenAsync) : base(ownerId, callback, state) { - isAssociatedWithAsyncOpen = isCalledFromOpenAsync; + _isAssociatedWithAsyncOpen = isCalledFromOpenAsync; } #endregion @@ -428,12 +428,12 @@ namespace System.Management.Automation.Runspaces /// internal bool IsAssociatedWithAsyncOpen { - get { return isAssociatedWithAsyncOpen; } + get { return _isAssociatedWithAsyncOpen; } } #endregion } - + /// /// Encapsulated the results of a RunspacePool.BeginGetRunspace method /// @@ -441,8 +441,8 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private Runspace runspace; - private bool isActive; + private Runspace _runspace; + private bool _isActive; #endregion @@ -463,7 +463,7 @@ namespace System.Management.Automation.Runspaces internal GetRunspaceAsyncResult(Guid ownerId, AsyncCallback callback, object state) : base(ownerId, callback, state) { - isActive = true; + _isActive = true; } #endregion @@ -480,11 +480,11 @@ namespace System.Management.Automation.Runspaces { get { - return runspace; + return _runspace; } set { - runspace = value; + _runspace = value; } } @@ -498,14 +498,14 @@ namespace System.Management.Automation.Runspaces { lock (SyncObject) { - return isActive; + return _isActive; } } set { lock (SyncObject) { - isActive = value; + _isActive = value; } } } @@ -524,7 +524,7 @@ namespace System.Management.Automation.Runspaces internal void DoComplete(object state) { SetAsCompleted(null); - } + } #endregion } @@ -540,12 +540,12 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private RunspacePoolInternal internalPool; - private object syncObject = new object(); + private RunspacePoolInternal _internalPool; + private object _syncObject = new object(); private event EventHandler InternalStateChanged = null; private event EventHandler InternalForwardEvent = null; private event EventHandler InternalRunspaceCreated = null; - private bool isRemote = false; + private bool _isRemote = false; #endregion @@ -578,14 +578,14 @@ namespace System.Management.Automation.Runspaces /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// - internal RunspacePool(int minRunspaces, int maxRunspaces, + internal RunspacePool(int minRunspaces, int maxRunspaces, RunspaceConfiguration runspaceConfiguration, PSHost host) { // Currently we support only Local Runspace Pool.. // this needs to be changed once remote runspace pool // is implemented - internalPool = new RunspacePoolInternal(minRunspaces, + _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, runspaceConfiguration, host); } @@ -623,7 +623,7 @@ namespace System.Management.Automation.Runspaces // this needs to be changed once remote runspace pool // is implemented - internalPool = new RunspacePoolInternal(minRunspaces, + _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, initialSessionState, host); } @@ -638,15 +638,15 @@ namespace System.Management.Automation.Runspaces /// Connection information. /// Session name. internal RunspacePool( - int minRunspaces, - int maxRunspaces, - TypeTable typeTable, - PSHost host, + int minRunspaces, + int maxRunspaces, + TypeTable typeTable, + PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) { - internalPool = new RemoteRunspacePoolInternal( + _internalPool = new RemoteRunspacePoolInternal( minRunspaces, maxRunspaces, typeTable, @@ -655,7 +655,7 @@ namespace System.Management.Automation.Runspaces connectionInfo, name); - isRemote = true; + _isRemote = true; } /// @@ -685,10 +685,10 @@ namespace System.Management.Automation.Runspaces throw new NotSupportedException(); } - this.internalPool = new RemoteRunspacePoolInternal(instanceId, name, isDisconnected, connectCommands, + _internalPool = new RemoteRunspacePoolInternal(instanceId, name, isDisconnected, connectCommands, connectionInfo, host, typeTable); - isRemote = true; + _isRemote = true; } #endregion @@ -703,7 +703,7 @@ namespace System.Management.Automation.Runspaces { get { - return internalPool.InstanceId; + return _internalPool.InstanceId; } } @@ -714,7 +714,7 @@ namespace System.Management.Automation.Runspaces { get { - return internalPool.IsDisposed; + return _internalPool.IsDisposed; } } @@ -725,7 +725,7 @@ namespace System.Management.Automation.Runspaces { get { - return internalPool.RunspacePoolStateInfo; + return _internalPool.RunspacePoolStateInfo; } } @@ -737,7 +737,7 @@ namespace System.Management.Automation.Runspaces { get { - return internalPool.InitialSessionState; + return _internalPool.InitialSessionState; } } @@ -748,7 +748,7 @@ namespace System.Management.Automation.Runspaces { get { - return internalPool.ConnectionInfo; + return _internalPool.ConnectionInfo; } } @@ -757,8 +757,8 @@ namespace System.Management.Automation.Runspaces /// public TimeSpan CleanupInterval { - get { return this.internalPool.CleanupInterval; } - set { this.internalPool.CleanupInterval = value; } + get { return _internalPool.CleanupInterval; } + set { _internalPool.CleanupInterval = value; } } /// @@ -766,7 +766,7 @@ namespace System.Management.Automation.Runspaces /// public RunspacePoolAvailability RunspacePoolAvailability { - get { return internalPool.RunspacePoolAvailability; } + get { return _internalPool.RunspacePoolAvailability; } } #endregion @@ -780,7 +780,7 @@ namespace System.Management.Automation.Runspaces { add { - lock (syncObject) + lock (_syncObject) { bool firstEntry = (null == InternalStateChanged); InternalStateChanged += value; @@ -789,7 +789,7 @@ namespace System.Management.Automation.Runspaces // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. - internalPool.StateChanged += + _internalPool.StateChanged += new EventHandler(OnStateChanged); } } @@ -797,12 +797,12 @@ namespace System.Management.Automation.Runspaces remove { - lock (syncObject) + lock (_syncObject) { InternalStateChanged -= value; if (null == InternalStateChanged) { - internalPool.StateChanged -= + _internalPool.StateChanged -= new EventHandler(OnStateChanged); } } @@ -816,10 +816,10 @@ namespace System.Management.Automation.Runspaces /// private void OnStateChanged(object source, RunspacePoolStateChangedEventArgs args) { - if (ConnectionInfo is NewProcessConnectionInfo ) + if (ConnectionInfo is NewProcessConnectionInfo) { NewProcessConnectionInfo connectionInfo = ConnectionInfo as NewProcessConnectionInfo; - if (connectionInfo.Process != null && + if (connectionInfo.Process != null && (args.RunspacePoolStateInfo.State == RunspacePoolState.Opened || args.RunspacePoolStateInfo.State == RunspacePoolState.Broken)) { @@ -840,28 +840,28 @@ namespace System.Management.Automation.Runspaces { add { - lock (syncObject) + lock (_syncObject) { bool firstEntry = InternalForwardEvent == null; InternalForwardEvent += value; - + if (firstEntry) { - internalPool.ForwardEvent += OnInternalPoolForwardEvent; + _internalPool.ForwardEvent += OnInternalPoolForwardEvent; } } } remove { - lock (syncObject) + lock (_syncObject) { InternalForwardEvent -= value; if (InternalForwardEvent == null) { - internalPool.ForwardEvent -= OnInternalPoolForwardEvent; + _internalPool.ForwardEvent -= OnInternalPoolForwardEvent; } } } @@ -895,7 +895,7 @@ namespace System.Management.Automation.Runspaces { add { - lock (syncObject) + lock (_syncObject) { bool firstEntry = (null == InternalRunspaceCreated); InternalRunspaceCreated += value; @@ -904,19 +904,19 @@ namespace System.Management.Automation.Runspaces // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. - internalPool.RunspaceCreated += OnRunspaceCreated; + _internalPool.RunspaceCreated += OnRunspaceCreated; } } } remove { - lock (syncObject) + lock (_syncObject) { InternalRunspaceCreated -= value; if (null == InternalRunspaceCreated) { - internalPool.RunspaceCreated -= OnRunspaceCreated; + _internalPool.RunspaceCreated -= OnRunspaceCreated; } } } @@ -990,7 +990,7 @@ namespace System.Management.Automation.Runspaces /// public void Disconnect() { - internalPool.Disconnect(); + _internalPool.Disconnect(); } /// @@ -1000,7 +1000,7 @@ namespace System.Management.Automation.Runspaces /// A user supplied state to call the callback with. public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { - return internalPool.BeginDisconnect(callback, state); + return _internalPool.BeginDisconnect(callback, state); } /// @@ -1009,7 +1009,7 @@ namespace System.Management.Automation.Runspaces /// Asynchronous call result object. public void EndDisconnect(IAsyncResult asyncResult) { - internalPool.EndDisconnect(asyncResult); + _internalPool.EndDisconnect(asyncResult); } /// @@ -1017,7 +1017,7 @@ namespace System.Management.Automation.Runspaces /// public void Connect() { - internalPool.Connect(); + _internalPool.Connect(); } /// @@ -1027,7 +1027,7 @@ namespace System.Management.Automation.Runspaces /// public IAsyncResult BeginConnect(AsyncCallback callback, object state) { - return internalPool.BeginConnect(callback, state); + return _internalPool.BeginConnect(callback, state); } /// @@ -1036,7 +1036,7 @@ namespace System.Management.Automation.Runspaces /// Asynchronous call result object. public void EndConnect(IAsyncResult asyncResult) { - internalPool.EndConnect(asyncResult); + _internalPool.EndConnect(asyncResult); } /// @@ -1046,7 +1046,7 @@ namespace System.Management.Automation.Runspaces /// public Collection CreateDisconnectedPowerShells() { - return internalPool.CreateDisconnectedPowerShells(this); + return _internalPool.CreateDisconnectedPowerShells(this); } /// @@ -1055,7 +1055,7 @@ namespace System.Management.Automation.Runspaces /// RunspacePoolCapability public RunspacePoolCapability GetCapabilities() { - return internalPool.GetCapabilities(); + return _internalPool.GetCapabilities(); } #endregion @@ -1079,7 +1079,7 @@ namespace System.Management.Automation.Runspaces /// public bool SetMaxRunspaces(int maxRunspaces) { - return internalPool.SetMaxRunspaces(maxRunspaces); + return _internalPool.SetMaxRunspaces(maxRunspaces); } /// @@ -1090,7 +1090,7 @@ namespace System.Management.Automation.Runspaces /// public int GetMaxRunspaces() { - return internalPool.GetMaxRunspaces(); + return _internalPool.GetMaxRunspaces(); } /// @@ -1109,7 +1109,7 @@ namespace System.Management.Automation.Runspaces /// public bool SetMinRunspaces(int minRunspaces) { - return internalPool.SetMinRunspaces(minRunspaces); + return _internalPool.SetMinRunspaces(minRunspaces); } /// @@ -1120,9 +1120,9 @@ namespace System.Management.Automation.Runspaces /// public int GetMinRunspaces() { - return internalPool.GetMinRunspaces(); + return _internalPool.GetMinRunspaces(); } - + /// /// Retrieves the number of runspaces available at the time of calling /// this method. @@ -1132,7 +1132,7 @@ namespace System.Management.Automation.Runspaces /// public int GetAvailableRunspaces() { - return internalPool.GetAvailableRunspaces(); + return _internalPool.GetAvailableRunspaces(); } /// @@ -1144,7 +1144,7 @@ namespace System.Management.Automation.Runspaces /// public void Open() { - internalPool.Open(); + _internalPool.Open(); } /// @@ -1166,7 +1166,7 @@ namespace System.Management.Automation.Runspaces /// public IAsyncResult BeginOpen(AsyncCallback callback, object state) { - return internalPool.BeginOpen(callback, state); + return _internalPool.BeginOpen(callback, state); } /// @@ -1187,7 +1187,7 @@ namespace System.Management.Automation.Runspaces /// public void EndOpen(IAsyncResult asyncResult) { - internalPool.EndOpen(asyncResult); + _internalPool.EndOpen(asyncResult); } /// @@ -1203,9 +1203,9 @@ namespace System.Management.Automation.Runspaces /// public void Close() { - internalPool.Close(); + _internalPool.Close(); } - + /// /// Closes the RunspacePool asynchronously and cleans all the internal /// resources. This will close all the runspaces in the @@ -1226,7 +1226,7 @@ namespace System.Management.Automation.Runspaces /// public IAsyncResult BeginClose(AsyncCallback callback, object state) { - return internalPool.BeginClose(callback, state); + return _internalPool.BeginClose(callback, state); } /// @@ -1241,7 +1241,7 @@ namespace System.Management.Automation.Runspaces /// public void EndClose(IAsyncResult asyncResult) { - internalPool.EndClose(asyncResult); + _internalPool.EndClose(asyncResult); } /// @@ -1249,7 +1249,7 @@ namespace System.Management.Automation.Runspaces /// public void Dispose() { - internalPool.Dispose(true); + _internalPool.Dispose(true); GC.SuppressFinalize(this); } @@ -1267,7 +1267,7 @@ namespace System.Management.Automation.Runspaces /// public PSPrimitiveDictionary GetApplicationPrivateData() { - return internalPool.GetApplicationPrivateData(); + return _internalPool.GetApplicationPrivateData(); } #endregion @@ -1287,7 +1287,7 @@ namespace System.Management.Automation.Runspaces { get { - return this.internalPool.ThreadOptions; + return _internalPool.ThreadOptions; } set @@ -1297,7 +1297,7 @@ namespace System.Management.Automation.Runspaces throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } - this.internalPool.ThreadOptions = value; + _internalPool.ThreadOptions = value; } } @@ -1315,7 +1315,7 @@ namespace System.Management.Automation.Runspaces { get { - return this.internalPool.ApartmentState; + return _internalPool.ApartmentState; } set @@ -1325,7 +1325,7 @@ namespace System.Management.Automation.Runspaces throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } - this.internalPool.ApartmentState = value; + _internalPool.ApartmentState = value; } } #endif @@ -1347,7 +1347,7 @@ namespace System.Management.Automation.Runspaces internal IAsyncResult BeginGetRunspace( AsyncCallback callback, object state) { - return internalPool.BeginGetRunspace(callback, state); + return _internalPool.BeginGetRunspace(callback, state); } /// @@ -1357,7 +1357,7 @@ namespace System.Management.Automation.Runspaces /// internal void CancelGetRunspace(IAsyncResult asyncResult) { - internalPool.CancelGetRunspace(asyncResult); + _internalPool.CancelGetRunspace(asyncResult); } /// @@ -1377,7 +1377,7 @@ namespace System.Management.Automation.Runspaces /// internal Runspace EndGetRunspace(IAsyncResult asyncResult) { - return internalPool.EndGetRunspace(asyncResult); + return _internalPool.EndGetRunspace(asyncResult); } /// @@ -1399,7 +1399,7 @@ namespace System.Management.Automation.Runspaces /// internal void ReleaseRunspace(Runspace runspace) { - internalPool.ReleaseRunspace(runspace); + _internalPool.ReleaseRunspace(runspace); } /// @@ -1409,7 +1409,7 @@ namespace System.Management.Automation.Runspaces { get { - return isRemote; + return _isRemote; } } @@ -1421,9 +1421,9 @@ namespace System.Management.Automation.Runspaces { get { - if (internalPool is RemoteRunspacePoolInternal) + if (_internalPool is RemoteRunspacePoolInternal) { - return (RemoteRunspacePoolInternal)internalPool; + return (RemoteRunspacePoolInternal)_internalPool; } else { @@ -1434,7 +1434,7 @@ namespace System.Management.Automation.Runspaces internal void AssertPoolIsOpen() { - internalPool.AssertPoolIsOpen(); + _internalPool.AssertPoolIsOpen(); } #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index ca1a1d388..19ad11076 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -35,18 +35,18 @@ namespace System.Management.Automation.Runspaces.Internal protected InitialSessionState _initialSessionState; protected PSHost host; protected Guid instanceId; - private bool isDisposed; + private bool _isDisposed; protected bool isServicingRequests; protected object syncObject = new object(); - private static readonly TimeSpan DefaultCleanupPeriod = new TimeSpan(0, 15, 0); // 15 minutes. - private TimeSpan cleanupInterval; - private Timer cleanupTimer; + private static readonly TimeSpan s_defaultCleanupPeriod = new TimeSpan(0, 15, 0); // 15 minutes. + private TimeSpan _cleanupInterval; + private Timer _cleanupTimer; #endregion #region Constructor - + /// /// Constructor which creates a RunspacePool using the /// supplied , @@ -142,7 +142,7 @@ namespace System.Management.Automation.Runspaces.Internal _initialSessionState = initialSessionState.Clone(); this.host = host; - this.threadOptions = initialSessionState.ThreadOptions; + _threadOptions = initialSessionState.ThreadOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = initialSessionState.ApartmentState; @@ -187,8 +187,8 @@ namespace System.Management.Automation.Runspaces.Internal instanceId = Guid.NewGuid(); PSEtwLog.SetActivityIdForCurrentThread(instanceId); - this.cleanupInterval = DefaultCleanupPeriod; - this.cleanupTimer = new Timer(new TimerCallback(CleanupCallback), null, Timeout.Infinite, Timeout.Infinite); + _cleanupInterval = s_defaultCleanupPeriod; + _cleanupTimer = new Timer(new TimerCallback(CleanupCallback), null, Timeout.Infinite, Timeout.Infinite); } /// @@ -219,7 +219,7 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return isDisposed; + return _isDisposed; } } @@ -241,18 +241,18 @@ namespace System.Management.Automation.Runspaces.Internal /// internal virtual PSPrimitiveDictionary GetApplicationPrivateData() { - if (applicationPrivateData == null) + if (_applicationPrivateData == null) { lock (this.syncObject) { - if (applicationPrivateData == null) + if (_applicationPrivateData == null) { - applicationPrivateData = new PSPrimitiveDictionary(); + _applicationPrivateData = new PSPrimitiveDictionary(); } } } - return applicationPrivateData; + return _applicationPrivateData; } internal virtual void PropagateApplicationPrivateData(Runspace runspace) @@ -260,7 +260,7 @@ namespace System.Management.Automation.Runspaces.Internal runspace.SetApplicationPrivateData(this.GetApplicationPrivateData()); } - private PSPrimitiveDictionary applicationPrivateData; + private PSPrimitiveDictionary _applicationPrivateData; /// /// Gets the RunspaceConfiguration object that this pool uses @@ -302,12 +302,12 @@ namespace System.Management.Automation.Runspaces.Internal /// public TimeSpan CleanupInterval { - get { return this.cleanupInterval; } + get { return _cleanupInterval; } set { lock (this.syncObject) { - this.cleanupInterval = value; + _cleanupInterval = value; } } } @@ -320,7 +320,7 @@ namespace System.Management.Automation.Runspaces.Internal get { return (stateInfo.State == RunspacePoolState.Opened) ? - RunspacePoolAvailability.Available : + RunspacePoolAvailability.Available : RunspacePoolAvailability.None; } } @@ -648,12 +648,12 @@ namespace System.Management.Automation.Runspaces.Internal RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; - if ((null == rsAsyncResult) || + if ((null == rsAsyncResult) || (rsAsyncResult.OwnerId != instanceId) || (!rsAsyncResult.IsAssociatedWithAsyncOpen)) { throw PSTraceSource.NewArgumentException("asyncResult", - RunspacePoolStrings.AsyncResultNotOwned, + RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); } @@ -720,7 +720,7 @@ namespace System.Management.Automation.Runspaces.Internal (rsAsyncResult.IsAssociatedWithAsyncOpen)) { throw PSTraceSource.NewArgumentException("asyncResult", - RunspacePoolStrings.AsyncResultNotOwned, + RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginClose"); } @@ -846,16 +846,16 @@ namespace System.Management.Automation.Runspaces.Internal /// public virtual void Dispose(bool disposing) { - if (!isDisposed) + if (!_isDisposed) { if (disposing) { Close(); - cleanupTimer.Dispose(); + _cleanupTimer.Dispose(); _initialSessionState = null; host = null; } - isDisposed = true; + _isDisposed = true; } } @@ -874,15 +874,15 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return this.threadOptions; + return _threadOptions; } set { - this.threadOptions = value; + _threadOptions = value; } } - private PSThreadOptions threadOptions = PSThreadOptions.Default; + private PSThreadOptions _threadOptions = PSThreadOptions.Default; #if !CORECLR // No ApartmentState In CoreCLR /// @@ -952,7 +952,7 @@ namespace System.Management.Automation.Runspaces.Internal if ((null == grsAsyncResult) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException("asyncResult", - RunspacePoolStrings.AsyncResultNotOwned, + RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); } @@ -991,7 +991,7 @@ namespace System.Management.Automation.Runspaces.Internal if ((null == grsAsyncResult) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException("asyncResult", - RunspacePoolStrings.AsyncResultNotOwned, + RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); } @@ -1071,14 +1071,14 @@ namespace System.Management.Automation.Runspaces.Internal Runspace rs = CreateRunspace(); pool.Push(rs); } - catch(Exception exception) + catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); SetStateToBroken(exception); // rethrow the exception throw; } - + bool shouldRaiseEvents = false; // RunspacePool might be closed while we are still opening // we should not change state from closed to opened.. @@ -1133,7 +1133,7 @@ namespace System.Management.Automation.Runspaces.Internal Dbg.Assert(o is AsyncResult, "OpenThreadProc expects AsyncResult"); // Since this is an internal method, we can safely cast the // object to AsyncResult object. - AsyncResult asyncObject = (AsyncResult)o; + AsyncResult asyncObject = (AsyncResult)o; // variable to keep track of exceptions. Exception exception = null; @@ -1211,7 +1211,6 @@ namespace System.Management.Automation.Runspaces.Internal // open the runspace synchronously CloseHelper(); return null; - } private void CloseHelper() @@ -1252,7 +1251,7 @@ namespace System.Management.Automation.Runspaces.Internal asyncObject.SetAsCompleted(exception); } } - + #endregion #region Private Methods @@ -1278,7 +1277,7 @@ namespace System.Management.Automation.Runspaces.Internal /// internal void AssertPoolIsOpen() { - lock(syncObject) + lock (syncObject) { if (stateInfo.State != RunspacePoolState.Opened) { @@ -1342,7 +1341,7 @@ namespace System.Management.Automation.Runspaces.Internal // Start/Reset the cleanup timer to release idle runspaces in the pool. lock (this.syncObject) { - this.cleanupTimer.Change(CleanupInterval, CleanupInterval); + _cleanupTimer.Change(CleanupInterval, CleanupInterval); } // raise the RunspaceCreated event and let callers handle it. @@ -1383,7 +1382,7 @@ namespace System.Management.Automation.Runspaces.Internal this.stateInfo.State != RunspacePoolState.Disconnecting && this.stateInfo.State != RunspacePoolState.Connecting), "Local RunspacePool cannot be in disconnect/connect states"); - + bool isCleanupTimerChanged = false; // Clean up the pool only if more runspaces // than minimum requested are present. @@ -1403,10 +1402,10 @@ namespace System.Management.Automation.Runspaces.Internal lock (pool) { if (pool.Count <= 0) - { + { break; // break from while } - + runspaceToDestroy = pool.Pop(); } @@ -1416,7 +1415,7 @@ namespace System.Management.Automation.Runspaces.Internal { lock (this.syncObject) { - this.cleanupTimer.Change(Timeout.Infinite, Timeout.Infinite); + _cleanupTimer.Change(Timeout.Infinite, Timeout.Infinite); isCleanupTimerChanged = true; } } @@ -1577,7 +1576,7 @@ namespace System.Management.Automation.Runspaces.Internal "Local RunspacePool cannot be in disconnect/connect states"); bool useCallingThread = (bool)useCallingThreadState; - GetRunspaceAsyncResult runspaceRequester = null; + GetRunspaceAsyncResult runspaceRequester = null; try { @@ -1663,7 +1662,7 @@ namespace System.Management.Automation.Runspaces.Internal } } } while (true); - endOuterWhile: ; + endOuterWhile:; } finally { diff --git a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs index 5e68b95dd..8a09fece9 100644 --- a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs +++ b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation.Internal.Host internal partial class InternalHostUserInterface : PSHostUserInterface { - /// /// /// See base class @@ -27,16 +26,16 @@ namespace System.Management.Automation.Internal.Host PSCredential PromptForCredential ( - string caption, + string caption, string message, string userName, string targetName ) { - return PromptForCredential( caption, message, userName, + return PromptForCredential(caption, message, userName, targetName, PSCredentialTypes.Default, - PSCredentialUIOptions.Default ); + PSCredentialUIOptions.Default); } /// @@ -49,7 +48,7 @@ namespace System.Management.Automation.Internal.Host PSCredential PromptForCredential ( - string caption, + string caption, string message, string userName, string targetName, @@ -57,7 +56,7 @@ namespace System.Management.Automation.Internal.Host PSCredentialUIOptions options ) { - if (externalUI == null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -65,13 +64,13 @@ namespace System.Management.Automation.Internal.Host PSCredential result = null; try { - result = externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options); + result = _externalUI.PromptForCredential(caption, message, userName, targetName, allowedCredentialTypes, options); } catch (PipelineStoppedException) { //PipelineStoppedException is thrown by host when it wants //to stop the pipeline. - LocalPipeline lpl = (LocalPipeline) ((RunspaceBase) this.parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); if (lpl == null) { throw; @@ -81,7 +80,6 @@ namespace System.Management.Automation.Internal.Host return result; } - } } diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index f0486f58e..a6a9d0c8a 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -13,8 +13,8 @@ namespace System.Management.Automation.Runspaces using System.Threading; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Internal; - - #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings + +#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings /// /// This class has common base implementation for Pipeline class. @@ -23,7 +23,7 @@ namespace System.Management.Automation.Runspaces internal abstract class PipelineBase : Pipeline { #region constructors - + /// /// Create a pipeline initialized with a command string /// @@ -34,15 +34,15 @@ namespace System.Management.Automation.Runspaces /// /// Command is null and add to history is true /// - protected PipelineBase (Runspace runspace, string command, bool addToHistory, bool isNested) - :base(runspace) + protected PipelineBase(Runspace runspace, string command, bool addToHistory, bool isNested) + : base(runspace) { Initialize(runspace, command, addToHistory, isNested); //Initialize streams - _inputStream = new ObjectStream (); - _outputStream = new ObjectStream (); - ErrorStream = new ObjectStream (); + _inputStream = new ObjectStream(); + _outputStream = new ObjectStream(); + ErrorStream = new ObjectStream(); } /// @@ -125,8 +125,8 @@ namespace System.Management.Automation.Runspaces /// times. This is accomplished via creating a master pipeline /// then cloning it and executing the cloned copy. /// - protected PipelineBase (PipelineBase pipeline) - : this (pipeline.Runspace, null,false,pipeline.IsNested) + protected PipelineBase(PipelineBase pipeline) + : this(pipeline.Runspace, null, false, pipeline.IsNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (null == pipeline) @@ -139,20 +139,20 @@ namespace System.Management.Automation.Runspaces } _addToHistory = pipeline._addToHistory; - _historyString = pipeline._historyString; + _historyString = pipeline._historyString; foreach (Command command in pipeline.Commands) { - Command clone = command.Clone () ; + Command clone = command.Clone(); // Attach the cloned Command to this pipeline. - Commands.Add (clone); + Commands.Add(clone); } } #endregion constructors #region properties - + private Runspace _runspace; /// @@ -205,7 +205,7 @@ namespace System.Management.Automation.Runspaces } } - private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo (PipelineState.NotStarted); + private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted); /// /// Info about current state of the pipeline. @@ -220,7 +220,7 @@ namespace System.Management.Automation.Runspaces lock (SyncRoot) { //Note:We do not return internal state. - return _pipelineStateInfo.Clone (); + return _pipelineStateInfo.Clone(); } } } @@ -280,17 +280,17 @@ namespace System.Management.Automation.Runspaces /// /// Synchronous call to stop the running pipeline. /// - override public void Stop () + override public void Stop() { - CoreStop (true); + CoreStop(true); } /// /// Asynchronous call to stop the running pipeline. /// - override public void StopAsync () + override public void StopAsync() { - CoreStop (false); + CoreStop(false); } /// @@ -298,7 +298,7 @@ namespace System.Management.Automation.Runspaces /// /// If true pipeline is stoped synchronously /// else asynchronously. - private void CoreStop (bool syncCall) + private void CoreStop(bool syncCall) { //Is pipeline already in stopping state. bool alreadyStopping = false; @@ -307,8 +307,8 @@ namespace System.Management.Automation.Runspaces switch (PipelineState) { case PipelineState.NotStarted: - SetPipelineState (PipelineState.Stopping); - SetPipelineState (PipelineState.Stopped); + SetPipelineState(PipelineState.Stopping); + SetPipelineState(PipelineState.Stopped); break; //If pipeline execution has failed or completed or @@ -324,7 +324,7 @@ namespace System.Management.Automation.Runspaces break; case PipelineState.Running: - SetPipelineState (PipelineState.Stopping); + SetPipelineState(PipelineState.Stopping); break; } } @@ -342,7 +342,7 @@ namespace System.Management.Automation.Runspaces } //Raise the event outside the lock - RaisePipelineStateEvents (); + RaisePipelineStateEvents(); //A pipeline can be stoped before it is started. See NotStarted //case in above switch statement. This is done to allow stoping a pipeline @@ -360,14 +360,14 @@ namespace System.Management.Automation.Runspaces } //Start stop operation in derived class - ImplementStop (syncCall); + ImplementStop(syncCall); } - + /// /// Stop execution of pipeline /// /// If false, call is asynchronous - protected abstract void ImplementStop (bool syncCall); + protected abstract void ImplementStop(bool syncCall); #endregion stop @@ -387,7 +387,7 @@ namespace System.Management.Automation.Runspaces /// On Synchronous Invoke if output is throttled and no one is reading from /// output pipe, Execution will block after buffer is full. /// - override public Collection Invoke (IEnumerable input) + override public Collection Invoke(IEnumerable input) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -398,14 +398,14 @@ namespace System.Management.Automation.Runspaces CoreInvoke(input, true); //Wait for pipeline to finish execution - PipelineFinishedEvent.WaitOne (); + PipelineFinishedEvent.WaitOne(); if (SyncInvokeCall) { //Raise the pipeline completion events. These events are set in //pipeline execution thread. However for Synchornous execution //we raise the event in the main thread. - RaisePipelineStateEvents (); + RaisePipelineStateEvents(); } if (PipelineStateInfo.State == PipelineState.Stopped) @@ -426,7 +426,7 @@ namespace System.Management.Automation.Runspaces //Execution completed successfully // 2004/06/30-JonN was ReadAll() which was non-blocking - return Output.NonBlockingRead (Int32.MaxValue); + return Output.NonBlockingRead(Int32.MaxValue); } /// @@ -435,9 +435,9 @@ namespace System.Management.Automation.Runspaces /// /// Results are returned through the reader. /// - override public void InvokeAsync () + override public void InvokeAsync() { - CoreInvoke (null, false); + CoreInvoke(null, false); } private bool _syncInvokeCall; @@ -502,10 +502,10 @@ namespace System.Management.Automation.Runspaces if (PipelineState != PipelineState.NotStarted) { InvalidPipelineStateException e = - new InvalidPipelineStateException + new InvalidPipelineStateException ( StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed), - PipelineState, + PipelineState, PipelineState.NotStarted ); throw e; @@ -523,10 +523,10 @@ namespace System.Management.Automation.Runspaces //ObjectDisposed exception will be thrown foreach (object temp in input) { - _inputStream.Write (temp); + _inputStream.Write(temp); } } - _inputStream.Close (); + _inputStream.Close(); } _syncInvokeCall = syncCall; @@ -538,7 +538,7 @@ namespace System.Management.Automation.Runspaces //added to list of running pipelines. This avoids the race condition //where Close is called after pipeline is added to list of //running pipeline but before event is created. - _pipelineFinishedEvent = new ManualResetEvent (false); + _pipelineFinishedEvent = new ManualResetEvent(false); //1) Do the check to ensure that pipeline no other // pipeline is running. @@ -551,7 +551,7 @@ namespace System.Management.Automation.Runspaces //state where pipeline can be run. //StartPipelineExecution raises this event. See Windows Bug 1160481 for //more details. - SetPipelineState (PipelineState.Running); + SetPipelineState(PipelineState.Running); } try @@ -585,12 +585,12 @@ namespace System.Management.Automation.Runspaces /// /// Starts execution of pipeline. /// - protected abstract void StartPipelineExecution (); + protected abstract void StartPipelineExecution(); #region concurrent pipeline check - bool _performNestedCheck = true; + private bool _performNestedCheck = true; /// /// For nested pipeline, system checks that Execute is called from @@ -607,7 +607,7 @@ namespace System.Management.Automation.Runspaces } } - Thread _nestedPipelineExecutionThread; + private Thread _nestedPipelineExecutionThread; /// /// This is the thread on which NestedPipeline can be executed. @@ -646,9 +646,9 @@ namespace System.Management.Automation.Runspaces /// 3) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// - internal void DoConcurrentCheck (bool syncCall, object syncObject, bool isInLock) + internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock) { - PipelineBase currentPipeline = (PipelineBase)RunspaceBase.GetCurrentlyRunningPipeline (); + PipelineBase currentPipeline = (PipelineBase)RunspaceBase.GetCurrentlyRunningPipeline(); if (IsNested == false) { @@ -711,7 +711,7 @@ namespace System.Management.Automation.Runspaces // This shouldn't fail so we'll clear the IsNested and IsChild flags and then return // That way executions proceeds but everything gets clean up at the end when the pipeline completes this.IsChild = false; - this._isNested = false; + _isNested = false; return; } @@ -719,10 +719,10 @@ namespace System.Management.Automation.Runspaces RunspaceStrings.NestedPipelineNoParentPipeline); } - Dbg.Assert (currentPipeline.NestedPipelineExecutionThread != null, "Current pipeline should always have NestedPipelineExecutionThread set"); + Dbg.Assert(currentPipeline.NestedPipelineExecutionThread != null, "Current pipeline should always have NestedPipelineExecutionThread set"); Thread th = Thread.CurrentThread; - if (currentPipeline.NestedPipelineExecutionThread.Equals (th) == false) + if (currentPipeline.NestedPipelineExecutionThread.Equals(th) == false) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NestedPipelineNoParentPipeline); @@ -827,13 +827,13 @@ namespace System.Management.Automation.Runspaces /// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents /// raises event for each item in this queue. /// - protected void SetPipelineState (PipelineState state, Exception reason) + protected void SetPipelineState(PipelineState state, Exception reason) { lock (SyncRoot) { if (state != PipelineState) { - _pipelineStateInfo = new PipelineStateInfo (state, reason); + _pipelineStateInfo = new PipelineStateInfo(state, reason); //Add _pipelineStateInfo to _executionEventQueue. //RaisePipelineStateEvents will raise event for each item @@ -858,15 +858,15 @@ namespace System.Management.Automation.Runspaces /// Set the new execution state /// /// the new state - protected void SetPipelineState (PipelineState state) + protected void SetPipelineState(PipelineState state) { - SetPipelineState (state, null); + SetPipelineState(state, null); } /// /// Raises events for changes in execution state. /// - protected void RaisePipelineStateEvents () + protected void RaisePipelineStateEvents() { Queue tempEventQueue = null; EventHandler stateChanged = null; @@ -887,7 +887,7 @@ namespace System.Management.Automation.Runspaces //Clear the events if there are no EventHandlers. This //ensures that events do not get called for state //changes prior to their registration. - _executionEventQueue.Clear (); + _executionEventQueue.Clear(); } } @@ -920,9 +920,8 @@ namespace System.Management.Automation.Runspaces #pragma warning restore 56500 } } - } - + private ManualResetEvent _pipelineFinishedEvent; /// @@ -953,7 +952,6 @@ namespace System.Management.Automation.Runspaces { return _outputStream; } - } private ObjectStreamBase _errorStream; @@ -1022,7 +1020,7 @@ namespace System.Management.Automation.Runspaces } #endregion streams - + #region history //History information is internal so that Pipeline serialization code @@ -1110,7 +1108,7 @@ namespace System.Management.Automation.Runspaces } - private object _syncRoot = new object (); + private object _syncRoot = new object(); /// /// Object used for synchronization @@ -1130,7 +1128,7 @@ namespace System.Management.Automation.Runspaces /// /// Set to true when object is disposed /// - bool _disposed; + private bool _disposed; /// /// Protected dispose which can be overridden by derived classes. diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 4a1998503..f0f023213 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -17,18 +17,23 @@ using System; using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.Interpreter { - internal abstract class AddInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class AddInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private AddInstruction() { + private AddInstruction() + { } - internal sealed class AddInt32 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddInt32 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l + (Int32)r)); @@ -37,8 +42,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddInt16 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddInt16 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l + (Int16)r); @@ -47,8 +54,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddInt64 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddInt64 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l + (Int64)r); @@ -57,8 +66,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddUInt16 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddUInt16 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l + (UInt16)r); @@ -67,8 +78,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddUInt32 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddUInt32 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l + (UInt32)r); @@ -77,8 +90,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddUInt64 : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddUInt64 : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((Int16)l + (Int16)r); @@ -87,8 +102,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddSingle : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddSingle : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l + (Single)r); @@ -97,8 +114,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddDouble : AddInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddDouble : AddInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l + (Double)r; @@ -107,39 +126,46 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new AddInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new AddInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new AddInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AddUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AddUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AddUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new AddSingle()); - case TypeCode.Double: return _Double ?? (_Double = new AddDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new AddSingle()); + case TypeCode.Double: return s_double ?? (s_double = new AddDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "Add()"; } } - internal abstract class AddOvfInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; + internal abstract class AddOvfInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private AddOvfInstruction() { + private AddOvfInstruction() + { } - internal sealed class AddOvfInt32 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfInt32 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l + (Int32)r)); @@ -148,8 +174,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfInt16 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfInt16 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l + (Int16)r); @@ -158,8 +186,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfInt64 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfInt64 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l + (Int64)r); @@ -168,8 +198,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfUInt16 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfUInt16 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l + (UInt16)r); @@ -178,8 +210,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfUInt32 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfUInt32 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l + (UInt32)r); @@ -188,8 +222,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfUInt64 : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfUInt64 : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l + (Int16)r); @@ -198,8 +234,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfSingle : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfSingle : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l + (Single)r); @@ -208,8 +246,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class AddOvfDouble : AddOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class AddOvfDouble : AddOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l + (Double)r; @@ -218,24 +258,27 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new AddOvfInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new AddOvfInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new AddOvfInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AddOvfUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AddOvfUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AddOvfUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new AddOvfSingle()); - case TypeCode.Double: return _Double ?? (_Double = new AddOvfDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddOvfInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddOvfInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddOvfInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddOvfUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddOvfUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddOvfUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new AddOvfSingle()); + case TypeCode.Double: return s_double ?? (s_double = new AddOvfDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "AddOvf()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs b/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs index 2da18f023..e2a39751f 100644 --- a/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/ArrayOperations.cs @@ -15,20 +15,25 @@ using System; -namespace System.Management.Automation.Interpreter { - internal sealed class NewArrayInitInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal sealed class NewArrayInitInstruction : Instruction + { private readonly int _elementCount; - internal NewArrayInitInstruction(int elementCount) { + internal NewArrayInitInstruction(int elementCount) + { _elementCount = elementCount; } public override int ConsumedStack { get { return _elementCount; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { TElement[] array = new TElement[_elementCount]; - for (int i = _elementCount - 1; i >= 0; i--) { + for (int i = _elementCount - 1; i >= 0; i--) + { array[i] = (TElement)frame.Pop(); } frame.Push(array); @@ -36,24 +41,28 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class NewArrayInstruction : Instruction { + internal sealed class NewArrayInstruction : Instruction + { internal NewArrayInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { int length = (int)frame.Pop(); frame.Push(new TElement[length]); return +1; } } - internal sealed class NewArrayBoundsInstruction : Instruction { + internal sealed class NewArrayBoundsInstruction : Instruction + { private readonly Type _elementType; private readonly int _rank; - internal NewArrayBoundsInstruction(Type elementType, int rank) { + internal NewArrayBoundsInstruction(Type elementType, int rank) + { _elementType = elementType; _rank = rank; } @@ -61,9 +70,11 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return _rank; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var lengths = new int[_rank]; - for (int i = _rank - 1; i >= 0; i--) { + for (int i = _rank - 1; i >= 0; i--) + { lengths[i] = (int)frame.Pop(); } var array = Array.CreateInstance(_elementType, lengths); @@ -72,31 +83,36 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class GetArrayItemInstruction : Instruction { + internal sealed class GetArrayItemInstruction : Instruction + { internal GetArrayItemInstruction() { } public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { int index = (int)frame.Pop(); TElement[] array = (TElement[])frame.Pop(); frame.Push(array[index]); return +1; } - public override string InstructionName { + public override string InstructionName + { get { return "GetArrayItem"; } } } - internal sealed class SetArrayItemInstruction : Instruction { + internal sealed class SetArrayItemInstruction : Instruction + { internal SetArrayItemInstruction() { } public override int ConsumedStack { get { return 3; } } public override int ProducedStack { get { return 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { TElement value = (TElement)frame.Pop(); int index = (int)frame.Pop(); TElement[] array = (TElement[])frame.Pop(); @@ -104,7 +120,8 @@ namespace System.Management.Automation.Interpreter { return +1; } - public override string InstructionName { + public override string InstructionName + { get { return "SetArrayItem"; } } } diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index c93a70c2a..531a37e4a 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -18,24 +18,29 @@ using System.Diagnostics; using System.Collections.Generic; using System.Globalization; -namespace System.Management.Automation.Interpreter { - internal struct RuntimeLabel { +namespace System.Management.Automation.Interpreter +{ + internal struct RuntimeLabel + { public readonly int Index; public readonly int StackDepth; public readonly int ContinuationStackDepth; - public RuntimeLabel(int index, int continuationStackDepth, int stackDepth) { + public RuntimeLabel(int index, int continuationStackDepth, int stackDepth) + { Index = index; ContinuationStackDepth = continuationStackDepth; StackDepth = stackDepth; } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.InvariantCulture, "->{0} C({1}) S({2})", Index, ContinuationStackDepth, StackDepth); } } - internal sealed class BranchLabel { + internal sealed class BranchLabel + { internal const int UnknownIndex = Int32.MinValue; internal const int UnknownDepth = Int32.MinValue; @@ -48,65 +53,78 @@ namespace System.Management.Automation.Interpreter { // that need to be updated after we emit the label. private List _forwardBranchFixups; - public BranchLabel() { + public BranchLabel() + { } - internal int LabelIndex { + internal int LabelIndex + { get { return _labelIndex; } set { _labelIndex = value; } } - internal bool HasRuntimeLabel { - get { return _labelIndex != UnknownIndex; } + internal bool HasRuntimeLabel + { + get { return _labelIndex != UnknownIndex; } } - internal int TargetIndex { + internal int TargetIndex + { get { return _targetIndex; } } - internal int StackDepth { + internal int StackDepth + { get { return _stackDepth; } } - internal RuntimeLabel ToRuntimeLabel() { + internal RuntimeLabel ToRuntimeLabel() + { Debug.Assert(_targetIndex != UnknownIndex && _stackDepth != UnknownDepth && _continuationStackDepth != UnknownDepth); return new RuntimeLabel(_targetIndex, _continuationStackDepth, _stackDepth); } - internal void Mark(InstructionList instructions) { + internal void Mark(InstructionList instructions) + { //ContractUtils.Requires(_targetIndex == UnknownIndex && _stackDepth == UnknownDepth && _continuationStackDepth == UnknownDepth); _stackDepth = instructions.CurrentStackDepth; _continuationStackDepth = instructions.CurrentContinuationsDepth; _targetIndex = instructions.Count; - if (_forwardBranchFixups != null) { - foreach (var branchIndex in _forwardBranchFixups) { + if (_forwardBranchFixups != null) + { + foreach (var branchIndex in _forwardBranchFixups) + { FixupBranch(instructions, branchIndex); } _forwardBranchFixups = null; } } - internal void AddBranch(InstructionList instructions, int branchIndex) { + internal void AddBranch(InstructionList instructions, int branchIndex) + { Debug.Assert(((_targetIndex == UnknownIndex) == (_stackDepth == UnknownDepth))); Debug.Assert(((_targetIndex == UnknownIndex) == (_continuationStackDepth == UnknownDepth))); - if (_targetIndex == UnknownIndex) { - if (_forwardBranchFixups == null) { + if (_targetIndex == UnknownIndex) + { + if (_forwardBranchFixups == null) + { _forwardBranchFixups = new List(); } _forwardBranchFixups.Add(branchIndex); - } else { + } + else + { FixupBranch(instructions, branchIndex); } } - internal void FixupBranch(InstructionList instructions, int branchIndex) { + internal void FixupBranch(InstructionList instructions, int branchIndex) + { Debug.Assert(_targetIndex != UnknownIndex); instructions.FixupBranch(branchIndex, _targetIndex - branchIndex); } } - - } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs index 005baa1e0..bee10b2ff 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs @@ -237,160 +237,160 @@ namespace System.Management.Automation.Interpreter { } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheFunc(Func method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new FuncCallInstruction(method); + lock (s_cache) { + s_cache[info] = new FuncCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } public static MethodInfo CacheAction(Action method) { var info = method.GetMethodInfo(); - lock (_cache) { - _cache[info] = new ActionCallInstruction(method); + lock (s_cache) { + s_cache[info] = new ActionCallInstruction(method); } return info; } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs index 585adb662..485d74054 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs @@ -12,13 +12,16 @@ * * * ***************************************************************************/ + using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; -namespace System.Management.Automation.Interpreter { - internal abstract partial class CallInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal abstract partial class CallInstruction : Instruction + { public abstract MethodInfo Info { get; } /// @@ -29,39 +32,47 @@ namespace System.Management.Automation.Interpreter { #region Construction internal CallInstruction() { } - - private static readonly Dictionary _cache = new Dictionary(); - public static CallInstruction Create(MethodInfo info) { + private static readonly Dictionary s_cache = new Dictionary(); + + public static CallInstruction Create(MethodInfo info) + { return Create(info, info.GetParameters()); } /// /// Creates a new ReflectedCaller which can be used to quickly invoke the provided MethodInfo. /// - public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters) { + public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters) + { int argumentCount = parameters.Length; - if (!info.IsStatic) { + if (!info.IsStatic) + { argumentCount++; } // A workaround for CLR bug #796414 (Unable to create delegates for Array.Get/Set): // T[]::Address - not supported by ETs due to T& return value - if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) { + if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) + { return GetArrayAccessor(info, argumentCount); } - if (info is DynamicMethod || !info.IsStatic && info.DeclaringType.GetTypeInfo().IsValueType) { + if (info is DynamicMethod || !info.IsStatic && info.DeclaringType.GetTypeInfo().IsValueType) + { return new MethodInfoCallInstruction(info, argumentCount); } - if (argumentCount >= MaxHelpers) { + if (argumentCount >= MaxHelpers) + { // no delegate for this size, fallback to reflection invoke return new MethodInfoCallInstruction(info, argumentCount); } - foreach (ParameterInfo pi in parameters) { - if (pi.ParameterType.IsByRef) { + foreach (ParameterInfo pi in parameters) + { + if (pi.ParameterType.IsByRef) + { // we don't support ref args via generics. return new MethodInfoCallInstruction(info, argumentCount); } @@ -69,28 +80,40 @@ namespace System.Management.Automation.Interpreter { // see if we've created one w/ a delegate CallInstruction res; - if (ShouldCache(info)) { - lock (_cache) { - if (_cache.TryGetValue(info, out res)) { + if (ShouldCache(info)) + { + lock (s_cache) + { + if (s_cache.TryGetValue(info, out res)) + { return res; } } } // create it - try { - if (argumentCount < MaxArgs) { + try + { + if (argumentCount < MaxArgs) + { res = FastCreate(info, parameters); - } else { + } + else + { res = SlowCreate(info, parameters); } - } catch (TargetInvocationException tie) { - if (!(tie.InnerException is NotSupportedException)) { + } + catch (TargetInvocationException tie) + { + if (!(tie.InnerException is NotSupportedException)) + { throw; } res = new MethodInfoCallInstruction(info, argumentCount); - } catch (NotSupportedException) { + } + catch (NotSupportedException) + { // if Delegate.CreateDelegate can't handle the method fallback to // the slow reflection version. For example this can happen w/ // a generic method defined on an interface and implemented on a class or @@ -99,75 +122,88 @@ namespace System.Management.Automation.Interpreter { } // cache it for future users if it's a reasonable method to cache - if (ShouldCache(info)) { - lock (_cache) { - _cache[info] = res; + if (ShouldCache(info)) + { + lock (s_cache) + { + s_cache[info] = res; } } - return res; + return res; } - private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount) { + private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount) + { Type arrayType = info.DeclaringType; bool isGetter = info.Name == "Get"; - switch (arrayType.GetArrayRank()) { + switch (arrayType.GetArrayRank()) + { case 1: return Create(isGetter ? - arrayType.GetMethod("GetValue", new[] { typeof(int)}) : + arrayType.GetMethod("GetValue", new[] { typeof(int) }) : new Action(ArrayItemSetter1).GetMethodInfo() ); - - case 2: - return Create(isGetter ? + + case 2: + return Create(isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int) }) : new Action(ArrayItemSetter2).GetMethodInfo() ); - case 3: + case 3: return Create(isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int), typeof(int) }) : new Action(ArrayItemSetter3).GetMethodInfo() ); - default: + default: return new MethodInfoCallInstruction(info, argumentCount); } } - public static void ArrayItemSetter1(Array array, int index0, object value) { + public static void ArrayItemSetter1(Array array, int index0, object value) + { array.SetValue(value, index0); } - public static void ArrayItemSetter2(Array array, int index0, int index1, object value) { + public static void ArrayItemSetter2(Array array, int index0, int index1, object value) + { array.SetValue(value, index0, index1); } - public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value) { + public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value) + { array.SetValue(value, index0, index1, index2); } - private static bool ShouldCache(MethodInfo info) { + private static bool ShouldCache(MethodInfo info) + { return !(info is DynamicMethod); } - + /// /// Gets the next type or null if no more types are available. /// - private static Type TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index) { - if (!target.IsStatic) { + private static Type TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index) + { + if (!target.IsStatic) + { index--; - if (index < 0) { + if (index < 0) + { return target.DeclaringType; } } - if (index < pi.Length) { + if (index < pi.Length) + { // next in signature return pi[index].ParameterType; } - if (target.ReturnType == typeof(void) || index > pi.Length) { + if (target.ReturnType == typeof(void) || index > pi.Length) + { // no more parameters return null; } @@ -176,20 +212,24 @@ namespace System.Management.Automation.Interpreter { return target.ReturnType; } - private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi) { + private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi) + { return pi.Length != index || (pi.Length == index && !target.IsStatic); } /// /// Uses reflection to create new instance of the appropriate ReflectedCaller /// - private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { + private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) + { List types = new List(); if (!info.IsStatic) types.Add(info.DeclaringType); - foreach (ParameterInfo pi in pis) { + foreach (ParameterInfo pi in pis) + { types.Add(pi.ParameterType); } - if (info.ReturnType != typeof(void)) { + if (info.ReturnType != typeof(void)) + { types.Add(info.ReturnType); } Type[] arrTypes = types.ToArray(); @@ -204,85 +244,113 @@ namespace System.Management.Automation.Interpreter { public sealed override int ProducedStack { get { return Info.ReturnType == typeof(void) ? 0 : 1; } } public sealed override int ConsumedStack { get { return ArgumentCount; } } - public sealed override string InstructionName { + public sealed override string InstructionName + { get { return "Call"; } } - public override string ToString() { + public override string ToString() + { return "Call(" + Info + ")"; } #endregion } - internal sealed partial class MethodInfoCallInstruction : CallInstruction { + internal sealed partial class MethodInfoCallInstruction : CallInstruction + { private readonly MethodInfo _target; private readonly int _argumentCount; public override MethodInfo Info { get { return _target; } } public override int ArgumentCount { get { return _argumentCount; } } - internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) { + internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) + { _target = target; _argumentCount = argumentCount; } - - public override object Invoke(params object[] args) { + + public override object Invoke(params object[] args) + { return InvokeWorker(args); } - - public override object InvokeInstance(object instance, params object[] args) { - if (_target.IsStatic) { - try { + + public override object InvokeInstance(object instance, params object[] args) + { + if (_target.IsStatic) + { + try + { return _target.Invoke(null, args); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } - try { + try + { return _target.Invoke(instance, args); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } - private object InvokeWorker(params object[] args) { - if (_target.IsStatic) { - try { + private object InvokeWorker(params object[] args) + { + if (_target.IsStatic) + { + try + { return _target.Invoke(null, args); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } - try { + try + { return _target.Invoke(args[0], GetNonStaticArgs(args)); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } - private static object[] GetNonStaticArgs(object[] args) { + private static object[] GetNonStaticArgs(object[] args) + { object[] newArgs = new object[args.Length - 1]; - for (int i = 0; i < newArgs.Length; i++) { + for (int i = 0; i < newArgs.Length; i++) + { newArgs[i] = args[i + 1]; } return newArgs; } - public sealed override int Run(InterpretedFrame frame) { + public sealed override int Run(InterpretedFrame frame) + { int first = frame.StackIndex - _argumentCount; object[] args = new object[_argumentCount]; - for (int i = 0; i < args.Length; i++) { + for (int i = 0; i < args.Length; i++) + { args[i] = frame.Data[first + i]; } object ret = Invoke(args); - if (_target.ReturnType != typeof(void)) { + if (_target.ReturnType != typeof(void)) + { frame.Data[first] = ret; frame.StackIndex = first + 1; - } else { + } + else + { frame.StackIndex = first; } return 1; diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index cd71aa921..e7260054d 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -24,10 +24,12 @@ using System.Management.Automation.Language; using System.Runtime.CompilerServices; using System.Threading; -namespace System.Management.Automation.Interpreter { +namespace System.Management.Automation.Interpreter +{ using LoopFunc = Func[], InterpretedFrame, int>; - internal abstract class OffsetInstruction : Instruction { + internal abstract class OffsetInstruction : Instruction + { internal const int Unknown = Int32.MinValue; internal const int CacheSize = 32; @@ -37,48 +39,59 @@ namespace System.Management.Automation.Interpreter { public int Offset { get { return _offset; } } public abstract Instruction[] Cache { get; } - public Instruction Fixup(int offset) { + public Instruction Fixup(int offset) + { Debug.Assert(_offset == Unknown && offset != Unknown); _offset = offset; var cache = Cache; - if (cache != null && offset >= 0 && offset < cache.Length) { + if (cache != null && offset >= 0 && offset < cache.Length) + { return cache[offset] ?? (cache[offset] = this); } return this; } - public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { + public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) + { return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : ""); } - public override string ToString() { + public override string ToString() + { return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")"); } } - internal sealed class BranchFalseInstruction : OffsetInstruction { - private static Instruction[] _cache; + internal sealed class BranchFalseInstruction : OffsetInstruction + { + private static Instruction[] s_cache; - public override Instruction[] Cache { - get { - if (_cache == null) { - _cache = new Instruction[CacheSize]; + public override Instruction[] Cache + { + get + { + if (s_cache == null) + { + s_cache = new Instruction[CacheSize]; } - return _cache; + return s_cache; } } - internal BranchFalseInstruction() { + internal BranchFalseInstruction() + { } public override int ConsumedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { Debug.Assert(_offset != Unknown); - if (!(bool)frame.Pop()) { + if (!(bool)frame.Pop()) + { return _offset; } @@ -86,27 +99,34 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class BranchTrueInstruction : OffsetInstruction { - private static Instruction[] _cache; + internal sealed class BranchTrueInstruction : OffsetInstruction + { + private static Instruction[] s_cache; - public override Instruction[] Cache { - get { - if (_cache == null) { - _cache = new Instruction[CacheSize]; + public override Instruction[] Cache + { + get + { + if (s_cache == null) + { + s_cache = new Instruction[CacheSize]; } - return _cache; + return s_cache; } } - internal BranchTrueInstruction() { + internal BranchTrueInstruction() + { } public override int ConsumedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { Debug.Assert(_offset != Unknown); - if ((bool)frame.Pop()) { + if ((bool)frame.Pop()) + { return _offset; } @@ -114,28 +134,35 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class CoalescingBranchInstruction : OffsetInstruction { - private static Instruction[] _cache; + internal sealed class CoalescingBranchInstruction : OffsetInstruction + { + private static Instruction[] s_cache; - public override Instruction[] Cache { - get { - if (_cache == null) { - _cache = new Instruction[CacheSize]; + public override Instruction[] Cache + { + get + { + if (s_cache == null) + { + s_cache = new Instruction[CacheSize]; } - return _cache; + return s_cache; } } - internal CoalescingBranchInstruction() { + internal CoalescingBranchInstruction() + { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { Debug.Assert(_offset != Unknown); - if (frame.Peek() != null) { + if (frame.Peek() != null) + { return _offset; } @@ -143,15 +170,19 @@ namespace System.Management.Automation.Interpreter { } } - internal class BranchInstruction : OffsetInstruction { - private static Instruction[][][] _caches; + internal class BranchInstruction : OffsetInstruction + { + private static Instruction[][][] s_caches; - public override Instruction[] Cache { - get { - if (_caches == null) { - _caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; + public override Instruction[] Cache + { + get + { + if (s_caches == null) + { + s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } - return _caches[ConsumedStack][ProducedStack] ?? (_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); + return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); } } @@ -159,50 +190,60 @@ namespace System.Management.Automation.Interpreter { internal readonly bool _hasValue; internal BranchInstruction() - : this(false, false) { + : this(false, false) + { } - public BranchInstruction(bool hasResult, bool hasValue) { + public BranchInstruction(bool hasResult, bool hasValue) + { _hasResult = hasResult; _hasValue = hasValue; } - public override int ConsumedStack { + public override int ConsumedStack + { get { return _hasValue ? 1 : 0; } } - public override int ProducedStack { + public override int ProducedStack + { get { return _hasResult ? 1 : 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { Debug.Assert(_offset != Unknown); return _offset; } } - internal abstract class IndexedBranchInstruction : Instruction { + internal abstract class IndexedBranchInstruction : Instruction + { protected const int CacheSize = 32; internal readonly int _labelIndex; - public IndexedBranchInstruction(int labelIndex) { + public IndexedBranchInstruction(int labelIndex) + { _labelIndex = labelIndex; } - public RuntimeLabel GetLabel(InterpretedFrame frame) { + public RuntimeLabel GetLabel(InterpretedFrame frame) + { Debug.Assert(_labelIndex != UnknownInstrIndex); return frame.Interpreter._labels[_labelIndex]; } - public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { + public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) + { Debug.Assert(_labelIndex != UnknownInstrIndex); int targetIndex = labelIndexer(_labelIndex); return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : ""); } - public override string ToString() { + public override string ToString() + { Debug.Assert(_labelIndex != UnknownInstrIndex); return InstructionName + "[" + _labelIndex + "]"; } @@ -232,9 +273,10 @@ namespace System.Management.Automation.Interpreter { /// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and /// the current thread is in "abort requested" state. /// - internal sealed class GotoInstruction : IndexedBranchInstruction { + internal sealed class GotoInstruction : IndexedBranchInstruction + { private const int Variants = 4; - private static readonly GotoInstruction[] Cache = new GotoInstruction[Variants * CacheSize]; + private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize]; private readonly bool _hasResult; @@ -249,29 +291,35 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedContinuations { get { return 0; } } public override int ProducedContinuations { get { return 0; } } - public override int ConsumedStack { + public override int ConsumedStack + { get { return _hasValue ? 1 : 0; } } - public override int ProducedStack { + public override int ProducedStack + { get { return _hasResult ? 1 : 0; } } private GotoInstruction(int targetIndex, bool hasResult, bool hasValue) - : base(targetIndex) { + : base(targetIndex) + { _hasResult = hasResult; _hasValue = hasValue; } - internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue) { - if (labelIndex < CacheSize) { + internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue) + { + if (labelIndex < CacheSize) + { var index = Variants * labelIndex | (hasResult ? 2 : 0) | (hasValue ? 1 : 0); - return Cache[index] ?? (Cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue)); + return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue)); } return new GotoInstruction(labelIndex, hasResult, hasValue); } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // Are we jumping out of catch/finally while aborting the current thread? Interpreter.AbortThreadIfRequested(frame, _labelIndex); @@ -280,12 +328,13 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction { - + internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction + { private readonly bool _hasFinally = false; private TryCatchFinallyHandler _tryHandler; - internal void SetTryHandler(TryCatchFinallyHandler tryHandler) { + internal void SetTryHandler(TryCatchFinallyHandler tryHandler) + { Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } @@ -293,21 +342,26 @@ namespace System.Management.Automation.Interpreter { public override int ProducedContinuations { get { return _hasFinally ? 1 : 0; } } private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally) - : base(targetIndex) { + : base(targetIndex) + { _hasFinally = hasFinally; } - internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex) { + internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex) + { return new EnterTryCatchFinallyInstruction(labelIndex, true); } - internal static EnterTryCatchFinallyInstruction CreateTryCatch() { + internal static EnterTryCatchFinallyInstruction CreateTryCatch() + { return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false); } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); - if (_hasFinally) { + if (_hasFinally) + { // Push finally. frame.PushContinuation(_labelIndex); } @@ -316,24 +370,31 @@ namespace System.Management.Automation.Interpreter { // Start to run the try/catch/finally blocks var instructions = frame.Interpreter.Instructions.Instructions; - try { + try + { // run the try block int index = frame.InstructionIndex; - while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) { + while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) + { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the try block and is about to jump out of the try/catch blocks - if (index == _tryHandler.GotoEndTargetIndex) { + if (index == _tryHandler.GotoEndTargetIndex) + { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumpes out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } - } catch (RethrowException) { + } + catch (RethrowException) + { // a rethrow instruction in the try handler gets to run throw; - } catch (Exception exception) { + } + catch (Exception exception) + { frame.SaveTraceToException(exception); // rethrow if there is no catch blocks defined for this try block if (!_tryHandler.IsCatchBlockExist) { throw; } @@ -345,33 +406,41 @@ namespace System.Management.Automation.Interpreter { #if !CORECLR // Thread.Abort and ThreadAbortException are not in CoreCLR. // stay in the current catch so that ThreadAbortException is not rethrown by CLR: var abort = exception as ThreadAbortException; - if (abort != null) { + if (abort != null) + { Interpreter.AnyAbortException = abort; frame.CurrentAbortHandler = exHandler; } #endif bool rethrow = false; - try { + try + { // run the catch block int index = frame.InstructionIndex; - while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex) { + while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex) + { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the catch block and is about to jump out of the try/catch blocks - if (index == _tryHandler.GotoEndTargetIndex) { + if (index == _tryHandler.GotoEndTargetIndex) + { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumpes out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } - } catch (RethrowException) { + } + catch (RethrowException) + { // a rethrow instruction in a catch block gets to run rethrow = true; } if (rethrow) { throw; } - } finally { + } + finally + { if (_tryHandler.IsFinallyBlockExist) { // We get to the finally block in two paths: @@ -388,7 +457,8 @@ namespace System.Management.Automation.Interpreter { // run the finally block // we cannot jump out of the finally block, and we cannot have an immediate rethrow in it int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex; - while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) { + while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) + { index += instructions[index].Run(frame); frame.InstructionIndex = index; } @@ -412,28 +482,34 @@ namespace System.Management.Automation.Interpreter { /// /// The first instruction of finally block. /// - internal sealed class EnterFinallyInstruction : IndexedBranchInstruction { - private readonly static EnterFinallyInstruction[] Cache = new EnterFinallyInstruction[CacheSize]; + internal sealed class EnterFinallyInstruction : IndexedBranchInstruction + { + private readonly static EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize]; public override int ProducedStack { get { return 2; } } public override int ConsumedContinuations { get { return 1; } } - private EnterFinallyInstruction(int labelIndex) - : base (labelIndex) { + private EnterFinallyInstruction(int labelIndex) + : base(labelIndex) + { } - internal static EnterFinallyInstruction Create(int labelIndex) { - if (labelIndex < CacheSize) { - return Cache[labelIndex] ?? (Cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); + internal static EnterFinallyInstruction Create(int labelIndex) + { + if (labelIndex < CacheSize) + { + return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); } return new EnterFinallyInstruction(labelIndex); } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown // in this case we need to set the stack depth // Else we were getting into this finnaly block from a 'Goto' jump, and the stack depth is alreayd set properly - if (!frame.IsJumpHappened()) { + if (!frame.IsJumpHappened()) + { frame.SetStackDepth(GetLabel(frame).StackDepth); } @@ -446,15 +522,18 @@ namespace System.Management.Automation.Interpreter { /// /// The last instruction of finally block. /// - internal sealed class LeaveFinallyInstruction : Instruction { + internal sealed class LeaveFinallyInstruction : Instruction + { internal static readonly Instruction Instance = new LeaveFinallyInstruction(); public override int ConsumedStack { get { return 2; } } - - private LeaveFinallyInstruction() { + + private LeaveFinallyInstruction() + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.PopPendingContinuation(); // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown @@ -466,14 +545,16 @@ namespace System.Management.Automation.Interpreter { } // no-op: we need this just to balance the stack depth. - internal sealed class EnterExceptionHandlerInstruction : Instruction { + internal sealed class EnterExceptionHandlerInstruction : Instruction + { internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false); internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true); // True if try-expression is non-void. private readonly bool _hasValue; - private EnterExceptionHandlerInstruction(bool hasValue) { + private EnterExceptionHandlerInstruction(bool hasValue) + { _hasValue = hasValue; } @@ -489,7 +570,8 @@ namespace System.Management.Automation.Interpreter { // Fault handlers: The value is kept on stack during fault handler evaluation. public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // nop (the exception value is pushed by the interpreter in HandleCatch) return 1; } @@ -498,34 +580,41 @@ namespace System.Management.Automation.Interpreter { /// /// The last instruction of a catch exception handler. /// - internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction { - private static LeaveExceptionHandlerInstruction[] Cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; + internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction + { + private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; private readonly bool _hasValue; // The catch block yields a value if the body is non-void. This value is left on the stack. - public override int ConsumedStack { + public override int ConsumedStack + { get { return _hasValue ? 1 : 0; } } - public override int ProducedStack { + public override int ProducedStack + { get { return _hasValue ? 1 : 0; } } private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue) - : base(labelIndex) { + : base(labelIndex) + { _hasValue = hasValue; } - internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue) { - if (labelIndex < CacheSize) { + internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue) + { + if (labelIndex < CacheSize) + { int index = (2 * labelIndex) | (hasValue ? 1 : 0); - return Cache[index] ?? (Cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); + return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); } return new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread. Interpreter.AbortThreadIfRequested(frame, _labelIndex); return GetLabel(frame).Index - frame.InstructionIndex; @@ -535,7 +624,8 @@ namespace System.Management.Automation.Interpreter { /// /// The last instruction of a fault exception handler. /// - internal sealed class LeaveFaultInstruction : Instruction { + internal sealed class LeaveFaultInstruction : Instruction + { internal static readonly Instruction NonVoid = new LeaveFaultInstruction(true); internal static readonly Instruction Void = new LeaveFaultInstruction(false); @@ -545,20 +635,24 @@ namespace System.Management.Automation.Interpreter { // We compile the body of a fault block as void. // However, we keep the exception object that was pushed upon entering the fault block on the stack during execution of the block // and pop it at the end. - public override int ConsumedStack { + public override int ConsumedStack + { get { return 1; } } // While emitting instructions a non-void try-fault expression is expected to produce a value. - public override int ProducedStack { + public override int ProducedStack + { get { return _hasValue ? 1 : 0; } } - private LeaveFaultInstruction(bool hasValue) { + private LeaveFaultInstruction(bool hasValue) + { _hasValue = hasValue; } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // TODO: ThreadAbortException ? object exception = frame.Pop(); @@ -569,7 +663,8 @@ namespace System.Management.Automation.Interpreter { } - internal sealed class ThrowInstruction : Instruction { + internal sealed class ThrowInstruction : Instruction + { internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false); internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false); internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true); @@ -577,24 +672,30 @@ namespace System.Management.Automation.Interpreter { private readonly bool _hasResult, _rethrow; - private ThrowInstruction(bool hasResult, bool isRethrow) { + private ThrowInstruction(bool hasResult, bool isRethrow) + { _hasResult = hasResult; _rethrow = isRethrow; } - public override int ProducedStack { + public override int ProducedStack + { get { return _hasResult ? 1 : 0; } } - public override int ConsumedStack { - get { - return 1; + public override int ConsumedStack + { + get + { + return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var ex = (Exception)frame.Pop(); - if (_rethrow) { + if (_rethrow) + { // ExceptionHandler handler; // return frame.Interpreter.GotoHandler(frame, ex, out handler); throw new RethrowException(); @@ -603,10 +704,12 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SwitchInstruction : Instruction { + internal sealed class SwitchInstruction : Instruction + { private readonly Dictionary _cases; - internal SwitchInstruction(Dictionary cases) { + internal SwitchInstruction(Dictionary cases) + { Assert.NotNull(cases); _cases = cases; } @@ -614,33 +717,38 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { int target; return _cases.TryGetValue((int)frame.Pop(), out target) ? target : 1; } } - internal sealed class EnterLoopInstruction : Instruction { + internal sealed class EnterLoopInstruction : Instruction + { private readonly int _instructionIndex; private Dictionary _variables; private Dictionary _closureVariables; private PowerShellLoopExpression _loop; private int _loopEnd; private int _compilationThreshold; - - internal EnterLoopInstruction(PowerShellLoopExpression loop, LocalVariables locals, int compilationThreshold, int instructionIndex) { + + internal EnterLoopInstruction(PowerShellLoopExpression loop, LocalVariables locals, int compilationThreshold, int instructionIndex) + { _loop = loop; _variables = locals.CopyLocals(); _closureVariables = locals.ClosureVariables; _compilationThreshold = compilationThreshold; _instructionIndex = instructionIndex; } - - internal void FinishLoop(int loopEnd) { + + internal void FinishLoop(int loopEnd) + { _loopEnd = loopEnd; } - - public override int Run(InterpretedFrame frame) { + + public override int Run(InterpretedFrame frame) + { // Don't lock here, it's a frequently hit path. // // There could be multiple threads racing, but that is okay. @@ -652,40 +760,49 @@ namespace System.Management.Automation.Interpreter { // The second we explicitly guard against inside of Compile(). // // We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation. - if (unchecked(_compilationThreshold--) == 0) { - if (frame.Interpreter.CompileSynchronously) { + if (unchecked(_compilationThreshold--) == 0) + { + if (frame.Interpreter.CompileSynchronously) + { Compile(frame); - } else { + } + else + { // Kick off the compile on another thread so this one can keep going ThreadPool.QueueUserWorkItem(Compile, frame); } } return 1; } - - private bool Compiled { + + private bool Compiled + { get { return _loop == null; } } - - private void Compile(object frameObj) { - if (Compiled) { + + private void Compile(object frameObj) + { + if (Compiled) + { return; } - - lock (this) { - if (Compiled) { + + lock (this) + { + if (Compiled) + { return; } - + //PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted loop compiled"); - + InterpretedFrame frame = (InterpretedFrame)frameObj; var compiler = new LoopCompiler(_loop, frame.Interpreter.LabelMapping, _variables, _closureVariables, _instructionIndex, _loopEnd); var instructions = frame.Interpreter.Instructions.Instructions; - + // replace this instruction with an optimized one: instructions[_instructionIndex] = new CompiledLoopInstruction(compiler.CreateDelegate()); - + // invalidate this instruction, some threads may still hold on it: _loop = null; _variables = null; @@ -694,15 +811,18 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class CompiledLoopInstruction : Instruction { + internal sealed class CompiledLoopInstruction : Instruction + { private readonly LoopFunc _compiledLoop; - public CompiledLoopInstruction(LoopFunc compiledLoop) { + public CompiledLoopInstruction(LoopFunc compiledLoop) + { Assert.NotNull(compiledLoop); _compiledLoop = compiledLoop; } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { return _compiledLoop(frame.Data, frame.Closure, frame); } } diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index 3f8c0b598..e4e096dd2 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -18,18 +18,23 @@ using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.Interpreter { - internal abstract class DivInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class DivInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private DivInstruction() { + private DivInstruction() + { } - internal sealed class DivInt32 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivInt32 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject((Int32)l / (Int32)r); @@ -38,8 +43,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivInt16 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivInt16 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)((Int16)l / (Int16)r); @@ -48,8 +55,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivInt64 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivInt64 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)((Int64)l / (Int64)r); @@ -58,8 +67,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivUInt16 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivUInt16 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)((UInt16)l / (UInt16)r); @@ -68,8 +79,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivUInt32 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivUInt32 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)((UInt32)l / (UInt32)r); @@ -78,8 +91,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivUInt64 : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivUInt64 : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)((Int16)l / (Int16)r); @@ -88,8 +103,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivSingle : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivSingle : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l / (Single)r); @@ -98,8 +115,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class DivDouble : DivInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class DivDouble : DivInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l / (Double)r; @@ -108,24 +127,27 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new DivInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new DivInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new DivInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new DivUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new DivUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new DivUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new DivSingle()); - case TypeCode.Double: return _Double ?? (_Double = new DivDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new DivInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new DivInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new DivInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new DivUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new DivUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new DivUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new DivSingle()); + case TypeCode.Double: return s_double ?? (s_double = new DivDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "Div()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs b/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs index a88466a61..4f84132d5 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicInstructionN.cs @@ -19,15 +19,18 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection; -namespace System.Management.Automation.Interpreter { - internal sealed partial class DynamicInstructionN : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal sealed partial class DynamicInstructionN : Instruction + { private readonly CallInstruction _target; private readonly object _targetDelegate; private readonly CallSite _site; private readonly int _argumentCount; private readonly bool _isVoid; - public DynamicInstructionN(Type delegateType, CallSite site) { + public DynamicInstructionN(Type delegateType, CallSite site) + { var methodInfo = delegateType.GetMethod("Invoke"); var parameters = methodInfo.GetParameters(); @@ -38,25 +41,31 @@ namespace System.Management.Automation.Interpreter { } public DynamicInstructionN(Type delegateType, CallSite site, bool isVoid) - : this(delegateType, site) { + : this(delegateType, site) + { _isVoid = isVoid; } public override int ProducedStack { get { return _isVoid ? 0 : 1; } } public override int ConsumedStack { get { return _argumentCount; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { int first = frame.StackIndex - _argumentCount; object[] args = new object[1 + _argumentCount]; args[0] = _site; - for (int i = 0; i < _argumentCount; i++) { + for (int i = 0; i < _argumentCount; i++) + { args[1 + i] = frame.Data[first + i]; } object ret = _target.InvokeInstance(_targetDelegate, args); - if (_isVoid) { + if (_isVoid) + { frame.StackIndex = first; - } else { + } + else + { frame.Data[first] = ret; frame.StackIndex = first + 1; } @@ -64,7 +73,8 @@ namespace System.Management.Automation.Interpreter { return 1; } - public override string ToString() { + public override string ToString() + { return "DynamicInstructionN(" + _site + ")"; } } diff --git a/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs b/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs index 24ff94058..3279931df 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs @@ -19,15 +19,18 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection; -namespace System.Management.Automation.Interpreter { +namespace System.Management.Automation.Interpreter +{ /// /// Implements dynamic call site with many arguments. Wraps the arguments into . /// - internal sealed partial class DynamicSplatInstruction : Instruction { + internal sealed partial class DynamicSplatInstruction : Instruction + { private readonly CallSite> _site; private readonly int _argumentCount; - internal DynamicSplatInstruction(int argumentCount, CallSite> site) { + internal DynamicSplatInstruction(int argumentCount, CallSite> site) + { _site = site; _argumentCount = argumentCount; } @@ -35,7 +38,8 @@ namespace System.Management.Automation.Interpreter { public override int ProducedStack { get { return 1; } } public override int ConsumedStack { get { return _argumentCount; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { int first = frame.StackIndex - _argumentCount; object ret = _site.Target(_site, new ArgumentArray(frame.Data, first, _argumentCount)); frame.Data[first] = ret; @@ -44,7 +48,8 @@ namespace System.Management.Automation.Interpreter { return 1; } - public override string ToString() { + public override string ToString() + { return "DynamicSplatInstruction(" + _site + ")"; } } diff --git a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs index 0ba982e4b..229beddf6 100644 --- a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs @@ -19,132 +19,164 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal abstract class EqualInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal abstract class EqualInstruction : Instruction + { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double; + private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private EqualInstruction() { + private EqualInstruction() + { } - internal sealed class EqualBoolean : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualBoolean : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Boolean)frame.Pop()) == ((Boolean)frame.Pop())); return +1; } } - internal sealed class EqualSByte : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualSByte : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((SByte)frame.Pop()) == ((SByte)frame.Pop())); return +1; } } - internal sealed class EqualInt16 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualInt16 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int16)frame.Pop()) == ((Int16)frame.Pop())); return +1; } } - internal sealed class EqualChar : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualChar : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Char)frame.Pop()) == ((Char)frame.Pop())); return +1; } } - internal sealed class EqualInt32 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualInt32 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int32)frame.Pop()) == ((Int32)frame.Pop())); return +1; } } - internal sealed class EqualInt64 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualInt64 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int64)frame.Pop()) == ((Int64)frame.Pop())); return +1; } } - internal sealed class EqualByte : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualByte : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Byte)frame.Pop()) == ((Byte)frame.Pop())); return +1; } } - internal sealed class EqualUInt16 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualUInt16 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt16)frame.Pop()) == ((UInt16)frame.Pop())); return +1; } } - internal sealed class EqualUInt32 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualUInt32 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt32)frame.Pop()) == ((UInt32)frame.Pop())); return +1; } } - internal sealed class EqualUInt64 : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualUInt64 : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt64)frame.Pop()) == ((UInt64)frame.Pop())); return +1; } } - internal sealed class EqualSingle : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualSingle : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Single)frame.Pop()) == ((Single)frame.Pop())); return +1; } } - internal sealed class EqualDouble : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualDouble : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Double)frame.Pop()) == ((Double)frame.Pop())); return +1; } } - internal sealed class EqualReference : EqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class EqualReference : EqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(frame.Pop() == frame.Pop()); return +1; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { var typeInfo = type.GetTypeInfo(); // Boxed enums can be unboxed as their underlying types: var typeToUse = typeInfo.IsEnum ? Enum.GetUnderlyingType(type) : type; - switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return _Boolean ?? (_Boolean = new EqualBoolean()); - case TypeCode.SByte: return _SByte ?? (_SByte = new EqualSByte()); - case TypeCode.Byte: return _Byte ?? (_Byte = new EqualByte()); - case TypeCode.Char: return _Char ?? (_Char = new EqualChar()); - case TypeCode.Int16: return _Int16 ?? (_Int16 = new EqualInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new EqualInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new EqualInt64()); + switch (typeToUse.GetTypeCode()) + { + case TypeCode.Boolean: return s_boolean ?? (s_boolean = new EqualBoolean()); + case TypeCode.SByte: return s_SByte ?? (s_SByte = new EqualSByte()); + case TypeCode.Byte: return s_byte ?? (s_byte = new EqualByte()); + case TypeCode.Char: return s_char ?? (s_char = new EqualChar()); + case TypeCode.Int16: return s_int16 ?? (s_int16 = new EqualInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new EqualInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new EqualInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new EqualInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new EqualInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new EqualInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new EqualInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new EqualInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new EqualInt64()); - case TypeCode.Single: return _Single ?? (_Single = new EqualSingle()); - case TypeCode.Double: return _Double ?? (_Double = new EqualDouble()); + case TypeCode.Single: return s_single ?? (s_single = new EqualSingle()); + case TypeCode.Double: return s_double ?? (s_double = new EqualDouble()); case TypeCode.Object: - if (!typeInfo.IsValueType) { - return _Reference ?? (_Reference = new EqualReference()); + if (!typeInfo.IsValueType) + { + return s_reference ?? (s_reference = new EqualReference()); } // TODO: Nullable throw new NotImplementedException(); @@ -154,7 +186,8 @@ namespace System.Management.Automation.Interpreter { } } - public override string ToString() { + public override string ToString() + { return "Equal()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/FieldOperations.cs b/src/System.Management.Automation/engine/interpreter/FieldOperations.cs index 7f1b87cba..489139b3b 100644 --- a/src/System.Management.Automation/engine/interpreter/FieldOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/FieldOperations.cs @@ -19,27 +19,33 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal sealed class LoadStaticFieldInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal sealed class LoadStaticFieldInstruction : Instruction + { private readonly FieldInfo _field; - public LoadStaticFieldInstruction(FieldInfo field) { + public LoadStaticFieldInstruction(FieldInfo field) + { Debug.Assert(field.IsStatic); _field = field; } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push(_field.GetValue(null)); return +1; } } - internal sealed class LoadFieldInstruction : Instruction { + internal sealed class LoadFieldInstruction : Instruction + { private readonly FieldInfo _field; - public LoadFieldInstruction(FieldInfo field) { + public LoadFieldInstruction(FieldInfo field) + { Assert.NotNull(field); _field = field; } @@ -47,16 +53,19 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push(_field.GetValue(frame.Pop())); return +1; } } - internal sealed class StoreFieldInstruction : Instruction { + internal sealed class StoreFieldInstruction : Instruction + { private readonly FieldInfo _field; - public StoreFieldInstruction(FieldInfo field) { + public StoreFieldInstruction(FieldInfo field) + { Assert.NotNull(field); _field = field; } @@ -64,7 +73,8 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { object value = frame.Pop(); object self = frame.Pop(); _field.SetValue(self, value); @@ -72,10 +82,12 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class StoreStaticFieldInstruction : Instruction { + internal sealed class StoreStaticFieldInstruction : Instruction + { private readonly FieldInfo _field; - public StoreStaticFieldInstruction(FieldInfo field) { + public StoreStaticFieldInstruction(FieldInfo field) + { Assert.NotNull(field); _field = field; } @@ -83,7 +95,8 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { object value = frame.Pop(); _field.SetValue(null, value); return +1; diff --git a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs index 2a6b9fb31..fdc95c243 100644 --- a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs @@ -19,125 +19,153 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal abstract class GreaterThanInstruction : Instruction { - private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class GreaterThanInstruction : Instruction + { + private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private GreaterThanInstruction() { + private GreaterThanInstruction() + { } - internal sealed class GreaterThanSByte : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanSByte : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { SByte right = (SByte)frame.Pop(); frame.Push(((SByte)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanInt16 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanInt16 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int16 right = (Int16)frame.Pop(); frame.Push(((Int16)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanChar : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanChar : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Char right = (Char)frame.Pop(); frame.Push(((Char)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanInt32 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanInt32 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int32 right = (Int32)frame.Pop(); frame.Push(((Int32)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanInt64 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanInt64 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int64 right = (Int64)frame.Pop(); frame.Push(((Int64)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanByte : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanByte : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Byte right = (Byte)frame.Pop(); frame.Push(((Byte)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanUInt16 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanUInt16 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt16 right = (UInt16)frame.Pop(); frame.Push(((UInt16)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanUInt32 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanUInt32 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt32 right = (UInt32)frame.Pop(); frame.Push(((UInt32)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanUInt64 : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanUInt64 : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt64 right = (UInt64)frame.Pop(); frame.Push(((UInt64)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanSingle : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanSingle : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Single right = (Single)frame.Pop(); frame.Push(((Single)frame.Pop()) > right); return +1; } } - internal sealed class GreaterThanDouble : GreaterThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class GreaterThanDouble : GreaterThanInstruction + { + public override int Run(InterpretedFrame frame) + { Double right = (Double)frame.Pop(); frame.Push(((Double)frame.Pop()) > right); return +1; } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.SByte: return _SByte ?? (_SByte = new GreaterThanSByte()); - case TypeCode.Byte: return _Byte ?? (_Byte = new GreaterThanByte()); - case TypeCode.Char: return _Char ?? (_Char = new GreaterThanChar()); - case TypeCode.Int16: return _Int16 ?? (_Int16 = new GreaterThanInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new GreaterThanInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new GreaterThanInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new GreaterThanUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new GreaterThanUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new GreaterThanUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new GreaterThanSingle()); - case TypeCode.Double: return _Double ?? (_Double = new GreaterThanDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanSByte()); + case TypeCode.Byte: return s_byte ?? (s_byte = new GreaterThanByte()); + case TypeCode.Char: return s_char ?? (s_char = new GreaterThanChar()); + case TypeCode.Int16: return s_int16 ?? (s_int16 = new GreaterThanInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new GreaterThanInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new GreaterThanInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new GreaterThanSingle()); + case TypeCode.Double: return s_double ?? (s_double = new GreaterThanDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "GreaterThan()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs b/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs index 0c9047fd6..a994e5bb0 100644 --- a/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs +++ b/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs @@ -25,8 +25,10 @@ using System.Management.Automation.Interpreter; using System.Runtime.CompilerServices; using System.Collections.Generic; -namespace System.Management.Automation.Interpreter { - internal interface ILightCallSiteBinder { +namespace System.Management.Automation.Interpreter +{ + internal interface ILightCallSiteBinder + { bool AcceptsArgumentArray { get; } } } diff --git a/src/System.Management.Automation/engine/interpreter/Instruction.cs b/src/System.Management.Automation/engine/interpreter/Instruction.cs index 3562e8eb3..542ba84e6 100644 --- a/src/System.Management.Automation/engine/interpreter/Instruction.cs +++ b/src/System.Management.Automation/engine/interpreter/Instruction.cs @@ -19,12 +19,15 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal interface IInstructionProvider { +namespace System.Management.Automation.Interpreter +{ + internal interface IInstructionProvider + { void AddInstructions(LightCompiler compiler); } - internal abstract partial class Instruction { + internal abstract partial class Instruction + { public const int UnknownInstrIndex = int.MaxValue; public virtual int ConsumedStack { get { return 0; } } @@ -32,40 +35,48 @@ namespace System.Management.Automation.Interpreter { public virtual int ConsumedContinuations { get { return 0; } } public virtual int ProducedContinuations { get { return 0; } } - public int StackBalance { + public int StackBalance + { get { return ProducedStack - ConsumedStack; } } - public int ContinuationsBalance { + public int ContinuationsBalance + { get { return ProducedContinuations - ConsumedContinuations; } } public abstract int Run(InterpretedFrame frame); - public virtual string InstructionName { + public virtual string InstructionName + { get { return GetType().Name.Replace("Instruction", ""); } } - public override string ToString() { + public override string ToString() + { return InstructionName + "()"; } - public virtual string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { + public virtual string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) + { return ToString(); } - public virtual object GetDebugCookie(LightCompiler compiler) { + public virtual object GetDebugCookie(LightCompiler compiler) + { return null; } } - internal sealed class NotInstruction : Instruction { + internal sealed class NotInstruction : Instruction + { public static readonly Instruction Instance = new NotInstruction(); private NotInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push((bool)frame.Pop() ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True); return +1; } diff --git a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs index 949f13752..a6d890bb8 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs @@ -26,14 +26,18 @@ using System.Collections.Generic; //using Microsoft.Scripting.Math; -namespace System.Management.Automation.Interpreter { - internal abstract class InstructionFactory { +namespace System.Management.Automation.Interpreter +{ + internal abstract class InstructionFactory + { // TODO: weak table for types in a collectible assembly? - private static Dictionary _factories; + private static Dictionary s_factories; - internal static InstructionFactory GetFactory(Type type) { - if (_factories == null) { - _factories = new Dictionary() { + internal static InstructionFactory GetFactory(Type type) + { + if (s_factories == null) + { + s_factories = new Dictionary() { { typeof(object), InstructionFactory.Factory }, { typeof(bool), InstructionFactory.Factory }, { typeof(byte), InstructionFactory.Factory }, @@ -55,11 +59,13 @@ namespace System.Management.Automation.Interpreter { }; } - lock (_factories) { + lock (s_factories) + { InstructionFactory factory; - if (!_factories.TryGetValue(type, out factory)) { + if (!s_factories.TryGetValue(type, out factory)) + { factory = (InstructionFactory)typeof(InstructionFactory<>).MakeGenericType(type).GetField("Factory").GetValue(null); - _factories[type] = factory; + s_factories[type] = factory; } return factory; } @@ -74,7 +80,8 @@ namespace System.Management.Automation.Interpreter { internal protected abstract Instruction NewArrayInit(int elementCount); } - internal sealed class InstructionFactory : InstructionFactory { + internal sealed class InstructionFactory : InstructionFactory + { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly InstructionFactory Factory = new InstructionFactory(); @@ -87,31 +94,38 @@ namespace System.Management.Automation.Interpreter { private InstructionFactory() { } - internal protected override Instruction GetArrayItem() { + internal protected override Instruction GetArrayItem() + { return _getArrayItem ?? (_getArrayItem = new GetArrayItemInstruction()); } - internal protected override Instruction SetArrayItem() { + internal protected override Instruction SetArrayItem() + { return _setArrayItem ?? (_setArrayItem = new SetArrayItemInstruction()); } - internal protected override Instruction TypeIs() { + internal protected override Instruction TypeIs() + { return _typeIs ?? (_typeIs = new TypeIsInstruction()); } - internal protected override Instruction TypeAs() { + internal protected override Instruction TypeAs() + { return _typeAs ?? (_typeAs = new TypeAsInstruction()); } - internal protected override Instruction DefaultValue() { + internal protected override Instruction DefaultValue() + { return _defaultValue ?? (_defaultValue = new DefaultValueInstruction()); } - internal protected override Instruction NewArray() { + internal protected override Instruction NewArray() + { return _newArray ?? (_newArray = new NewArrayInstruction()); } - internal protected override Instruction NewArrayInit(int elementCount) { + internal protected override Instruction NewArrayInit(int elementCount) + { return new NewArrayInitInstruction(elementCount); } } diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 4ebde9d47..8dee16fe6 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -21,10 +21,12 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { +namespace System.Management.Automation.Interpreter +{ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [DebuggerTypeProxy(typeof(InstructionArray.DebugView))] - internal struct InstructionArray { + internal struct InstructionArray + { internal readonly int MaxStackDepth; internal readonly int MaxContinuationDepth; internal readonly Instruction[] Instructions; @@ -34,9 +36,9 @@ namespace System.Management.Automation.Interpreter { // list of (instruction index, cookie) sorted by instruction index: internal readonly List> DebugCookies; - internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions, - object[] objects, RuntimeLabel[] labels, List> debugCookies) { - + internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions, + object[] objects, RuntimeLabel[] labels, List> debugCookies) + { MaxStackDepth = maxStackDepth; MaxContinuationDepth = maxContinuationDepth; Instructions = instructions; @@ -45,27 +47,31 @@ namespace System.Management.Automation.Interpreter { Labels = labels; } - internal int Length { + internal int Length + { get { return Instructions.Length; } } #region Debug View - internal sealed class DebugView { + internal sealed class DebugView + { private readonly InstructionArray _array; - public DebugView(InstructionArray array) { + public DebugView(InstructionArray array) + { _array = array; - } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public InstructionList.DebugView.InstructionView[]/*!*/ A0 { - get { + public InstructionList.DebugView.InstructionView[]/*!*/ A0 + { + get + { return InstructionList.DebugView.GetInstructionViews( - _array.Instructions, - _array.Objects, - (index) => _array.Labels[index].Index, + _array.Instructions, + _array.Objects, + (index) => _array.Labels[index].Index, _array.DebugCookies ); } @@ -77,7 +83,8 @@ namespace System.Management.Automation.Interpreter { [DebuggerTypeProxy(typeof(InstructionList.DebugView))] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] - internal sealed class InstructionList { + internal sealed class InstructionList + { private readonly List _instructions = new List(); private List _objects; @@ -87,34 +94,38 @@ namespace System.Management.Automation.Interpreter { private int _maxContinuationDepth; private int _runtimeLabelCount; private List _labels; - + // list of (instruction index, cookie) sorted by instruction index: private List> _debugCookies = null; #region Debug View - internal sealed class DebugView { + internal sealed class DebugView + { private readonly InstructionList _list; - public DebugView(InstructionList list) { + public DebugView(InstructionList list) + { _list = list; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public InstructionView[]/*!*/ A0 { - get { + public InstructionView[]/*!*/ A0 + { + get + { return GetInstructionViews( - _list._instructions, - _list._objects, - (index) => _list._labels[index].TargetIndex, + _list._instructions, + _list._objects, + (index) => _list._labels[index].TargetIndex, _list._debugCookies ); } } internal static InstructionView[] GetInstructionViews(IList instructions, IList objects, - Func labelIndexer, IList> debugCookies) { - + Func labelIndexer, IList> debugCookies) + { var result = new List(); int index = 0; int stackDepth = 0; @@ -123,9 +134,11 @@ namespace System.Management.Automation.Interpreter { var cookieEnumerator = (debugCookies ?? Automation.Utils.EmptyArray>()).GetEnumerator(); var hasCookie = cookieEnumerator.MoveNext(); - for (int i = 0; i < instructions.Count; i++) { + for (int i = 0; i < instructions.Count; i++) + { object cookie = null; - while (hasCookie && cookieEnumerator.Current.Key == i) { + while (hasCookie && cookieEnumerator.Current.Key == i) + { cookie = cookieEnumerator.Current.Value; hasCookie = cookieEnumerator.MoveNext(); } @@ -134,7 +147,7 @@ namespace System.Management.Automation.Interpreter { int contDiff = instructions[i].ContinuationsBalance; string name = instructions[i].ToDebugString(i, cookie, labelIndexer, objects); result.Add(new InstructionView(instructions[i], name, i, stackDepth, continuationsDepth)); - + index++; stackDepth += stackDiff; continuationsDepth += contDiff; @@ -143,28 +156,33 @@ namespace System.Management.Automation.Interpreter { } [DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")] - internal struct InstructionView { + internal struct InstructionView + { private readonly int _index; private readonly int _stackDepth; private readonly int _continuationsDepth; private readonly string _name; private readonly Instruction _instruction; - internal string GetName() { + internal string GetName() + { return _index + (_continuationsDepth == 0 ? "" : " C(" + _continuationsDepth + ")") + (_stackDepth == 0 ? "" : " S(" + _stackDepth + ")"); } - internal string GetValue() { + internal string GetValue() + { return _name; } - internal string GetDisplayType() { + internal string GetDisplayType() + { return _instruction.ContinuationsBalance + "/" + _instruction.StackBalance; } - public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth) { + public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth) + { _instruction = instruction; _name = name; _index = index; @@ -173,31 +191,35 @@ namespace System.Management.Automation.Interpreter { } } } - + #endregion #region Core Emit Ops - public void Emit(Instruction instruction) { + public void Emit(Instruction instruction) + { _instructions.Add(instruction); UpdateStackDepth(instruction); } - private void UpdateStackDepth(Instruction instruction) { + private void UpdateStackDepth(Instruction instruction) + { Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 && instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0); _currentStackDepth -= instruction.ConsumedStack; Debug.Assert(_currentStackDepth >= 0); _currentStackDepth += instruction.ProducedStack; - if (_currentStackDepth > _maxStackDepth) { + if (_currentStackDepth > _maxStackDepth) + { _maxStackDepth = _currentStackDepth; } _currentContinuationsDepth -= instruction.ConsumedContinuations; Debug.Assert(_currentContinuationsDepth >= 0); _currentContinuationsDepth += instruction.ProducedContinuations; - if (_currentContinuationsDepth > _maxContinuationDepth) { + if (_currentContinuationsDepth > _maxContinuationDepth) + { _maxContinuationDepth = _currentContinuationsDepth; } } @@ -206,9 +228,11 @@ namespace System.Management.Automation.Interpreter { /// Attaches a cookie to the last emitted instruction. /// [Conditional("DEBUG")] - public void SetDebugCookie(object cookie) { + public void SetDebugCookie(object cookie) + { #if DEBUG - if (_debugCookies == null) { + if (_debugCookies == null) + { _debugCookies = new List>(); } @@ -217,23 +241,28 @@ namespace System.Management.Automation.Interpreter { #endif } - public int Count { + public int Count + { get { return _instructions.Count; } } - public int CurrentStackDepth { + public int CurrentStackDepth + { get { return _currentStackDepth; } } - public int CurrentContinuationsDepth { + public int CurrentContinuationsDepth + { get { return _currentContinuationsDepth; } } - public int MaxStackDepth { + public int MaxStackDepth + { get { return _maxStackDepth; } } - internal Instruction GetInstruction(int index) { + internal Instruction GetInstruction(int index) + { return _instructions[index]; } @@ -260,7 +289,8 @@ namespace System.Management.Automation.Interpreter { }); } #endif - public InstructionArray ToArray() { + public InstructionArray ToArray() + { #if STATS lock (_executedInstructions) { _instructions.ForEach((instr) => { @@ -280,7 +310,7 @@ namespace System.Management.Automation.Interpreter { return new InstructionArray( _maxStackDepth, _maxContinuationDepth, - _instructions.ToArray(), + _instructions.ToArray(), (_objects != null) ? _objects.ToArray() : null, BuildRuntimeLabels(), _debugCookies @@ -295,70 +325,89 @@ namespace System.Management.Automation.Interpreter { private const int PushIntMaxCachedValue = 100; private const int CachedObjectCount = 256; - private static Instruction _null; - private static Instruction _true; - private static Instruction _false; - private static Instruction[] _ints; - private static Instruction[] _loadObjectCached; + private static Instruction s_null; + private static Instruction s_true; + private static Instruction s_false; + private static Instruction[] s_ints; + private static Instruction[] s_loadObjectCached; - public void EmitLoad(object value) { + public void EmitLoad(object value) + { EmitLoad(value, null); } - public void EmitLoad(bool value) { - if ((bool)value) { - Emit(_true ?? (_true = new LoadObjectInstruction(value))); - } else { - Emit(_false ?? (_false = new LoadObjectInstruction(value))); + public void EmitLoad(bool value) + { + if ((bool)value) + { + Emit(s_true ?? (s_true = new LoadObjectInstruction(value))); + } + else + { + Emit(s_false ?? (s_false = new LoadObjectInstruction(value))); } } - public void EmitLoad(object value, Type type) { - if (value == null) { - Emit(_null ?? (_null = new LoadObjectInstruction(null))); + public void EmitLoad(object value, Type type) + { + if (value == null) + { + Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); return; } - if (type == null || type.GetTypeInfo().IsValueType) { - if (value is bool) { + if (type == null || type.GetTypeInfo().IsValueType) + { + if (value is bool) + { EmitLoad((bool)value); return; - } - - if (value is int) { + } + + if (value is int) + { int i = (int)value; - if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { - if (_ints == null) { - _ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; + if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) + { + if (s_ints == null) + { + s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } i -= PushIntMinCachedValue; - Emit(_ints[i] ?? (_ints[i] = new LoadObjectInstruction(value))); + Emit(s_ints[i] ?? (s_ints[i] = new LoadObjectInstruction(value))); return; } } } - if (_objects == null) { + if (_objects == null) + { _objects = new List(); - if (_loadObjectCached == null) { - _loadObjectCached = new Instruction[CachedObjectCount]; + if (s_loadObjectCached == null) + { + s_loadObjectCached = new Instruction[CachedObjectCount]; } } - if (_objects.Count < _loadObjectCached.Length) { + if (_objects.Count < s_loadObjectCached.Length) + { uint index = (uint)_objects.Count; _objects.Add(value); - Emit(_loadObjectCached[index] ?? (_loadObjectCached[index] = new LoadCachedObjectInstruction(index))); - } else { + Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index))); + } + else + { Emit(new LoadObjectInstruction(value)); } } - public void EmitDup() { + public void EmitDup() + { Emit(DupInstruction.Instance); } - public void EmitPop() { + public void EmitPop() + { Emit(PopInstruction.Instance); } @@ -366,12 +415,15 @@ namespace System.Management.Automation.Interpreter { #region Locals - internal void SwitchToBoxed(int index, int instructionIndex) { + internal void SwitchToBoxed(int index, int instructionIndex) + { var instruction = _instructions[instructionIndex] as IBoxableInstruction; - if (instruction != null) { + if (instruction != null) + { var newInstruction = instruction.BoxIfIndexMatches(index); - if (newInstruction != null) { + if (newInstruction != null) + { _instructions[instructionIndex] = newInstruction; } } @@ -379,209 +431,278 @@ namespace System.Management.Automation.Interpreter { private const int LocalInstrCacheSize = 64; - private static Instruction[] _loadLocal; - private static Instruction[] _loadLocalBoxed; - private static Instruction[] _loadLocalFromClosure; - private static Instruction[] _loadLocalFromClosureBoxed; - private static Instruction[] _assignLocal; - private static Instruction[] _storeLocal; - private static Instruction[] _assignLocalBoxed; - private static Instruction[] _storeLocalBoxed; - private static Instruction[] _assignLocalToClosure; - private static Instruction[] _initReference; - private static Instruction[] _initImmutableRefBox; - private static Instruction[] _parameterBox; - private static Instruction[] _parameter; + private static Instruction[] s_loadLocal; + private static Instruction[] s_loadLocalBoxed; + private static Instruction[] s_loadLocalFromClosure; + private static Instruction[] s_loadLocalFromClosureBoxed; + private static Instruction[] s_assignLocal; + private static Instruction[] s_storeLocal; + private static Instruction[] s_assignLocalBoxed; + private static Instruction[] s_storeLocalBoxed; + private static Instruction[] s_assignLocalToClosure; + private static Instruction[] s_initReference; + private static Instruction[] s_initImmutableRefBox; + private static Instruction[] s_parameterBox; + private static Instruction[] s_parameter; - public void EmitLoadLocal(int index) { - if (_loadLocal == null) { - _loadLocal = new Instruction[LocalInstrCacheSize]; + public void EmitLoadLocal(int index) + { + if (s_loadLocal == null) + { + s_loadLocal = new Instruction[LocalInstrCacheSize]; } - if (index < _loadLocal.Length) { - Emit(_loadLocal[index] ?? (_loadLocal[index] = new LoadLocalInstruction(index))); - } else { + if (index < s_loadLocal.Length) + { + Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index))); + } + else + { Emit(new LoadLocalInstruction(index)); } } - public void EmitLoadLocalBoxed(int index) { + public void EmitLoadLocalBoxed(int index) + { Emit(LoadLocalBoxed(index)); } - internal static Instruction LoadLocalBoxed(int index) { - if (_loadLocalBoxed == null) { - _loadLocalBoxed = new Instruction[LocalInstrCacheSize]; + internal static Instruction LoadLocalBoxed(int index) + { + if (s_loadLocalBoxed == null) + { + s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; } - if (index < _loadLocalBoxed.Length) { - return _loadLocalBoxed[index] ?? (_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index)); - } else { + if (index < s_loadLocalBoxed.Length) + { + return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index)); + } + else + { return new LoadLocalBoxedInstruction(index); } } - public void EmitLoadLocalFromClosure(int index) { - if (_loadLocalFromClosure == null) { - _loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; + public void EmitLoadLocalFromClosure(int index) + { + if (s_loadLocalFromClosure == null) + { + s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; } - if (index < _loadLocalFromClosure.Length) { - Emit(_loadLocalFromClosure[index] ?? (_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index))); - } else { + if (index < s_loadLocalFromClosure.Length) + { + Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index))); + } + else + { Emit(new LoadLocalFromClosureInstruction(index)); } } - public void EmitLoadLocalFromClosureBoxed(int index) { - if (_loadLocalFromClosureBoxed == null) { - _loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; + public void EmitLoadLocalFromClosureBoxed(int index) + { + if (s_loadLocalFromClosureBoxed == null) + { + s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; } - if (index < _loadLocalFromClosureBoxed.Length) { - Emit(_loadLocalFromClosureBoxed[index] ?? (_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index))); - } else { + if (index < s_loadLocalFromClosureBoxed.Length) + { + Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index))); + } + else + { Emit(new LoadLocalFromClosureBoxedInstruction(index)); } } - public void EmitAssignLocal(int index) { - if (_assignLocal == null) { - _assignLocal = new Instruction[LocalInstrCacheSize]; + public void EmitAssignLocal(int index) + { + if (s_assignLocal == null) + { + s_assignLocal = new Instruction[LocalInstrCacheSize]; } - if (index < _assignLocal.Length) { - Emit(_assignLocal[index] ?? (_assignLocal[index] = new AssignLocalInstruction(index))); - } else { + if (index < s_assignLocal.Length) + { + Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index))); + } + else + { Emit(new AssignLocalInstruction(index)); } } - public void EmitStoreLocal(int index) { - if (_storeLocal == null) { - _storeLocal = new Instruction[LocalInstrCacheSize]; + public void EmitStoreLocal(int index) + { + if (s_storeLocal == null) + { + s_storeLocal = new Instruction[LocalInstrCacheSize]; } - if (index < _storeLocal.Length) { - Emit(_storeLocal[index] ?? (_storeLocal[index] = new StoreLocalInstruction(index))); - } else { + if (index < s_storeLocal.Length) + { + Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index))); + } + else + { Emit(new StoreLocalInstruction(index)); } } - public void EmitAssignLocalBoxed(int index) { + public void EmitAssignLocalBoxed(int index) + { Emit(AssignLocalBoxed(index)); } - internal static Instruction AssignLocalBoxed(int index) { - if (_assignLocalBoxed == null) { - _assignLocalBoxed = new Instruction[LocalInstrCacheSize]; + internal static Instruction AssignLocalBoxed(int index) + { + if (s_assignLocalBoxed == null) + { + s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; } - if (index < _assignLocalBoxed.Length) { - return _assignLocalBoxed[index] ?? (_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index)); - } else { + if (index < s_assignLocalBoxed.Length) + { + return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index)); + } + else + { return new AssignLocalBoxedInstruction(index); } } - public void EmitStoreLocalBoxed(int index) { + public void EmitStoreLocalBoxed(int index) + { Emit(StoreLocalBoxed(index)); } - internal static Instruction StoreLocalBoxed(int index) { - if (_storeLocalBoxed == null) { - _storeLocalBoxed = new Instruction[LocalInstrCacheSize]; + internal static Instruction StoreLocalBoxed(int index) + { + if (s_storeLocalBoxed == null) + { + s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; } - if (index < _storeLocalBoxed.Length) { - return _storeLocalBoxed[index] ?? (_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index)); - } else { + if (index < s_storeLocalBoxed.Length) + { + return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index)); + } + else + { return new StoreLocalBoxedInstruction(index); } } - public void EmitAssignLocalToClosure(int index) { - if (_assignLocalToClosure == null) { - _assignLocalToClosure = new Instruction[LocalInstrCacheSize]; + public void EmitAssignLocalToClosure(int index) + { + if (s_assignLocalToClosure == null) + { + s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; } - if (index < _assignLocalToClosure.Length) { - Emit(_assignLocalToClosure[index] ?? (_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index))); - } else { + if (index < s_assignLocalToClosure.Length) + { + Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index))); + } + else + { Emit(new AssignLocalToClosureInstruction(index)); } } - public void EmitStoreLocalToClosure(int index) { + public void EmitStoreLocalToClosure(int index) + { EmitAssignLocalToClosure(index); EmitPop(); } - public void EmitInitializeLocal(int index, Type type) { + public void EmitInitializeLocal(int index, Type type) + { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) { + if (value != null) + { Emit(new InitializeLocalInstruction.ImmutableValue(index, value)); - } else if (type.GetTypeInfo().IsValueType) { + } + else if (type.GetTypeInfo().IsValueType) + { Emit(new InitializeLocalInstruction.MutableValue(index, type)); - } else { + } + else + { Emit(InitReference(index)); } } - internal void EmitInitializeParameter(int index) { + internal void EmitInitializeParameter(int index) + { Emit(Parameter(index)); } - internal static Instruction Parameter(int index) { - if (_parameter == null) { - _parameter = new Instruction[LocalInstrCacheSize]; + internal static Instruction Parameter(int index) + { + if (s_parameter == null) + { + s_parameter = new Instruction[LocalInstrCacheSize]; } - if (index < _parameter.Length) { - return _parameter[index] ?? (_parameter[index] = new InitializeLocalInstruction.Parameter(index)); + if (index < s_parameter.Length) + { + return s_parameter[index] ?? (s_parameter[index] = new InitializeLocalInstruction.Parameter(index)); } return new InitializeLocalInstruction.Parameter(index); } - internal static Instruction ParameterBox(int index) { - if (_parameterBox == null) { - _parameterBox = new Instruction[LocalInstrCacheSize]; + internal static Instruction ParameterBox(int index) + { + if (s_parameterBox == null) + { + s_parameterBox = new Instruction[LocalInstrCacheSize]; } - if (index < _parameterBox.Length) { - return _parameterBox[index] ?? (_parameterBox[index] = new InitializeLocalInstruction.ParameterBox(index)); + if (index < s_parameterBox.Length) + { + return s_parameterBox[index] ?? (s_parameterBox[index] = new InitializeLocalInstruction.ParameterBox(index)); } return new InitializeLocalInstruction.ParameterBox(index); } - internal static Instruction InitReference(int index) { - if (_initReference == null) { - _initReference = new Instruction[LocalInstrCacheSize]; + internal static Instruction InitReference(int index) + { + if (s_initReference == null) + { + s_initReference = new Instruction[LocalInstrCacheSize]; } - if (index < _initReference.Length) { - return _initReference[index] ?? (_initReference[index] = new InitializeLocalInstruction.Reference(index)); + if (index < s_initReference.Length) + { + return s_initReference[index] ?? (s_initReference[index] = new InitializeLocalInstruction.Reference(index)); } return new InitializeLocalInstruction.Reference(index); } - internal static Instruction InitImmutableRefBox(int index) { - if (_initImmutableRefBox == null) { - _initImmutableRefBox = new Instruction[LocalInstrCacheSize]; + internal static Instruction InitImmutableRefBox(int index) + { + if (s_initImmutableRefBox == null) + { + s_initImmutableRefBox = new Instruction[LocalInstrCacheSize]; } - if (index < _initImmutableRefBox.Length) { - return _initImmutableRefBox[index] ?? (_initImmutableRefBox[index] = new InitializeLocalInstruction.ImmutableBox(index, null)); + if (index < s_initImmutableRefBox.Length) + { + return s_initImmutableRefBox[index] ?? (s_initImmutableRefBox[index] = new InitializeLocalInstruction.ImmutableBox(index, null)); } return new InitializeLocalInstruction.ImmutableBox(index, null); } - public void EmitNewRuntimeVariables(int count) { + public void EmitNewRuntimeVariables(int count) + { Emit(new RuntimeVariablesInstruction(count)); } @@ -589,35 +710,46 @@ namespace System.Management.Automation.Interpreter { #region Array Operations - public void EmitGetArrayItem(Type arrayType) { + public void EmitGetArrayItem(Type arrayType) + { var elementType = arrayType.GetElementType(); var elementTypeInfo = elementType.GetTypeInfo(); - if (elementTypeInfo.IsClass || elementTypeInfo.IsInterface) { + if (elementTypeInfo.IsClass || elementTypeInfo.IsInterface) + { Emit(InstructionFactory.Factory.GetArrayItem()); - } else { + } + else + { Emit(InstructionFactory.GetFactory(elementType).GetArrayItem()); } } - public void EmitSetArrayItem(Type arrayType) { + public void EmitSetArrayItem(Type arrayType) + { var elementType = arrayType.GetElementType(); var elementTypeInfo = elementType.GetTypeInfo(); - if (elementTypeInfo.IsClass || elementTypeInfo.IsInterface) { + if (elementTypeInfo.IsClass || elementTypeInfo.IsInterface) + { Emit(InstructionFactory.Factory.SetArrayItem()); - } else { + } + else + { Emit(InstructionFactory.GetFactory(elementType).SetArrayItem()); } } - public void EmitNewArray(Type elementType) { + public void EmitNewArray(Type elementType) + { Emit(InstructionFactory.GetFactory(elementType).NewArray()); } - public void EmitNewArrayBounds(Type elementType, int rank) { + public void EmitNewArrayBounds(Type elementType, int rank) + { Emit(new NewArrayBoundsInstruction(elementType, rank)); } - public void EmitNewArrayInit(Type elementType, int elementCount) { + public void EmitNewArrayInit(Type elementType, int elementCount) + { Emit(InstructionFactory.GetFactory(elementType).NewArrayInit(elementCount)); } @@ -625,33 +757,46 @@ namespace System.Management.Automation.Interpreter { #region Arithmetic Operations - public void EmitAdd(Type type, bool @checked) { - if (@checked) { + public void EmitAdd(Type type, bool @checked) + { + if (@checked) + { Emit(AddOvfInstruction.Create(type)); - } else { + } + else + { Emit(AddInstruction.Create(type)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")] - public void EmitSub(Type type, bool @checked) { - if (@checked) { + public void EmitSub(Type type, bool @checked) + { + if (@checked) + { Emit(SubOvfInstruction.Create(type)); - } else { + } + else + { Emit(SubInstruction.Create(type)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")] - public void EmitMul(Type type, bool @checked) { - if (@checked) { + public void EmitMul(Type type, bool @checked) + { + if (@checked) + { Emit(MulOvfInstruction.Create(type)); - } else { + } + else + { Emit(MulInstruction.Create(type)); } } - public void EmitDiv(Type type) { + public void EmitDiv(Type type) + { Emit(DivInstruction.Create(type)); } @@ -659,29 +804,35 @@ namespace System.Management.Automation.Interpreter { #region Comparisons - public void EmitEqual(Type type) { + public void EmitEqual(Type type) + { Emit(EqualInstruction.Create(type)); } - public void EmitNotEqual(Type type) { + public void EmitNotEqual(Type type) + { Emit(NotEqualInstruction.Create(type)); } - public void EmitLessThan(Type type) { + public void EmitLessThan(Type type) + { Emit(LessThanInstruction.Create(type)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")] - public void EmitLessThanOrEqual(Type type) { + public void EmitLessThanOrEqual(Type type) + { throw new NotSupportedException(); } - public void EmitGreaterThan(Type type) { + public void EmitGreaterThan(Type type) + { Emit(GreaterThanInstruction.Create(type)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")] - public void EmitGreaterThanOrEqual(Type type) { + public void EmitGreaterThanOrEqual(Type type) + { throw new NotSupportedException(); } @@ -689,11 +840,13 @@ namespace System.Management.Automation.Interpreter { #region Conversions - public void EmitNumericConvertChecked(TypeCode from, TypeCode to) { + public void EmitNumericConvertChecked(TypeCode from, TypeCode to) + { Emit(new NumericConvertInstruction.Checked(from, to)); } - public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to) { + public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to) + { Emit(new NumericConvertInstruction.Unchecked(from, to)); } @@ -701,7 +854,8 @@ namespace System.Management.Automation.Interpreter { #region Boolean Operators - public void EmitNot() { + public void EmitNot() + { Emit(NotInstruction.Instance); } @@ -709,27 +863,33 @@ namespace System.Management.Automation.Interpreter { #region Types - public void EmitDefaultValue(Type type) { + public void EmitDefaultValue(Type type) + { Emit(InstructionFactory.GetFactory(type).DefaultValue()); } - public void EmitNew(ConstructorInfo constructorInfo) { + public void EmitNew(ConstructorInfo constructorInfo) + { Emit(new NewInstruction(constructorInfo)); } - internal void EmitCreateDelegate(LightDelegateCreator creator) { + internal void EmitCreateDelegate(LightDelegateCreator creator) + { Emit(new CreateDelegateInstruction(creator)); } - public void EmitTypeEquals() { + public void EmitTypeEquals() + { Emit(TypeEqualsInstruction.Instance); } - public void EmitTypeIs(Type type) { + public void EmitTypeIs(Type type) + { Emit(InstructionFactory.GetFactory(type).TypeIs()); } - public void EmitTypeAs(Type type) { + public void EmitTypeAs(Type type) + { Emit(InstructionFactory.GetFactory(type).TypeAs()); } @@ -737,40 +897,53 @@ namespace System.Management.Automation.Interpreter { #region Fields and Methods - private static readonly Dictionary _loadFields = new Dictionary(); + private static readonly Dictionary s_loadFields = new Dictionary(); - public void EmitLoadField(FieldInfo field) { + public void EmitLoadField(FieldInfo field) + { Emit(GetLoadField(field)); } - private Instruction GetLoadField(FieldInfo field) { - lock (_loadFields) { + private Instruction GetLoadField(FieldInfo field) + { + lock (s_loadFields) + { Instruction instruction; - if (!_loadFields.TryGetValue(field, out instruction)) { - if (field.IsStatic) { + if (!s_loadFields.TryGetValue(field, out instruction)) + { + if (field.IsStatic) + { instruction = new LoadStaticFieldInstruction(field); - } else { + } + else + { instruction = new LoadFieldInstruction(field); } - _loadFields.Add(field, instruction); + s_loadFields.Add(field, instruction); } return instruction; } } - - public void EmitStoreField(FieldInfo field) { - if (field.IsStatic) { + + public void EmitStoreField(FieldInfo field) + { + if (field.IsStatic) + { Emit(new StoreStaticFieldInstruction(field)); - } else { + } + else + { Emit(new StoreFieldInstruction(field)); } } - public void EmitCall(MethodInfo method) { + public void EmitCall(MethodInfo method) + { EmitCall(method, method.GetParameters()); } - public void EmitCall(MethodInfo method, ParameterInfo[] parameters) { + public void EmitCall(MethodInfo method, ParameterInfo[] parameters) + { Emit(CallInstruction.Create(method, parameters)); } @@ -778,7 +951,8 @@ namespace System.Management.Automation.Interpreter { #region Dynamic - public void EmitDynamic(Type type, CallSiteBinder binder) { + public void EmitDynamic(Type type, CallSiteBinder binder) + { Emit(CreateDynamicInstruction(type, binder)); } @@ -787,63 +961,78 @@ namespace System.Management.Automation.Interpreter { // *** BEGIN GENERATED CODE *** // generated by function: gen_instructionlist_factory from: generate_dynamic_instructions.py - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } - public void EmitDynamic(CallSiteBinder binder) { + public void EmitDynamic(CallSiteBinder binder) + { Emit(DynamicInstruction.Factory(binder)); } @@ -852,29 +1041,34 @@ namespace System.Management.Automation.Interpreter { #endregion - private static Dictionary> _factories = + private static Dictionary> s_factories = new Dictionary>(); - internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder) { + internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder) + { Func factory; - lock (_factories) { - if (!_factories.TryGetValue(delegateType, out factory)) { - if (delegateType.GetMethod("Invoke").ReturnType == typeof(void)) { + lock (s_factories) + { + if (!s_factories.TryGetValue(delegateType, out factory)) + { + if (delegateType.GetMethod("Invoke").ReturnType == typeof(void)) + { // TODO: We should generally support void returning binders but the only // ones that exist are delete index/member who's perf isn't that critical. return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder), true); } Type instructionType = DynamicInstructionN.GetDynamicInstructionType(delegateType); - if (instructionType == null) { + if (instructionType == null) + { return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder)); } factory = (Func) - instructionType.GetMethod("Factory").CreateDelegate(typeof (Func)); + instructionType.GetMethod("Factory").CreateDelegate(typeof(Func)); - _factories[delegateType] = factory; + s_factories[delegateType] = factory; } } return factory(binder); @@ -884,16 +1078,20 @@ namespace System.Management.Automation.Interpreter { #region Control Flow - private static readonly RuntimeLabel[] EmptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) }; + private static readonly RuntimeLabel[] s_emptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) }; - private RuntimeLabel[] BuildRuntimeLabels() { - if (_runtimeLabelCount == 0) { - return EmptyRuntimeLabels; + private RuntimeLabel[] BuildRuntimeLabels() + { + if (_runtimeLabelCount == 0) + { + return s_emptyRuntimeLabels; } var result = new RuntimeLabel[_runtimeLabelCount + 1]; - foreach (BranchLabel label in _labels) { - if (label.HasRuntimeLabel) { + foreach (BranchLabel label in _labels) + { + if (label.HasRuntimeLabel) + { result[label.LabelIndex] = label.ToRuntimeLabel(); } } @@ -902,8 +1100,10 @@ namespace System.Management.Automation.Interpreter { return result; } - public BranchLabel MakeLabel() { - if (_labels == null) { + public BranchLabel MakeLabel() + { + if (_labels == null) + { _labels = new List(); } @@ -912,12 +1112,15 @@ namespace System.Management.Automation.Interpreter { return label; } - internal void FixupBranch(int branchIndex, int offset) { + internal void FixupBranch(int branchIndex, int offset) + { _instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset); } - private int EnsureLabelIndex(BranchLabel label) { - if (label.HasRuntimeLabel) { + private int EnsureLabelIndex(BranchLabel label) + { + if (label.HasRuntimeLabel) + { return label.LabelIndex; } @@ -926,94 +1129,116 @@ namespace System.Management.Automation.Interpreter { return label.LabelIndex; } - public int MarkRuntimeLabel() { + public int MarkRuntimeLabel() + { BranchLabel handlerLabel = MakeLabel(); MarkLabel(handlerLabel); return EnsureLabelIndex(handlerLabel); } - public void MarkLabel(BranchLabel label) { + public void MarkLabel(BranchLabel label) + { label.Mark(this); } - public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue) { + public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue) + { Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue)); } - private void EmitBranch(OffsetInstruction instruction, BranchLabel label) { + private void EmitBranch(OffsetInstruction instruction, BranchLabel label) + { Emit(instruction); label.AddBranch(this, Count - 1); } - public void EmitBranch(BranchLabel label) { + public void EmitBranch(BranchLabel label) + { EmitBranch(new BranchInstruction(), label); } - public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue) { + public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue) + { EmitBranch(new BranchInstruction(hasResult, hasValue), label); } - public void EmitCoalescingBranch(BranchLabel leftNotNull) { + public void EmitCoalescingBranch(BranchLabel leftNotNull) + { EmitBranch(new CoalescingBranchInstruction(), leftNotNull); } - public void EmitBranchTrue(BranchLabel elseLabel) { + public void EmitBranchTrue(BranchLabel elseLabel) + { EmitBranch(new BranchTrueInstruction(), elseLabel); } - public void EmitBranchFalse(BranchLabel elseLabel) { + public void EmitBranchFalse(BranchLabel elseLabel) + { EmitBranch(new BranchFalseInstruction(), elseLabel); } - public void EmitThrow() { + public void EmitThrow() + { Emit(ThrowInstruction.Throw); } - public void EmitThrowVoid() { + public void EmitThrowVoid() + { Emit(ThrowInstruction.VoidThrow); } - public void EmitRethrow() { + public void EmitRethrow() + { Emit(ThrowInstruction.Rethrow); } - public void EmitRethrowVoid() { + public void EmitRethrowVoid() + { Emit(ThrowInstruction.VoidRethrow); } - public void EmitEnterTryFinally(BranchLabel finallyStartLabel) { + public void EmitEnterTryFinally(BranchLabel finallyStartLabel) + { Emit(EnterTryCatchFinallyInstruction.CreateTryFinally(EnsureLabelIndex(finallyStartLabel))); } - public void EmitEnterTryCatch() { + public void EmitEnterTryCatch() + { Emit(EnterTryCatchFinallyInstruction.CreateTryCatch()); } - public void EmitEnterFinally(BranchLabel finallyStartLabel) { + public void EmitEnterFinally(BranchLabel finallyStartLabel) + { Emit(EnterFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel))); } - public void EmitLeaveFinally() { + public void EmitLeaveFinally() + { Emit(LeaveFinallyInstruction.Instance); } - public void EmitLeaveFault(bool hasValue) { + public void EmitLeaveFault(bool hasValue) + { Emit(hasValue ? LeaveFaultInstruction.NonVoid : LeaveFaultInstruction.Void); } - public void EmitEnterExceptionHandlerNonVoid() { + public void EmitEnterExceptionHandlerNonVoid() + { Emit(EnterExceptionHandlerInstruction.NonVoid); } - public void EmitEnterExceptionHandlerVoid() { + public void EmitEnterExceptionHandlerVoid() + { Emit(EnterExceptionHandlerInstruction.Void); } - public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel) { + public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel) + { Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue)); } - public void EmitSwitch(Dictionary cases) { + public void EmitSwitch(Dictionary cases) + { Emit(new SwitchInstruction(cases)); } diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 865c6ff5a..44dfd0c2c 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -26,8 +26,10 @@ using System.Management.Automation.Language; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal sealed class InterpretedFrame { +namespace System.Management.Automation.Interpreter +{ + internal sealed class InterpretedFrame + { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ThreadLocal CurrentFrame = new ThreadLocal(); @@ -53,13 +55,15 @@ namespace System.Management.Automation.Interpreter { // No handlers within this handler re-abort the current thread when left. public ExceptionHandler CurrentAbortHandler; - internal InterpretedFrame(Interpreter interpreter, StrongBox[] closure) { + internal InterpretedFrame(Interpreter interpreter, StrongBox[] closure) + { Interpreter = interpreter; StackIndex = interpreter.LocalCount; Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth]; int c = interpreter.Instructions.MaxContinuationDepth; - if (c > 0) { + if (c > 0) + { _continuations = new int[c]; } @@ -69,41 +73,50 @@ namespace System.Management.Automation.Interpreter { _pendingValue = Interpreter.NoValue; } - public DebugInfo GetDebugInfo(int instructionIndex) { + public DebugInfo GetDebugInfo(int instructionIndex) + { return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex); } - public string Name { + public string Name + { get { return Interpreter._name; } } #region Data Stack Operations - public void Push(object value) { + public void Push(object value) + { Data[StackIndex++] = value; } - public void Push(bool value) { + public void Push(bool value) + { Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; } - public void Push(int value) { + public void Push(int value) + { Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value); } - public object Pop() { + public object Pop() + { return Data[--StackIndex]; } - internal void SetStackDepth(int depth) { + internal void SetStackDepth(int depth) + { StackIndex = Interpreter.LocalCount + depth; } - public object Peek() { + public object Peek() + { return Data[StackIndex - 1]; } - public void Dup() { + public void Dup() + { int i = StackIndex; Data[i] = Data[i - 1]; StackIndex = i + 1; @@ -123,11 +136,13 @@ namespace System.Management.Automation.Interpreter { #region Stack Trace - public InterpretedFrame Parent { + public InterpretedFrame Parent + { get { return _parent; } } - public static bool IsInterpretedFrame(MethodBase method) { + public static bool IsInterpretedFrame(MethodBase method) + { //ContractUtils.RequiresNotNull(method, "method"); return method.DeclaringType == typeof(Interpreter) && method.Name == "Run"; } @@ -136,45 +151,59 @@ namespace System.Management.Automation.Interpreter { /// A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames. /// This method filters out the duplicate CLR frames. /// - public static IEnumerable GroupStackFrames(IEnumerable stackTrace) { + public static IEnumerable GroupStackFrames(IEnumerable stackTrace) + { bool inInterpretedFrame = false; - foreach (StackFrame frame in stackTrace) { - if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod())) { - if (inInterpretedFrame) { + foreach (StackFrame frame in stackTrace) + { + if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod())) + { + if (inInterpretedFrame) + { continue; } inInterpretedFrame = true; - } else { + } + else + { inInterpretedFrame = false; } yield return frame; } } - public IEnumerable GetStackTraceDebugInfo() { + public IEnumerable GetStackTraceDebugInfo() + { var frame = this; - do { + do + { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; } while (frame != null); } - internal void SaveTraceToException(Exception exception) { - if (exception.Data[typeof(InterpretedFrameInfo)] == null) { + internal void SaveTraceToException(Exception exception) + { + if (exception.Data[typeof(InterpretedFrameInfo)] == null) + { exception.Data[typeof(InterpretedFrameInfo)] = new List(GetStackTraceDebugInfo()).ToArray(); } } - public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) { + public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) + { return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[]; } #if DEBUG - internal string[] Trace { - get { + internal string[] Trace + { + get + { var trace = new List(); var frame = this; - do { + do + { trace.Add(frame.Name); frame = frame.Parent; } while (frame != null); @@ -183,14 +212,16 @@ namespace System.Management.Automation.Interpreter { } #endif - internal ThreadLocal.StorageInfo Enter() { + internal ThreadLocal.StorageInfo Enter() + { var currentFrame = InterpretedFrame.CurrentFrame.GetStorageInfo(); _parent = currentFrame.Value; currentFrame.Value = this; return currentFrame; } - internal void Leave(ThreadLocal.StorageInfo currentFrame) { + internal void Leave(ThreadLocal.StorageInfo currentFrame) + { currentFrame.Value = _parent; } @@ -203,15 +234,18 @@ namespace System.Management.Automation.Interpreter { return _pendingContinuation >= 0; } - public void RemoveContinuation() { + public void RemoveContinuation() + { _continuationIndex--; } - public void PushContinuation(int continuation) { + public void PushContinuation(int continuation) + { _continuations[_continuationIndex++] = continuation; } - public int YieldToCurrentContinuation() { + public int YieldToCurrentContinuation() + { var target = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(target.StackDepth); return target.Index - InstructionIndex; @@ -220,19 +254,22 @@ namespace System.Management.Automation.Interpreter { /// /// Get called from the LeaveFinallyInstruction /// - public int YieldToPendingContinuation() { + public int YieldToPendingContinuation() + { Debug.Assert(_pendingContinuation >= 0); RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation]; // the current continuation might have higher priority (continuationIndex is the depth of the current continuation): - if (pendingTarget.ContinuationStackDepth < _continuationIndex) { + if (pendingTarget.ContinuationStackDepth < _continuationIndex) + { RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(currentTarget.StackDepth); return currentTarget.Index - InstructionIndex; } SetStackDepth(pendingTarget.StackDepth); - if (_pendingValue != Interpreter.NoValue) { + if (_pendingValue != Interpreter.NoValue) + { Data[StackIndex - 1] = _pendingValue; } @@ -242,7 +279,8 @@ namespace System.Management.Automation.Interpreter { return pendingTarget.Index - InstructionIndex; } - internal void PushPendingContinuation() { + internal void PushPendingContinuation() + { Push(_pendingContinuation); Push(_pendingValue); @@ -250,35 +288,42 @@ namespace System.Management.Automation.Interpreter { _pendingValue = Interpreter.NoValue; } - internal void PopPendingContinuation() { + internal void PopPendingContinuation() + { _pendingValue = Pop(); _pendingContinuation = (int)Pop(); } - private static MethodInfo _Goto; - private static MethodInfo _VoidGoto; + private static MethodInfo s_goto; + private static MethodInfo s_voidGoto; - internal static MethodInfo GotoMethod { - get { return _Goto ?? (_Goto = typeof(InterpretedFrame).GetMethod("Goto")); } + internal static MethodInfo GotoMethod + { + get { return s_goto ?? (s_goto = typeof(InterpretedFrame).GetMethod("Goto")); } } - internal static MethodInfo VoidGotoMethod { - get { return _VoidGoto ?? (_VoidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); } + internal static MethodInfo VoidGotoMethod + { + get { return s_voidGoto ?? (s_voidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); } } - public int VoidGoto(int labelIndex) { + public int VoidGoto(int labelIndex) + { return Goto(labelIndex, Interpreter.NoValue, gotoExceptionHandler: false); } - public int Goto(int labelIndex, object value, bool gotoExceptionHandler) { + public int Goto(int labelIndex, object value, bool gotoExceptionHandler) + { // TODO: we know this at compile time (except for compiled loop): RuntimeLabel target = Interpreter._labels[labelIndex]; Debug.Assert(!gotoExceptionHandler || (gotoExceptionHandler && _continuationIndex == target.ContinuationStackDepth), "When it's time to jump to the exception handler, all previous finally blocks should already be processed"); - if (_continuationIndex == target.ContinuationStackDepth) { + if (_continuationIndex == target.ContinuationStackDepth) + { SetStackDepth(target.StackDepth); - if (value != Interpreter.NoValue) { + if (value != Interpreter.NoValue) + { Data[StackIndex - 1] = value; } return target.Index - InstructionIndex; @@ -291,6 +336,5 @@ namespace System.Management.Automation.Interpreter { } #endregion - } } diff --git a/src/System.Management.Automation/engine/interpreter/Interpreter.cs b/src/System.Management.Automation/engine/interpreter/Interpreter.cs index 3cfe6eff9..1a4048808 100644 --- a/src/System.Management.Automation/engine/interpreter/Interpreter.cs +++ b/src/System.Management.Automation/engine/interpreter/Interpreter.cs @@ -33,7 +33,8 @@ using System.Threading; using System.Diagnostics; using System.Collections.Generic; -namespace System.Management.Automation.Interpreter { +namespace System.Management.Automation.Interpreter +{ /// /// A simple forth-style stack machine for executing Expression trees /// without the need to compile to IL and then invoke the JIT. This trades @@ -43,7 +44,8 @@ namespace System.Management.Automation.Interpreter { /// /// The core loop in the interpreter is the RunInstructions method. /// - internal sealed class Interpreter { + internal sealed class Interpreter + { internal static readonly object NoValue = new object(); internal const int RethrowOnReturn = Int32.MaxValue; @@ -63,8 +65,8 @@ namespace System.Management.Automation.Interpreter { internal readonly DebugInfo[] _debugInfos; internal Interpreter(string name, LocalVariables locals, HybridReferenceDictionary labelMapping, - InstructionArray instructions, DebugInfo[] debugInfos, int compilationThreshold) { - + InstructionArray instructions, DebugInfo[] debugInfos, int compilationThreshold) + { _name = name; _localCount = locals.LocalCount; _closureVariables = locals.ClosureVariables; @@ -78,34 +80,43 @@ namespace System.Management.Automation.Interpreter { _compilationThreshold = compilationThreshold; } - internal int ClosureSize { - get { - if (_closureVariables == null) { + internal int ClosureSize + { + get + { + if (_closureVariables == null) + { return 0; } return _closureVariables.Count; } } - internal int LocalCount { - get { + internal int LocalCount + { + get + { return _localCount; } } - internal bool CompileSynchronously { + internal bool CompileSynchronously + { get { return _compilationThreshold <= 1; } } - internal InstructionArray Instructions { + internal InstructionArray Instructions + { get { return _instructions; } } - internal Dictionary ClosureVariables { - get { return _closureVariables; } + internal Dictionary ClosureVariables + { + get { return _closureVariables; } } - internal HybridReferenceDictionary LabelMapping { + internal HybridReferenceDictionary LabelMapping + { get { return _labelMapping; } } @@ -119,10 +130,12 @@ namespace System.Management.Automation.Interpreter { /// Each group of subsequent frames of Run method corresponds to a single interpreted frame. /// [SpecialName, MethodImpl(MethodImplOptions.NoInlining)] - public void Run(InterpretedFrame frame) { + public void Run(InterpretedFrame frame) + { var instructions = _instructions.Instructions; int index = frame.InstructionIndex; - while (index < instructions.Length) { + while (index < instructions.Length) + { index += instructions[index].Run(frame); frame.InstructionIndex = index; } @@ -140,16 +153,19 @@ namespace System.Management.Automation.Interpreter { /// If the target that 'Goto' jumps to is inside the current catch block or the subsequent finally block, /// we delay the call to 'Abort' method, because we want to finish the catch/finally blocks /// - internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) { + internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) + { var abortHandler = frame.CurrentAbortHandler; var targetInstrIndex = frame.Interpreter._labels[targetLabelIndex].Index; - if (abortHandler != null && - !abortHandler.IsInsideCatchBlock(targetInstrIndex) && - !abortHandler.IsInsideFinallyBlock(targetInstrIndex)) { + if (abortHandler != null && + !abortHandler.IsInsideCatchBlock(targetInstrIndex) && + !abortHandler.IsInsideFinallyBlock(targetInstrIndex)) + { frame.CurrentAbortHandler = null; var currentThread = Thread.CurrentThread; - if ((currentThread.ThreadState & System.Threading.ThreadState.AbortRequested) != 0) { + if ((currentThread.ThreadState & System.Threading.ThreadState.AbortRequested) != 0) + { Debug.Assert(AnyAbortException != null); // The current abort reason needs to be preserved. @@ -167,11 +183,13 @@ namespace System.Management.Automation.Interpreter { /// So this method doesn't need to do anything when running with CoreCLR /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) {} + internal static void AbortThreadIfRequested(InterpretedFrame frame, int targetLabelIndex) { } #endif - internal int ReturnAndRethrowLabelIndex { - get { + internal int ReturnAndRethrowLabelIndex + { + get + { // the last label is "return and rethrow" label: Debug.Assert(_labels[_labels.Length - 1].Index == RethrowOnReturn); return _labels.Length - 1; diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index d85adc250..a8f5760aa 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -27,13 +27,14 @@ using System.Text; using System.Reflection.Emit; using System.Diagnostics; -namespace System.Management.Automation.Interpreter { - +namespace System.Management.Automation.Interpreter +{ /// /// Contains compiler state corresponding to a LabelTarget /// See also LabelScopeInfo. /// - internal sealed class LabelInfo { + internal sealed class LabelInfo + { // The tree node representing this label private readonly LabelTarget _node; @@ -54,28 +55,35 @@ namespace System.Management.Automation.Interpreter { // LabelTarget can only be defined in one place private bool _acrossBlockJump; - internal LabelInfo(LabelTarget node) { + internal LabelInfo(LabelTarget node) + { _node = node; } - internal BranchLabel GetLabel(LightCompiler compiler) { + internal BranchLabel GetLabel(LightCompiler compiler) + { EnsureLabel(compiler); return _label; } - internal void Reference(LabelScopeInfo block) { + internal void Reference(LabelScopeInfo block) + { _references.Add(block); - if (HasDefinitions) { + if (HasDefinitions) + { ValidateJump(block); } } - internal void Define(LabelScopeInfo block) { + internal void Define(LabelScopeInfo block) + { // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) - for (LabelScopeInfo j = block; j != null; j = j.Parent) { - if (j.ContainsTarget(_node)) { + for (LabelScopeInfo j = block; j != null; j = j.Parent) + { + if (j.ContainsTarget(_node)) + { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name)); } } @@ -84,15 +92,20 @@ namespace System.Management.Automation.Interpreter { block.AddLabelInfo(_node, this); // Once defined, validate all jumps - if (HasDefinitions && !HasMultipleDefinitions) { - foreach (var r in _references) { + if (HasDefinitions && !HasMultipleDefinitions) + { + foreach (var r in _references) + { ValidateJump(r); } - } else { + } + else + { // Was just redefined, if we had any across block jumps, they're // now invalid - if (_acrossBlockJump) { - throw new InvalidOperationException("Ambiguous jump"); + if (_acrossBlockJump) + { + throw new InvalidOperationException("Ambiguous jump"); } // For local jumps, we need a new IL label // This is okay because: @@ -102,21 +115,26 @@ namespace System.Management.Automation.Interpreter { } } - private void ValidateJump(LabelScopeInfo reference) { + private void ValidateJump(LabelScopeInfo reference) + { // look for a simple jump out - for (LabelScopeInfo j = reference; j != null; j = j.Parent) { - if (DefinedIn(j)) { + for (LabelScopeInfo j = reference; j != null; j = j.Parent) + { + if (DefinedIn(j)) + { // found it, jump is valid! return; } - if (j.Kind == LabelScopeKind.Filter) { + if (j.Kind == LabelScopeKind.Filter) + { break; } } _acrossBlockJump = true; - if (HasMultipleDefinitions) { + if (HasMultipleDefinitions) + { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name)); } @@ -125,92 +143,122 @@ namespace System.Management.Automation.Interpreter { LabelScopeInfo common = CommonNode(def, reference, b => b.Parent); // Validate that we aren't jumping across a finally - for (LabelScopeInfo j = reference; j != common; j = j.Parent) { - if (j.Kind == LabelScopeKind.Filter) { + for (LabelScopeInfo j = reference; j != common; j = j.Parent) + { + if (j.Kind == LabelScopeKind.Filter) + { throw new InvalidOperationException("Control cannot leave filter test"); } } // Valdiate that we aren't jumping into a catch or an expression - for (LabelScopeInfo j = def; j != common; j = j.Parent) { - if (!j.CanJumpInto) { - if (j.Kind == LabelScopeKind.Expression) { + for (LabelScopeInfo j = def; j != common; j = j.Parent) + { + if (!j.CanJumpInto) + { + if (j.Kind == LabelScopeKind.Expression) + { throw new InvalidOperationException("Control cannot enter an expression"); - } else { + } + else + { throw new InvalidOperationException("Control cannot enter try"); } } } } - internal void ValidateFinish() { + internal void ValidateFinish() + { // Make sure that if this label was jumped to, it is also defined - if (_references.Count > 0 && !HasDefinitions) { + if (_references.Count > 0 && !HasDefinitions) + { throw new InvalidOperationException("label target undefined"); } } - private void EnsureLabel(LightCompiler compiler) { - if (_label == null) { + private void EnsureLabel(LightCompiler compiler) + { + if (_label == null) + { _label = compiler.Instructions.MakeLabel(); } - } + } - private bool DefinedIn(LabelScopeInfo scope) { - if (_definitions == scope) { + private bool DefinedIn(LabelScopeInfo scope) + { + if (_definitions == scope) + { return true; } HashSet definitions = _definitions as HashSet; - if (definitions != null) { + if (definitions != null) + { return definitions.Contains(scope); } return false; } - private bool HasDefinitions { - get { + private bool HasDefinitions + { + get + { return _definitions != null; } } - private LabelScopeInfo FirstDefinition() { + private LabelScopeInfo FirstDefinition() + { LabelScopeInfo scope = _definitions as LabelScopeInfo; - if (scope != null) { + if (scope != null) + { return scope; } return ((HashSet)_definitions).First(); } - private void AddDefinition(LabelScopeInfo scope) { - if (_definitions == null) { + private void AddDefinition(LabelScopeInfo scope) + { + if (_definitions == null) + { _definitions = scope; - } else { + } + else + { HashSet set = _definitions as HashSet; - if(set == null) { + if (set == null) + { _definitions = set = new HashSet() { (LabelScopeInfo)_definitions }; } set.Add(scope); } } - private bool HasMultipleDefinitions { - get { + private bool HasMultipleDefinitions + { + get + { return _definitions is HashSet; } } - internal static T CommonNode(T first, T second, Func parent) where T : class { + internal static T CommonNode(T first, T second, Func parent) where T : class + { var cmp = EqualityComparer.Default; - if (cmp.Equals(first, second)) { + if (cmp.Equals(first, second)) + { return first; } var set = new HashSet(cmp); - for (T t = first; t != null; t = parent(t)) { + for (T t = first; t != null; t = parent(t)) + { set.Add(t); } - for (T t = second; t != null; t = parent(t)) { - if (set.Contains(t)) { + for (T t = second; t != null; t = parent(t)) + { + if (set.Contains(t)) + { return t; } } @@ -218,7 +266,8 @@ namespace System.Management.Automation.Interpreter { } } - internal enum LabelScopeKind { + internal enum LabelScopeKind + { // any "statement like" node that can be jumped into Statement, @@ -250,12 +299,14 @@ namespace System.Management.Automation.Interpreter { // well as creating them for the first expression we can't jump into. The // "Kind" property indicates what kind of scope this is. // - internal sealed class LabelScopeInfo { - private HybridReferenceDictionary Labels; // lazily allocated, we typically use this only once every 6th-7th block + internal sealed class LabelScopeInfo + { + private HybridReferenceDictionary _labels; // lazily allocated, we typically use this only once every 6th-7th block internal readonly LabelScopeKind Kind; internal readonly LabelScopeInfo Parent; - internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) { + internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) + { Parent = parent; Kind = kind; } @@ -263,9 +314,12 @@ namespace System.Management.Automation.Interpreter { /// /// Returns true if we can jump into this node /// - internal bool CanJumpInto { - get { - switch (Kind) { + internal bool CanJumpInto + { + get + { + switch (Kind) + { case LabelScopeKind.Block: case LabelScopeKind.Statement: case LabelScopeKind.Switch: @@ -277,31 +331,37 @@ namespace System.Management.Automation.Interpreter { } - internal bool ContainsTarget(LabelTarget target) { - if (Labels == null) { + internal bool ContainsTarget(LabelTarget target) + { + if (_labels == null) + { return false; } - return Labels.ContainsKey(target); + return _labels.ContainsKey(target); } - internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { - if (Labels == null) { + internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) + { + if (_labels == null) + { info = null; return false; } - return Labels.TryGetValue(target, out info); + return _labels.TryGetValue(target, out info); } - internal void AddLabelInfo(LabelTarget target, LabelInfo info) { + internal void AddLabelInfo(LabelTarget target, LabelInfo info) + { Debug.Assert(CanJumpInto); - if (Labels == null) { - Labels = new HybridReferenceDictionary(); + if (_labels == null) + { + _labels = new HybridReferenceDictionary(); } - Labels[target] = info; + _labels[target] = info; } } } diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index 332ec5381..fd9093091 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -19,125 +19,153 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal abstract class LessThanInstruction : Instruction { - private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class LessThanInstruction : Instruction + { + private static Instruction s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private LessThanInstruction() { + private LessThanInstruction() + { } - internal sealed class LessThanSByte : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanSByte : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { SByte right = (SByte)frame.Pop(); frame.Push(((SByte)frame.Pop()) < right); return +1; } } - internal sealed class LessThanInt16 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanInt16 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int16 right = (Int16)frame.Pop(); frame.Push(((Int16)frame.Pop()) < right); return +1; } } - internal sealed class LessThanChar : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanChar : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Char right = (Char)frame.Pop(); frame.Push(((Char)frame.Pop()) < right); return +1; } } - internal sealed class LessThanInt32 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanInt32 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int32 right = (Int32)frame.Pop(); frame.Push(((Int32)frame.Pop()) < right); return +1; } } - internal sealed class LessThanInt64 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanInt64 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Int64 right = (Int64)frame.Pop(); frame.Push(((Int64)frame.Pop()) < right); return +1; } } - internal sealed class LessThanByte : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanByte : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Byte right = (Byte)frame.Pop(); frame.Push(((Byte)frame.Pop()) < right); return +1; } } - internal sealed class LessThanUInt16 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanUInt16 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt16 right = (UInt16)frame.Pop(); frame.Push(((UInt16)frame.Pop()) < right); return +1; } } - internal sealed class LessThanUInt32 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanUInt32 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt32 right = (UInt32)frame.Pop(); frame.Push(((UInt32)frame.Pop()) < right); return +1; } } - internal sealed class LessThanUInt64 : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanUInt64 : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { UInt64 right = (UInt64)frame.Pop(); frame.Push(((UInt64)frame.Pop()) < right); return +1; } } - internal sealed class LessThanSingle : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanSingle : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Single right = (Single)frame.Pop(); frame.Push(((Single)frame.Pop()) < right); return +1; } } - internal sealed class LessThanDouble : LessThanInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class LessThanDouble : LessThanInstruction + { + public override int Run(InterpretedFrame frame) + { Double right = (Double)frame.Pop(); frame.Push(((Double)frame.Pop()) < right); return +1; } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.SByte: return _SByte ?? (_SByte = new LessThanSByte()); - case TypeCode.Byte: return _Byte ?? (_Byte = new LessThanByte()); - case TypeCode.Char: return _Char ?? (_Char = new LessThanChar()); - case TypeCode.Int16: return _Int16 ?? (_Int16 = new LessThanInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new LessThanInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new LessThanInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new LessThanUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new LessThanUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new LessThanUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new LessThanSingle()); - case TypeCode.Double: return _Double ?? (_Double = new LessThanDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.SByte: return s_SByte ?? (s_SByte = new LessThanSByte()); + case TypeCode.Byte: return s_byte ?? (s_byte = new LessThanByte()); + case TypeCode.Char: return s_char ?? (s_char = new LessThanChar()); + case TypeCode.Int16: return s_int16 ?? (s_int16 = new LessThanInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new LessThanInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new LessThanInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new LessThanUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new LessThanUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new LessThanUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new LessThanSingle()); + case TypeCode.Double: return s_double ?? (s_double = new LessThanDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "LessThan()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 3679f5466..7b09adc82 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -31,8 +31,10 @@ using System.Reflection; using AstUtils = System.Management.Automation.Interpreter.Utils; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal sealed class ExceptionHandler { +namespace System.Management.Automation.Interpreter +{ + internal sealed class ExceptionHandler + { public readonly Type ExceptionType; public readonly int StartIndex; public readonly int EndIndex; @@ -44,7 +46,8 @@ namespace System.Management.Automation.Interpreter { public bool IsFault { get { return ExceptionType == null; } } - internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIndex, int handlerEndIndex, Type exceptionType) { + internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIndex, int handlerEndIndex, Type exceptionType) + { StartIndex = start; EndIndex = end; LabelIndex = labelIndex; @@ -53,39 +56,47 @@ namespace System.Management.Automation.Interpreter { HandlerEndIndex = handlerEndIndex; } - internal void SetParent(TryCatchFinallyHandler tryHandler) { + internal void SetParent(TryCatchFinallyHandler tryHandler) + { Debug.Assert(Parent == null); Parent = tryHandler; } - public bool Matches(Type exceptionType) { - if (ExceptionType == null || ExceptionType.IsAssignableFrom(exceptionType)) { + public bool Matches(Type exceptionType) + { + if (ExceptionType == null || ExceptionType.IsAssignableFrom(exceptionType)) + { return true; } return false; } - public bool IsBetterThan(ExceptionHandler other) { + public bool IsBetterThan(ExceptionHandler other) + { if (other == null) return true; Debug.Assert(StartIndex == other.StartIndex && EndIndex == other.EndIndex, "we only need to compare handlers for the same try block"); return HandlerStartIndex < other.HandlerStartIndex; } - internal bool IsInsideTryBlock(int index) { + internal bool IsInsideTryBlock(int index) + { return index >= StartIndex && index < EndIndex; } - internal bool IsInsideCatchBlock(int index) { + internal bool IsInsideCatchBlock(int index) + { return index >= HandlerStartIndex && index < HandlerEndIndex; } - internal bool IsInsideFinallyBlock(int index) { + internal bool IsInsideFinallyBlock(int index) + { Debug.Assert(Parent != null); return Parent.IsFinallyBlockExist && index >= Parent.FinallyStartIndex && index < Parent.FinallyEndIndex; } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.InvariantCulture, "{0} [{1}-{2}] [{3}->{4}]", (IsFault ? "fault" : "catch(" + ExceptionType.Name + ")"), StartIndex, EndIndex, @@ -175,36 +186,42 @@ namespace System.Management.Automation.Interpreter { } [Serializable] - internal class DebugInfo { + internal class DebugInfo + { // TODO: readonly public int StartLine, EndLine; public int Index; public string FileName; public bool IsClear; - private static readonly DebugInfoComparer _debugComparer = new DebugInfoComparer(); + private static readonly DebugInfoComparer s_debugComparer = new DebugInfoComparer(); - private class DebugInfoComparer : IComparer { + private class DebugInfoComparer : IComparer + { //We allow comparison between int and DebugInfo here - int IComparer.Compare(DebugInfo d1, DebugInfo d2) { + int IComparer.Compare(DebugInfo d1, DebugInfo d2) + { if (d1.Index > d2.Index) return 1; else if (d1.Index == d2.Index) return 0; else return -1; } } - - public static DebugInfo GetMatchingDebugInfo(DebugInfo[] debugInfos, int index) { + + public static DebugInfo GetMatchingDebugInfo(DebugInfo[] debugInfos, int index) + { //Create a faked DebugInfo to do the search DebugInfo d = new DebugInfo { Index = index }; //to find the closest debug info before the current index - int i = Array.BinarySearch(debugInfos, d, _debugComparer); - if (i < 0) { + int i = Array.BinarySearch(debugInfos, d, s_debugComparer); + if (i < 0) + { //~i is the index for the first bigger element //if there is no bigger element, ~i is the length of the array i = ~i; - if (i == 0) { + if (i == 0) + { return null; } //return the last one that is smaller @@ -214,10 +231,14 @@ namespace System.Management.Automation.Interpreter { return debugInfos[i]; } - public override string ToString() { - if (IsClear) { + public override string ToString() + { + if (IsClear) + { return String.Format(CultureInfo.InvariantCulture, "{0}: clear", Index); - } else { + } + else + { return String.Format(CultureInfo.InvariantCulture, "{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName); } } @@ -226,25 +247,29 @@ namespace System.Management.Automation.Interpreter { // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [Serializable] - internal struct InterpretedFrameInfo { + internal struct InterpretedFrameInfo + { public readonly string MethodName; - + // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public readonly DebugInfo DebugInfo; - public InterpretedFrameInfo(string methodName, DebugInfo info) { + public InterpretedFrameInfo(string methodName, DebugInfo info) + { MethodName = methodName; DebugInfo = info; } - public override string ToString() { + public override string ToString() + { return MethodName + (DebugInfo != null ? ": " + DebugInfo : null); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] - internal sealed class LightCompiler { + internal sealed class LightCompiler + { internal const int DefaultCompilationThreshold = 32; // zero: sync compilation @@ -252,7 +277,7 @@ namespace System.Management.Automation.Interpreter { private readonly InstructionList _instructions; private readonly LocalVariables _locals = new LocalVariables(); - + private readonly List _debugInfos = new List(); private readonly HybridReferenceDictionary _treeLabels = new HybridReferenceDictionary(); private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda); @@ -267,31 +292,37 @@ namespace System.Management.Automation.Interpreter { private readonly LightCompiler _parent; - private static LocalDefinition[] EmptyLocals = Automation.Utils.EmptyArray(); + private static LocalDefinition[] s_emptyLocals = Automation.Utils.EmptyArray(); - public LightCompiler(int compilationThreshold) { + public LightCompiler(int compilationThreshold) + { _instructions = new InstructionList(); _compilationThreshold = compilationThreshold < 0 ? DefaultCompilationThreshold : compilationThreshold; } private LightCompiler(LightCompiler parent) - : this(parent._compilationThreshold) { + : this(parent._compilationThreshold) + { _parent = parent; } - public InstructionList Instructions { + public InstructionList Instructions + { get { return _instructions; } } - public LocalVariables Locals { + public LocalVariables Locals + { get { return _locals; } } - internal static Expression Unbox(Expression strongBoxExpression) { + internal static Expression Unbox(Expression strongBoxExpression) + { return Expression.Field(strongBoxExpression, typeof(StrongBox).GetField("Value")); } - public LightDelegateCreator CompileTop(LambdaExpression node) { + public LightDelegateCreator CompileTop(LambdaExpression node) + { for (int index = 0; index < node.Parameters.Count; index++) { var p = node.Parameters[index]; @@ -300,9 +331,10 @@ namespace System.Management.Automation.Interpreter { } Compile(node.Body); - + // pop the result of the last expression: - if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) { + if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) + { _instructions.EmitPop(); } @@ -329,8 +361,10 @@ namespace System.Management.Automation.Interpreter { // return new LightDelegateCreator(MakeInterpreter(node.Name), node); //} - private Interpreter MakeInterpreter(string lambdaName) { - if (_forceCompile) { + private Interpreter MakeInterpreter(string lambdaName) + { + if (_forceCompile) + { return null; } @@ -339,41 +373,58 @@ namespace System.Management.Automation.Interpreter { } - private void CompileConstantExpression(Expression expr) { + private void CompileConstantExpression(Expression expr) + { var node = (ConstantExpression)expr; _instructions.EmitLoad(node.Value, node.Type); } - private void CompileDefaultExpression(Expression expr) { + private void CompileDefaultExpression(Expression expr) + { CompileDefaultExpression(expr.Type); } - private void CompileDefaultExpression(Type type) { - if (type != typeof(void)) { - if (type.GetTypeInfo().IsValueType) { + private void CompileDefaultExpression(Type type) + { + if (type != typeof(void)) + { + if (type.GetTypeInfo().IsValueType) + { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) { + if (value != null) + { _instructions.EmitLoad(value); - } else { + } + else + { _instructions.EmitDefaultValue(type); } - } else { + } + else + { _instructions.EmitLoad(null); } } } - private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) { + private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) + { LocalVariable local; - if (_locals.TryGetLocalOrClosure(expr, out local)) { - if (!local.InClosure && !local.IsBoxed) { + if (_locals.TryGetLocalOrClosure(expr, out local)) + { + if (!local.InClosure && !local.IsBoxed) + { _locals.Box(expr, _instructions); } return local; - } else if (_parent != null) { + } + else if (_parent != null) + { _parent.EnsureAvailableForClosure(expr); return _locals.AddClosureVariable(expr); - } else { + } + else + { throw new InvalidOperationException("unbound variable: " + expr); } } @@ -384,34 +435,46 @@ namespace System.Management.Automation.Interpreter { // } //} - private LocalVariable ResolveLocal(ParameterExpression variable) { + private LocalVariable ResolveLocal(ParameterExpression variable) + { LocalVariable local; - if (!_locals.TryGetLocalOrClosure(variable, out local)) { + if (!_locals.TryGetLocalOrClosure(variable, out local)) + { local = EnsureAvailableForClosure(variable); } return local; } - public void CompileGetVariable(ParameterExpression variable) { + public void CompileGetVariable(ParameterExpression variable) + { LocalVariable local = ResolveLocal(variable); - if (local.InClosure) { + if (local.InClosure) + { _instructions.EmitLoadLocalFromClosure(local.Index); - } else if (local.IsBoxed) { + } + else if (local.IsBoxed) + { _instructions.EmitLoadLocalBoxed(local.Index); - } else { + } + else + { _instructions.EmitLoadLocal(local.Index); } _instructions.SetDebugCookie(variable.Name); } - public void CompileGetBoxedVariable(ParameterExpression variable) { + public void CompileGetBoxedVariable(ParameterExpression variable) + { LocalVariable local = ResolveLocal(variable); - if (local.InClosure) { + if (local.InClosure) + { _instructions.EmitLoadLocalFromClosureBoxed(local.Index); - } else { + } + else + { Debug.Assert(local.IsBoxed); _instructions.EmitLoadLocal(local.Index); } @@ -419,25 +482,40 @@ namespace System.Management.Automation.Interpreter { _instructions.SetDebugCookie(variable.Name); } - public void CompileSetVariable(ParameterExpression variable, bool isVoid) { + public void CompileSetVariable(ParameterExpression variable, bool isVoid) + { LocalVariable local = ResolveLocal(variable); - if (local.InClosure) { - if (isVoid) { + if (local.InClosure) + { + if (isVoid) + { _instructions.EmitStoreLocalToClosure(local.Index); - } else { + } + else + { _instructions.EmitAssignLocalToClosure(local.Index); } - } else if (local.IsBoxed) { - if (isVoid) { + } + else if (local.IsBoxed) + { + if (isVoid) + { _instructions.EmitStoreLocalBoxed(local.Index); - } else { + } + else + { _instructions.EmitAssignLocalBoxed(local.Index); } - } else { - if (isVoid) { + } + else + { + if (isVoid) + { _instructions.EmitStoreLocal(local.Index); - } else { + } + else + { _instructions.EmitAssignLocal(local.Index); } } @@ -445,12 +523,14 @@ namespace System.Management.Automation.Interpreter { _instructions.SetDebugCookie(variable.Name); } - public void CompileParameterExpression(Expression expr) { + public void CompileParameterExpression(Expression expr) + { var node = (ParameterExpression)expr; CompileGetVariable(node); } - private void CompileBlockExpression(Expression expr, bool asVoid) { + private void CompileBlockExpression(Expression expr, bool asVoid) + { var node = (BlockExpression)expr; var end = CompileBlockStart(node); @@ -459,12 +539,14 @@ namespace System.Management.Automation.Interpreter { CompileBlockEnd(end); } - private LocalDefinition[] CompileBlockStart(BlockExpression node) { + private LocalDefinition[] CompileBlockStart(BlockExpression node) + { var start = _instructions.Count; - + LocalDefinition[] locals; var variables = node.Variables; - if (variables.Count != 0) { + if (variables.Count != 0) + { // TODO: basic flow analysis so we don't have to initialize all // variables. locals = new LocalDefinition[variables.Count]; @@ -478,11 +560,14 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitInitializeLocal(local.Index, variable.Type); _instructions.SetDebugCookie(variable.Name); } - } else { - locals = EmptyLocals; + } + else + { + locals = s_emptyLocals; } - for (int i = 0; i < node.Expressions.Count - 1; i++) { + for (int i = 0; i < node.Expressions.Count - 1; i++) + { CompileAsVoid(node.Expressions[i]); } return locals; @@ -497,11 +582,13 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileIndexExpression(Expression expr) { + private void CompileIndexExpression(Expression expr) + { var index = (IndexExpression)expr; // instance: - if (index.Object != null) { + if (index.Object != null) + { Compile(index.Object); } @@ -512,24 +599,32 @@ namespace System.Management.Automation.Interpreter { Compile(arg); } - if (index.Indexer != null) { + if (index.Indexer != null) + { _instructions.EmitCall(index.Indexer.GetMethod); - } else if (index.Arguments.Count != 1) { + } + else if (index.Arguments.Count != 1) + { _instructions.EmitCall(index.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)); - } else { + } + else + { _instructions.EmitGetArrayItem(index.Object.Type); } } - private void CompileIndexAssignment(BinaryExpression node, bool asVoid) { + private void CompileIndexAssignment(BinaryExpression node, bool asVoid) + { var index = (IndexExpression)node.Left; - if (!asVoid) { + if (!asVoid) + { throw new NotImplementedException(); } // instance: - if (index.Object != null) { + if (index.Object != null) + { Compile(index.Object); } @@ -543,20 +638,27 @@ namespace System.Management.Automation.Interpreter { // value: Compile(node.Right); - if (index.Indexer != null) { + if (index.Indexer != null) + { _instructions.EmitCall(index.Indexer.SetMethod); - } else if (index.Arguments.Count != 1) { + } + else if (index.Arguments.Count != 1) + { _instructions.EmitCall(index.Object.Type.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance)); - } else { + } + else + { _instructions.EmitSetArrayItem(index.Object.Type); } } - private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { + private void CompileMemberAssignment(BinaryExpression node, bool asVoid) + { var member = (MemberExpression)node.Left; PropertyInfo pi = member.Member as PropertyInfo; - if (pi != null) { + if (pi != null) + { var method = pi.SetMethod; if (member.Expression != null) { @@ -565,33 +667,41 @@ namespace System.Management.Automation.Interpreter { Compile(node.Right); int start = _instructions.Count; - if (!asVoid) { + if (!asVoid) + { LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start); _instructions.EmitAssignLocal(local.Index); _instructions.EmitCall(method); _instructions.EmitLoadLocal(local.Index); _locals.UndefineLocal(local, _instructions.Count); - } else { + } + else + { _instructions.EmitCall(method); } return; } FieldInfo fi = member.Member as FieldInfo; - if (fi != null) { - if (member.Expression != null) { + if (fi != null) + { + if (member.Expression != null) + { Compile(member.Expression); } Compile(node.Right); int start = _instructions.Count; - if (!asVoid) { + if (!asVoid) + { LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start); _instructions.EmitAssignLocal(local.Index); _instructions.EmitStoreField(fi); _instructions.EmitLoadLocal(local.Index); _locals.UndefineLocal(local, _instructions.Count); - } else { + } + else + { _instructions.EmitStoreField(fi); } return; @@ -600,28 +710,31 @@ namespace System.Management.Automation.Interpreter { throw new NotImplementedException(); } - private void CompileVariableAssignment(BinaryExpression node, bool asVoid) { + private void CompileVariableAssignment(BinaryExpression node, bool asVoid) + { this.Compile(node.Right); var target = (ParameterExpression)node.Left; CompileSetVariable(target, asVoid); } - private void CompileAssignBinaryExpression(Expression expr, bool asVoid) { + private void CompileAssignBinaryExpression(Expression expr, bool asVoid) + { var node = (BinaryExpression)expr; - switch (node.Left.NodeType) { + switch (node.Left.NodeType) + { case ExpressionType.Index: - CompileIndexAssignment(node, asVoid); + CompileIndexAssignment(node, asVoid); break; case ExpressionType.MemberAccess: - CompileMemberAssignment(node, asVoid); + CompileMemberAssignment(node, asVoid); break; case ExpressionType.Parameter: case ExpressionType.Extension: - CompileVariableAssignment(node, asVoid); + CompileVariableAssignment(node, asVoid); break; default: @@ -629,15 +742,20 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileBinaryExpression(Expression expr) { + private void CompileBinaryExpression(Expression expr) + { var node = (BinaryExpression)expr; - if (node.Method != null) { + if (node.Method != null) + { Compile(node.Left); Compile(node.Right); _instructions.EmitCall(node.Method); - } else { - switch (node.NodeType) { + } + else + { + switch (node.NodeType) + { case ExpressionType.ArrayIndex: Debug.Assert(node.Right.Type == typeof(int)); Compile(node.Left); @@ -676,7 +794,8 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileEqual(Expression left, Expression right) { + private void CompileEqual(Expression left, Expression right) + { Debug.Assert(left.Type == right.Type || !left.Type.GetTypeInfo().IsValueType && !right.Type.GetTypeInfo().IsValueType); Compile(left); @@ -684,7 +803,8 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitEqual(left.Type); } - private void CompileNotEqual(Expression left, Expression right) { + private void CompileNotEqual(Expression left, Expression right) + { Debug.Assert(left.Type == right.Type || !left.Type.GetTypeInfo().IsValueType && !right.Type.GetTypeInfo().IsValueType); Compile(left); @@ -692,7 +812,8 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitNotEqual(left.Type); } - private void CompileComparison(ExpressionType nodeType, Expression left, Expression right) { + private void CompileComparison(ExpressionType nodeType, Expression left, Expression right) + { Debug.Assert(left.Type == right.Type && TypeUtils.IsNumeric(left.Type)); // TODO: @@ -700,8 +821,9 @@ namespace System.Management.Automation.Interpreter { Compile(left); Compile(right); - - switch (nodeType) { + + switch (nodeType) + { case ExpressionType.LessThan: _instructions.EmitLessThan(left.Type); break; case ExpressionType.LessThanOrEqual: _instructions.EmitLessThanOrEqual(left.Type); break; case ExpressionType.GreaterThan: _instructions.EmitGreaterThan(left.Type); break; @@ -710,11 +832,13 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileArithmetic(ExpressionType nodeType, Expression left, Expression right) { + private void CompileArithmetic(ExpressionType nodeType, Expression left, Expression right) + { Debug.Assert(left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)); Compile(left); Compile(right); - switch (nodeType) { + switch (nodeType) + { case ExpressionType.Add: _instructions.EmitAdd(left.Type, false); break; case ExpressionType.AddChecked: _instructions.EmitAdd(left.Type, true); break; case ExpressionType.Subtract: _instructions.EmitSub(left.Type, false); break; @@ -726,36 +850,49 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileConvertUnaryExpression(Expression expr) { + private void CompileConvertUnaryExpression(Expression expr) + { var node = (UnaryExpression)expr; - if (node.Method != null) { + if (node.Method != null) + { Compile(node.Operand); // We should be able to ignore Int32ToObject - if (node.Method != ScriptingRuntimeHelpers.Int32ToObjectMethod) { + if (node.Method != ScriptingRuntimeHelpers.Int32ToObjectMethod) + { _instructions.EmitCall(node.Method); } - } else if (node.Type == typeof(void)) { + } + else if (node.Type == typeof(void)) + { CompileAsVoid(node.Operand); - } else { + } + else + { Compile(node.Operand); CompileConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked); } } - private void CompileConvertToType(Type typeFrom, Type typeTo, bool isChecked) { + private void CompileConvertToType(Type typeFrom, Type typeTo, bool isChecked) + { Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void)); - if (typeTo == typeFrom) { + if (typeTo == typeFrom) + { return; } TypeCode from = typeFrom.GetTypeCode(); TypeCode to = typeTo.GetTypeCode(); - if (TypeUtils.IsNumeric(from) && TypeUtils.IsNumeric(to)) { - if (isChecked) { + if (TypeUtils.IsNumeric(from) && TypeUtils.IsNumeric(to)) + { + if (isChecked) + { _instructions.EmitNumericConvertChecked(from, to); - } else { + } + else + { _instructions.EmitNumericConvertUnchecked(from, to); } return; @@ -766,23 +903,32 @@ namespace System.Management.Automation.Interpreter { return; } - private void CompileNotExpression(UnaryExpression node) { - if (node.Operand.Type == typeof(bool)) { + private void CompileNotExpression(UnaryExpression node) + { + if (node.Operand.Type == typeof(bool)) + { Compile(node.Operand); _instructions.EmitNot(); - } else { + } + else + { throw new NotImplementedException(); } } - private void CompileUnaryExpression(Expression expr) { + private void CompileUnaryExpression(Expression expr) + { var node = (UnaryExpression)expr; - - if (node.Method != null) { + + if (node.Method != null) + { Compile(node.Operand); _instructions.EmitCall(node.Method); - } else { - switch (node.NodeType) { + } + else + { + switch (node.NodeType) + { case ExpressionType.Not: CompileNotExpression(node); return; @@ -795,29 +941,37 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileAndAlsoBinaryExpression(Expression expr) { + private void CompileAndAlsoBinaryExpression(Expression expr) + { CompileLogicalBinaryExpression(expr, true); } - private void CompileOrElseBinaryExpression(Expression expr) { + private void CompileOrElseBinaryExpression(Expression expr) + { CompileLogicalBinaryExpression(expr, false); } - private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) { + private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) + { var node = (BinaryExpression)expr; - if (node.Method != null) { + if (node.Method != null) + { throw new NotImplementedException(); } Debug.Assert(node.Left.Type == node.Right.Type); - if (node.Left.Type == typeof(bool)) { + if (node.Left.Type == typeof(bool)) + { var elseLabel = _instructions.MakeLabel(); var endLabel = _instructions.MakeLabel(); Compile(node.Left); - if (andAlso) { + if (andAlso) + { _instructions.EmitBranchFalse(elseLabel); - } else { + } + else + { _instructions.EmitBranchTrue(elseLabel); } Compile(node.Right); @@ -832,27 +986,34 @@ namespace System.Management.Automation.Interpreter { throw new NotImplementedException(); } - private void CompileConditionalExpression(Expression expr, bool asVoid) { + private void CompileConditionalExpression(Expression expr, bool asVoid) + { var node = (ConditionalExpression)expr; Compile(node.Test); - if (node.IfTrue == AstUtils.Empty()) { + if (node.IfTrue == AstUtils.Empty()) + { var endOfFalse = _instructions.MakeLabel(); _instructions.EmitBranchTrue(endOfFalse); Compile(node.IfFalse, asVoid); _instructions.MarkLabel(endOfFalse); - } else { + } + else + { var endOfTrue = _instructions.MakeLabel(); _instructions.EmitBranchFalse(endOfTrue); Compile(node.IfTrue, asVoid); - if (node.IfFalse != AstUtils.Empty()) { + if (node.IfFalse != AstUtils.Empty()) + { var endOfFalse = _instructions.MakeLabel(); _instructions.EmitBranch(endOfFalse, false, !asVoid); _instructions.MarkLabel(endOfTrue); Compile(node.IfFalse, asVoid); _instructions.MarkLabel(endOfFalse); - } else { + } + else + { _instructions.MarkLabel(endOfTrue); } } @@ -860,42 +1021,46 @@ namespace System.Management.Automation.Interpreter { #region Loops - private void CompileLoopExpression(Expression expr) { - // var node = (LoopExpression)expr; - // var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count); - // - // PushLabelBlock(LabelScopeKind.Statement); - // LabelInfo breakLabel = DefineLabel(node.BreakLabel); - // LabelInfo continueLabel = DefineLabel(node.ContinueLabel); - // - // _instructions.MarkLabel(continueLabel.GetLabel(this)); - // - // // emit loop body: - // _instructions.Emit(enterLoop); - // CompileAsVoid(node.Body); - // - // // emit loop branch: - // _instructions.EmitBranch(continueLabel.GetLabel(this), expr.Type != typeof(void), false); - // - // _instructions.MarkLabel(breakLabel.GetLabel(this)); - // - // PopLabelBlock(LabelScopeKind.Statement); - // - // enterLoop.FinishLoop(_instructions.Count); + private void CompileLoopExpression(Expression expr) + { + // var node = (LoopExpression)expr; + // var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count); + // + // PushLabelBlock(LabelScopeKind.Statement); + // LabelInfo breakLabel = DefineLabel(node.BreakLabel); + // LabelInfo continueLabel = DefineLabel(node.ContinueLabel); + // + // _instructions.MarkLabel(continueLabel.GetLabel(this)); + // + // // emit loop body: + // _instructions.Emit(enterLoop); + // CompileAsVoid(node.Body); + // + // // emit loop branch: + // _instructions.EmitBranch(continueLabel.GetLabel(this), expr.Type != typeof(void), false); + // + // _instructions.MarkLabel(breakLabel.GetLabel(this)); + // + // PopLabelBlock(LabelScopeKind.Statement); + // + // enterLoop.FinishLoop(_instructions.Count); } #endregion - private void CompileSwitchExpression(Expression expr) { + private void CompileSwitchExpression(Expression expr) + { var node = (SwitchExpression)expr; // Currently only supports int test values, with no method - if (node.SwitchValue.Type != typeof(int) || node.Comparison != null) { + if (node.SwitchValue.Type != typeof(int) || node.Comparison != null) + { throw new NotImplementedException(); } // Test values must be constant - if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) { + if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) + { throw new NotImplementedException(); } LabelInfo end = DefineLabel(null); @@ -906,26 +1071,31 @@ namespace System.Management.Automation.Interpreter { int switchIndex = _instructions.Count; _instructions.EmitSwitch(caseDict); - if (node.DefaultBody != null) { + if (node.DefaultBody != null) + { Compile(node.DefaultBody); - } else { + } + else + { Debug.Assert(!hasValue); } _instructions.EmitBranch(end.GetLabel(this), false, hasValue); - for (int i = 0; i < node.Cases.Count; i++) { + for (int i = 0; i < node.Cases.Count; i++) + { var switchCase = node.Cases[i]; int caseOffset = _instructions.Count - switchIndex; for (int index = 0; index < switchCase.TestValues.Count; index++) { var testValue = (ConstantExpression)switchCase.TestValues[index]; - caseDict[(int) testValue.Value] = caseOffset; + caseDict[(int)testValue.Value] = caseOffset; } Compile(switchCase.Body); - if (i < node.Cases.Count - 1) { + if (i < node.Cases.Count - 1) + { _instructions.EmitBranch(end.GetLabel(this), false, hasValue); } } @@ -933,7 +1103,8 @@ namespace System.Management.Automation.Interpreter { _instructions.MarkLabel(end.GetLabel(this)); } - private void CompileLabelExpression(Expression expr) { + private void CompileLabelExpression(Expression expr) + { var node = (LabelExpression)expr; // If we're an immediate child of a block, our label will already @@ -941,11 +1112,13 @@ namespace System.Management.Automation.Interpreter { // label isn't exposed except to its own child expression. LabelInfo label = null; - if (_labelBlock.Kind == LabelScopeKind.Block) { + if (_labelBlock.Kind == LabelScopeKind.Block) + { _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch - if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) { + if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) + { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } @@ -953,14 +1126,19 @@ namespace System.Management.Automation.Interpreter { Debug.Assert(label != null); } - if (label == null) { + if (label == null) + { label = DefineLabel(node.Target); } - if (node.DefaultValue != null) { - if (node.Target.Type == typeof(void)) { + if (node.DefaultValue != null) + { + if (node.Target.Type == typeof(void)) + { CompileAsVoid(node.DefaultValue); - } else { + } + else + { Compile(node.DefaultValue); } } @@ -968,47 +1146,57 @@ namespace System.Management.Automation.Interpreter { _instructions.MarkLabel(label.GetLabel(this)); } - private void CompileGotoExpression(Expression expr) { + private void CompileGotoExpression(Expression expr) + { var node = (GotoExpression)expr; var labelInfo = ReferenceLabel(node.Target); - if (node.Value != null) { + if (node.Value != null) + { Compile(node.Value); } _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), node.Value != null && node.Value.Type != typeof(void)); } - public BranchLabel GetBranchLabel(LabelTarget target) { + public BranchLabel GetBranchLabel(LabelTarget target) + { return ReferenceLabel(target).GetLabel(this); } - public void PushLabelBlock(LabelScopeKind type) { + public void PushLabelBlock(LabelScopeKind type) + { _labelBlock = new LabelScopeInfo(_labelBlock, type); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] - public void PopLabelBlock(LabelScopeKind kind) { + public void PopLabelBlock(LabelScopeKind kind) + { Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent; } - private LabelInfo EnsureLabel(LabelTarget node) { + private LabelInfo EnsureLabel(LabelTarget node) + { LabelInfo result; - if (!_treeLabels.TryGetValue(node, out result)) { + if (!_treeLabels.TryGetValue(node, out result)) + { _treeLabels[node] = result = new LabelInfo(node); } return result; } - private LabelInfo ReferenceLabel(LabelTarget node) { + private LabelInfo ReferenceLabel(LabelTarget node) + { LabelInfo result = EnsureLabel(node); result.Reference(_labelBlock); return result; } - internal LabelInfo DefineLabel(LabelTarget node) { - if (node == null) { + internal LabelInfo DefineLabel(LabelTarget node) + { + if (node == null) + { return new LabelInfo(null); } LabelInfo result = EnsureLabel(node); @@ -1016,16 +1204,19 @@ namespace System.Management.Automation.Interpreter { return result; } - private bool TryPushLabelBlock(Expression node) { + private bool TryPushLabelBlock(Expression node) + { // Anything that is "statement-like" -- e.g. has no associated // stack state can be jumped into, with the exception of try-blocks // We indicate this by a "Block" // // Otherwise, we push an "Expression" to indicate that it can't be // jumped into - switch (node.NodeType) { + switch (node.NodeType) + { default: - if (_labelBlock.Kind != LabelScopeKind.Expression) { + if (_labelBlock.Kind != LabelScopeKind.Expression) + { PushLabelBlock(LabelScopeKind.Expression); return true; } @@ -1034,13 +1225,16 @@ namespace System.Management.Automation.Interpreter { // LabelExpression is a bit special, if it's directly in a // block it becomes associate with the block's scope. Same // thing if it's in a switch case body. - if (_labelBlock.Kind == LabelScopeKind.Block) { + if (_labelBlock.Kind == LabelScopeKind.Block) + { var label = ((LabelExpression)node).Target; - if (_labelBlock.ContainsTarget(label)) { + if (_labelBlock.ContainsTarget(label)) + { return false; } if (_labelBlock.Parent.Kind == LabelScopeKind.Switch && - _labelBlock.Parent.ContainsTarget(label)) { + _labelBlock.Parent.ContainsTarget(label)) + { return false; } } @@ -1050,7 +1244,8 @@ namespace System.Management.Automation.Interpreter { PushLabelBlock(LabelScopeKind.Block); // Labels defined immediately in the block are valid for // the whole block. - if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) { + if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) + { DefineBlockLabels(node); } return true; @@ -1070,7 +1265,8 @@ namespace System.Management.Automation.Interpreter { // Remove this when Convert(Void) goes away. case ExpressionType.Convert: - if (node.Type != typeof(void)) { + if (node.Type != typeof(void)) + { // treat it as an expression goto default; } @@ -1085,60 +1281,78 @@ namespace System.Management.Automation.Interpreter { } } - private void DefineBlockLabels(Expression node) { + private void DefineBlockLabels(Expression node) + { var block = node as BlockExpression; - if (block == null) { + if (block == null) + { return; } - for (int i = 0, n = block.Expressions.Count; i < n; i++) { + for (int i = 0, n = block.Expressions.Count; i < n; i++) + { Expression e = block.Expressions[i]; var label = e as LabelExpression; - if (label != null) { + if (label != null) + { DefineLabel(label.Target); } } } - private HybridReferenceDictionary GetBranchMapping() { + private HybridReferenceDictionary GetBranchMapping() + { var newLabelMapping = new HybridReferenceDictionary(_treeLabels.Count); - foreach (var kvp in _treeLabels) { + foreach (var kvp in _treeLabels) + { newLabelMapping[kvp.Key] = kvp.Value.GetLabel(this); } return newLabelMapping; } - private void CompileThrowUnaryExpression(Expression expr, bool asVoid) { + private void CompileThrowUnaryExpression(Expression expr, bool asVoid) + { var node = (UnaryExpression)expr; - if (node.Operand == null) { + if (node.Operand == null) + { CompileParameterExpression(_exceptionForRethrowStack.Peek()); - if (asVoid) { + if (asVoid) + { _instructions.EmitRethrowVoid(); - } else { + } + else + { _instructions.EmitRethrow(); } - } else { + } + else + { Compile(node.Operand); - if (asVoid) { + if (asVoid) + { _instructions.EmitThrowVoid(); - } else { + } + else + { _instructions.EmitThrow(); } } - } // TODO: remove (replace by true fault support) - private bool EndsWithRethrow(Expression expr) { - if (expr.NodeType == ExpressionType.Throw) { + private bool EndsWithRethrow(Expression expr) + { + if (expr.NodeType == ExpressionType.Throw) + { var node = (UnaryExpression)expr; return node.Operand == null; } BlockExpression block = expr as BlockExpression; - if (block != null) { + if (block != null) + { return EndsWithRethrow(block.Expressions[block.Expressions.Count - 1]); } return false; @@ -1146,10 +1360,12 @@ namespace System.Management.Automation.Interpreter { // TODO: remove (replace by true fault support) - private void CompileAsVoidRemoveRethrow(Expression expr) { + private void CompileAsVoidRemoveRethrow(Expression expr) + { int stackDepth = _instructions.CurrentStackDepth; - if (expr.NodeType == ExpressionType.Throw) { + if (expr.NodeType == ExpressionType.Throw) + { Debug.Assert(((UnaryExpression)expr).Operand == null); return; } @@ -1164,7 +1380,8 @@ namespace System.Management.Automation.Interpreter { CompileBlockEnd(end); } - private void CompileTryExpression(Expression expr) { + private void CompileTryExpression(Expression expr) + { var node = (TryExpression)expr; BranchLabel end = _instructions.MakeLabel(); @@ -1172,17 +1389,20 @@ namespace System.Management.Automation.Interpreter { int tryStart = _instructions.Count; BranchLabel startOfFinally = null; - if (node.Finally != null) { + if (node.Finally != null) + { startOfFinally = _instructions.MakeLabel(); _instructions.EmitEnterTryFinally(startOfFinally); - } else { + } + else + { _instructions.EmitEnterTryCatch(); } List exHandlers = null; var enterTryInstr = _instructions.GetInstruction(tryStart) as EnterTryCatchFinallyInstruction; Debug.Assert(enterTryInstr != null); - + PushLabelBlock(LabelScopeKind.Try); Compile(node.Body); @@ -1192,19 +1412,26 @@ namespace System.Management.Automation.Interpreter { // handlers jump here: _instructions.MarkLabel(gotoEnd); _instructions.EmitGoto(end, hasValue, hasValue); - + // keep the result on the stack: - if (node.Handlers.Count > 0) { + if (node.Handlers.Count > 0) + { exHandlers = new List(); // TODO: emulates faults (replace by true fault support) - if (node.Finally == null && node.Handlers.Count == 1) { + if (node.Finally == null && node.Handlers.Count == 1) + { var handler = node.Handlers[0]; - if (handler.Filter == null && handler.Test == typeof(Exception) && handler.Variable == null) { - if (EndsWithRethrow(handler.Body)) { - if (hasValue) { + if (handler.Filter == null && handler.Test == typeof(Exception) && handler.Variable == null) + { + if (EndsWithRethrow(handler.Body)) + { + if (hasValue) + { _instructions.EmitEnterExceptionHandlerNonVoid(); - } else { + } + else + { _instructions.EmitEnterExceptionHandlerVoid(); } @@ -1261,7 +1488,7 @@ namespace System.Management.Automation.Interpreter { _exceptionForRethrowStack.Pop(); // keep the value of the body on the stack: - Debug.Assert(hasValue == (handler.Body.Type != typeof (void))); + Debug.Assert(hasValue == (handler.Body.Type != typeof(void))); _instructions.EmitLeaveExceptionHandler(hasValue, gotoEnd); exHandlers.Add(new ExceptionHandler(tryStart, tryEnd, handlerLabel, handlerStart, @@ -1271,12 +1498,14 @@ namespace System.Management.Automation.Interpreter { _locals.UndefineLocal(local, _instructions.Count); } - if (node.Fault != null) { + if (node.Fault != null) + { throw new NotImplementedException(); } } - - if (node.Finally != null) { + + if (node.Finally != null) + { Debug.Assert(startOfFinally != null); PushLabelBlock(LabelScopeKind.Finally); @@ -1303,7 +1532,8 @@ namespace System.Management.Automation.Interpreter { PopLabelBlock(LabelScopeKind.Try); } - private void CompileDynamicExpression(Expression expr) { + private void CompileDynamicExpression(Expression expr) + { var node = (DynamicExpression)expr; for (int index = 0; index < node.Arguments.Count; index++) @@ -1315,9 +1545,10 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitDynamic(node.DelegateType, node.Binder); } - private void CompileMethodCallExpression(Expression expr) { + private void CompileMethodCallExpression(Expression expr) + { var node = (MethodCallExpression)expr; - + var parameters = node.Method.GetParameters(); // TODO: @@ -1329,11 +1560,13 @@ namespace System.Management.Automation.Interpreter { // need to generate code. var declaringTypeInfo = node.Method.DeclaringType.GetTypeInfo(); if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef) || - (!node.Method.IsStatic && declaringTypeInfo.IsValueType && !declaringTypeInfo.IsPrimitive)) { + (!node.Method.IsStatic && declaringTypeInfo.IsValueType && !declaringTypeInfo.IsPrimitive)) + { _forceCompile = true; } - if (!node.Method.IsStatic) { + if (!node.Method.IsStatic) + { Compile(node.Object); } @@ -1346,12 +1579,15 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitCall(node.Method, parameters); } - private void CompileNewExpression(Expression expr) { + private void CompileNewExpression(Expression expr) + { var node = (NewExpression)expr; - if (node.Constructor != null) { + if (node.Constructor != null) + { var parameters = node.Constructor.GetParameters(); - if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef)) { + if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef)) + { _forceCompile = true; } } @@ -1365,27 +1601,38 @@ namespace System.Management.Automation.Interpreter { } _instructions.EmitNew(node.Constructor); } - else { + else + { Debug.Assert(expr.Type.GetTypeInfo().IsValueType); _instructions.EmitDefaultValue(node.Type); } } - private void CompileMemberExpression(Expression expr) { + private void CompileMemberExpression(Expression expr) + { var node = (MemberExpression)expr; var member = node.Member; FieldInfo fi = member as FieldInfo; - if (fi != null) { - if (fi.IsLiteral) { + if (fi != null) + { + if (fi.IsLiteral) + { _instructions.EmitLoad(fi.GetValue(null), fi.FieldType); - } else if (fi.IsStatic) { - if (fi.IsInitOnly) { + } + else if (fi.IsStatic) + { + if (fi.IsInitOnly) + { _instructions.EmitLoad(fi.GetValue(null), fi.FieldType); - } else { + } + else + { _instructions.EmitLoadField(fi); } - } else { + } + else + { Compile(node.Expression); _instructions.EmitLoadField(fi); } @@ -1393,9 +1640,11 @@ namespace System.Management.Automation.Interpreter { } PropertyInfo pi = member as PropertyInfo; - if (pi != null) { + if (pi != null) + { var method = pi.GetMethod; - if (node.Expression != null) { + if (node.Expression != null) + { Compile(node.Expression); } _instructions.EmitCall(method); @@ -1406,7 +1655,8 @@ namespace System.Management.Automation.Interpreter { throw new System.NotImplementedException(); } - private void CompileNewArrayExpression(Expression expr) { + private void CompileNewArrayExpression(Expression expr) + { var node = (NewArrayExpression)expr; for (int index = 0; index < node.Expressions.Count; index++) @@ -1418,35 +1668,49 @@ namespace System.Management.Automation.Interpreter { Type elementType = node.Type.GetElementType(); int rank = node.Expressions.Count; - if (node.NodeType == ExpressionType.NewArrayInit) { + if (node.NodeType == ExpressionType.NewArrayInit) + { _instructions.EmitNewArrayInit(elementType, rank); - } else if (node.NodeType == ExpressionType.NewArrayBounds) { - if (rank == 1) { + } + else if (node.NodeType == ExpressionType.NewArrayBounds) + { + if (rank == 1) + { _instructions.EmitNewArray(elementType); - } else { + } + else + { _instructions.EmitNewArrayBounds(elementType, rank); } - } else { + } + else + { throw new System.NotImplementedException(); } } - private void CompileExtensionExpression(Expression expr) { + private void CompileExtensionExpression(Expression expr) + { var instructionProvider = expr as IInstructionProvider; - if (instructionProvider != null) { + if (instructionProvider != null) + { instructionProvider.AddInstructions(this); return; } - if (expr.CanReduce) { + if (expr.CanReduce) + { Compile(expr.Reduce()); - } else { + } + else + { throw new System.NotImplementedException(); } } - private void CompileDebugInfoExpression(Expression expr) { + private void CompileDebugInfoExpression(Expression expr) + { var node = (DebugInfoExpression)expr; int start = _instructions.Count; var info = new DebugInfo() @@ -1460,7 +1724,8 @@ namespace System.Management.Automation.Interpreter { _debugInfos.Add(info); } - private void CompileRuntimeVariablesExpression(Expression expr) { + private void CompileRuntimeVariablesExpression(Expression expr) + { // Generates IRuntimeVariables for all requested variables var node = (RuntimeVariablesExpression)expr; for (int index = 0; index < node.Variables.Count; index++) @@ -1474,27 +1739,36 @@ namespace System.Management.Automation.Interpreter { } - private void CompileLambdaExpression(Expression expr) { + private void CompileLambdaExpression(Expression expr) + { var node = (LambdaExpression)expr; var compiler = new LightCompiler(this); var creator = compiler.CompileTop(node); - if (compiler._locals.ClosureVariables != null) { - foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) { + if (compiler._locals.ClosureVariables != null) + { + foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) + { CompileGetBoxedVariable(variable); } } _instructions.EmitCreateDelegate(creator); } - private void CompileCoalesceBinaryExpression(Expression expr) { + private void CompileCoalesceBinaryExpression(Expression expr) + { var node = (BinaryExpression)expr; - if (TypeUtils.IsNullableType(node.Left.Type)) { + if (TypeUtils.IsNullableType(node.Left.Type)) + { throw new NotImplementedException(); - } else if (node.Conversion != null) { + } + else if (node.Conversion != null) + { throw new NotImplementedException(); - } else { + } + else + { var leftNotNull = _instructions.MakeLabel(); Compile(node.Left); _instructions.EmitCoalescingBranch(leftNotNull); @@ -1504,11 +1778,13 @@ namespace System.Management.Automation.Interpreter { } } - private void CompileInvocationExpression(Expression expr) { + private void CompileInvocationExpression(Expression expr) + { var node = (InvocationExpression)expr; // TODO: LambdaOperand optimization (see compiler) - if (typeof(LambdaExpression).IsAssignableFrom(node.Expression.Type)) { + if (typeof(LambdaExpression).IsAssignableFrom(node.Expression.Type)) + { throw new System.NotImplementedException(); } @@ -1526,32 +1802,37 @@ namespace System.Management.Automation.Interpreter { // ) // ); //} else { - CompileMethodCallExpression(Expression.Call(node.Expression, node.Expression.Type.GetMethod("Invoke"), node.Arguments)); + CompileMethodCallExpression(Expression.Call(node.Expression, node.Expression.Type.GetMethod("Invoke"), node.Arguments)); //} } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] - private void CompileListInitExpression(Expression expr) { + private void CompileListInitExpression(Expression expr) + { throw new System.NotImplementedException(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] - private void CompileMemberInitExpression(Expression expr) { + private void CompileMemberInitExpression(Expression expr) + { throw new System.NotImplementedException(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] - private void CompileQuoteUnaryExpression(Expression expr) { + private void CompileQuoteUnaryExpression(Expression expr) + { throw new System.NotImplementedException(); } - private void CompileUnboxUnaryExpression(Expression expr) { + private void CompileUnboxUnaryExpression(Expression expr) + { var node = (UnaryExpression)expr; // unboxing is a nop: Compile(node.Operand); } - private void CompileTypeEqualExpression(Expression expr) { + private void CompileTypeEqualExpression(Expression expr) + { Debug.Assert(expr.NodeType == ExpressionType.TypeEqual); var node = (TypeBinaryExpression)expr; @@ -1560,43 +1841,55 @@ namespace System.Management.Automation.Interpreter { _instructions.EmitTypeEquals(); } - private void CompileTypeAsExpression(UnaryExpression node) { + private void CompileTypeAsExpression(UnaryExpression node) + { Compile(node.Operand); _instructions.EmitTypeAs(node.Type); } - private void CompileTypeIsExpression(Expression expr) { + private void CompileTypeIsExpression(Expression expr) + { Debug.Assert(expr.NodeType == ExpressionType.TypeIs); var node = (TypeBinaryExpression)expr; Compile(node.Expression); // use TypeEqual for sealed types: - if (node.TypeOperand.GetTypeInfo().IsSealed) { + if (node.TypeOperand.GetTypeInfo().IsSealed) + { _instructions.EmitLoad(node.TypeOperand); _instructions.EmitTypeEquals(); - } else { + } + else + { _instructions.EmitTypeIs(node.TypeOperand); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] - private void CompileReducibleExpression(Expression expr) { + private void CompileReducibleExpression(Expression expr) + { throw new System.NotImplementedException(); } - internal void Compile(Expression expr, bool asVoid) { - if (asVoid) { + internal void Compile(Expression expr, bool asVoid) + { + if (asVoid) + { CompileAsVoid(expr); - } else { + } + else + { Compile(expr); } } - internal void CompileAsVoid(Expression expr) { + internal void CompileAsVoid(Expression expr) + { bool pushLabelBlock = TryPushLabelBlock(expr); int startingStackDepth = _instructions.CurrentStackDepth; - switch (expr.NodeType) { + switch (expr.NodeType) + { case ExpressionType.Assign: CompileAssignBinaryExpression(expr, true); break; @@ -1617,21 +1910,25 @@ namespace System.Management.Automation.Interpreter { default: CompileNoLabelPush(expr); - if (expr.Type != typeof(void)) { + if (expr.Type != typeof(void)) + { _instructions.EmitPop(); } break; } Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth); - if (pushLabelBlock) { + if (pushLabelBlock) + { PopLabelBlock(_labelBlock.Kind); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - private void CompileNoLabelPush(Expression expr) { + private void CompileNoLabelPush(Expression expr) + { int startingStackDepth = _instructions.CurrentStackDepth; - switch (expr.NodeType) { + switch (expr.NodeType) + { case ExpressionType.Add: CompileBinaryExpression(expr); break; case ExpressionType.AddChecked: CompileBinaryExpression(expr); break; case ExpressionType.And: CompileBinaryExpression(expr); break; @@ -1723,13 +2020,14 @@ namespace System.Management.Automation.Interpreter { Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth + (expr.Type == typeof(void) ? 0 : 1)); } - public void Compile(Expression expr) { + public void Compile(Expression expr) + { bool pushLabelBlock = TryPushLabelBlock(expr); CompileNoLabelPush(expr); - if (pushLabelBlock) { + if (pushLabelBlock) + { PopLabelBlock(_labelBlock.Kind); } } - } } diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index ac2745fa4..12daf7f9b 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -24,13 +24,14 @@ using System.Runtime.CompilerServices; using System.Threading; //using Microsoft.Scripting.Generation; -namespace System.Management.Automation.Interpreter { - +namespace System.Management.Automation.Interpreter +{ /// /// Manages creation of interpreted delegates. These delegates will get /// compiled if they are executed often enough. /// - internal sealed class LightDelegateCreator { + internal sealed class LightDelegateCreator + { // null if we are forced to compile private readonly Interpreter _interpreter; private readonly Expression _lambda; @@ -40,7 +41,8 @@ namespace System.Management.Automation.Interpreter { private Delegate _compiled; private readonly object _compileLock = new object(); - internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda) { + internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda) + { Assert.NotNull(lambda); _interpreter = interpreter; _lambda = lambda; @@ -52,15 +54,18 @@ namespace System.Management.Automation.Interpreter { // _lambda = lambda; //} - internal Interpreter Interpreter { + internal Interpreter Interpreter + { get { return _interpreter; } } - private bool HasClosure { + private bool HasClosure + { get { return _interpreter != null && _interpreter.ClosureSize > 0; } } - internal bool HasCompiled { + internal bool HasCompiled + { get { return _compiled != null; } } @@ -68,16 +73,20 @@ namespace System.Management.Automation.Interpreter { /// true if the compiled delegate has the same type as the lambda; /// false if the type was changed for interpretation. /// - internal bool SameDelegateType { + internal bool SameDelegateType + { get { return _compiledDelegateType == DelegateType; } } - public Delegate CreateDelegate() { + public Delegate CreateDelegate() + { return CreateDelegate(null); } - internal Delegate CreateDelegate(StrongBox[] closure) { - if (_compiled != null) { + internal Delegate CreateDelegate(StrongBox[] closure) + { + if (_compiled != null) + { // If the delegate type we want is not a Func/Action, we can't // use the compiled code directly. So instead just fall through // and create an interpreted LightLambda, which will pick up @@ -86,12 +95,14 @@ namespace System.Management.Automation.Interpreter { // Ideally, we would just rebind the compiled delegate using // Delegate.CreateDelegate. Unfortunately, it doesn't work on // dynamic methods. - if (SameDelegateType) { + if (SameDelegateType) + { return CreateCompiledDelegate(closure); } } - if (_interpreter == null) { + if (_interpreter == null) + { // We can't interpret, so force a compile Compile(null); Delegate compiled = CreateCompiledDelegate(closure); @@ -103,10 +114,13 @@ namespace System.Management.Automation.Interpreter { return new LightLambda(this, closure, _interpreter._compilationThreshold).MakeDelegate(DelegateType); } - private Type DelegateType { - get { + private Type DelegateType + { + get + { LambdaExpression le = _lambda as LambdaExpression; - if (le != null) { + if (le != null) + { return le.Type; } return null; @@ -117,10 +131,12 @@ namespace System.Management.Automation.Interpreter { /// /// Used by LightLambda to get the compiled delegate. /// - internal Delegate CreateCompiledDelegate(StrongBox[] closure) { + internal Delegate CreateCompiledDelegate(StrongBox[] closure) + { Debug.Assert(HasClosure == (closure != null)); - if (HasClosure) { + if (HasClosure) + { // We need to apply the closure to get the actual delegate. var applyClosure = (Func[], Delegate>)_compiled; return applyClosure(closure); @@ -133,38 +149,47 @@ namespace System.Management.Automation.Interpreter { /// future calls to Run will execute the compiled code instead of /// interpreting. /// - internal void Compile(object state) { - if (_compiled != null) { + internal void Compile(object state) + { + if (_compiled != null) + { return; } // Compilation is expensive, we only want to do it once. - lock (_compileLock) { - if (_compiled != null) { + lock (_compileLock) + { + if (_compiled != null) + { return; } //PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted lambda compiled"); - + // Interpreter needs a standard delegate type. // So change the lambda's delegate type to Func<...> or // Action<...> so it can be called from the LightLambda.Run // methods. LambdaExpression lambda = (_lambda as LambdaExpression);// ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce(); - if (_interpreter != null) { + if (_interpreter != null) + { _compiledDelegateType = GetFuncOrAction(lambda); lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters); } - if (HasClosure) { + if (HasClosure) + { _compiled = LightLambdaClosureVisitor.BindLambda(lambda, _interpreter.ClosureVariables); - } else { + } + else + { _compiled = lambda.Compile(); } } } - private static Type GetFuncOrAction(LambdaExpression lambda) { + private static Type GetFuncOrAction(LambdaExpression lambda) + { Type delegateType; bool isVoid = lambda.ReturnType == typeof(void); @@ -172,18 +197,23 @@ namespace System.Management.Automation.Interpreter { // lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) { // return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type)); //} else { - Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); - if (isVoid) { - if (Expression.TryGetActionType(types, out delegateType)) { - return delegateType; - } - } else { - types = types.AddLast(lambda.ReturnType); - if (Expression.TryGetFuncType(types, out delegateType)) { - return delegateType; - } + Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); + if (isVoid) + { + if (Expression.TryGetActionType(types, out delegateType)) + { + return delegateType; } - return lambda.Type; + } + else + { + types = types.AddLast(lambda.ReturnType); + if (Expression.TryGetFuncType(types, out delegateType)) + { + return delegateType; + } + } + return lambda.Type; //} } } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambda.cs b/src/System.Management.Automation/engine/interpreter/LightLambda.cs index 4ed081c9f..ea2566e32 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambda.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambda.cs @@ -30,20 +30,23 @@ using System.Threading; using AstUtils = System.Management.Automation.Interpreter.Utils; -namespace System.Management.Automation.Interpreter { - - internal sealed class LightLambdaCompileEventArgs : EventArgs { +namespace System.Management.Automation.Interpreter +{ + internal sealed class LightLambdaCompileEventArgs : EventArgs + { public Delegate Compiled { get; private set; } - internal LightLambdaCompileEventArgs(Delegate compiled) { + internal LightLambdaCompileEventArgs(Delegate compiled) + { Compiled = compiled; } } - internal partial class LightLambda { + internal partial class LightLambda + { private readonly StrongBox[] _closure; private readonly Interpreter _interpreter; - private static readonly CacheDict> _runCache = new CacheDict>(100); + private static readonly CacheDict> s_runCache = new CacheDict>(100); // Adaptive compilation support private readonly LightDelegateCreator _delegateCreator; @@ -55,37 +58,46 @@ namespace System.Management.Automation.Interpreter { /// public event EventHandler Compile; - internal LightLambda(LightDelegateCreator delegateCreator, StrongBox[] closure, int compilationThreshold) { + internal LightLambda(LightDelegateCreator delegateCreator, StrongBox[] closure, int compilationThreshold) + { _delegateCreator = delegateCreator; _closure = closure; _interpreter = delegateCreator.Interpreter; _compilationThreshold = compilationThreshold; } - private static Func GetRunDelegateCtor(Type delegateType) { - lock (_runCache) { + private static Func GetRunDelegateCtor(Type delegateType) + { + lock (s_runCache) + { Func fastCtor; - if (_runCache.TryGetValue(delegateType, out fastCtor)) { + if (s_runCache.TryGetValue(delegateType, out fastCtor)) + { return fastCtor; } return MakeRunDelegateCtor(delegateType); } } - private static Func MakeRunDelegateCtor(Type delegateType) { + private static Func MakeRunDelegateCtor(Type delegateType) + { var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); Type[] paramTypes; string name = "Run"; - if (paramInfos.Length >= MaxParameters) { + if (paramInfos.Length >= MaxParameters) + { return null; } - if (method.ReturnType == typeof(void)) { + if (method.ReturnType == typeof(void)) + { name += "Void"; paramTypes = new Type[paramInfos.Length]; - } else { + } + else + { paramTypes = new Type[paramInfos.Length + 1]; paramTypes[paramTypes.Length - 1] = method.ReturnType; } @@ -93,57 +105,70 @@ namespace System.Management.Automation.Interpreter { MethodInfo runMethod; if (method.ReturnType == typeof(void) && paramTypes.Length == 2 && - paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) { + paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) + { runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance); paramTypes[0] = paramInfos[0].ParameterType.GetElementType(); paramTypes[1] = paramInfos[1].ParameterType.GetElementType(); - } else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) { + } + else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) + { runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance); - } else { - for (int i = 0; i < paramInfos.Length; i++) { + } + else + { + for (int i = 0; i < paramInfos.Length; i++) + { paramTypes[i] = paramInfos[i].ParameterType; - if (paramTypes[i].IsByRef) { + if (paramTypes[i].IsByRef) + { return null; } } - if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) { + if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) + { name = "Make" + name + paramInfos.Length; - + MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes); - return _runCache[delegateType] = (Func)ctorMethod.CreateDelegate(typeof(Func)); + return s_runCache[delegateType] = (Func)ctorMethod.CreateDelegate(typeof(Func)); } runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance); } #if !SILVERLIGHT - try { + try + { DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true); var ilgen = dm.GetILGenerator(); ilgen.Emit(OpCodes.Ldarg_0); ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod); ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) })); ilgen.Emit(OpCodes.Ret); - return _runCache[delegateType] = (Func)dm.CreateDelegate(typeof(Func)); - } catch (SecurityException) { + return s_runCache[delegateType] = (Func)dm.CreateDelegate(typeof(Func)); + } + catch (SecurityException) + { } #endif // we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate. var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod; - return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda); + return s_runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda); } - + //TODO enable sharing of these custom delegates - private Delegate CreateCustomDelegate(Type delegateType) { + private Delegate CreateCustomDelegate(Type delegateType) + { //PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate"); var method = delegateType.GetMethod("Invoke"); var paramInfos = method.GetParameters(); var parameters = new ParameterExpression[paramInfos.Length]; var parametersAsObject = new Expression[paramInfos.Length]; - for (int i = 0; i < paramInfos.Length; i++) { + for (int i = 0; i < paramInfos.Length; i++) + { ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name); parameters[i] = parameter; parametersAsObject[i] = Expression.Convert(parameter, typeof(object)); @@ -157,23 +182,30 @@ namespace System.Management.Automation.Interpreter { return lambda.Compile(); } - internal Delegate MakeDelegate(Type delegateType) { + internal Delegate MakeDelegate(Type delegateType) + { Func fastCtor = GetRunDelegateCtor(delegateType); - if (fastCtor != null) { + if (fastCtor != null) + { return fastCtor(this); - } else { + } + else + { return CreateCustomDelegate(delegateType); } } - private bool TryGetCompiled() { + private bool TryGetCompiled() + { // Use the compiled delegate if available. - if (_delegateCreator.HasCompiled) { + if (_delegateCreator.HasCompiled) + { _compiled = _delegateCreator.CreateCompiledDelegate(_closure); // Send it to anyone who's interested. var compileEvent = Compile; - if (compileEvent != null && _delegateCreator.SameDelegateType) { + if (compileEvent != null && _delegateCreator.SameDelegateType) + { compileEvent(this, new LightLambdaCompileEventArgs(_compiled)); } @@ -191,17 +223,21 @@ namespace System.Management.Automation.Interpreter { // The second we explicitly guard against inside of Compile(). // // We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation. - if (unchecked(_compilationThreshold--) == 0) { + if (unchecked(_compilationThreshold--) == 0) + { #if SILVERLIGHT if (PlatformAdaptationLayer.IsCompactFramework) { _compilationThreshold = Int32.MaxValue; return false; } #endif - if (_interpreter.CompileSynchronously) { + if (_interpreter.CompileSynchronously) + { _delegateCreator.Compile(null); return TryGetCompiled(); - } else { + } + else + { // Kick off the compile on another thread so this one can keep going ThreadPool.QueueUserWorkItem(_delegateCreator.Compile, null); } @@ -210,11 +246,13 @@ namespace System.Management.Automation.Interpreter { return false; } - private InterpretedFrame MakeFrame() { + private InterpretedFrame MakeFrame() + { return new InterpretedFrame(_interpreter, _closure); } - internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) { + internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) + { //if (_compiled != null || TryGetCompiled()) { // ((ActionRef)_compiled)(ref arg0, ref arg1); // return; @@ -225,29 +263,38 @@ namespace System.Management.Automation.Interpreter { frame.Data[0] = arg0; frame.Data[1] = arg1; var currentFrame = frame.Enter(); - try { + try + { _interpreter.Run(frame); - } finally { + } + finally + { frame.Leave(currentFrame); arg0 = (T0)frame.Data[0]; arg1 = (T1)frame.Data[1]; } } - - public object Run(params object[] arguments) { - if (_compiled != null || TryGetCompiled()) { + + public object Run(params object[] arguments) + { + if (_compiled != null || TryGetCompiled()) + { return _compiled.DynamicInvoke(arguments); } var frame = MakeFrame(); - for (int i = 0; i < arguments.Length; i++) { + for (int i = 0; i < arguments.Length; i++) + { frame.Data[i] = arguments[i]; } var currentFrame = frame.Enter(); - try { + try + { _interpreter.Run(frame); - } finally { + } + finally + { frame.Leave(currentFrame); } return frame.Pop(); diff --git a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs index e34077728..3e38a495f 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs @@ -29,8 +29,8 @@ using AstUtils = System.Management.Automation.Interpreter.Utils; using Microsoft.PowerShell.CoreClr.Stubs; #endif -namespace System.Management.Automation.Interpreter { - +namespace System.Management.Automation.Interpreter +{ /// /// Visits a LambdaExpression, replacing the constants with direct accesses /// to their StrongBox fields. This is very similar to what @@ -39,7 +39,8 @@ namespace System.Management.Automation.Interpreter { /// Also inserts debug information tracking similar to what the interpreter /// would do. /// - internal sealed class LightLambdaClosureVisitor : ExpressionVisitor { + internal sealed class LightLambdaClosureVisitor : ExpressionVisitor + { /// /// Local variable mapping. /// @@ -58,7 +59,8 @@ namespace System.Management.Automation.Interpreter { /// private readonly Stack> _shadowedVars = new Stack>(); - private LightLambdaClosureVisitor(Dictionary closureVariables, ParameterExpression closureArray) { + private LightLambdaClosureVisitor(Dictionary closureVariables, ParameterExpression closureArray) + { Assert.NotNull(closureVariables, closureArray); _closureArray = closureArray; _closureVars = closureVariables; @@ -71,7 +73,8 @@ namespace System.Management.Automation.Interpreter { /// The lambda to bind. /// Variables which are being accessed defined in the outer scope. /// A delegate that can be called to produce a delegate bound to the passed in closure array. - internal static Func[], Delegate> BindLambda(LambdaExpression lambda, Dictionary closureVariables) { + internal static Func[], Delegate> BindLambda(LambdaExpression lambda, Dictionary closureVariables) + { // 1. Create rewriter var closure = Expression.Parameter(typeof(StrongBox[]), "closure"); var visitor = new LightLambdaClosureVisitor(closureVariables, closure); @@ -88,63 +91,79 @@ namespace System.Management.Automation.Interpreter { #region closures - protected override Expression VisitLambda(Expression node) { + protected override Expression VisitLambda(Expression node) + { _shadowedVars.Push(new HashSet(node.Parameters)); Expression b = Visit(node.Body); _shadowedVars.Pop(); - if (b == node.Body) { + if (b == node.Body) + { return node; } return Expression.Lambda(b, node.Name, node.TailCall, node.Parameters); } - protected override Expression VisitBlock(BlockExpression node) { - if (node.Variables.Count > 0) { + protected override Expression VisitBlock(BlockExpression node) + { + if (node.Variables.Count > 0) + { _shadowedVars.Push(new HashSet(node.Variables)); } var b = Visit(node.Expressions); - if (node.Variables.Count > 0) { + if (node.Variables.Count > 0) + { _shadowedVars.Pop(); } - if (b == node.Expressions) { + if (b == node.Expressions) + { return node; } return Expression.Block(node.Variables, b); } - protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable != null) { + protected override CatchBlock VisitCatchBlock(CatchBlock node) + { + if (node.Variable != null) + { _shadowedVars.Push(new HashSet(new[] { node.Variable })); } Expression b = Visit(node.Body); Expression f = Visit(node.Filter); - if (node.Variable != null) { + if (node.Variable != null) + { _shadowedVars.Pop(); } - if (b == node.Body && f == node.Filter) { + if (b == node.Body && f == node.Filter) + { return node; } return Expression.MakeCatchBlock(node.Test, node.Variable, b, f); } - protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { + protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) + { int count = node.Variables.Count; var boxes = new List(); var vars = new List(); var indexes = new int[count]; - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { Expression box = GetClosureItem(node.Variables[i], false); - if (box == null) { + if (box == null) + { indexes[i] = vars.Count; vars.Add(node.Variables[i]); - } else { + } + else + { indexes[i] = -1 - boxes.Count; boxes.Add(box); } } // No variables were rewritten. Just return the original node. - if (boxes.Count == 0) { + if (boxes.Count == 0) + { return node; } @@ -152,7 +171,8 @@ namespace System.Management.Automation.Interpreter { // All of them were rewritten. Just return the array, wrapped in a // read-only collection. - if (vars.Count == 0) { + if (vars.Count == 0) + { return Expression.Invoke( Expression.Constant((Func)RuntimeVariables.Create), boxesArray @@ -164,22 +184,26 @@ namespace System.Management.Automation.Interpreter { return Expression.Invoke(AstUtils.Constant(helper), Expression.RuntimeVariables(vars), boxesArray, AstUtils.Constant(indexes)); } - protected override Expression VisitParameter(ParameterExpression node) { + protected override Expression VisitParameter(ParameterExpression node) + { Expression closureItem = GetClosureItem(node, true); - if (closureItem == null) { + if (closureItem == null) + { return node; } // Convert can go away if we switch to strongly typed StrongBox return AstUtils.Convert(closureItem, node.Type); } - protected override Expression VisitBinary(BinaryExpression node) { + protected override Expression VisitBinary(BinaryExpression node) + { if (node.NodeType == ExpressionType.Assign && - node.Left.NodeType == ExpressionType.Parameter) { - + node.Left.NodeType == ExpressionType.Parameter) + { var variable = (ParameterExpression)node.Left; Expression closureItem = GetClosureItem(variable, true); - if (closureItem != null) { + if (closureItem != null) + { // We need to convert to object to store the value in the box. return Expression.Block( new[] { variable }, @@ -192,16 +216,20 @@ namespace System.Management.Automation.Interpreter { return base.VisitBinary(node); } - private Expression GetClosureItem(ParameterExpression variable, bool unbox) { + private Expression GetClosureItem(ParameterExpression variable, bool unbox) + { // Skip variables that are shadowed by a nested scope/lambda - foreach (HashSet hidden in _shadowedVars) { - if (hidden.Contains(variable)) { + foreach (HashSet hidden in _shadowedVars) + { + if (hidden.Contains(variable)) + { return null; } } LocalVariable loc; - if (!_closureVars.TryGetValue(variable, out loc)) { + if (!_closureVars.TryGetValue(variable, out loc)) + { throw new InvalidOperationException("unbound variable: " + variable.Name); } @@ -209,7 +237,8 @@ namespace System.Management.Automation.Interpreter { return (unbox) ? LightCompiler.Unbox(result) : result; } - protected override Expression VisitExtension(Expression node) { + protected override Expression VisitExtension(Expression node) + { // Reduce extensions now so we can find embedded variables return Visit(node.ReduceExtensions()); } @@ -220,7 +249,8 @@ namespace System.Management.Automation.Interpreter { /// /// Provides a list of variables, supporing read/write of the values /// - private sealed class MergedRuntimeVariables : IRuntimeVariables { + private sealed class MergedRuntimeVariables : IRuntimeVariables + { private readonly IRuntimeVariables _first; private readonly IRuntimeVariables _second; @@ -228,30 +258,39 @@ namespace System.Management.Automation.Interpreter { // Positive values mean the first array, negative means the second private readonly int[] _indexes; - private MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) { + private MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) + { _first = first; _second = second; _indexes = indexes; } - internal static IRuntimeVariables Create(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) { + internal static IRuntimeVariables Create(IRuntimeVariables first, IRuntimeVariables second, int[] indexes) + { return new MergedRuntimeVariables(first, second, indexes); } - int IRuntimeVariables.Count { + int IRuntimeVariables.Count + { get { return _indexes.Length; } } - object IRuntimeVariables.this[int index] { - get { + object IRuntimeVariables.this[int index] + { + get + { index = _indexes[index]; return (index >= 0) ? _first[index] : _second[-1 - index]; } - set { + set + { index = _indexes[index]; - if (index >= 0) { + if (index >= 0) + { _first[index] = value; - } else { + } + else + { _second[-1 - index] = value; } } diff --git a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs index a7232229a..be8b89766 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs @@ -24,81 +24,99 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Collections.Generic; -namespace System.Management.Automation.Interpreter { - internal interface IBoxableInstruction { +namespace System.Management.Automation.Interpreter +{ + internal interface IBoxableInstruction + { Instruction BoxIfIndexMatches(int index); } - internal abstract class LocalAccessInstruction : Instruction { + internal abstract class LocalAccessInstruction : Instruction + { internal readonly int _index; - protected LocalAccessInstruction(int index) { + protected LocalAccessInstruction(int index) + { _index = index; } - public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { - return cookie == null ? - InstructionName + "(" + _index + ")" : + public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) + { + return cookie == null ? + InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } } #region Load - internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction { + internal sealed class LoadLocalInstruction : LocalAccessInstruction, IBoxableInstruction + { internal LoadLocalInstruction(int index) - : base(index) { + : base(index) + { } public override int ProducedStack { get { return 1; } } - - public override int Run(InterpretedFrame frame) { + + public override int Run(InterpretedFrame frame) + { frame.Data[frame.StackIndex++] = frame.Data[_index]; //frame.Push(frame.Data[_index]); return +1; } - - public Instruction BoxIfIndexMatches(int index) { + + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? InstructionList.LoadLocalBoxed(index) : null; } } - internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction { + internal sealed class LoadLocalBoxedInstruction : LocalAccessInstruction + { internal LoadLocalBoxedInstruction(int index) - : base(index) { + : base(index) + { } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = (StrongBox)frame.Data[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } - internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction { + internal sealed class LoadLocalFromClosureInstruction : LocalAccessInstruction + { internal LoadLocalFromClosureInstruction(int index) - : base(index) { + : base(index) + { } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box.Value; return +1; } } - internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction { + internal sealed class LoadLocalFromClosureBoxedInstruction : LocalAccessInstruction + { internal LoadLocalFromClosureBoxedInstruction(int index) - : base(index) { + : base(index) + { } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = frame.Closure[_index]; frame.Data[frame.StackIndex++] = box; return +1; @@ -109,80 +127,97 @@ namespace System.Management.Automation.Interpreter { #region Store, Assign - internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction { + internal sealed class AssignLocalInstruction : LocalAccessInstruction, IBoxableInstruction + { internal AssignLocalInstruction(int index) - : base(index) { + : base(index) + { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = frame.Peek(); return +1; } - public Instruction BoxIfIndexMatches(int index) { + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? InstructionList.AssignLocalBoxed(index) : null; } } - internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction { + internal sealed class StoreLocalInstruction : LocalAccessInstruction, IBoxableInstruction + { internal StoreLocalInstruction(int index) - : base(index) { + : base(index) + { } public override int ConsumedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = frame.Data[--frame.StackIndex]; //frame.Data[_index] = frame.Pop(); return +1; } - public Instruction BoxIfIndexMatches(int index) { + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? InstructionList.StoreLocalBoxed(index) : null; } } - internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction { + internal sealed class AssignLocalBoxedInstruction : LocalAccessInstruction + { internal AssignLocalBoxedInstruction(int index) - : base(index) { + : base(index) + { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = (StrongBox)frame.Data[_index]; box.Value = frame.Peek(); return +1; } } - internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction { + internal sealed class StoreLocalBoxedInstruction : LocalAccessInstruction + { internal StoreLocalBoxedInstruction(int index) - : base(index) { + : base(index) + { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = (StrongBox)frame.Data[_index]; box.Value = frame.Data[--frame.StackIndex]; return +1; } } - internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction { + internal sealed class AssignLocalToClosureInstruction : LocalAccessInstruction + { internal AssignLocalToClosureInstruction(int index) - : base(index) { + : base(index) + { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var box = frame.Closure[_index]; box.Value = frame.Peek(); return +1; @@ -194,117 +229,147 @@ namespace System.Management.Automation.Interpreter { #region Initialize [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors")] - internal abstract class InitializeLocalInstruction : LocalAccessInstruction { + internal abstract class InitializeLocalInstruction : LocalAccessInstruction + { internal InitializeLocalInstruction(int index) - : base(index) { + : base(index) + { } - internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction { + internal sealed class Reference : InitializeLocalInstruction, IBoxableInstruction + { internal Reference(int index) - : base(index) { + : base(index) + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = null; return 1; } - public Instruction BoxIfIndexMatches(int index) { + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? InstructionList.InitImmutableRefBox(index) : null; } - public override string InstructionName { + public override string InstructionName + { get { return "InitRef"; } } } - internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction { + internal sealed class ImmutableValue : InitializeLocalInstruction, IBoxableInstruction + { private readonly object _defaultValue; internal ImmutableValue(int index, object defaultValue) - : base(index) { + : base(index) + { _defaultValue = defaultValue; } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = _defaultValue; return 1; } - public Instruction BoxIfIndexMatches(int index) { + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? new ImmutableBox(index, _defaultValue) : null; } - public override string InstructionName { + public override string InstructionName + { get { return "InitImmutableValue"; } } } - internal sealed class ImmutableBox : InitializeLocalInstruction { + internal sealed class ImmutableBox : InitializeLocalInstruction + { // immutable value: private readonly object _defaultValue; internal ImmutableBox(int index, object defaultValue) - : base(index) { + : base(index) + { _defaultValue = defaultValue; } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = new StrongBox(_defaultValue); return 1; } - public override string InstructionName { + public override string InstructionName + { get { return "InitImmutableBox"; } } } - internal sealed class ParameterBox : InitializeLocalInstruction { + internal sealed class ParameterBox : InitializeLocalInstruction + { public ParameterBox(int index) - : base(index) { + : base(index) + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = new StrongBox(frame.Data[_index]); return 1; } - } - internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction { + internal sealed class Parameter : InitializeLocalInstruction, IBoxableInstruction + { internal Parameter(int index) - : base(index) { + : base(index) + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // nop return 1; } - public Instruction BoxIfIndexMatches(int index) { - if (index == _index) { + public Instruction BoxIfIndexMatches(int index) + { + if (index == _index) + { return InstructionList.ParameterBox(index); } return null; } - public override string InstructionName { + public override string InstructionName + { get { return "InitParameter"; } } } - internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction { + internal sealed class MutableValue : InitializeLocalInstruction, IBoxableInstruction + { private readonly Type _type; internal MutableValue(int index, Type type) - : base(index) { + : base(index) + { _type = type; } - public override int Run(InterpretedFrame frame) { - try { + public override int Run(InterpretedFrame frame) + { + try + { frame.Data[_index] = Activator.CreateInstance(_type); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } @@ -312,29 +377,35 @@ namespace System.Management.Automation.Interpreter { return 1; } - public Instruction BoxIfIndexMatches(int index) { + public Instruction BoxIfIndexMatches(int index) + { return (index == _index) ? new MutableBox(index, _type) : null; } - public override string InstructionName { + public override string InstructionName + { get { return "InitMutableValue"; } } } - internal sealed class MutableBox : InitializeLocalInstruction { + internal sealed class MutableBox : InitializeLocalInstruction + { private readonly Type _type; internal MutableBox(int index, Type type) - : base(index) { + : base(index) + { _type = type; } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[_index] = new StrongBox(Activator.CreateInstance(_type)); return 1; } - public override string InstructionName { + public override string InstructionName + { get { return "InitMutableBox"; } } } @@ -344,26 +415,31 @@ namespace System.Management.Automation.Interpreter { #region RuntimeVariables - internal sealed class RuntimeVariablesInstruction : Instruction { + internal sealed class RuntimeVariablesInstruction : Instruction + { private readonly int _count; - public RuntimeVariablesInstruction(int count) { + public RuntimeVariablesInstruction(int count) + { _count = count; } public override int ProducedStack { get { return 1; } } public override int ConsumedStack { get { return _count; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { var ret = new IStrongBox[_count]; - for (int i = ret.Length - 1; i >= 0; i--) { + for (int i = ret.Length - 1; i >= 0; i--) + { ret[i] = (IStrongBox)frame.Pop(); } frame.Push(RuntimeVariables.Create(ret)); return +1; } - public override string ToString() { + public override string ToString() + { return "GetRuntimeVariables()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index 8e313748a..c18e39d7d 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -25,71 +25,91 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal sealed class LocalVariable { +namespace System.Management.Automation.Interpreter +{ + internal sealed class LocalVariable + { private const int IsBoxedFlag = 1; private const int InClosureFlag = 2; public readonly int Index; private int _flags; - public bool IsBoxed { + public bool IsBoxed + { get { return (_flags & IsBoxedFlag) != 0; } - set { - if (value) { + set + { + if (value) + { _flags |= IsBoxedFlag; - } else { + } + else + { _flags &= ~IsBoxedFlag; } } } - public bool InClosure { + public bool InClosure + { get { return (_flags & InClosureFlag) != 0; } } - public bool InClosureOrBoxed { + public bool InClosureOrBoxed + { get { return InClosure | IsBoxed; } } - internal LocalVariable(int index, bool closure, bool boxed) { + internal LocalVariable(int index, bool closure, bool boxed) + { Index = index; _flags = (closure ? InClosureFlag : 0) | (boxed ? IsBoxedFlag : 0); } - internal Expression LoadFromArray(Expression frameData, Expression closure) { + internal Expression LoadFromArray(Expression frameData, Expression closure) + { Expression result = Expression.ArrayAccess(InClosure ? closure : frameData, Expression.Constant(Index)); return IsBoxed ? Expression.Convert(result, typeof(StrongBox)) : result; } - public override string ToString() { + public override string ToString() + { return String.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null); } } - internal struct LocalDefinition { + internal struct LocalDefinition + { private readonly int _index; private readonly ParameterExpression _parameter; - internal LocalDefinition(int localIndex, ParameterExpression parameter) { + internal LocalDefinition(int localIndex, ParameterExpression parameter) + { _index = localIndex; _parameter = parameter; } - public int Index { - get { + public int Index + { + get + { return _index; } } - public ParameterExpression Parameter { - get { + public ParameterExpression Parameter + { + get + { return _parameter; } } - public override bool Equals(object obj) { - if (obj is LocalDefinition) { + public override bool Equals(object obj) + { + if (obj is LocalDefinition) + { LocalDefinition other = (LocalDefinition)obj; return other.Index == Index && other.Parameter == Parameter; } @@ -97,32 +117,39 @@ namespace System.Management.Automation.Interpreter { return false; } - public override int GetHashCode() { - if (_parameter == null) { + public override int GetHashCode() + { + if (_parameter == null) + { return 0; } return _parameter.GetHashCode() ^ _index.GetHashCode(); } - public static bool operator ==(LocalDefinition self, LocalDefinition other) { + public static bool operator ==(LocalDefinition self, LocalDefinition other) + { return self.Index == other.Index && self.Parameter == other.Parameter; } - public static bool operator !=(LocalDefinition self, LocalDefinition other) { + public static bool operator !=(LocalDefinition self, LocalDefinition other) + { return self.Index != other.Index || self.Parameter != other.Parameter; } } - internal sealed class LocalVariables { + internal sealed class LocalVariables + { private readonly HybridReferenceDictionary _variables = new HybridReferenceDictionary(); private Dictionary _closureVariables; private int _localCount, _maxLocalCount; - internal LocalVariables() { + internal LocalVariables() + { } - public LocalDefinition DefineLocal(ParameterExpression variable, int start) { + public LocalDefinition DefineLocal(ParameterExpression variable, int start) + { //ContractUtils.RequiresNotNull(variable, "variable"); //ContractUtils.Requires(start >= 0, "start", "start must be positive"); @@ -130,13 +157,17 @@ namespace System.Management.Automation.Interpreter { _maxLocalCount = System.Math.Max(_localCount, _maxLocalCount); VariableScope existing, newScope; - if (_variables.TryGetValue(variable, out existing)) { + if (_variables.TryGetValue(variable, out existing)) + { newScope = new VariableScope(result, start, existing); - if (existing.ChildScopes == null) { + if (existing.ChildScopes == null) + { existing.ChildScopes = new List(); } existing.ChildScopes.Add(newScope); - } else { + } + else + { newScope = new VariableScope(result, start, null); } @@ -144,28 +175,35 @@ namespace System.Management.Automation.Interpreter { return new LocalDefinition(result.Index, variable); } - public void UndefineLocal(LocalDefinition definition, int end) { + public void UndefineLocal(LocalDefinition definition, int end) + { var scope = _variables[definition.Parameter]; scope.Stop = end; - if (scope.Parent != null) { + if (scope.Parent != null) + { _variables[definition.Parameter] = scope.Parent; - } else { + } + else + { _variables.Remove(definition.Parameter); } - + _localCount--; } - internal void Box(ParameterExpression variable, InstructionList instructions) { + internal void Box(ParameterExpression variable, InstructionList instructions) + { var scope = _variables[variable]; LocalVariable local = scope.Variable; Debug.Assert(!local.IsBoxed && !local.InClosure); _variables[variable].Variable.IsBoxed = true; - + int curChild = 0; - for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) { - if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) { + for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) + { + if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) + { // skip boxing in the child scope var child = scope.ChildScopes[curChild]; i = child.Stop; @@ -178,30 +216,37 @@ namespace System.Management.Automation.Interpreter { } } - public int LocalCount { + public int LocalCount + { get { return _maxLocalCount; } } - public int GetOrDefineLocal(ParameterExpression var) { + public int GetOrDefineLocal(ParameterExpression var) + { int index = GetLocalIndex(var); - if (index == -1) { + if (index == -1) + { return DefineLocal(var, 0).Index; } return index; } - public int GetLocalIndex(ParameterExpression var) { + public int GetLocalIndex(ParameterExpression var) + { VariableScope loc; return _variables.TryGetValue(var, out loc) ? loc.Variable.Index : -1; } - public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable local) { + public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable local) + { VariableScope scope; - if (_variables.TryGetValue(var, out scope)) { + if (_variables.TryGetValue(var, out scope)) + { local = scope.Variable; return true; } - if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) { + if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) + { return true; } @@ -213,9 +258,11 @@ namespace System.Management.Automation.Interpreter { /// Gets a copy of the local variables which are defined in the current scope. /// /// - internal Dictionary CopyLocals() { + internal Dictionary CopyLocals() + { var res = new Dictionary(_variables.Count); - foreach (var keyValue in _variables) { + foreach (var keyValue in _variables) + { res[keyValue.Key] = keyValue.Value.Variable; } return res; @@ -224,21 +271,26 @@ namespace System.Management.Automation.Interpreter { /// /// Checks to see if the given variable is defined within the current local scope. /// - internal bool ContainsVariable(ParameterExpression variable) { + internal bool ContainsVariable(ParameterExpression variable) + { return _variables.ContainsKey(variable); } /// /// Gets the variables which are defined in an outer scope and available within the current scope. /// - internal Dictionary ClosureVariables { - get { + internal Dictionary ClosureVariables + { + get + { return _closureVariables; } } - - internal LocalVariable AddClosureVariable(ParameterExpression variable) { - if (_closureVariables == null) { + + internal LocalVariable AddClosureVariable(ParameterExpression variable) + { + if (_closureVariables == null) + { _closureVariables = new Dictionary(); } LocalVariable result = new LocalVariable(_closureVariables.Count, true, false); @@ -249,14 +301,16 @@ namespace System.Management.Automation.Interpreter { /// /// Tracks where a variable is defined and what range of instructions it's used in /// - private sealed class VariableScope { + private sealed class VariableScope + { public readonly int Start; public int Stop = Int32.MaxValue; public readonly LocalVariable Variable; public readonly VariableScope Parent; public List ChildScopes; - public VariableScope(LocalVariable variable, int start, VariableScope parent) { + public VariableScope(LocalVariable variable, int start, VariableScope parent) + { Variable = variable; Start = start; Parent = parent; diff --git a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs index afb255e2c..811b7889d 100644 --- a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs @@ -23,24 +23,29 @@ using System.Diagnostics; using System.Management.Automation.Language; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { +namespace System.Management.Automation.Interpreter +{ using AstUtils = System.Management.Automation.Interpreter.Utils; using LoopFunc = Func[], InterpretedFrame, int>; using System.Collections.ObjectModel; - internal sealed class LoopCompiler : ExpressionVisitor { - private struct LoopVariable { + internal sealed class LoopCompiler : ExpressionVisitor + { + private struct LoopVariable + { public ExpressionAccess Access; // a variable that holds on the strong box for closure variables: public ParameterExpression BoxStorage; - public LoopVariable(ExpressionAccess access, ParameterExpression box) { + public LoopVariable(ExpressionAccess access, ParameterExpression box) + { Access = access; BoxStorage = box; } - public override string ToString() { + public override string ToString() + { return Access.ToString() + " " + BoxStorage; } } @@ -82,30 +87,37 @@ namespace System.Management.Automation.Interpreter { _loopEndInstructionIndex = loopEndInstructionIndex; } - internal LoopFunc CreateDelegate() { + internal LoopFunc CreateDelegate() + { var loop = Visit(_loop); var body = new List(); var finallyClause = new List(); - foreach (var variable in _loopVariables) { + foreach (var variable in _loopVariables) + { LocalVariable local; - if (!_outerVariables.TryGetValue(variable.Key, out local)) { + if (!_outerVariables.TryGetValue(variable.Key, out local)) + { local = _closureVariables[variable.Key]; } Expression elemRef = local.LoadFromArray(_frameDataVar, _frameClosureVar); - if (local.InClosureOrBoxed) { + if (local.InClosureOrBoxed) + { var box = variable.Value.BoxStorage; Debug.Assert(box != null); body.Add(Expression.Assign(box, elemRef)); AddTemp(box); - } else { + } + else + { // Always initialize the variable even if it is only written to. // If a write-only variable is actually not assigned during execution of the loop we will still write some value back. // This value must be the original value, which we assign at entry. body.Add(Expression.Assign(variable.Key, AstUtils.Convert(elemRef, variable.Key.Type))); - if ((variable.Value.Access & ExpressionAccess.Write) != 0) { + if ((variable.Value.Access & ExpressionAccess.Write) != 0) + { finallyClause.Add(Expression.Assign(elemRef, AstUtils.Box(variable.Key))); } @@ -113,9 +125,12 @@ namespace System.Management.Automation.Interpreter { } } - if (finallyClause.Count > 0) { + if (finallyClause.Count > 0) + { body.Add(Expression.TryFinally(loop, Expression.Block(finallyClause))); - } else { + } + else + { body.Add(loop); } @@ -128,10 +143,12 @@ namespace System.Management.Automation.Interpreter { return lambda.Compile(); } - protected override Expression VisitExtension(Expression node) { + protected override Expression VisitExtension(Expression node) + { // Reduce extensions before we visit them so that we operate on a plain DLR tree, // where we know relationships among the nodes (which nodes represent write context etc.). - if (node.CanReduce) { + if (node.CanReduce) + { return Visit(node.Reduce()); } @@ -140,25 +157,28 @@ namespace System.Management.Automation.Interpreter { #region Gotos - protected override Expression VisitGoto(GotoExpression node) { + protected override Expression VisitGoto(GotoExpression node) + { BranchLabel label; var target = node.Target; var value = Visit(node.Value); - + // TODO: Is it possible for an inner reducible node of the loop to rely on nodes produced by reducing outer reducible nodes? // Unknown label => must be within the loop: - if (!_labelMapping.TryGetValue(target, out label)) { + if (!_labelMapping.TryGetValue(target, out label)) + { return node.Update(target, value); } // Known label within the loop: - if (label.TargetIndex >= _loopStartInstructionIndex && label.TargetIndex < _loopEndInstructionIndex) { + if (label.TargetIndex >= _loopStartInstructionIndex && label.TargetIndex < _loopEndInstructionIndex) + { return node.Update(target, value); } - return Expression.Return(_returnLabel, + return Expression.Return(_returnLabel, (value != null && value.Type != typeof(void)) ? Expression.Call(_frameVar, InterpretedFrame.GotoMethod, Expression.Constant(label.LabelIndex), AstUtils.Box(value)) : Expression.Call(_frameVar, InterpretedFrame.VoidGotoMethod, Expression.Constant(label.LabelIndex)), @@ -175,73 +195,92 @@ namespace System.Management.Automation.Interpreter { // We will consider a variable as "read" if it is read anywhere in the loop even though // the first operation might actually always be "write". We could do better if we had CFG. - protected override Expression VisitBlock(BlockExpression node) { + protected override Expression VisitBlock(BlockExpression node) + { var variables = ((BlockExpression)node).Variables; var prevLocals = EnterVariableScope(variables); - + var res = base.VisitBlock(node); ExitVariableScope(prevLocals); return res; } - private HashSet EnterVariableScope(ICollection variables) { - if (_loopLocals == null) { + private HashSet EnterVariableScope(ICollection variables) + { + if (_loopLocals == null) + { _loopLocals = new HashSet(variables); return null; } - + var prevLocals = new HashSet(_loopLocals); _loopLocals.UnionWith(variables); return prevLocals; } - protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable != null) { + protected override CatchBlock VisitCatchBlock(CatchBlock node) + { + if (node.Variable != null) + { var prevLocals = EnterVariableScope(new[] { node.Variable }); var res = base.VisitCatchBlock(node); ExitVariableScope(prevLocals); return res; - } else { + } + else + { return base.VisitCatchBlock(node); } } - protected override Expression VisitLambda(Expression node) { + protected override Expression VisitLambda(Expression node) + { var prevLocals = EnterVariableScope(node.Parameters); - try { + try + { return base.VisitLambda(node); - } finally { + } + finally + { ExitVariableScope(prevLocals); } } - private void ExitVariableScope(HashSet prevLocals) { + private void ExitVariableScope(HashSet prevLocals) + { _loopLocals = prevLocals; } - protected override Expression VisitBinary(BinaryExpression node) { + protected override Expression VisitBinary(BinaryExpression node) + { // reduce compound assignments: - if (node.CanReduce) { + if (node.CanReduce) + { return Visit(node.Reduce()); } Debug.Assert(!node.NodeType.IsReadWriteAssignment()); var param = node.Left as ParameterExpression; - if (param != null && node.NodeType == ExpressionType.Assign) { + if (param != null && node.NodeType == ExpressionType.Assign) + { var left = VisitVariable(param, ExpressionAccess.Write); var right = Visit(node.Right); // left parameter is a boxed variable: - if (left.Type != param.Type) { + if (left.Type != param.Type) + { Debug.Assert(left.Type == typeof(object)); Expression rightVar; - if (right.NodeType != ExpressionType.Parameter) { + if (right.NodeType != ExpressionType.Parameter) + { // { left.Value = (object)(rightVar = right), rightVar } rightVar = AddTemp(Expression.Parameter(right.Type)); right = Expression.Assign(rightVar, right); - } else { + } + else + { // { left.Value = (object)right, right } rightVar = right; } @@ -250,18 +289,23 @@ namespace System.Management.Automation.Interpreter { node.Update(left, null, Expression.Convert(right, left.Type)), rightVar ); - } else { + } + else + { return node.Update(left, null, right); } - - } else { + } + else + { return base.VisitBinary(node); } } - protected override Expression VisitUnary(UnaryExpression node) { + protected override Expression VisitUnary(UnaryExpression node) + { // reduce inplace increment/decrement: - if (node.CanReduce) { + if (node.CanReduce) + { return Visit(node.Reduce()); } Debug.Assert(!node.NodeType.IsReadWriteAssignment()); @@ -271,50 +315,65 @@ namespace System.Management.Automation.Interpreter { // TODO: if we supported ref/out parameter we would need to override // MethodCallExpression, VisitDynamic and VisitNew - protected override Expression VisitParameter(ParameterExpression node) { + protected override Expression VisitParameter(ParameterExpression node) + { return VisitVariable(node, ExpressionAccess.Read); } - private Expression VisitVariable(ParameterExpression node, ExpressionAccess access) { + private Expression VisitVariable(ParameterExpression node, ExpressionAccess access) + { ParameterExpression box; LoopVariable existing; LocalVariable loc; - if (_loopLocals.Contains(node)) { + if (_loopLocals.Contains(node)) + { // local to the loop - not propagated in or out return node; - } else if (_loopVariables.TryGetValue(node, out existing)) { + } + else if (_loopVariables.TryGetValue(node, out existing)) + { // existing outer variable that we are already tracking box = existing.BoxStorage; _loopVariables[node] = new LoopVariable(existing.Access | access, box); - } else if (_outerVariables.TryGetValue(node, out loc) || - (_closureVariables != null && _closureVariables.TryGetValue(node, out loc))) { + } + else if (_outerVariables.TryGetValue(node, out loc) || + (_closureVariables != null && _closureVariables.TryGetValue(node, out loc))) + { // not tracking this variable yet, but defined in outer scope and seen for the 1st time box = loc.InClosureOrBoxed ? Expression.Parameter(typeof(StrongBox), node.Name) : null; _loopVariables[node] = new LoopVariable(access, box); - } else { + } + else + { // node is a variable defined in a nested lambda -> skip return node; } - if (box != null) { - if ((access & ExpressionAccess.Write) != 0) { + if (box != null) + { + if ((access & ExpressionAccess.Write) != 0) + { // compound assignments were reduced: Debug.Assert((access & ExpressionAccess.Read) == 0); // box.Value = (object)rhs return LightCompiler.Unbox(box); - } else { + } + else + { // (T)box.Value return Expression.Convert(LightCompiler.Unbox(box), node.Type); } } - + return node; } - private ParameterExpression AddTemp(ParameterExpression variable) { - if (_temps == null) { + private ParameterExpression AddTemp(ParameterExpression variable) + { + if (_temps == null) + { _temps = new List(); } diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 861b6552e..2a716a42b 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -17,18 +17,23 @@ using System; using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.Interpreter { - internal abstract class MulInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class MulInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private MulInstruction() { + private MulInstruction() + { } - internal sealed class MulInt32 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulInt32 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l * (Int32)r)); @@ -37,8 +42,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulInt16 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulInt16 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l * (Int16)r); @@ -47,8 +54,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulInt64 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulInt64 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l * (Int64)r); @@ -57,8 +66,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulUInt16 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulUInt16 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l * (UInt16)r); @@ -67,8 +78,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulUInt32 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulUInt32 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l * (UInt32)r); @@ -77,8 +90,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulUInt64 : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulUInt64 : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((Int16)l * (Int16)r); @@ -87,8 +102,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulSingle : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulSingle : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); @@ -97,8 +114,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulDouble : MulInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulDouble : MulInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; @@ -107,39 +126,46 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new MulInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new MulInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new MulInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new MulUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new MulUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new MulUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new MulSingle()); - case TypeCode.Double: return _Double ?? (_Double = new MulDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new MulSingle()); + case TypeCode.Double: return s_double ?? (s_double = new MulDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "Mul()"; } } - internal abstract class MulOvfInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; + internal abstract class MulOvfInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private MulOvfInstruction() { + private MulOvfInstruction() + { } - internal sealed class MulOvfInt32 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfInt32 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l * (Int32)r)); @@ -148,8 +174,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfInt16 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfInt16 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l * (Int16)r); @@ -158,8 +186,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfInt64 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfInt64 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l * (Int64)r); @@ -168,8 +198,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfUInt16 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfUInt16 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l * (UInt16)r); @@ -178,8 +210,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfUInt32 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfUInt32 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l * (UInt32)r); @@ -188,8 +222,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfUInt64 : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfUInt64 : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l * (Int16)r); @@ -198,8 +234,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfSingle : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfSingle : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r); @@ -208,8 +246,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class MulOvfDouble : MulOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class MulOvfDouble : MulOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r; @@ -218,24 +258,27 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new MulOvfInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new MulOvfInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new MulOvfInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new MulOvfUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new MulOvfUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new MulOvfUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new MulOvfSingle()); - case TypeCode.Double: return _Double ?? (_Double = new MulOvfDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle()); + case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "MulOvf()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index 01a06fabe..9e24c2220 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -19,132 +19,164 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal abstract class NotEqualInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal abstract class NotEqualInstruction : Instruction + { // Perf: EqualityComparer but is 3/2 to 2 times slower. - private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double; + private static Instruction s_reference,s_boolean,s_SByte,s_int16,s_char,s_int32,s_int64,s_byte,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private NotEqualInstruction() { + private NotEqualInstruction() + { } - internal sealed class NotEqualBoolean : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualBoolean : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Boolean)frame.Pop()) != ((Boolean)frame.Pop())); return +1; } } - internal sealed class NotEqualSByte : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualSByte : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((SByte)frame.Pop()) != ((SByte)frame.Pop())); return +1; } } - internal sealed class NotEqualInt16 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualInt16 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int16)frame.Pop()) != ((Int16)frame.Pop())); return +1; } } - internal sealed class NotEqualChar : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualChar : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Char)frame.Pop()) != ((Char)frame.Pop())); return +1; } } - internal sealed class NotEqualInt32 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualInt32 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int32)frame.Pop()) != ((Int32)frame.Pop())); return +1; } } - internal sealed class NotEqualInt64 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualInt64 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Int64)frame.Pop()) != ((Int64)frame.Pop())); return +1; } } - internal sealed class NotEqualByte : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualByte : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Byte)frame.Pop()) != ((Byte)frame.Pop())); return +1; } } - internal sealed class NotEqualUInt16 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualUInt16 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt16)frame.Pop()) != ((UInt16)frame.Pop())); return +1; } } - internal sealed class NotEqualUInt32 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualUInt32 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt32)frame.Pop()) != ((UInt32)frame.Pop())); return +1; } } - internal sealed class NotEqualUInt64 : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualUInt64 : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((UInt64)frame.Pop()) != ((UInt64)frame.Pop())); return +1; } } - internal sealed class NotEqualSingle : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualSingle : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Single)frame.Pop()) != ((Single)frame.Pop())); return +1; } } - internal sealed class NotEqualDouble : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualDouble : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(((Double)frame.Pop()) != ((Double)frame.Pop())); return +1; } } - internal sealed class NotEqualReference : NotEqualInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class NotEqualReference : NotEqualInstruction + { + public override int Run(InterpretedFrame frame) + { frame.Push(frame.Pop() != frame.Pop()); return +1; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { var typeInfo = type.GetTypeInfo(); // Boxed enums can be unboxed as their underlying types: var typeToUse = typeInfo.IsEnum ? Enum.GetUnderlyingType(type) : type; - switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return _Boolean ?? (_Boolean = new NotEqualBoolean()); - case TypeCode.SByte: return _SByte ?? (_SByte = new NotEqualSByte()); - case TypeCode.Byte: return _Byte ?? (_Byte = new NotEqualByte()); - case TypeCode.Char: return _Char ?? (_Char = new NotEqualChar()); - case TypeCode.Int16: return _Int16 ?? (_Int16 = new NotEqualInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new NotEqualInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new NotEqualInt64()); + switch (typeToUse.GetTypeCode()) + { + case TypeCode.Boolean: return s_boolean ?? (s_boolean = new NotEqualBoolean()); + case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte()); + case TypeCode.Byte: return s_byte ?? (s_byte = new NotEqualByte()); + case TypeCode.Char: return s_char ?? (s_char = new NotEqualChar()); + case TypeCode.Int16: return s_int16 ?? (s_int16 = new NotEqualInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new NotEqualInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new NotEqualInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NotEqualInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NotEqualInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new NotEqualInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualInt64()); - case TypeCode.Single: return _Single ?? (_Single = new NotEqualSingle()); - case TypeCode.Double: return _Double ?? (_Double = new NotEqualDouble()); + case TypeCode.Single: return s_single ?? (s_single = new NotEqualSingle()); + case TypeCode.Double: return s_double ?? (s_double = new NotEqualDouble()); case TypeCode.Object: - if (!typeInfo.IsValueType) { - return _Reference ?? (_Reference = new NotEqualReference()); + if (!typeInfo.IsValueType) + { + return s_reference ?? (s_reference = new NotEqualReference()); } // TODO: Nullable throw new NotImplementedException(); @@ -154,7 +186,8 @@ namespace System.Management.Automation.Interpreter { } } - public override string ToString() { + public override string ToString() + { return "NotEqual()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs b/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs index 69d0abcd9..759977068 100644 --- a/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NumericConvertInstruction.cs @@ -19,11 +19,14 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal abstract class NumericConvertInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal abstract class NumericConvertInstruction : Instruction + { internal readonly TypeCode _from, _to; - protected NumericConvertInstruction(TypeCode from, TypeCode to) { + protected NumericConvertInstruction(TypeCode from, TypeCode to) + { _from = from; _to = to; } @@ -31,25 +34,31 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override string ToString() { + public override string ToString() + { return InstructionName + "(" + _from + "->" + _to + ")"; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - internal sealed class Unchecked : NumericConvertInstruction { + internal sealed class Unchecked : NumericConvertInstruction + { public override string InstructionName { get { return "UncheckedConvert"; } } public Unchecked(TypeCode from, TypeCode to) - : base(from, to) { + : base(from, to) + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push(Convert(frame.Pop())); return +1; } - private object Convert(object obj) { - switch (_from) { + private object Convert(object obj) + { + switch (_from) + { case TypeCode.Byte: return ConvertInt32((Byte)obj); case TypeCode.SByte: return ConvertInt32((SByte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); @@ -65,9 +74,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertInt32(int obj) { - unchecked { - switch (_to) { + private object ConvertInt32(int obj) + { + unchecked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -84,9 +96,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertInt64(Int64 obj) { - unchecked { - switch (_to) { + private object ConvertInt64(Int64 obj) + { + unchecked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -103,9 +118,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertUInt64(UInt64 obj) { - unchecked { - switch (_to) { + private object ConvertUInt64(UInt64 obj) + { + unchecked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -122,9 +140,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertDouble(Double obj) { - unchecked { - switch (_to) { + private object ConvertDouble(Double obj) + { + unchecked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -143,20 +164,25 @@ namespace System.Management.Automation.Interpreter { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - internal sealed class Checked : NumericConvertInstruction { + internal sealed class Checked : NumericConvertInstruction + { public override string InstructionName { get { return "CheckedConvert"; } } public Checked(TypeCode from, TypeCode to) - : base(from, to) { + : base(from, to) + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push(Convert(frame.Pop())); return +1; } - private object Convert(object obj) { - switch (_from) { + private object Convert(object obj) + { + switch (_from) + { case TypeCode.Byte: return ConvertInt32((Byte)obj); case TypeCode.SByte: return ConvertInt32((SByte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); @@ -172,9 +198,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertInt32(int obj) { - checked { - switch (_to) { + private object ConvertInt32(int obj) + { + checked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -191,9 +220,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertInt64(Int64 obj) { - checked { - switch (_to) { + private object ConvertInt64(Int64 obj) + { + checked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -210,9 +242,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertUInt64(UInt64 obj) { - checked { - switch (_to) { + private object ConvertUInt64(UInt64 obj) + { + checked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; @@ -229,9 +264,12 @@ namespace System.Management.Automation.Interpreter { } } - private object ConvertDouble(Double obj) { - checked { - switch (_to) { + private object ConvertDouble(Double obj) + { + checked + { + switch (_to) + { case TypeCode.Byte: return (Byte)obj; case TypeCode.SByte: return (SByte)obj; case TypeCode.Int16: return (Int16)obj; diff --git a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs index 0704edefb..a01d4f316 100644 --- a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs @@ -17,8 +17,9 @@ using System; using System.Diagnostics; using System.Management.Automation.Language; -namespace System.Management.Automation.Interpreter { - class UpdatePositionInstruction : Instruction +namespace System.Management.Automation.Interpreter +{ + internal class UpdatePositionInstruction : Instruction { private readonly int _sequencePoint; private readonly bool _checkBreakpoints; diff --git a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs index 99d8320da..dbfe3e272 100644 --- a/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/RuntimeVariables.cs @@ -21,30 +21,39 @@ using System.Runtime.CompilerServices; using Microsoft.PowerShell.CoreClr.Stubs; #endif -namespace System.Management.Automation.Interpreter { - internal sealed class RuntimeVariables : IRuntimeVariables { +namespace System.Management.Automation.Interpreter +{ + internal sealed class RuntimeVariables : IRuntimeVariables + { private readonly IStrongBox[] _boxes; - private RuntimeVariables(IStrongBox[] boxes) { + private RuntimeVariables(IStrongBox[] boxes) + { _boxes = boxes; } - int IRuntimeVariables.Count { - get { + int IRuntimeVariables.Count + { + get + { return _boxes.Length; } } - object IRuntimeVariables.this[int index] { - get { + object IRuntimeVariables.this[int index] + { + get + { return _boxes[index].Value; } - set { + set + { _boxes[index].Value = value; } } - internal static IRuntimeVariables Create(IStrongBox[] boxes) { + internal static IRuntimeVariables Create(IStrongBox[] boxes) + { return new RuntimeVariables(boxes); } } diff --git a/src/System.Management.Automation/engine/interpreter/StackOperations.cs b/src/System.Management.Automation/engine/interpreter/StackOperations.cs index 29a794113..d1624f115 100644 --- a/src/System.Management.Automation/engine/interpreter/StackOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/StackOperations.cs @@ -18,67 +18,81 @@ using System; using System.Diagnostics; using System.Globalization; -namespace System.Management.Automation.Interpreter { - internal sealed class LoadObjectInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal sealed class LoadObjectInstruction : Instruction + { private readonly object _value; - internal LoadObjectInstruction(object value) { + internal LoadObjectInstruction(object value) + { _value = value; } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[frame.StackIndex++] = _value; return +1; } - public override string ToString() { + public override string ToString() + { return "LoadObject(" + (_value ?? "null") + ")"; } } - internal sealed class LoadCachedObjectInstruction : Instruction { + internal sealed class LoadCachedObjectInstruction : Instruction + { private readonly uint _index; - internal LoadCachedObjectInstruction(uint index) { + internal LoadCachedObjectInstruction(uint index) + { _index = index; } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[frame.StackIndex++] = frame.Interpreter._objects[_index]; return +1; } - public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { + public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) + { return String.Format(CultureInfo.InvariantCulture, "LoadCached({0}: {1})", _index, objects[(int)_index]); } - - public override string ToString() { + + public override string ToString() + { return "LoadCached(" + _index + ")"; } } - internal sealed class PopInstruction : Instruction { + internal sealed class PopInstruction : Instruction + { internal static readonly PopInstruction Instance = new PopInstruction(); private PopInstruction() { } public override int ConsumedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Pop(); return +1; } - public override string ToString() { + public override string ToString() + { return "Pop()"; } } - internal sealed class DupInstruction : Instruction { + internal sealed class DupInstruction : Instruction + { internal readonly static DupInstruction Instance = new DupInstruction(); private DupInstruction() { } @@ -86,12 +100,14 @@ namespace System.Management.Automation.Interpreter { public override int ConsumedStack { get { return 0; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Data[frame.StackIndex++] = frame.Peek(); return +1; } - public override string ToString() { + public override string ToString() + { return "Dup()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index 64f620bda..eef296e88 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -17,18 +17,23 @@ using System; using System.Diagnostics; using System.Reflection; -namespace System.Management.Automation.Interpreter { - internal abstract class SubInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; +namespace System.Management.Automation.Interpreter +{ + internal abstract class SubInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private SubInstruction() { + private SubInstruction() + { } - internal sealed class SubInt32 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubInt32 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l - (Int32)r)); @@ -37,8 +42,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubInt16 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubInt16 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l - (Int16)r); @@ -47,8 +54,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubInt64 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubInt64 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l - (Int64)r); @@ -57,8 +66,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubUInt16 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubUInt16 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l - (UInt16)r); @@ -67,8 +78,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubUInt32 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubUInt32 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l - (UInt32)r); @@ -77,8 +90,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubUInt64 : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubUInt64 : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((Int16)l - (Int16)r); @@ -87,8 +102,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubSingle : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubSingle : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); @@ -97,8 +114,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubDouble : SubInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubDouble : SubInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; @@ -107,39 +126,46 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new SubInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new SubInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new SubInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new SubUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new SubUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new SubUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new SubSingle()); - case TypeCode.Double: return _Double ?? (_Double = new SubDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new SubSingle()); + case TypeCode.Double: return s_double ?? (s_double = new SubDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "Sub()"; } } - internal abstract class SubOvfInstruction : Instruction { - private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Single, _Double; + internal abstract class SubOvfInstruction : Instruction + { + private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private SubOvfInstruction() { + private SubOvfInstruction() + { } - internal sealed class SubOvfInt32 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfInt32 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l - (Int32)r)); @@ -148,8 +174,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfInt16 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfInt16 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l - (Int16)r); @@ -158,8 +186,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfInt64 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfInt64 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l - (Int64)r); @@ -168,8 +198,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfUInt16 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfUInt16 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l - (UInt16)r); @@ -178,8 +210,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfUInt32 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfUInt32 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l - (UInt32)r); @@ -188,8 +222,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfUInt64 : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfUInt64 : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l - (Int16)r); @@ -198,8 +234,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfSingle : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfSingle : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); @@ -208,8 +246,10 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class SubOvfDouble : SubOvfInstruction { - public override int Run(InterpretedFrame frame) { + internal sealed class SubOvfDouble : SubOvfInstruction + { + public override int Run(InterpretedFrame frame) + { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; @@ -218,24 +258,27 @@ namespace System.Management.Automation.Interpreter { } } - public static Instruction Create(Type type) { + public static Instruction Create(Type type) + { Debug.Assert(!type.GetTypeInfo().IsEnum); - switch (type.GetTypeCode()) { - case TypeCode.Int16: return _Int16 ?? (_Int16 = new SubOvfInt16()); - case TypeCode.Int32: return _Int32 ?? (_Int32 = new SubOvfInt32()); - case TypeCode.Int64: return _Int64 ?? (_Int64 = new SubOvfInt64()); - case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new SubOvfUInt16()); - case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new SubOvfUInt32()); - case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new SubOvfUInt64()); - case TypeCode.Single: return _Single ?? (_Single = new SubOvfSingle()); - case TypeCode.Double: return _Double ?? (_Double = new SubOvfDouble()); + switch (type.GetTypeCode()) + { + case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubOvfInt16()); + case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubOvfInt32()); + case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubOvfInt64()); + case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); + case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); + case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); + case TypeCode.Single: return s_single ?? (s_single = new SubOvfSingle()); + case TypeCode.Double: return s_double ?? (s_double = new SubOvfDouble()); default: throw Assert.Unreachable; } } - public override string ToString() { + public override string ToString() + { return "SubOvf()"; } } diff --git a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs index c2c9d1920..90fdcb0cf 100644 --- a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs @@ -19,25 +19,33 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -namespace System.Management.Automation.Interpreter { - internal sealed class CreateDelegateInstruction : Instruction { +namespace System.Management.Automation.Interpreter +{ + internal sealed class CreateDelegateInstruction : Instruction + { private readonly LightDelegateCreator _creator; - internal CreateDelegateInstruction(LightDelegateCreator delegateCreator) { + internal CreateDelegateInstruction(LightDelegateCreator delegateCreator) + { _creator = delegateCreator; } public override int ConsumedStack { get { return _creator.Interpreter.ClosureSize; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { StrongBox[] closure; - if (ConsumedStack > 0) { + if (ConsumedStack > 0) + { closure = new StrongBox[ConsumedStack]; - for (int i = closure.Length - 1; i >= 0; i--) { + for (int i = closure.Length - 1; i >= 0; i--) + { closure[i] = (StrongBox)frame.Pop(); } - } else { + } + else + { closure = null; } @@ -48,28 +56,34 @@ namespace System.Management.Automation.Interpreter { } } - internal sealed class NewInstruction : Instruction { + internal sealed class NewInstruction : Instruction + { private readonly ConstructorInfo _constructor; private readonly int _argCount; - public NewInstruction(ConstructorInfo constructor) { + public NewInstruction(ConstructorInfo constructor) + { _constructor = constructor; _argCount = constructor.GetParameters().Length; - } public override int ConsumedStack { get { return _argCount; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { object[] args = new object[_argCount]; - for (int i = _argCount - 1; i >= 0; i--) { + for (int i = _argCount - 1; i >= 0; i--) + { args[i] = frame.Pop(); } object ret; - try { + try + { ret = _constructor.Invoke(args); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { ExceptionHelpers.UpdateForRethrow(e.InnerException); throw e.InnerException; } @@ -77,83 +91,100 @@ namespace System.Management.Automation.Interpreter { return +1; } - public override string ToString() { + public override string ToString() + { return "New " + _constructor.DeclaringType.Name + "(" + _constructor + ")"; } } - internal sealed class DefaultValueInstruction : Instruction { + internal sealed class DefaultValueInstruction : Instruction + { internal DefaultValueInstruction() { } public override int ConsumedStack { get { return 0; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { frame.Push(default(T)); return +1; } - public override string ToString() { + public override string ToString() + { return "New " + typeof(T); } } - internal sealed class TypeIsInstruction : Instruction { + internal sealed class TypeIsInstruction : Instruction + { internal TypeIsInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // unfortunately Type.IsInstanceOfType() is 35-times slower than "is T" so we use generic code: frame.Push(ScriptingRuntimeHelpers.BooleanToObject(frame.Pop() is T)); return +1; } - public override string ToString() { - return "TypeIs " + typeof(T).Name; + public override string ToString() + { + return "TypeIs " + typeof(T).Name; } } - internal sealed class TypeAsInstruction : Instruction { + internal sealed class TypeAsInstruction : Instruction + { internal TypeAsInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { // can't use as w/o generic constraint object value = frame.Pop(); - if (value is T) { + if (value is T) + { frame.Push(value); - } else { + } + else + { frame.Push(null); } return +1; } - public override string ToString() { + public override string ToString() + { return "TypeAs " + typeof(T).Name; } } - internal sealed class TypeEqualsInstruction : Instruction { + internal sealed class TypeEqualsInstruction : Instruction + { public static readonly TypeEqualsInstruction Instance = new TypeEqualsInstruction(); public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } - private TypeEqualsInstruction() { + private TypeEqualsInstruction() + { } - public override int Run(InterpretedFrame frame) { + public override int Run(InterpretedFrame frame) + { object type = frame.Pop(); object obj = frame.Pop(); frame.Push(ScriptingRuntimeHelpers.BooleanToObject(obj != null && (object)obj.GetType() == type)); return +1; } - public override string InstructionName { + public override string InstructionName + { get { return "TypeEquals()"; } } } diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index fb2a4cf7a..5183defe6 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -1,7 +1,8 @@ // // Copyright (C) Microsoft. All rights reserved. // -using System; + +using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; @@ -52,6 +53,27 @@ namespace System.Management.Automation.Interpreter { switch (type.GetTypeCode()) { + case TypeCode.Char: + case TypeCode.SByte: + case TypeCode.Byte: + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.Double: + case TypeCode.Single: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + return true; + } + } + return false; + } + + internal static bool IsNumeric(TypeCode typeCode) + { + switch (typeCode) + { case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: @@ -63,28 +85,7 @@ namespace System.Management.Automation.Interpreter case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: - return true; - } - } - return false; - } - - internal static bool IsNumeric(TypeCode typeCode) - { - switch (typeCode) - { - case TypeCode.Char: - case TypeCode.SByte: - case TypeCode.Byte: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.Double: - case TypeCode.Single: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - return true; + return true; } return false; } @@ -96,15 +97,15 @@ namespace System.Management.Automation.Interpreter { switch (type.GetTypeCode()) { - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.Double: - case TypeCode.Single: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - return true; + case TypeCode.Int16: + case TypeCode.Int32: + case TypeCode.Int64: + case TypeCode.Double: + case TypeCode.Single: + case TypeCode.UInt16: + case TypeCode.UInt32: + case TypeCode.UInt64: + return true; } } return false; @@ -124,7 +125,6 @@ namespace System.Management.Automation.Interpreter internal static partial class DelegateHelpers { - #region Generated Maximum Delegate Arity // *** BEGIN GENERATED CODE *** @@ -156,71 +156,71 @@ namespace System.Management.Automation.Interpreter Array.Resize(ref types, types.Length - 1); switch (types.Length) { - case 0: return typeof(Action); - #region Generated Delegate Action Types + case 0: return typeof(Action); + #region Generated Delegate Action Types - // *** BEGIN GENERATED CODE *** - // generated by function: gen_delegate_action from: generate_dynsites.py + // *** BEGIN GENERATED CODE *** + // generated by function: gen_delegate_action from: generate_dynsites.py - case 1: return typeof(Action<>).MakeGenericType(types); - case 2: return typeof(Action<,>).MakeGenericType(types); - case 3: return typeof(Action<,,>).MakeGenericType(types); - case 4: return typeof(Action<,,,>).MakeGenericType(types); - case 5: return typeof(Action<,,,,>).MakeGenericType(types); - case 6: return typeof(Action<,,,,,>).MakeGenericType(types); - case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); - case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); - case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); - case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); - case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); - case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); - case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); - case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); - case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); - case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); + case 1: return typeof(Action<>).MakeGenericType(types); + case 2: return typeof(Action<,>).MakeGenericType(types); + case 3: return typeof(Action<,,>).MakeGenericType(types); + case 4: return typeof(Action<,,,>).MakeGenericType(types); + case 5: return typeof(Action<,,,,>).MakeGenericType(types); + case 6: return typeof(Action<,,,,,>).MakeGenericType(types); + case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); + case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); + case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); + case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); + case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); + case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); + case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); + case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); + case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); + case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); - // *** END GENERATED CODE *** + // *** END GENERATED CODE *** - #endregion + #endregion } } else { switch (types.Length) { - #region Generated Delegate Func Types + #region Generated Delegate Func Types - // *** BEGIN GENERATED CODE *** - // generated by function: gen_delegate_func from: generate_dynsites.py + // *** BEGIN GENERATED CODE *** + // generated by function: gen_delegate_func from: generate_dynsites.py - case 1: return typeof(Func<>).MakeGenericType(types); - case 2: return typeof(Func<,>).MakeGenericType(types); - case 3: return typeof(Func<,,>).MakeGenericType(types); - case 4: return typeof(Func<,,,>).MakeGenericType(types); - case 5: return typeof(Func<,,,,>).MakeGenericType(types); - case 6: return typeof(Func<,,,,,>).MakeGenericType(types); - case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); - case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); - case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); - case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); - case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); - case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); - case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); - case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); - case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); - case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); - case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); + case 1: return typeof(Func<>).MakeGenericType(types); + case 2: return typeof(Func<,>).MakeGenericType(types); + case 3: return typeof(Func<,,>).MakeGenericType(types); + case 4: return typeof(Func<,,,>).MakeGenericType(types); + case 5: return typeof(Func<,,,,>).MakeGenericType(types); + case 6: return typeof(Func<,,,,,>).MakeGenericType(types); + case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); + case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); + case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); + case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); + case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); + case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); + case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); + case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); + case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); + case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); + case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); - // *** END GENERATED CODE *** + // *** END GENERATED CODE *** - #endregion + #endregion } } throw Assert.Unreachable; } } - class ScriptingRuntimeHelpers + internal class ScriptingRuntimeHelpers { internal static object Int32ToObject(int i) { @@ -242,25 +242,25 @@ namespace System.Management.Automation.Interpreter { switch (type.GetTypeCode()) { - case TypeCode.Boolean: return ScriptingRuntimeHelpers.False; - case TypeCode.SByte: return default(SByte); - case TypeCode.Byte: return default(Byte); - case TypeCode.Char: return default(Char); - case TypeCode.Int16: return default(Int16); - case TypeCode.Int32: return ScriptingRuntimeHelpers.Int32ToObject(0); - case TypeCode.Int64: return default(Int64); - case TypeCode.UInt16: return default(UInt16); - case TypeCode.UInt32: return default(UInt32); - case TypeCode.UInt64: return default(UInt64); - case TypeCode.Single: return default(Single); - case TypeCode.Double: return default(Double); - case TypeCode.DateTime: return default(DateTime); - case TypeCode.Decimal: return default(Decimal); - // TypeCode.Empty: null; - // TypeCode.Object: default(object) == null; - // TypeCode.DBNull: default(DBNull) == null; - // TypeCode.String: default(string) == null; - default: return null; + case TypeCode.Boolean: return ScriptingRuntimeHelpers.False; + case TypeCode.SByte: return default(SByte); + case TypeCode.Byte: return default(Byte); + case TypeCode.Char: return default(Char); + case TypeCode.Int16: return default(Int16); + case TypeCode.Int32: return ScriptingRuntimeHelpers.Int32ToObject(0); + case TypeCode.Int64: return default(Int64); + case TypeCode.UInt16: return default(UInt16); + case TypeCode.UInt32: return default(UInt32); + case TypeCode.UInt64: return default(UInt64); + case TypeCode.Single: return default(Single); + case TypeCode.Double: return default(Double); + case TypeCode.DateTime: return default(DateTime); + case TypeCode.Decimal: return default(Decimal); + // TypeCode.Empty: null; + // TypeCode.Object: default(object) == null; + // TypeCode.DBNull: default(DBNull) == null; + // TypeCode.String: default(string) == null; + default: return null; } } } @@ -302,7 +302,7 @@ namespace System.Management.Automation.Interpreter return DynamicMetaObject.Create( GetArgument(index), Expression.Call( - _GetArgMethod, + s_getArgMethod, AstUtils.Convert(parameter, typeof(ArgumentArray)), AstUtils.Constant(index) ) @@ -315,7 +315,7 @@ namespace System.Management.Automation.Interpreter return array._arguments[array._first + index]; } - private static readonly MethodInfo _GetArgMethod = new Func(GetArg).GetMethodInfo(); + private static readonly MethodInfo s_getArgMethod = new Func(GetArg).GetMethodInfo(); } internal static class ExceptionHelpers @@ -370,7 +370,7 @@ namespace System.Management.Automation.Interpreter /// /// A hybrid dictionary which compares based upon object identity. /// - class HybridReferenceDictionary where TKey : class + internal class HybridReferenceDictionary where TKey : class { private KeyValuePair[] _keysAndValues; private Dictionary _dict; @@ -472,7 +472,6 @@ namespace System.Management.Automation.Interpreter } return _count; } - } public IEnumerator> GetEnumerator() @@ -675,13 +674,15 @@ namespace System.Management.Automation.Interpreter } } - internal class ThreadLocal { + internal class ThreadLocal + { private StorageInfo[] _stores; // array of storage indexed by managed thread ID - private static readonly StorageInfo[] Updating = Automation.Utils.EmptyArray(); // a marker used when updating the array + private static readonly StorageInfo[] s_updating = Automation.Utils.EmptyArray(); // a marker used when updating the array private readonly bool _refCounted; - - public ThreadLocal() { + + public ThreadLocal() + { } /// @@ -694,7 +695,8 @@ namespace System.Management.Automation.Interpreter /// local is back to it's original state. This allows the ThreadLocal object /// to not check the current owning thread on retrieval. /// - public ThreadLocal(bool refCounted) { + public ThreadLocal(bool refCounted) + { _refCounted = refCounted; } @@ -703,11 +705,14 @@ namespace System.Management.Automation.Interpreter /// /// Gets or sets the value for the current thread. /// - public T Value { - get { + public T Value + { + get + { return GetStorageInfo().Value; } - set { + set + { GetStorageInfo().Value = value; } } @@ -716,12 +721,14 @@ namespace System.Management.Automation.Interpreter /// Gets the current value if its not == null or calls the provided function /// to create a new value. /// - public T GetOrCreate(Func func) { + public T GetOrCreate(Func func) + { Assert.NotNull(func); StorageInfo si = GetStorageInfo(); T res = si.Value; - if (res == null) { + if (res == null) + { si.Value = res = func(); } @@ -732,7 +739,8 @@ namespace System.Management.Automation.Interpreter /// Calls the provided update function with the current value and /// replaces the current value with the result of the function. /// - public T Update(Func updater) { + public T Update(Func updater) + { Assert.NotNull(updater); StorageInfo si = GetStorageInfo(); @@ -742,7 +750,8 @@ namespace System.Management.Automation.Interpreter /// /// Replaces the current value with a new one and returns the old value. /// - public T Update(T newValue) { + public T Update(T newValue) + { StorageInfo si = GetStorageInfo(); var oldValue = si.Value; si.Value = newValue; @@ -772,7 +781,8 @@ namespace System.Management.Automation.Interpreter } } #else - private static int GetCurrentThreadId() { + private static int GetCurrentThreadId() + { return Thread.CurrentThread.ManagedThreadId; } #endif @@ -780,18 +790,22 @@ namespace System.Management.Automation.Interpreter /// /// Gets the StorageInfo for the current thread. /// - public StorageInfo GetStorageInfo() { + public StorageInfo GetStorageInfo() + { return GetStorageInfo(_stores); } - private StorageInfo GetStorageInfo(StorageInfo[] curStorage) { + private StorageInfo GetStorageInfo(StorageInfo[] curStorage) + { int threadId = GetCurrentThreadId(); // fast path if we already have a value in the array - if (curStorage != null && curStorage.Length > threadId) { + if (curStorage != null && curStorage.Length > threadId) + { StorageInfo res = curStorage[threadId]; - if (res != null && (_refCounted || res.Thread == Thread.CurrentThread)) { + if (res != null && (_refCounted || res.Thread == Thread.CurrentThread)) + { return res; } } @@ -804,10 +818,13 @@ namespace System.Management.Automation.Interpreter /// during the initial fast check then spin until we hit non-empty storage and try the fast /// path again. /// - private StorageInfo RetryOrCreateStorageInfo(StorageInfo[] curStorage) { - if (curStorage == Updating) { + private StorageInfo RetryOrCreateStorageInfo(StorageInfo[] curStorage) + { + if (curStorage == s_updating) + { // we need to retry - while ((curStorage = _stores) == Updating) { + while ((curStorage = _stores) == s_updating) + { Thread.Sleep(0); } @@ -822,31 +839,39 @@ namespace System.Management.Automation.Interpreter /// /// Creates the StorageInfo for the thread when one isn't already present. /// - private StorageInfo CreateStorageInfo() { + private StorageInfo CreateStorageInfo() + { // we do our own locking, tell hosts this is a bad time to interrupt us. #if !SILVERLIGHT && !CORECLR Thread.BeginCriticalRegion(); #endif - StorageInfo[] curStorage = Updating; - try { + StorageInfo[] curStorage = s_updating; + try + { int threadId = GetCurrentThreadId(); StorageInfo newInfo = new StorageInfo(Thread.CurrentThread); // set to updating while potentially resizing/mutating, then we'll // set back to the current value. - while ((curStorage = Interlocked.Exchange(ref _stores, Updating)) == Updating) { + while ((curStorage = Interlocked.Exchange(ref _stores, s_updating)) == s_updating) + { // another thread is already updating... Thread.Sleep(0); } // check and make sure we have a space in the array for our value - if (curStorage == null) { + if (curStorage == null) + { curStorage = new StorageInfo[threadId + 1]; - } else if (curStorage.Length <= threadId) { + } + else if (curStorage.Length <= threadId) + { StorageInfo[] newStorage = new StorageInfo[threadId + 1]; - for (int i = 0; i < curStorage.Length; i++) { + for (int i = 0; i < curStorage.Length; i++) + { // leave out the threads that have exited - if (curStorage[i] != null && curStorage[i].Thread.IsAlive) { + if (curStorage[i] != null && curStorage[i].Thread.IsAlive) + { newStorage[i] = curStorage[i]; } } @@ -858,8 +883,11 @@ namespace System.Management.Automation.Interpreter Debug.Assert(curStorage[threadId] == null || curStorage[threadId].Thread != Thread.CurrentThread); return curStorage[threadId] = newInfo; - } finally { - if (curStorage != Updating) { + } + finally + { + if (curStorage != s_updating) + { // let others access the storage again Interlocked.Exchange(ref _stores, curStorage); } @@ -874,11 +902,13 @@ namespace System.Management.Automation.Interpreter /// has been re-used so we also store the thread which owns the value. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO - internal sealed class StorageInfo { + internal sealed class StorageInfo + { internal readonly Thread Thread; // the thread that owns the StorageInfo public T Value; // the current value for the owning thread - internal StorageInfo(Thread curThread) { + internal StorageInfo(Thread curThread) + { Assert.NotNull(curThread); Thread = curThread; @@ -888,7 +918,7 @@ namespace System.Management.Automation.Interpreter #endregion } - static class Assert + internal static class Assert { internal static Exception Unreachable { @@ -943,18 +973,18 @@ namespace System.Management.Automation.Interpreter ReadWrite = Read | Write, } - static class Utils + internal static class Utils { internal static Expression Constant(object value) { return Expression.Constant(value); } - private static readonly DefaultExpression VoidInstance = Expression.Empty(); + private static readonly DefaultExpression s_voidInstance = Expression.Empty(); public static DefaultExpression Empty() { - return VoidInstance; + return s_voidInstance; } public static Expression Void(Expression expression) @@ -1028,34 +1058,34 @@ namespace System.Management.Automation.Interpreter { switch (type) { - // unary: - case ExpressionType.PostDecrementAssign: - case ExpressionType.PostIncrementAssign: - case ExpressionType.PreDecrementAssign: - case ExpressionType.PreIncrementAssign: + // unary: + case ExpressionType.PostDecrementAssign: + case ExpressionType.PostIncrementAssign: + case ExpressionType.PreDecrementAssign: + case ExpressionType.PreIncrementAssign: - // binary - compound: - case ExpressionType.AddAssign: - case ExpressionType.AddAssignChecked: - case ExpressionType.AndAssign: - case ExpressionType.DivideAssign: - case ExpressionType.ExclusiveOrAssign: - case ExpressionType.LeftShiftAssign: - case ExpressionType.ModuloAssign: - case ExpressionType.MultiplyAssign: - case ExpressionType.MultiplyAssignChecked: - case ExpressionType.OrAssign: - case ExpressionType.PowerAssign: - case ExpressionType.RightShiftAssign: - case ExpressionType.SubtractAssign: - case ExpressionType.SubtractAssignChecked: - return true; + // binary - compound: + case ExpressionType.AddAssign: + case ExpressionType.AddAssignChecked: + case ExpressionType.AndAssign: + case ExpressionType.DivideAssign: + case ExpressionType.ExclusiveOrAssign: + case ExpressionType.LeftShiftAssign: + case ExpressionType.ModuloAssign: + case ExpressionType.MultiplyAssign: + case ExpressionType.MultiplyAssignChecked: + case ExpressionType.OrAssign: + case ExpressionType.PowerAssign: + case ExpressionType.RightShiftAssign: + case ExpressionType.SubtractAssign: + case ExpressionType.SubtractAssignChecked: + return true; } return false; } } - static class CollectionExtension + internal static class CollectionExtension { internal static bool TrueForAll(this IEnumerable collection, Predicate predicate) { @@ -1114,8 +1144,6 @@ namespace System.Management.Automation.Interpreter } return true; } - - } internal sealed class ListEqualityComparer : EqualityComparer> diff --git a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs index 990c13dba..1dfdcc453 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs @@ -3,13 +3,13 @@ Project: PowerShell - File: PSParseError.cs Contents: PowerShell error interface for syntax editors Classes: System.Management.Automation.PSParseError --********************************************************************/ + using System; using System.Text; using System.Text.RegularExpressions; diff --git a/src/System.Management.Automation/engine/lang/interface/PSParser.cs b/src/System.Management.Automation/engine/lang/interface/PSParser.cs index c00dcb09d..dde5dcbb7 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParser.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParser.cs @@ -3,13 +3,13 @@ Project: PowerShell - File: PSParser.cs Contents: PowerShell parser interface for syntax editors Classes: System.Management.Automation.PSParser --********************************************************************/ + using System; using System.Text; using System.Text.RegularExpressions; @@ -86,15 +86,15 @@ namespace System.Management.Automation #region Parsing Logic - private readonly List tokenList = new List(); - private Language.ParseError[] errors; + private readonly List _tokenList = new List(); + private Language.ParseError[] _errors; private void Parse(string script) { try { var parser = new Language.Parser { ProduceV2Tokens = true }; - parser.Parse(null, script, tokenList, out errors, ParseMode.Default); + parser.Parse(null, script, _tokenList, out _errors, ParseMode.Default); } catch (Exception e) { @@ -112,9 +112,9 @@ namespace System.Management.Automation { Collection resultTokens = new Collection(); // Skip the last token, it's always EOF. - for (int i = 0; i < tokenList.Count - 1; i++) + for (int i = 0; i < _tokenList.Count - 1; i++) { - var token = tokenList[i]; + var token = _tokenList[i]; resultTokens.Add(new PSToken(token)); } @@ -130,7 +130,7 @@ namespace System.Management.Automation get { Collection resultErrors = new Collection(); - foreach (var error in errors) + foreach (var error in _errors) { resultErrors.Add(new PSParseError(error)); } diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 0e8eb61d6..976e3e255 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -3,13 +3,13 @@ Project: PowerShell - File: PSToken.cs Contents: PowerShell token interface for syntax editors Classes: System.Management.Automation.PSToken --********************************************************************/ + using System; using System.Management.Automation.Language; using System.Collections.Generic; @@ -97,7 +97,7 @@ namespace System.Management.Automation { return PSTokenType.Type; } - return _tokenKindMapping[(int)token.Kind]; + return s_tokenKindMapping[(int)token.Kind]; } private PSTokenType _type; @@ -113,7 +113,7 @@ namespace System.Management.Automation } } - private readonly static PSTokenType[] _tokenKindMapping = new PSTokenType[] + private readonly static PSTokenType[] s_tokenKindMapping = new PSTokenType[] { #region Flags for unclassified tokens diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index a9d5bc4ce..4d99be85d 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -111,7 +111,7 @@ namespace System.Management.Automation { internal LoopFlowException(string label) { - this.Label = label ?? ""; + this.Label = label ?? ""; } internal LoopFlowException(SerializationInfo info, StreamingContext context) @@ -125,9 +125,9 @@ namespace System.Management.Automation /// Label, indicates nested loop level affected by exception. /// No label means most nested loop is affected. /// - public string Label - { - get; + public string Label + { + get; internal set; } @@ -289,7 +289,7 @@ namespace System.Management.Automation /// Ignores unescaped whitespace and comments marked with #. /// Valid only with RegexMatch. /// - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="Whitespace")] + [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] IgnorePatternWhitespace = 0x08, /// /// Regex multiline mode, which recognizes the start and end of lines, @@ -336,25 +336,25 @@ namespace System.Management.Automation // Cache for ints and chars to avoid overhead of boxing every time... for (int i = 0; i < (_MaxCache - _MinCache); i++) { - _integerCache[i] = (object)(i + _MinCache); + s_integerCache[i] = (object)(i + _MinCache); } for (char ch = (char)0; ch < 255; ch++) { - _chars[ch] = new string(ch, 1); + s_chars[ch] = new string(ch, 1); } } private const int _MinCache = -100; private const int _MaxCache = 1000; - private static readonly object[] _integerCache = new object[_MaxCache - _MinCache]; - private static readonly string[] _chars = new string[255]; + private static readonly object[] s_integerCache = new object[_MaxCache - _MinCache]; + private static readonly string[] s_chars = new string[255]; internal static readonly object _TrueObject = (object)true; internal static readonly object _FalseObject = (object)false; internal static string CharToString(char ch) { - if (ch < 255) return _chars[ch]; + if (ch < 255) return s_chars[ch]; return new string(ch, 1); } @@ -372,7 +372,7 @@ namespace System.Management.Automation { if (value < _MaxCache && value >= _MinCache) { - return _integerCache[value - _MinCache]; + return s_integerCache[value - _MinCache]; } return (object)value; } @@ -542,12 +542,12 @@ namespace System.Management.Automation private static RegexOptions parseRegexOptions(SplitOptions options) { int[][] map = { - new int[] { (int)SplitOptions.CultureInvariant, (int)RegexOptions.CultureInvariant }, - new int[] { (int)SplitOptions.IgnorePatternWhitespace, (int)RegexOptions.IgnorePatternWhitespace }, - new int[] { (int)SplitOptions.Multiline, (int)RegexOptions.Multiline }, - new int[] { (int)SplitOptions.Singleline, (int)RegexOptions.Singleline }, - new int[] { (int)SplitOptions.IgnoreCase, (int)RegexOptions.IgnoreCase }, - new int[] { (int)SplitOptions.ExplicitCapture, (int)RegexOptions.ExplicitCapture }, + new int[] { (int)SplitOptions.CultureInvariant, (int)RegexOptions.CultureInvariant }, + new int[] { (int)SplitOptions.IgnorePatternWhitespace, (int)RegexOptions.IgnorePatternWhitespace }, + new int[] { (int)SplitOptions.Multiline, (int)RegexOptions.Multiline }, + new int[] { (int)SplitOptions.Singleline, (int)RegexOptions.Singleline }, + new int[] { (int)SplitOptions.IgnoreCase, (int)RegexOptions.IgnoreCase }, + new int[] { (int)SplitOptions.ExplicitCapture, (int)RegexOptions.ExplicitCapture }, }; RegexOptions result = RegexOptions.None; @@ -604,7 +604,7 @@ namespace System.Management.Automation else { // The first argument to split is always required. - throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, + throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, "BadOperatorArgument", ParserStrings.BadOperatorArgument, "-split", rval); } if (args.Length >= 2) @@ -660,12 +660,12 @@ namespace System.Management.Automation for (int strIndex = 0; strIndex < item.Length; strIndex++) { object isDelimChar = predicate.DoInvokeReturnAsIs( - useLocalScope: true, + useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: CharToString(item[strIndex]), - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: new object[] {item, strIndex}); + dollarUnder: CharToString(item[strIndex]), + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: new object[] { item, strIndex }); if (LanguagePrimitives.IsTrue(isDelimChar)) { split.Add(buf.ToString()); @@ -1204,7 +1204,6 @@ namespace System.Management.Automation } return resultList.ToArray(); - } /// @@ -1218,24 +1217,24 @@ namespace System.Management.Automation if (options != RegexOptions.IgnoreCase) return new Regex(patternString, options); - lock (_regexCache) + lock (s_regexCache) { Regex result; - if (_regexCache.TryGetValue(patternString, out result)) + if (s_regexCache.TryGetValue(patternString, out result)) { return result; } else { - if (_regexCache.Count > MaxRegexCache) - _regexCache.Clear(); + if (s_regexCache.Count > MaxRegexCache) + s_regexCache.Clear(); Regex re = new Regex(patternString, RegexOptions.IgnoreCase); - _regexCache.Add(patternString, re); + s_regexCache.Add(patternString, re); return re; } } } - private static Dictionary _regexCache = new Dictionary(); + private static Dictionary s_regexCache = new Dictionary(); private const int MaxRegexCache = 1000; /// @@ -1351,15 +1350,15 @@ namespace System.Management.Automation /// Internal exception from a flow control statement /// internal static object CallMethod( - IScriptExtent errorPosition, - object target, - string methodName, + IScriptExtent errorPosition, + object target, + string methodName, PSMethodInvocationConstraints invocationConstraints, - object[] paramArray, - bool callStatic, + object[] paramArray, + bool callStatic, object valueToSet) { - Dbg.Assert(methodName != null, "methodName was null"); + Dbg.Assert(methodName != null, "methodName was null"); PSMethodInfo targetMethod = null; object targetBase = null; @@ -1447,7 +1446,6 @@ namespace System.Management.Automation { return targetMethod.Invoke(paramArray); } - } } catch (MethodInvocationException mie) @@ -1489,14 +1487,16 @@ namespace System.Management.Automation /// This is a simple enumerator class that just enumerates of a range of numbers. It's used in enumerating /// elements when the range operator .. is used. /// - internal class RangeEnumerator :IEnumerator + internal class RangeEnumerator : IEnumerator { private int _lowerBound; - internal int LowerBound { + internal int LowerBound + { get { return _lowerBound; } } private int _upperBound; - internal int UpperBound { + internal int UpperBound + { get { return _upperBound; } } @@ -1506,13 +1506,14 @@ namespace System.Management.Automation get { return _current; } } - internal int CurrentValue { + internal int CurrentValue + { get { return _current; } } - private int increment = 1; + private int _increment = 1; - private bool firstElement = true; + private bool _firstElement = true; public RangeEnumerator(int lowerBound, int upperBound) { @@ -1520,29 +1521,28 @@ namespace System.Management.Automation _current = _lowerBound; _upperBound = upperBound; if (lowerBound > upperBound) - increment = -1; + _increment = -1; } public void Reset() { _current = _lowerBound; - firstElement = true; + _firstElement = true; } public bool MoveNext() { - if (firstElement) + if (_firstElement) { - firstElement = false; + _firstElement = false; return true; } if (_current == _upperBound) return false; - _current += increment; + _current += _increment; return true; } - } #endregion RangeEnumerator @@ -1616,7 +1616,6 @@ namespace System.Management.Automation } else { - rte = NewInterpreterExceptionByMessage(exceptionType, errorPosition, message, resourceIdAndErrorId, innerException); } } diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 15f667b67..d6544b318 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -88,7 +88,7 @@ namespace System.Management.Automation /// This class will handle the logic for direct invocation of script blocks. /// /// - partial class ScriptBlock + public partial class ScriptBlock { /// /// Create a script block object based on a script string to be parsed immediately. @@ -411,7 +411,6 @@ namespace System.Management.Automation string functionName = pair.Key as string; if (string.IsNullOrWhiteSpace(functionName)) { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.EmptyFunctionNameInFunctionDefinitionDictionary); @@ -506,12 +505,12 @@ namespace System.Management.Automation public object InvokeReturnAsIs(params object[] args) { return DoInvokeReturnAsIs( - useLocalScope: true, + useLocalScope: true, errorHandlingBehavior: ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: args); + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: args); } internal T InvokeAsMemberFunctionT(object instance, object[] args) @@ -520,14 +519,14 @@ namespace System.Management.Automation Pipe pipe = new Pipe(result); InvokeWithPipe(useLocalScope: true, - errorHandlingBehavior: ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: instance ?? AutomationNull.Value, - outputPipe: pipe, - invocationInfo: null, + errorHandlingBehavior: ErrorHandlingBehavior.WriteToExternalErrorPipe, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: instance ?? AutomationNull.Value, + outputPipe: pipe, + invocationInfo: null, propagateAllExceptionsToTop: true, - args: args); + args: args); Diagnostics.Assert(result.Count == 1, "Code generation ensures we return the correct type"); return (T)result[0]; } @@ -538,14 +537,14 @@ namespace System.Management.Automation Pipe pipe = new Pipe(result); InvokeWithPipe(useLocalScope: true, - errorHandlingBehavior: ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: instance ?? AutomationNull.Value, - outputPipe: pipe, - invocationInfo: null, + errorHandlingBehavior: ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: instance ?? AutomationNull.Value, + outputPipe: pipe, + invocationInfo: null, propagateAllExceptionsToTop: true, - args: args); + args: args); Diagnostics.Assert(result.Count == 0, "Code generation ensures we return the correct type"); } @@ -666,7 +665,7 @@ namespace System.Management.Automation Pipe outputPipe = ((MshCommandRuntime)contextCmdlet.CommandRuntime).OutputPipe; ExecutionContext context = GetContextFromTLS(); var myInv = context.EngineSessionState.CurrentScope.GetAutomaticVariableValue(AutomaticVariable.MyInvocation); - InvocationInfo inInfo = myInv == AutomationNull.Value ? null : (InvocationInfo) myInv; + InvocationInfo inInfo = myInv == AutomationNull.Value ? null : (InvocationInfo)myInv; InvokeWithPipe(useLocalScope, errorHandlingBehavior, dollarUnder, input, scriptThis, outputPipe, inInfo, propagateAllExceptionsToTop: false, args: args); } @@ -704,12 +703,12 @@ namespace System.Management.Automation #region Delegates - private static readonly ConditionalWeakTable> delegateTable = + private static readonly ConditionalWeakTable> s_delegateTable = new ConditionalWeakTable>(); internal Delegate GetDelegate(Type delegateType) { - var instanceDelegateTable = delegateTable.GetOrCreateValue(this); + var instanceDelegateTable = s_delegateTable.GetOrCreateValue(this); return instanceDelegateTable.GetOrAdd(delegateType, CreateDelegate); } @@ -777,14 +776,14 @@ namespace System.Management.Automation List rawResult = new List(); Pipe outputPipe = new Pipe(rawResult); InvokeWithPipe( - useLocalScope: true, + useLocalScope: true, errorHandlingBehavior: ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: dollarUnder, - input: null, - scriptThis: dollarThis, - outputPipe: outputPipe, - invocationInfo: null, - args: args); + dollarUnder: dollarUnder, + input: null, + scriptThis: dollarThis, + outputPipe: outputPipe, + invocationInfo: null, + args: args); return GetRawResult(rawResult); } @@ -841,14 +840,14 @@ namespace System.Management.Automation { List result = new List(); Pipe outputPipe = new Pipe(result); - InvokeWithPipe(useLocalScope: true, + InvokeWithPipe(useLocalScope: true, errorHandlingBehavior: ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: dollarUnder, - input: input, - scriptThis: AutomationNull.Value, - outputPipe: outputPipe, - invocationInfo: null, - args: args); + dollarUnder: dollarUnder, + input: input, + scriptThis: AutomationNull.Value, + outputPipe: outputPipe, + invocationInfo: null, + args: args); return GetWrappedResult(result); } @@ -906,14 +905,14 @@ namespace System.Management.Automation { List result = new List(); Pipe outputPipe = new Pipe(result); - InvokeWithPipe(useLocalScope: useLocalScope, + InvokeWithPipe(useLocalScope: useLocalScope, errorHandlingBehavior: errorHandlingBehavior, - dollarUnder: dollarUnder, - input: input, - scriptThis: scriptThis, - outputPipe: outputPipe, - invocationInfo: null, - args: args); + dollarUnder: dollarUnder, + input: input, + scriptThis: scriptThis, + outputPipe: outputPipe, + invocationInfo: null, + args: args); return GetRawResult(result); } @@ -939,59 +938,57 @@ namespace System.Management.Automation context = SessionStateInternal.ExecutionContext; shouldGenerateEvent = true; } - else if (context == null) - { - // This will throw. - GetContextFromTLS(); - } - else - { - if (propagateAllExceptionsToTop) - { - oldPropagateExceptions = context.PropagateExceptionsToEnclosingStatementBlock; - context.PropagateExceptionsToEnclosingStatementBlock = true; - } + else if (context == null) + { + // This will throw. + GetContextFromTLS(); + } + else + { + if (propagateAllExceptionsToTop) + { + oldPropagateExceptions = context.PropagateExceptionsToEnclosingStatementBlock; + context.PropagateExceptionsToEnclosingStatementBlock = true; + } - try - { - - var runspace = (RunspaceBase) context.CurrentRunspace; - shouldGenerateEvent = !runspace.RunActionIfNoRunningPipelinesWithThreadCheck(() => - InvokeWithPipeImpl(useLocalScope, functionsToDefine, variablesToDefine, errorHandlingBehavior, - dollarUnder, input, scriptThis, outputPipe, invocationInfo, args)); - - } - finally - { - if (propagateAllExceptionsToTop) - { - context.PropagateExceptionsToEnclosingStatementBlock = oldPropagateExceptions; - } - } - } + try + { + var runspace = (RunspaceBase)context.CurrentRunspace; + shouldGenerateEvent = !runspace.RunActionIfNoRunningPipelinesWithThreadCheck(() => + InvokeWithPipeImpl(useLocalScope, functionsToDefine, variablesToDefine, errorHandlingBehavior, + dollarUnder, input, scriptThis, outputPipe, invocationInfo, args)); + } + finally + { + if (propagateAllExceptionsToTop) + { + context.PropagateExceptionsToEnclosingStatementBlock = oldPropagateExceptions; + } + } + } if (shouldGenerateEvent) { context.Events.SubscribeEvent( - source: null, - eventName: PSEngineEvent.OnScriptBlockInvoke, - sourceIdentifier: PSEngineEvent.OnScriptBlockInvoke, - data: null, - handlerDelegate: new PSEventReceivedEventHandler(OnScriptBlockInvokeEventHandler), - supportEvent: true, - forwardEvent: false, + source: null, + eventName: PSEngineEvent.OnScriptBlockInvoke, + sourceIdentifier: PSEngineEvent.OnScriptBlockInvoke, + data: null, + handlerDelegate: new PSEventReceivedEventHandler(OnScriptBlockInvokeEventHandler), + supportEvent: true, + forwardEvent: false, shouldQueueAndProcessInExecutionThread: true, - maxTriggerCount: 1); + maxTriggerCount: 1); var scriptBlockInvocationEventArgs = new ScriptBlockInvocationEventArgs( this, useLocalScope, errorHandlingBehavior, dollarUnder, input, scriptThis, outputPipe, invocationInfo, args); context.Events.GenerateEvent( - sourceIdentifier: PSEngineEvent.OnScriptBlockInvoke, - sender: null, - args: new object[1] {scriptBlockInvocationEventArgs}, - extraData: null, + sourceIdentifier: PSEngineEvent.OnScriptBlockInvoke, + sender: null, + args: new object[1] { scriptBlockInvocationEventArgs }, + extraData: null, processInCurrentThread: true, waitForCompletionInCurrentThread: true); @@ -1009,7 +1006,7 @@ namespace System.Management.Automation { var eventArgs = (object)args.SourceEventArgs as ScriptBlockInvocationEventArgs; Diagnostics.Assert(eventArgs != null, "Event Arguments to OnScriptBlockInvokeEventHandler should not be null"); - + try { ScriptBlock sb = eventArgs.ScriptBlock; @@ -1021,7 +1018,7 @@ namespace System.Management.Automation } } - internal void SetPSScriptRootAndPSCommandPath (MutableTuple locals, ExecutionContext context) + internal void SetPSScriptRootAndPSCommandPath(MutableTuple locals, ExecutionContext context) { var psScriptRoot = string.Empty; var psCommandPath = string.Empty; @@ -1334,7 +1331,6 @@ namespace System.Management.Automation /// internal sealed class ScriptBlockInvocationEventArgs : EventArgs { - /// /// Constructs ScriptBlockInvocationEventArgs /// @@ -1357,14 +1353,14 @@ namespace System.Management.Automation /// The arguments to this script. /// scriptBlock is null /// - internal ScriptBlockInvocationEventArgs(ScriptBlock scriptBlock, - bool useLocalScope, - ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, - object dollarUnder, - object input, - object scriptThis, - Pipe outputPipe, - InvocationInfo invocationInfo, + internal ScriptBlockInvocationEventArgs(ScriptBlock scriptBlock, + bool useLocalScope, + ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior, + object dollarUnder, + object input, + object scriptThis, + Pipe outputPipe, + InvocationInfo invocationInfo, object[] args) { if (scriptBlock == null) @@ -1388,9 +1384,9 @@ namespace System.Management.Automation internal ScriptBlock.ErrorHandlingBehavior ErrorHandlingBehavior { get; set; } internal object DollarUnder { get; set; } internal object Input { get; set; } - internal object ScriptThis {get; set; } + internal object ScriptThis { get; set; } internal Pipe OutputPipe { get; set; } - internal InvocationInfo InvocationInfo {get; set; } + internal InvocationInfo InvocationInfo { get; set; } internal object[] Args { get; set; } /// diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 590cfa0ab..ebe62123b 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -19,9 +19,9 @@ namespace System.Management.Automation.Language object VisitErrorStatement(ErrorStatementAst errorStatementAst); /// object VisitErrorExpression(ErrorExpressionAst errorExpressionAst); - + #region Script Blocks - + /// object VisitScriptBlock(ScriptBlockAst scriptBlockAst); /// @@ -38,7 +38,7 @@ namespace System.Management.Automation.Language object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst); /// object VisitParameter(ParameterAst parameterAst); - + #endregion Script Blocks #region Statements @@ -328,9 +328,9 @@ namespace System.Management.Automation.Language protected AstSearcher(Func callback, bool stopOnFirst, bool searchNestedScriptBlocks) { - this._callback = callback; - this._stopOnFirst = stopOnFirst; - this._searchNestedScriptBlocks = searchNestedScriptBlocks; + _callback = callback; + _stopOnFirst = stopOnFirst; + _searchNestedScriptBlocks = searchNestedScriptBlocks; this.Results = new List(); } @@ -537,7 +537,6 @@ namespace System.Management.Automation.Language public virtual object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return null; } /// public virtual object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return null; } - } /// diff --git a/src/System.Management.Automation/engine/parser/CharTraits.cs b/src/System.Management.Automation/engine/parser/CharTraits.cs index d941b83dd..c652175fc 100644 --- a/src/System.Management.Automation/engine/parser/CharTraits.cs +++ b/src/System.Management.Automation/engine/parser/CharTraits.cs @@ -25,40 +25,39 @@ namespace System.Management.Automation.Language internal const char QuoteDoubleLeft = (char)0x201c; // left double quotation mark internal const char QuoteDoubleRight = (char)0x201d; // right double quotation mark internal const char QuoteLowDoubleLeft = (char)0x201E; // low double left quote used in german. - } [Flags] internal enum CharTraits { - None = 0x0000, + None = 0x0000, // For identifiers, is the character a letter? - IdentifierStart = 0x0002, + IdentifierStart = 0x0002, // The character is a valid first character of a multiplier - MultiplierStart = 0x0004, + MultiplierStart = 0x0004, // The character is a valid type suffix for numeric literals - TypeSuffix = 0x0008, + TypeSuffix = 0x0008, // The character is a whitespace character - Whitespace = 0x0010, + Whitespace = 0x0010, // The character terminates a line. - Newline = 0x0020, + Newline = 0x0020, // The character is a hexadecimal digit. - HexDigit = 0x0040, + HexDigit = 0x0040, // The character is a decimal digit. - Digit = 0x0080, + Digit = 0x0080, // The character is allowed as the first character in an unbraced variable name. - VarNameFirst = 0x0100, + VarNameFirst = 0x0100, // The character is not part of the token being scanned. - ForceStartNewToken = 0x0200, + ForceStartNewToken = 0x0200, // The character is not part of the token being scanned, when the token is known to be part of an assembly name. ForceStartNewAssemblyNameSpecToken = 0x0400, @@ -71,10 +70,10 @@ namespace System.Management.Automation.Language { static CharExtensions() { - Diagnostics.Assert(_traits.Length == 128, "Extention methods rely on this table size."); + Diagnostics.Assert(s_traits.Length == 128, "Extention methods rely on this table size."); } - private static readonly CharTraits[] _traits = new CharTraits[] + private static readonly CharTraits[] s_traits = new CharTraits[] { /* 0x0 */ CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0x1 */ CharTraits.None, @@ -212,7 +211,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.Whitespace) != 0; + return (s_traits[c] & CharTraits.Whitespace) != 0; } if (c <= 256) @@ -229,9 +228,9 @@ namespace System.Management.Automation.Language internal static bool IsDash(this char c) { return (c == '-' - || c == SpecialChars.EnDash - || c == SpecialChars.EmDash - || c == SpecialChars.HorizontalBar); + || c == SpecialChars.EnDash + || c == SpecialChars.EmDash + || c == SpecialChars.HorizontalBar); } // Return true if the character is any of the normal or special @@ -239,10 +238,10 @@ namespace System.Management.Automation.Language internal static bool IsSingleQuote(this char c) { return (c == '\'' - || c == SpecialChars.QuoteSingleLeft - || c == SpecialChars.QuoteSingleRight - || c == SpecialChars.QuoteSingleBase - || c == SpecialChars.QuoteReversed); + || c == SpecialChars.QuoteSingleLeft + || c == SpecialChars.QuoteSingleRight + || c == SpecialChars.QuoteSingleBase + || c == SpecialChars.QuoteReversed); } // Return true if the character is any of the normal or special @@ -250,9 +249,9 @@ namespace System.Management.Automation.Language internal static bool IsDoubleQuote(this char c) { return (c == '"' - || c == SpecialChars.QuoteDoubleLeft - || c == SpecialChars.QuoteDoubleRight - || c == SpecialChars.QuoteLowDoubleLeft); + || c == SpecialChars.QuoteDoubleLeft + || c == SpecialChars.QuoteDoubleRight + || c == SpecialChars.QuoteLowDoubleLeft); } // Return true if the character can be the first character of @@ -261,7 +260,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.VarNameFirst) != 0; + return (s_traits[c] & CharTraits.VarNameFirst) != 0; } return char.IsLetterOrDigit(c); } @@ -272,7 +271,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.IdentifierStart) != 0; + return (s_traits[c] & CharTraits.IdentifierStart) != 0; } return char.IsLetter(c); } @@ -283,7 +282,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & (CharTraits.IdentifierStart | CharTraits.Digit)) != 0; + return (s_traits[c] & (CharTraits.IdentifierStart | CharTraits.Digit)) != 0; } return char.IsLetterOrDigit(c); } @@ -293,7 +292,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.HexDigit) != 0; + return (s_traits[c] & CharTraits.HexDigit) != 0; } return false; } @@ -303,7 +302,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.Digit) != 0; + return (s_traits[c] & CharTraits.Digit) != 0; } return false; } @@ -313,7 +312,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.TypeSuffix) != 0; + return (s_traits[c] & CharTraits.TypeSuffix) != 0; } return false; } @@ -323,7 +322,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.MultiplierStart) != 0; + return (s_traits[c] & CharTraits.MultiplierStart) != 0; } return false; } @@ -336,7 +335,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.ForceStartNewToken) != 0; + return (s_traits[c] & CharTraits.ForceStartNewToken) != 0; } return c.IsWhitespace(); @@ -348,7 +347,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.ForceStartNewTokenAfterNumber) != 0; + return (s_traits[c] & CharTraits.ForceStartNewTokenAfterNumber) != 0; } return c.IsDash(); @@ -360,7 +359,7 @@ namespace System.Management.Automation.Language { if (c < 128) { - return (_traits[c] & CharTraits.ForceStartNewAssemblyNameSpecToken) != 0; + return (s_traits[c] & CharTraits.ForceStartNewAssemblyNameSpecToken) != 0; } return c.IsWhitespace(); diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index a1fc14fc8..79caa8e5b 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -32,490 +32,490 @@ namespace System.Management.Automation.Language internal const BindingFlags staticFlags = BindingFlags.Static | BindingFlags.NonPublic; internal const BindingFlags staticPublicFlags = BindingFlags.Static | BindingFlags.Public; internal const BindingFlags instancePublicFlags = BindingFlags.Instance | BindingFlags.Public; - + internal static readonly ConstructorInfo ObjectList_ctor = typeof(List).GetConstructor(PSTypeExtensions.EmptyTypes); internal static readonly MethodInfo ObjectList_ToArray = - typeof(List).GetMethod("ToArray", PSTypeExtensions.EmptyTypes); + typeof(List).GetMethod(nameof(List.ToArray), PSTypeExtensions.EmptyTypes); internal static readonly MethodInfo ArrayOps_GetMDArrayValue = - typeof(ArrayOps).GetMethod("GetMDArrayValue", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValue), staticFlags); internal static readonly MethodInfo ArrayOps_GetMDArrayValueOrSlice = - typeof(ArrayOps).GetMethod("GetMDArrayValueOrSlice", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValueOrSlice), staticFlags); internal static readonly MethodInfo ArrayOps_GetNonIndexable = - typeof(ArrayOps).GetMethod("GetNonIndexable", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetNonIndexable), staticFlags); internal static readonly MethodInfo ArrayOps_IndexStringMessage = - typeof(ArrayOps).GetMethod("IndexStringMessage", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.IndexStringMessage), staticFlags); internal static readonly MethodInfo ArrayOps_Multiply = - typeof(ArrayOps).GetMethod("Multiply", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.Multiply), staticFlags); internal static readonly MethodInfo ArrayOps_SetMDArrayValue = - typeof(ArrayOps).GetMethod("SetMDArrayValue", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.SetMDArrayValue), staticFlags); internal static readonly MethodInfo ArrayOps_SlicingIndex = - typeof(ArrayOps).GetMethod("SlicingIndex", staticFlags); + typeof(ArrayOps).GetMethod(nameof(ArrayOps.SlicingIndex), staticFlags); internal static readonly ConstructorInfo BreakException_ctor = typeof(BreakException).GetConstructor(instanceFlags, null, CallingConventions.Standard, - new Type[] {typeof(string)}, null); + new Type[] { typeof(string) }, null); internal static readonly MethodInfo CharOps_CompareIeq = - typeof(CharOps).GetMethod("CompareIeq", staticFlags); + typeof(CharOps).GetMethod(nameof(CharOps.CompareIeq), staticFlags); internal static readonly MethodInfo CharOps_CompareIne = - typeof(CharOps).GetMethod("CompareIne", staticFlags); + typeof(CharOps).GetMethod(nameof(CharOps.CompareIne), staticFlags); internal static readonly MethodInfo CharOps_CompareStringIeq = - typeof(CharOps).GetMethod("CompareStringIeq", staticFlags); + typeof(CharOps).GetMethod(nameof(CharOps.CompareStringIeq), staticFlags); internal static readonly MethodInfo CharOps_CompareStringIne = - typeof(CharOps).GetMethod("CompareStringIne", staticFlags); + typeof(CharOps).GetMethod(nameof(CharOps.CompareStringIne), staticFlags); internal static readonly MethodInfo CommandParameterInternal_CreateArgument = - typeof(CommandParameterInternal).GetMethod("CreateArgument", staticFlags); + typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateArgument), staticFlags); internal static readonly MethodInfo CommandParameterInternal_CreateParameter = - typeof(CommandParameterInternal).GetMethod("CreateParameter", staticFlags); + typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateParameter), staticFlags); internal static readonly MethodInfo CommandParameterInternal_CreateParameterWithArgument = - typeof(CommandParameterInternal).GetMethod("CreateParameterWithArgument", staticFlags); + typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateParameterWithArgument), staticFlags); internal static readonly MethodInfo CommandProcessorBase_CheckForSevereException = - typeof(CommandProcessorBase).GetMethod("CheckForSevereException", staticFlags); + typeof(CommandProcessorBase).GetMethod(nameof(CommandProcessorBase.CheckForSevereException), staticFlags); internal static readonly MethodInfo CommandRedirection_UnbindForExpression = - typeof(CommandRedirection).GetMethod("UnbindForExpression", instanceFlags); + typeof(CommandRedirection).GetMethod(nameof(CommandRedirection.UnbindForExpression), instanceFlags); internal static readonly ConstructorInfo ContinueException_ctor = typeof(ContinueException).GetConstructor(instanceFlags, null, CallingConventions.Standard, - new Type[] {typeof(string)}, null); + new Type[] { typeof(string) }, null); internal static readonly MethodInfo Convert_ChangeType = - typeof(Convert).GetMethod("ChangeType", new Type[] {typeof(object), typeof(Type)}); + typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }); internal static readonly MethodInfo Debugger_EnterScriptFunction = - typeof(ScriptDebugger).GetMethod("EnterScriptFunction", instanceFlags); + typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.EnterScriptFunction), instanceFlags); internal static readonly MethodInfo Debugger_ExitScriptFunction = - typeof(ScriptDebugger).GetMethod("ExitScriptFunction", instanceFlags); + typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.ExitScriptFunction), instanceFlags); internal static readonly MethodInfo Debugger_OnSequencePointHit = - typeof(ScriptDebugger).GetMethod("OnSequencePointHit", instanceFlags); + typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.OnSequencePointHit), instanceFlags); internal static readonly MethodInfo EnumerableOps_AddEnumerable = - typeof(EnumerableOps).GetMethod("AddEnumerable", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.AddEnumerable), staticFlags); internal static readonly MethodInfo EnumerableOps_AddObject = - typeof(EnumerableOps).GetMethod("AddObject", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.AddObject), staticFlags); internal static readonly MethodInfo EnumerableOps_Compare = - typeof(EnumerableOps).GetMethod("Compare", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Compare), staticFlags); internal static readonly MethodInfo EnumerableOps_Current = - typeof(EnumerableOps).GetMethod("Current", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Current), staticFlags); internal static readonly MethodInfo EnumerableOps_GetEnumerator = - typeof(EnumerableOps).GetMethod("GetEnumerator", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetEnumerator), staticFlags); internal static readonly MethodInfo EnumerableOps_GetCOMEnumerator = - typeof(EnumerableOps).GetMethod("GetCOMEnumerator", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetCOMEnumerator), staticFlags); internal static readonly MethodInfo EnumerableOps_GetGenericEnumerator = - typeof(EnumerableOps).GetMethod("GetGenericEnumerator", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetGenericEnumerator), staticFlags); internal static readonly MethodInfo EnumerableOps_GetSlice = - typeof(EnumerableOps).GetMethod("GetSlice", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetSlice), staticFlags); internal static readonly MethodInfo EnumerableOps_MethodInvoker = - typeof(EnumerableOps).GetMethod("MethodInvoker", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.MethodInvoker), staticFlags); internal static readonly MethodInfo EnumerableOps_Where = - typeof(EnumerableOps).GetMethod("Where", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Where), staticFlags); internal static readonly MethodInfo EnumerableOps_ForEach = - typeof(EnumerableOps).GetMethod("ForEach", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.ForEach), staticFlags); internal static readonly MethodInfo EnumerableOps_MoveNext = - typeof(EnumerableOps).GetMethod("MoveNext", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.MoveNext), staticFlags); internal static readonly MethodInfo EnumerableOps_Multiply = - typeof(EnumerableOps).GetMethod("Multiply", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Multiply), staticFlags); internal static readonly MethodInfo EnumerableOps_PropertyGetter = - typeof(EnumerableOps).GetMethod("PropertyGetter", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.PropertyGetter), staticFlags); internal static readonly MethodInfo EnumerableOps_SlicingIndex = - typeof(EnumerableOps).GetMethod("SlicingIndex", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.SlicingIndex), staticFlags); internal static readonly MethodInfo EnumerableOps_ToArray = - typeof(EnumerableOps).GetMethod("ToArray", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.ToArray), staticFlags); internal static readonly MethodInfo EnumerableOps_WriteEnumerableToPipe = - typeof(EnumerableOps).GetMethod("WriteEnumerableToPipe", staticFlags); + typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.WriteEnumerableToPipe), staticFlags); internal static readonly ConstructorInfo ErrorRecord__ctor = typeof(ErrorRecord).GetConstructor(instanceFlags | BindingFlags.Public, null, CallingConventions.Standard, - new Type[] {typeof(ErrorRecord), typeof(RuntimeException)}, null); + new Type[] { typeof(ErrorRecord), typeof(RuntimeException) }, null); internal static readonly PropertyInfo Exception_Message = - typeof(Exception).GetProperty("Message"); + typeof(Exception).GetProperty(nameof(Exception.Message)); internal static readonly MethodInfo ExceptionHandlingOps_CheckActionPreference = - typeof(ExceptionHandlingOps).GetMethod("CheckActionPreference", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.CheckActionPreference), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_ConvertToArgumentConversionException = - typeof(ExceptionHandlingOps).GetMethod("ConvertToArgumentConversionException", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToArgumentConversionException), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_ConvertToException = - typeof(ExceptionHandlingOps).GetMethod("ConvertToException", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToException), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_ConvertToMethodInvocationException = - typeof(ExceptionHandlingOps).GetMethod("ConvertToMethodInvocationException", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToMethodInvocationException), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_ConvertToRuntimeException = - typeof(ExceptionHandlingOps).GetMethod("ConvertToRuntimeException", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToRuntimeException), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_FindMatchingHandler = - typeof(ExceptionHandlingOps).GetMethod("FindMatchingHandler", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.FindMatchingHandler), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_RestoreStoppingPipeline = - typeof(ExceptionHandlingOps).GetMethod("RestoreStoppingPipeline", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.RestoreStoppingPipeline), staticFlags); internal static readonly MethodInfo ExceptionHandlingOps_SuspendStoppingPipeline = - typeof(ExceptionHandlingOps).GetMethod("SuspendStoppingPipeline", staticFlags); + typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.SuspendStoppingPipeline), staticFlags); internal static readonly PropertyInfo ExecutionContext_CurrentExceptionBeingHandled = - typeof(ExecutionContext).GetProperty("CurrentExceptionBeingHandled", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.CurrentExceptionBeingHandled), instanceFlags); internal static readonly FieldInfo ExecutionContext_Debugger = - typeof(ExecutionContext).GetField("_debugger", instanceFlags); + typeof(ExecutionContext).GetField(nameof(ExecutionContext._debugger), instanceFlags); internal static readonly FieldInfo ExecutionContext_DebuggingMode = - typeof(ExecutionContext).GetField("_debuggingMode", instanceFlags); + typeof(ExecutionContext).GetField(nameof(ExecutionContext._debuggingMode), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ExceptionHandlerInEnclosingStatementBlock = - typeof(ExecutionContext).GetProperty("PropagateExceptionsToEnclosingStatementBlock", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.PropagateExceptionsToEnclosingStatementBlock), instanceFlags); internal static readonly MethodInfo ExecutionContext_IsStrictVersion = - typeof(ExecutionContext).GetMethod("IsStrictVersion", staticFlags); + typeof(ExecutionContext).GetMethod(nameof(ExecutionContext.IsStrictVersion), staticFlags); internal static readonly PropertyInfo ExecutionContext_QuestionMarkVariableValue = - typeof(ExecutionContext).GetProperty("QuestionMarkVariableValue", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.QuestionMarkVariableValue), instanceFlags); internal static readonly PropertyInfo ExecutionContext_LanguageMode = - typeof(ExecutionContext).GetProperty("LanguageMode", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.LanguageMode), instanceFlags); internal static readonly PropertyInfo ExecutionContext_EngineIntrinsics = - typeof(ExecutionContext).GetProperty("EngineIntrinsics", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.EngineIntrinsics), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ShellFunctionErrorOutputPipe = - typeof(ExecutionContext).GetProperty("ShellFunctionErrorOutputPipe", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.ShellFunctionErrorOutputPipe), instanceFlags); internal static readonly PropertyInfo ExecutionContext_TypeTable = - typeof(ExecutionContext).GetProperty("TypeTable", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.TypeTable), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ExpressionWarningOutputPipe = - typeof(ExecutionContext).GetProperty("ExpressionWarningOutputPipe", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.ExpressionWarningOutputPipe), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ExpressionVerboseOutputPipe = - typeof(ExecutionContext).GetProperty("ExpressionVerboseOutputPipe", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.ExpressionVerboseOutputPipe), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ExpressionDebugOutputPipe = - typeof(ExecutionContext).GetProperty("ExpressionDebugOutputPipe", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.ExpressionDebugOutputPipe), instanceFlags); internal static readonly PropertyInfo ExecutionContext_ExpressionInformationOutputPipe = - typeof(ExecutionContext).GetProperty("ExpressionInformationOutputPipe", instanceFlags); + typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.ExpressionInformationOutputPipe), instanceFlags); internal static readonly MethodInfo FileRedirection_BindForExpression = - typeof(FileRedirection).GetMethod("BindForExpression", instanceFlags); + typeof(FileRedirection).GetMethod(nameof(FileRedirection.BindForExpression), instanceFlags); internal static readonly ConstructorInfo FileRedirection_ctor = typeof(FileRedirection).GetConstructor(instanceFlags, null, CallingConventions.Standard, - new Type[] {typeof(RedirectionStream), typeof(bool), typeof(string)}, null); + new Type[] { typeof(RedirectionStream), typeof(bool), typeof(string) }, null); internal static readonly MethodInfo FileRedirection_Dispose = - typeof(FileRedirection).GetMethod("Dispose"); + typeof(FileRedirection).GetMethod(nameof(FileRedirection.Dispose)); internal static readonly FieldInfo FunctionContext__currentSequencePointIndex = - typeof(FunctionContext).GetField("_currentSequencePointIndex", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._currentSequencePointIndex), instanceFlags); internal static readonly FieldInfo FunctionContext__executionContext = - typeof(FunctionContext).GetField("_executionContext", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._executionContext), instanceFlags); internal static readonly FieldInfo FunctionContext__functionName = - typeof(FunctionContext).GetField("_functionName", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._functionName), instanceFlags); internal static readonly FieldInfo FunctionContext__localsTuple = - typeof(FunctionContext).GetField("_localsTuple", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._localsTuple), instanceFlags); internal static readonly FieldInfo FunctionContext__outputPipe = - typeof(FunctionContext).GetField("_outputPipe", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._outputPipe), instanceFlags); internal static readonly FieldInfo FunctionContext__traps = - typeof(FunctionContext).GetField("_traps", instanceFlags); + typeof(FunctionContext).GetField(nameof(FunctionContext._traps), instanceFlags); internal static readonly MethodInfo FunctionContext_PopTrapHandlers = - typeof(FunctionContext).GetMethod("PopTrapHandlers", instanceFlags); + typeof(FunctionContext).GetMethod(nameof(FunctionContext.PopTrapHandlers), instanceFlags); internal static readonly MethodInfo FunctionContext_PushTrapHandlers = - typeof(FunctionContext).GetMethod("PushTrapHandlers", instanceFlags); + typeof(FunctionContext).GetMethod(nameof(FunctionContext.PushTrapHandlers), instanceFlags); internal static readonly MethodInfo FunctionOps_DefineFunction = - typeof(FunctionOps).GetMethod("DefineFunction", staticFlags); + typeof(FunctionOps).GetMethod(nameof(FunctionOps.DefineFunction), staticFlags); internal static readonly MethodInfo FunctionOps_DefineWorkflows = - typeof(FunctionOps).GetMethod("DefineWorkflows", staticFlags); + typeof(FunctionOps).GetMethod(nameof(FunctionOps.DefineWorkflows), staticFlags); internal static readonly ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Standard, new Type[] { typeof(int), typeof(IEqualityComparer) }, null); internal static readonly MethodInfo HashtableOps_Add = - typeof(HashtableOps).GetMethod("Add", staticFlags); + typeof(HashtableOps).GetMethod(nameof(HashtableOps.Add), staticFlags); internal static readonly MethodInfo HashtableOps_AddKeyValuePair = - typeof(HashtableOps).GetMethod("AddKeyValuePair", staticFlags); + typeof(HashtableOps).GetMethod(nameof(HashtableOps.AddKeyValuePair), staticFlags); internal static readonly PropertyInfo ICollection_Count = - typeof(ICollection).GetProperty("Count"); + typeof(ICollection).GetProperty(nameof(ICollection.Count)); internal static readonly MethodInfo IComparable_CompareTo = - typeof(IComparable).GetMethod("CompareTo"); + typeof(IComparable).GetMethod(nameof(IComparable.CompareTo)); internal static readonly MethodInfo IDictionary_set_Item = typeof(IDictionary).GetMethod("set_Item"); internal static readonly MethodInfo IDisposable_Dispose = - typeof(IDisposable).GetMethod("Dispose"); + typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose)); internal static readonly MethodInfo IEnumerable_GetEnumerator = - typeof(IEnumerable).GetMethod("GetEnumerator"); + typeof(IEnumerable).GetMethod(nameof(IEnumerable.GetEnumerator)); internal static readonly PropertyInfo IEnumerator_Current = - typeof(IEnumerator).GetProperty("Current"); + typeof(IEnumerator).GetProperty(nameof(IEnumerator.Current)); internal static readonly MethodInfo IEnumerator_MoveNext = - typeof(IEnumerator).GetMethod("MoveNext"); + typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext)); internal static readonly MethodInfo IList_get_Item = typeof(IList).GetMethod("get_Item"); internal static readonly MethodInfo InterpreterError_NewInterpreterException = - typeof(InterpreterError).GetMethod("NewInterpreterException", staticFlags); + typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterException), staticFlags); internal static readonly MethodInfo InterpreterError_NewInterpreterExceptionWithInnerException = - typeof(InterpreterError).GetMethod("NewInterpreterExceptionWithInnerException", staticFlags); + typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterExceptionWithInnerException), staticFlags); internal static readonly MethodInfo IntOps_Range = - typeof(IntOps).GetMethod("Range", staticFlags); + typeof(IntOps).GetMethod(nameof(IntOps.Range), staticFlags); internal static readonly MethodInfo LanguagePrimitives_GetInvalidCastMessages = - typeof(LanguagePrimitives).GetMethod("GetInvalidCastMessages", staticFlags); + typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.GetInvalidCastMessages), staticFlags); internal static readonly MethodInfo LanguagePrimitives_ThrowInvalidCastException = - typeof(LanguagePrimitives).GetMethod("ThrowInvalidCastException", staticFlags); + typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.ThrowInvalidCastException), staticFlags); internal static readonly MethodInfo LocalPipeline_GetExecutionContextFromTLS = - typeof(LocalPipeline).GetMethod("GetExecutionContextFromTLS", staticFlags); + typeof(LocalPipeline).GetMethod(nameof(LocalPipeline.GetExecutionContextFromTLS), staticFlags); internal static readonly MethodInfo LoopFlowException_MatchLabel = - typeof(LoopFlowException).GetMethod("MatchLabel", instanceFlags); + typeof(LoopFlowException).GetMethod(nameof(LoopFlowException.MatchLabel), instanceFlags); internal static readonly MethodInfo MergingRedirection_BindForExpression = - typeof(MergingRedirection).GetMethod("BindForExpression", instanceFlags); + typeof(MergingRedirection).GetMethod(nameof(MergingRedirection.BindForExpression), instanceFlags); internal static readonly ConstructorInfo MethodException_ctor = typeof(MethodException).GetConstructor(instanceFlags, null, - new Type[] {typeof(string), typeof(Exception), typeof(string), typeof(object[])}, null); + new Type[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, null); internal static readonly MethodInfo MutableTuple_IsValueSet = - typeof(MutableTuple).GetMethod("IsValueSet", instanceFlags); + typeof(MutableTuple).GetMethod(nameof(MutableTuple.IsValueSet), instanceFlags); internal static readonly MethodInfo Object_Equals = - typeof(object).GetMethod("Equals", new Type[] { typeof(object) } ); + typeof(object).GetMethod(nameof(object.Equals), new Type[] { typeof(object) }); internal static readonly ConstructorInfo OrderedDictionary_ctor = typeof(OrderedDictionary).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, - CallingConventions.Standard, new Type[] {typeof(int), typeof(IEqualityComparer)}, null); + CallingConventions.Standard, new Type[] { typeof(int), typeof(IEqualityComparer) }, null); internal static readonly MethodInfo Parser_ScanNumber = - typeof(Parser).GetMethod("ScanNumber", staticFlags); + typeof(Parser).GetMethod(nameof(Parser.ScanNumber), staticFlags); internal static readonly MethodInfo ParserOps_ContainsOperatorCompiled = - typeof(ParserOps).GetMethod("ContainsOperatorCompiled", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.ContainsOperatorCompiled), staticFlags); internal static readonly MethodInfo ParserOps_ImplicitOp = - typeof(ParserOps).GetMethod("ImplicitOp", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.ImplicitOp), staticFlags); internal static readonly MethodInfo ParserOps_JoinOperator = - typeof(ParserOps).GetMethod("JoinOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.JoinOperator), staticFlags); internal static readonly MethodInfo ParserOps_LikeOperator = - typeof(ParserOps).GetMethod("LikeOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.LikeOperator), staticFlags); internal static readonly MethodInfo ParserOps_MatchOperator = - typeof(ParserOps).GetMethod("MatchOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.MatchOperator), staticFlags); internal static readonly MethodInfo ParserOps_ReplaceOperator = - typeof(ParserOps).GetMethod("ReplaceOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.ReplaceOperator), staticFlags); internal static readonly MethodInfo ParserOps_SplitOperator = - typeof(ParserOps).GetMethod("SplitOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.SplitOperator), staticFlags); internal static readonly MethodInfo ParserOps_UnaryJoinOperator = - typeof(ParserOps).GetMethod("UnaryJoinOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.UnaryJoinOperator), staticFlags); internal static readonly MethodInfo ParserOps_UnarySplitOperator = - typeof(ParserOps).GetMethod("UnarySplitOperator", staticFlags); + typeof(ParserOps).GetMethod(nameof(ParserOps.UnarySplitOperator), staticFlags); internal static readonly ConstructorInfo Pipe_ctor = typeof(Pipe).GetConstructor(instanceFlags, null, CallingConventions.Standard, new Type[] { typeof(List) }, null); internal static readonly MethodInfo Pipe_Add = - typeof(Pipe).GetMethod("Add", instanceFlags); + typeof(Pipe).GetMethod(nameof(Pipe.Add), instanceFlags); internal static readonly MethodInfo Pipe_SetVariableListForTemporaryPipe = - typeof(Pipe).GetMethod("SetVariableListForTemporaryPipe", instanceFlags); + typeof(Pipe).GetMethod(nameof(Pipe.SetVariableListForTemporaryPipe), instanceFlags); internal static readonly MethodInfo PipelineOps_CheckAutomationNullInCommandArgument = - typeof(PipelineOps).GetMethod("CheckAutomationNullInCommandArgument", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckAutomationNullInCommandArgument), staticFlags); internal static readonly MethodInfo PipelineOps_CheckAutomationNullInCommandArgumentArray = - typeof(PipelineOps).GetMethod("CheckAutomationNullInCommandArgumentArray", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckAutomationNullInCommandArgumentArray), staticFlags); internal static readonly MethodInfo PipelineOps_CheckForInterrupts = - typeof(PipelineOps).GetMethod("CheckForInterrupts", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckForInterrupts), staticFlags); internal static readonly MethodInfo PipelineOps_GetExitException = - typeof(PipelineOps).GetMethod("GetExitException", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.GetExitException), staticFlags); internal static readonly MethodInfo PipelineOps_FlushPipe = - typeof(PipelineOps).GetMethod("FlushPipe", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.FlushPipe), staticFlags); internal static readonly MethodInfo PipelineOps_InvokePipeline = - typeof(PipelineOps).GetMethod("InvokePipeline", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.InvokePipeline), staticFlags); internal static readonly MethodInfo PipelineOps_Nop = - typeof(PipelineOps).GetMethod("Nop", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.Nop), staticFlags); internal static readonly MethodInfo PipelineOps_PipelineResult = - typeof(PipelineOps).GetMethod("PipelineResult", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.PipelineResult), staticFlags); internal static readonly MethodInfo PipelineOps_ClearPipe = - typeof(PipelineOps).GetMethod("ClearPipe", staticFlags); + typeof(PipelineOps).GetMethod(nameof(PipelineOps.ClearPipe), staticFlags); internal static readonly MethodInfo PSGetDynamicMemberBinder_GetIDictionaryMember = - typeof(PSGetDynamicMemberBinder).GetMethod("GetIDictionaryMember", staticFlags); + typeof(PSGetDynamicMemberBinder).GetMethod(nameof(PSGetDynamicMemberBinder.GetIDictionaryMember), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_CloneMemberInfo = - typeof(PSGetMemberBinder).GetMethod("CloneMemberInfo", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.CloneMemberInfo), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_GetAdaptedValue = - typeof(PSGetMemberBinder).GetMethod("GetAdaptedValue", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.GetAdaptedValue), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_GetTypeTableFromTLS = - typeof(PSGetMemberBinder).GetMethod("GetTypeTableFromTLS", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.GetTypeTableFromTLS), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_IsTypeNameSame = - typeof(PSGetMemberBinder).GetMethod("IsTypeNameSame", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.IsTypeNameSame), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_TryGetGenericDictionaryValue = - typeof(PSGetMemberBinder).GetMethod("TryGetGenericDictionaryValue", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetGenericDictionaryValue), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_TryGetInstanceMember = - typeof(PSGetMemberBinder).GetMethod("TryGetInstanceMember", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetInstanceMember), staticFlags); internal static readonly MethodInfo PSGetMemberBinder_TryGetIDictionaryValue = - typeof(PSGetMemberBinder).GetMethod("TryGetIDictionaryValue", staticFlags); + typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetIDictionaryValue), staticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_InvokeAdaptedMember = - typeof(PSInvokeMemberBinder).GetMethod("InvokeAdaptedMember", staticFlags); + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.InvokeAdaptedMember), staticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_InvokeAdaptedSetMember = - typeof(PSInvokeMemberBinder).GetMethod("InvokeAdaptedSetMember", staticFlags); + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.InvokeAdaptedSetMember), staticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_IsHeterogeneousArray = - typeof(PSInvokeMemberBinder).GetMethod("IsHeterogeneousArray", staticFlags); + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHeterogeneousArray), staticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogenousArray = - typeof(PSInvokeMemberBinder).GetMethod("IsHomogenousArray", staticFlags); + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogenousArray), staticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_TryGetInstanceMethod = - typeof(PSInvokeMemberBinder).GetMethod("TryGetInstanceMethod", staticFlags); + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.TryGetInstanceMethod), staticFlags); internal static readonly MethodInfo PSMethodInfo_Invoke = - typeof(PSMethodInfo).GetMethod("Invoke"); + typeof(PSMethodInfo).GetMethod(nameof(PSMethodInfo.Invoke)); internal static readonly PropertyInfo PSNoteProperty_Value = - typeof(PSNoteProperty).GetProperty("Value"); + typeof(PSNoteProperty).GetProperty(nameof(PSNoteProperty.Value)); internal static readonly MethodInfo PSObject_Base = - typeof(PSObject).GetMethod("Base", staticFlags); + typeof(PSObject).GetMethod(nameof(PSObject.Base), staticFlags); internal static readonly PropertyInfo PSObject_BaseObject = - typeof(PSObject).GetProperty("BaseObject"); + typeof(PSObject).GetProperty(nameof(PSObject.BaseObject)); internal static readonly FieldInfo PSObject_isDeserialized = - typeof(PSObject).GetField("isDeserialized", instanceFlags); + typeof(PSObject).GetField(nameof(PSObject.isDeserialized), instanceFlags); internal static readonly MethodInfo PSObject_ToStringParser = - typeof(PSObject).GetMethod("ToStringParser", staticFlags); + typeof(PSObject).GetMethod(nameof(PSObject.ToStringParser), staticFlags); internal static readonly PropertyInfo PSReference_Value = - typeof(PSReference).GetProperty("Value"); + typeof(PSReference).GetProperty(nameof(PSReference.Value)); internal static readonly MethodInfo PSScriptMethod_InvokeScript = - typeof(PSScriptMethod).GetMethod("InvokeScript", staticFlags); + typeof(PSScriptMethod).GetMethod(nameof(PSScriptMethod.InvokeScript), staticFlags); internal static readonly MethodInfo PSScriptProperty_InvokeGetter = - typeof(PSScriptProperty).GetMethod("InvokeGetter", instanceFlags); + typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeGetter), instanceFlags); internal static readonly MethodInfo PSScriptProperty_InvokeSetter = - typeof(PSScriptProperty).GetMethod("InvokeSetter", instanceFlags); + typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeSetter), instanceFlags); internal static readonly MethodInfo PSSetMemberBinder_SetAdaptedValue = - typeof(PSSetMemberBinder).GetMethod("SetAdaptedValue", staticFlags); + typeof(PSSetMemberBinder).GetMethod(nameof(PSSetMemberBinder.SetAdaptedValue), staticFlags); internal static readonly MethodInfo PSVariableAssignmentBinder_CopyInstanceMembersOfValueType = - typeof(PSVariableAssignmentBinder).GetMethod("CopyInstanceMembersOfValueType", staticFlags); + typeof(PSVariableAssignmentBinder).GetMethod(nameof(PSVariableAssignmentBinder.CopyInstanceMembersOfValueType), staticFlags); internal static readonly FieldInfo PSVariableAssignmentBinder__mutableValueWithInstanceMemberVersion = - typeof(PSVariableAssignmentBinder).GetField("_mutableValueWithInstanceMemberVersion", staticFlags); + typeof(PSVariableAssignmentBinder).GetField(nameof(PSVariableAssignmentBinder.s_mutableValueWithInstanceMemberVersion), staticFlags); internal static readonly MethodInfo PSCreateInstanceBinder_IsTargetTypeNonPublic = - typeof(PSCreateInstanceBinder).GetMethod("IsTargetTypeNonPublic", staticFlags); + typeof(PSCreateInstanceBinder).GetMethod(nameof(PSCreateInstanceBinder.IsTargetTypeNonPublic), staticFlags); internal static readonly MethodInfo PSCreateInstanceBinder_GetTargetTypeName = - typeof(PSCreateInstanceBinder).GetMethod("GetTargetTypeName", staticFlags); + typeof(PSCreateInstanceBinder).GetMethod(nameof(PSCreateInstanceBinder.GetTargetTypeName), staticFlags); internal static readonly ConstructorInfo RangeEnumerator_ctor = - typeof(RangeEnumerator).GetConstructor(new Type[] { typeof(int), typeof(int)}); + typeof(RangeEnumerator).GetConstructor(new Type[] { typeof(int), typeof(int) }); internal static readonly MethodInfo ReservedNameMembers_GeneratePSAdaptedMemberSet = - typeof(ReservedNameMembers).GetMethod("GeneratePSAdaptedMemberSet", staticFlags); + typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSAdaptedMemberSet), staticFlags); internal static readonly MethodInfo ReservedNameMembers_GeneratePSBaseMemberSet = - typeof(ReservedNameMembers).GetMethod("GeneratePSBaseMemberSet", staticFlags); + typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSBaseMemberSet), staticFlags); internal static readonly MethodInfo ReservedNameMembers_GeneratePSExtendedMemberSet = - typeof(ReservedNameMembers).GetMethod("GeneratePSExtendedMemberSet", staticFlags); + typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSExtendedMemberSet), staticFlags); internal static readonly MethodInfo ReservedNameMembers_GeneratePSObjectMemberSet = - typeof(ReservedNameMembers).GetMethod("GeneratePSObjectMemberSet", staticFlags); + typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSObjectMemberSet), staticFlags); internal static readonly MethodInfo ReservedNameMembers_PSTypeNames = - typeof(ReservedNameMembers).GetMethod("PSTypeNames"); + typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.PSTypeNames)); internal static readonly MethodInfo RestrictedLanguageChecker_CheckDataStatementLanguageModeAtRuntime = - typeof(RestrictedLanguageChecker).GetMethod("CheckDataStatementLanguageModeAtRuntime", staticFlags); + typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.CheckDataStatementLanguageModeAtRuntime), staticFlags); internal static readonly MethodInfo RestrictedLanguageChecker_CheckDataStatementAstAtRuntime = - typeof(RestrictedLanguageChecker).GetMethod("CheckDataStatementAstAtRuntime", staticFlags); + typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.CheckDataStatementAstAtRuntime), staticFlags); internal static readonly MethodInfo RestrictedLanguageChecker_EnsureUtilityModuleLoaded = - typeof(RestrictedLanguageChecker).GetMethod("EnsureUtilityModuleLoaded", staticFlags); + typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.EnsureUtilityModuleLoaded), staticFlags); + - internal static readonly ConstructorInfo ReturnException_ctor = typeof(ReturnException).GetConstructor(instanceFlags, null, CallingConventions.Standard, new Type[] { typeof(object) }, null); internal static readonly PropertyInfo RuntimeException_ErrorRecord = - typeof(RuntimeException).GetProperty("ErrorRecord"); + typeof(RuntimeException).GetProperty(nameof(RuntimeException.ErrorRecord)); internal static readonly MethodInfo ScriptBlock_DoInvokeReturnAsIs = - typeof(ScriptBlock).GetMethod("DoInvokeReturnAsIs", instanceFlags); + typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.DoInvokeReturnAsIs), instanceFlags); internal static readonly MethodInfo ScriptBlock_InvokeAsDelegateHelper = - typeof(ScriptBlock).GetMethod("InvokeAsDelegateHelper", instanceFlags); + typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.InvokeAsDelegateHelper), instanceFlags); internal static readonly MethodInfo ScriptBlock_InvokeAsMemberFunction = - typeof(ScriptBlock).GetMethod("InvokeAsMemberFunction", instanceFlags); + typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.InvokeAsMemberFunction), instanceFlags); internal static readonly MethodInfo ScriptBlockExpressionWrapper_GetScriptBlock = - typeof(ScriptBlockExpressionWrapper).GetMethod("GetScriptBlock", instanceFlags); + typeof(ScriptBlockExpressionWrapper).GetMethod(nameof(ScriptBlockExpressionWrapper.GetScriptBlock), instanceFlags); internal static readonly ConstructorInfo SetValueException_ctor = typeof(SetValueException).GetConstructor(instanceFlags, null, - new [] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, null); + new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, null); internal static readonly ConstructorInfo GetValueException_ctor = typeof(GetValueException).GetConstructor(instanceFlags, null, new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, null); internal static readonly ConstructorInfo StreamReader_ctor = - typeof(StreamReader).GetConstructor(new Type[] {typeof(string)}); + typeof(StreamReader).GetConstructor(new Type[] { typeof(string) }); internal static readonly MethodInfo StreamReader_ReadLine = - typeof(StreamReader).GetMethod("ReadLine"); + typeof(StreamReader).GetMethod(nameof(StreamReader.ReadLine)); internal static readonly ConstructorInfo String_ctor_char_int = typeof(String).GetConstructor(new Type[] { typeof(char), typeof(int) }); internal static readonly MethodInfo String_Concat_String = - typeof(String).GetMethod("Concat", staticPublicFlags, null, - CallingConventions.Standard, new Type[] {typeof(string), typeof(string)}, null); + typeof(String).GetMethod(nameof(String.Concat), staticPublicFlags, null, + CallingConventions.Standard, new Type[] { typeof(string), typeof(string) }, null); internal static readonly MethodInfo String_Equals = - typeof(String).GetMethod("Equals", staticPublicFlags, null, + typeof(String).GetMethod(nameof(String.Equals), staticPublicFlags, null, CallingConventions.Standard, - new Type[] {typeof(string), typeof(string), typeof(StringComparison)}, null); + new Type[] { typeof(string), typeof(string), typeof(StringComparison) }, null); internal static readonly MethodInfo String_get_Chars = typeof(string).GetMethod("get_Chars"); internal static readonly PropertyInfo String_Length = - typeof(string).GetProperty("Length"); + typeof(string).GetProperty(nameof(String.Length)); internal static readonly MethodInfo StringOps_Compare = - typeof(StringOps).GetMethod("Compare", staticFlags); + typeof(StringOps).GetMethod(nameof(StringOps.Compare), staticFlags); internal static readonly MethodInfo StringOps_Equals = - typeof(StringOps).GetMethod("Equals", staticFlags); + typeof(StringOps).GetMethod(nameof(StringOps.Equals), staticFlags); internal static readonly MethodInfo StringOps_FormatOperator = - typeof(StringOps).GetMethod("FormatOperator", staticFlags); + typeof(StringOps).GetMethod(nameof(StringOps.FormatOperator), staticFlags); internal static readonly MethodInfo StringOps_Multiply = - typeof(StringOps).GetMethod("Multiply", staticFlags); + typeof(StringOps).GetMethod(nameof(StringOps.Multiply), staticFlags); internal static readonly MethodInfo SwitchOps_ConditionSatisfiedRegex = - typeof(SwitchOps).GetMethod("ConditionSatisfiedRegex", staticFlags); + typeof(SwitchOps).GetMethod(nameof(SwitchOps.ConditionSatisfiedRegex), staticFlags); internal static readonly MethodInfo SwitchOps_ConditionSatisfiedWildcard = - typeof(SwitchOps).GetMethod("ConditionSatisfiedWildcard", staticFlags); + typeof(SwitchOps).GetMethod(nameof(SwitchOps.ConditionSatisfiedWildcard), staticFlags); internal static readonly MethodInfo SwitchOps_ResolveFilePath = - typeof(SwitchOps).GetMethod("ResolveFilePath", staticFlags); + typeof(SwitchOps).GetMethod(nameof(SwitchOps.ResolveFilePath), staticFlags); internal static readonly MethodInfo TypeOps_AsOperator = - typeof(TypeOps).GetMethod("AsOperator", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.AsOperator), staticFlags); internal static readonly MethodInfo TypeOps_AddPowerShellTypesToTheScope = - typeof(TypeOps).GetMethod("AddPowerShellTypesToTheScope", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.AddPowerShellTypesToTheScope), staticFlags); internal static readonly MethodInfo TypeOps_InitPowerShellTypesAtRuntime = - typeof(TypeOps).GetMethod("InitPowerShellTypesAtRuntime", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.InitPowerShellTypesAtRuntime), staticFlags); internal static readonly MethodInfo TypeOps_SetCurrentTypeResolutionState = - typeof(TypeOps).GetMethod("SetCurrentTypeResolutionState", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.SetCurrentTypeResolutionState), staticFlags); internal static readonly MethodInfo TypeOps_SetAssemblyDefiningPSTypes = - typeof(TypeOps).GetMethod("SetAssemblyDefiningPSTypes", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.SetAssemblyDefiningPSTypes), staticFlags); internal static readonly MethodInfo TypeOps_IsInstance = - typeof(TypeOps).GetMethod("IsInstance", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.IsInstance), staticFlags); internal static readonly MethodInfo TypeOps_ResolveTypeName = - typeof(TypeOps).GetMethod("ResolveTypeName", staticFlags); + typeof(TypeOps).GetMethod(nameof(TypeOps.ResolveTypeName), staticFlags); internal static readonly MethodInfo VariableOps_GetUsingValue = - typeof(VariableOps).GetMethod("GetUsingValue", staticFlags); + typeof(VariableOps).GetMethod(nameof(VariableOps.GetUsingValue), staticFlags); internal static readonly MethodInfo VariableOps_GetVariableAsRef = - typeof(VariableOps).GetMethod("GetVariableAsRef", staticFlags); + typeof(VariableOps).GetMethod(nameof(VariableOps.GetVariableAsRef), staticFlags); internal static readonly MethodInfo VariableOps_GetVariableValue = - typeof(VariableOps).GetMethod("GetVariableValue", staticFlags); + typeof(VariableOps).GetMethod(nameof(VariableOps.GetVariableValue), staticFlags); internal static readonly MethodInfo VariableOps_GetAutomaticVariableValue = - typeof(VariableOps).GetMethod("GetAutomaticVariableValue", staticFlags); + typeof(VariableOps).GetMethod(nameof(VariableOps.GetAutomaticVariableValue), staticFlags); internal static readonly MethodInfo VariableOps_SetVariableValue = - typeof(VariableOps).GetMethod("SetVariableValue", staticFlags); + typeof(VariableOps).GetMethod(nameof(VariableOps.SetVariableValue), staticFlags); - internal static readonly MethodInfo ClassOps_ValidateSetProperty = - typeof(ClassOps).GetMethod("ValidateSetProperty", staticPublicFlags); + internal static readonly MethodInfo ClassOps_ValidateSetProperty = + typeof(ClassOps).GetMethod(nameof(ClassOps.ValidateSetProperty), staticPublicFlags); internal static readonly MethodInfo ClassOps_CallBaseCtor = - typeof(ClassOps).GetMethod("CallBaseCtor", staticPublicFlags); + typeof(ClassOps).GetMethod(nameof(ClassOps.CallBaseCtor), staticPublicFlags); internal static readonly MethodInfo ClassOps_CallMethodNonVirtually = - typeof(ClassOps).GetMethod("CallMethodNonVirtually", staticPublicFlags); + typeof(ClassOps).GetMethod(nameof(ClassOps.CallMethodNonVirtually), staticPublicFlags); internal static readonly MethodInfo ClassOps_CallVoidMethodNonVirtually = - typeof(ClassOps).GetMethod("CallVoidMethodNonVirtually", staticPublicFlags); + typeof(ClassOps).GetMethod(nameof(ClassOps.CallVoidMethodNonVirtually), staticPublicFlags); internal static readonly MethodInfo ArgumentTransformationAttribute_Transform = - typeof(ArgumentTransformationAttribute).GetMethod("Transform", instancePublicFlags); + typeof(ArgumentTransformationAttribute).GetMethod(nameof(ArgumentTransformationAttribute.Transform), instancePublicFlags); // ReSharper restore InconsistentNaming } @@ -534,7 +534,7 @@ namespace System.Management.Automation.Language internal static readonly Expression NullTypeArray = Expression.Constant(null, typeof(Type[])); internal static readonly Expression NullType = Expression.Constant(null, typeof(Type)); internal static readonly Expression NullDelegateArray = Expression.Constant(null, typeof(Action[])); - internal static readonly Expression NullPipe = Expression.Constant(new Pipe {NullPipe = true}); + internal static readonly Expression NullPipe = Expression.Constant(new Pipe { NullPipe = true }); internal static readonly Expression ConstEmptyString = Expression.Constant(""); internal static readonly Expression CompareOptionsIgnoreCase = Expression.Constant(CompareOptions.IgnoreCase); internal static readonly Expression CompareOptionsNone = Expression.Constant(CompareOptions.None); @@ -551,7 +551,7 @@ namespace System.Management.Automation.Language internal static readonly Expression BoxedFalse = Expression.Field(null, typeof(Boxed).GetField("False", BindingFlags.Static | BindingFlags.NonPublic)); - private static readonly Expression[] _intConstants = new Expression[102]; + private static readonly Expression[] s_intConstants = new Expression[102]; internal static Expression Constant(int i) { @@ -561,11 +561,11 @@ namespace System.Management.Automation.Language return Expression.Constant(i); } - Expression result = _intConstants[i + 1]; + Expression result = s_intConstants[i + 1]; if (result == null) { result = Expression.Constant(i); - _intConstants[i + 1] = result; + s_intConstants[i + 1] = result; } return result; } @@ -579,7 +579,7 @@ namespace System.Management.Automation.Language } } - static class ExpressionExtensions + internal static class ExpressionExtensions { internal static Expression Convert(this Expression expr, Type type) { @@ -679,11 +679,11 @@ namespace System.Management.Automation.Language internal static readonly ParameterExpression _executionContextParameter; internal static readonly ParameterExpression _functionContext; internal static readonly ParameterExpression _returnPipe; - private static readonly Expression _setDollarQuestionToTrue; - private static readonly Expression _callCheckForInterrupts; - private static readonly Expression _getCurrentPipe; - private static readonly Expression _currentExceptionBeingHandled; - private static readonly CatchBlock _catchFlowControl; + private static readonly Expression s_setDollarQuestionToTrue; + private static readonly Expression s_callCheckForInterrupts; + private static readonly Expression s_getCurrentPipe; + private static readonly Expression s_currentExceptionBeingHandled; + private static readonly CatchBlock s_catchFlowControl; internal static readonly CatchBlock[] _stmtCatchHandlers; internal static readonly Type DottedLocalsTupleType = MutableTuple.MakeTupleType(SpecialVariables.AutomaticVariableTypes); @@ -700,28 +700,28 @@ namespace System.Management.Automation.Language _functionContext = Expression.Parameter(typeof(FunctionContext), "funcContext"); _executionContextParameter = Expression.Variable(typeof(ExecutionContext), "context"); - _setDollarQuestionToTrue = Expression.Assign( + s_setDollarQuestionToTrue = Expression.Assign( Expression.Property(_executionContextParameter, CachedReflectionInfo.ExecutionContext_QuestionMarkVariableValue), ExpressionCache.TrueConstant); - _callCheckForInterrupts = Expression.Call(CachedReflectionInfo.PipelineOps_CheckForInterrupts, + s_callCheckForInterrupts = Expression.Call(CachedReflectionInfo.PipelineOps_CheckForInterrupts, _executionContextParameter); - _getCurrentPipe = Expression.Field(_functionContext, CachedReflectionInfo.FunctionContext__outputPipe); - _returnPipe = Expression.Variable(_getCurrentPipe.Type, "returnPipe"); + s_getCurrentPipe = Expression.Field(_functionContext, CachedReflectionInfo.FunctionContext__outputPipe); + _returnPipe = Expression.Variable(s_getCurrentPipe.Type, "returnPipe"); var exception = Expression.Variable(typeof(Exception), "exception"); - _catchFlowControl = Expression.Catch(typeof(FlowControlException), Expression.Rethrow()); + s_catchFlowControl = Expression.Catch(typeof(FlowControlException), Expression.Rethrow()); var catchAll = Expression.Catch( exception, Expression.Block( Expression.Call( CachedReflectionInfo.ExceptionHandlingOps_CheckActionPreference, Compiler._functionContext, exception))); - _stmtCatchHandlers = new CatchBlock[] { _catchFlowControl, catchAll }; + _stmtCatchHandlers = new CatchBlock[] { s_catchFlowControl, catchAll }; - _currentExceptionBeingHandled = Expression.Property( + s_currentExceptionBeingHandled = Expression.Property( _executionContextParameter, CachedReflectionInfo.ExecutionContext_CurrentExceptionBeingHandled); int i; @@ -736,14 +736,14 @@ namespace System.Management.Automation.Language i + (int)AutomaticVariable.NumberOfAutomaticVariables); } - _builtinAttributeGenerator.Add(typeof(CmdletBindingAttribute), NewCmdletBindingAttribute); - _builtinAttributeGenerator.Add(typeof(ParameterAttribute), NewParameterAttribute); - _builtinAttributeGenerator.Add(typeof(OutputTypeAttribute), NewOutputTypeAttribute); - _builtinAttributeGenerator.Add(typeof(AliasAttribute), NewAliasAttribute); - _builtinAttributeGenerator.Add(typeof(ValidateSetAttribute), NewValidateSetAttribute); - _builtinAttributeGenerator.Add(typeof(DebuggerHiddenAttribute), NewDebuggerHiddenAttribute); - _builtinAttributeGenerator.Add(typeof(ValidateNotNullAttribute), NewValidateNotNullAttribute); - _builtinAttributeGenerator.Add(typeof(ValidateNotNullOrEmptyAttribute), NewValidateNotNullOrEmptyAttribute); + s_builtinAttributeGenerator.Add(typeof(CmdletBindingAttribute), NewCmdletBindingAttribute); + s_builtinAttributeGenerator.Add(typeof(ParameterAttribute), NewParameterAttribute); + s_builtinAttributeGenerator.Add(typeof(OutputTypeAttribute), NewOutputTypeAttribute); + s_builtinAttributeGenerator.Add(typeof(AliasAttribute), NewAliasAttribute); + s_builtinAttributeGenerator.Add(typeof(ValidateSetAttribute), NewValidateSetAttribute); + s_builtinAttributeGenerator.Add(typeof(DebuggerHiddenAttribute), NewDebuggerHiddenAttribute); + s_builtinAttributeGenerator.Add(typeof(ValidateNotNullAttribute), NewValidateNotNullAttribute); + s_builtinAttributeGenerator.Add(typeof(ValidateNotNullOrEmptyAttribute), NewValidateNotNullOrEmptyAttribute); } private Compiler(List sequencePoints) @@ -813,12 +813,12 @@ namespace System.Management.Automation.Language ExpressionType et = ExpressionType.Extension; switch (tokenKind) { - case TokenKind.Equals: return av.SetValue(this, right); - case TokenKind.PlusEquals: et = ExpressionType.Add; break; - case TokenKind.MinusEquals: et = ExpressionType.Subtract; break; - case TokenKind.MultiplyEquals: et = ExpressionType.Multiply; break; - case TokenKind.DivideEquals: et = ExpressionType.Divide; break; - case TokenKind.RemainderEquals: et = ExpressionType.Modulo; break; + case TokenKind.Equals: return av.SetValue(this, right); + case TokenKind.PlusEquals: et = ExpressionType.Add; break; + case TokenKind.MinusEquals: et = ExpressionType.Subtract; break; + case TokenKind.MultiplyEquals: et = ExpressionType.Multiply; break; + case TokenKind.DivideEquals: et = ExpressionType.Divide; break; + case TokenKind.RemainderEquals: et = ExpressionType.Modulo; break; } var exprs = new List(); @@ -951,7 +951,7 @@ namespace System.Management.Automation.Language if (targetType == null && argType == null) return null; - return new PSMethodInvocationConstraints(targetType, new[] {argType}); + return new PSMethodInvocationConstraints(targetType, new[] { argType }); } internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type[] argTypes) @@ -1005,7 +1005,7 @@ namespace System.Management.Automation.Language internal static RuntimeDefinedParameterDictionary GetParameterMetaData(ReadOnlyCollection parameters, bool automaticPositions, ref bool usesCmdletBinding) { var md = new RuntimeDefinedParameterDictionary(); - var listMd = new List(); + var listMd = new List(); var customParameterSet = false; for (int index = 0; index < parameters.Count; index++) { @@ -1022,8 +1022,8 @@ namespace System.Management.Automation.Language for (int index = 0; index < listMd.Count; index++) { var rdp = listMd[index]; - var paramAttribute = (ParameterAttribute) rdp.Attributes.First(attr => attr is ParameterAttribute); - if (!(rdp.ParameterType == typeof (SwitchParameter))) + var paramAttribute = (ParameterAttribute)rdp.Attributes.First(attr => attr is ParameterAttribute); + if (!(rdp.ParameterType == typeof(SwitchParameter))) { paramAttribute.Position = pos++; } @@ -1034,15 +1034,15 @@ namespace System.Management.Automation.Language return md; } - static readonly Dictionary _attributeGeneratorCache = new Dictionary(); - static readonly Dictionary> _builtinAttributeGenerator = new Dictionary>(10); + private static readonly Dictionary s_attributeGeneratorCache = new Dictionary(); + private static readonly Dictionary> s_builtinAttributeGenerator = new Dictionary>(10); - static Delegate GetAttributeGenerator(CallInfo callInfo) + private static Delegate GetAttributeGenerator(CallInfo callInfo) { Delegate result; - lock (_attributeGeneratorCache) + lock (s_attributeGeneratorCache) { - if (!_attributeGeneratorCache.TryGetValue(callInfo, out result)) + if (!s_attributeGeneratorCache.TryGetValue(callInfo, out result)) { var binder = PSAttributeGenerator.Get(callInfo); @@ -1053,26 +1053,26 @@ namespace System.Management.Automation.Language } result = Expression.Lambda(DynamicExpression.Dynamic(binder, typeof(object), parameters), parameters).Compile(); - _attributeGeneratorCache.Add(callInfo, result); + s_attributeGeneratorCache.Add(callInfo, result); } } return result; } - private static readonly CallSite> _attrArgToIntConverter = + private static readonly CallSite> s_attrArgToIntConverter = CallSite>.Create(PSConvertBinder.Get(typeof(int))); internal static readonly CallSite> _attrArgToStringConverter = CallSite>.Create(PSConvertBinder.Get(typeof(string))); - private static readonly CallSite> _attrArgToStringArrayConverter = + private static readonly CallSite> s_attrArgToStringArrayConverter = CallSite>.Create(PSConvertBinder.Get(typeof(string[]))); - private static readonly CallSite> _attrArgToBoolConverter = + private static readonly CallSite> s_attrArgToBoolConverter = CallSite>.Create(PSConvertBinder.Get(typeof(bool))); - private static readonly CallSite> _attrArgToConfirmImpactConverter = + private static readonly CallSite> s_attrArgToConfirmImpactConverter = CallSite>.Create(PSConvertBinder.Get(typeof(ConfirmImpact))); - private static readonly CallSite> _attrArgToRemotingCapabilityConverter = + private static readonly CallSite> s_attrArgToRemotingCapabilityConverter = CallSite>.Create(PSConvertBinder.Get(typeof(RemotingCapability))); - static void CheckNoPositionalArgs(AttributeAst ast) + private static void CheckNoPositionalArgs(AttributeAst ast) { var positionalArgCount = ast.PositionalArguments.Count; if (positionalArgCount > 0) @@ -1083,7 +1083,7 @@ namespace System.Management.Automation.Language } } - static void CheckNoNamedArgs(AttributeAst ast) + private static void CheckNoNamedArgs(AttributeAst ast) { if (ast.NamedArguments.Count > 0) { @@ -1095,11 +1095,11 @@ namespace System.Management.Automation.Language } } - static Attribute NewCmdletBindingAttribute(AttributeAst ast) + private static Attribute NewCmdletBindingAttribute(AttributeAst ast) { CheckNoPositionalArgs(ast); - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; var result = new CmdletBindingAttribute(); @@ -1117,27 +1117,27 @@ namespace System.Management.Automation.Language } else if (argumentName.Equals("SupportsShouldProcess", StringComparison.OrdinalIgnoreCase)) { - result.SupportsShouldProcess = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.SupportsShouldProcess = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("PositionalBinding", StringComparison.OrdinalIgnoreCase)) { - result.PositionalBinding = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.PositionalBinding = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("ConfirmImpact", StringComparison.OrdinalIgnoreCase)) { - result.ConfirmImpact = _attrArgToConfirmImpactConverter.Target(_attrArgToConfirmImpactConverter, argValue); + result.ConfirmImpact = s_attrArgToConfirmImpactConverter.Target(s_attrArgToConfirmImpactConverter, argValue); } else if (argumentName.Equals("SupportsTransactions", StringComparison.OrdinalIgnoreCase)) { - result.SupportsTransactions = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.SupportsTransactions = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("SupportsPaging", StringComparison.OrdinalIgnoreCase)) { - result.SupportsPaging = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.SupportsPaging = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("RemotingCapability", StringComparison.OrdinalIgnoreCase)) { - result.RemotingCapability = _attrArgToRemotingCapabilityConverter.Target(_attrArgToRemotingCapabilityConverter, argValue); + result.RemotingCapability = s_attrArgToRemotingCapabilityConverter.Target(s_attrArgToRemotingCapabilityConverter, argValue); } else { @@ -1150,11 +1150,11 @@ namespace System.Management.Automation.Language return result; } - static Attribute NewParameterAttribute(AttributeAst ast) + private static Attribute NewParameterAttribute(AttributeAst ast) { CheckNoPositionalArgs(ast); - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; var result = new ParameterAttribute(); @@ -1165,7 +1165,7 @@ namespace System.Management.Automation.Language if (argumentName.Equals("Position", StringComparison.OrdinalIgnoreCase)) { - result.Position = _attrArgToIntConverter.Target(_attrArgToIntConverter, argValue); + result.Position = s_attrArgToIntConverter.Target(s_attrArgToIntConverter, argValue); } else if (argumentName.Equals("ParameterSetName", StringComparison.OrdinalIgnoreCase)) { @@ -1173,19 +1173,19 @@ namespace System.Management.Automation.Language } else if (argumentName.Equals("Mandatory", StringComparison.OrdinalIgnoreCase)) { - result.Mandatory = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.Mandatory = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("ValueFromPipeline", StringComparison.OrdinalIgnoreCase)) { - result.ValueFromPipeline = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.ValueFromPipeline = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("ValueFromPipelineByPropertyName", StringComparison.OrdinalIgnoreCase)) { - result.ValueFromPipelineByPropertyName = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.ValueFromPipelineByPropertyName = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("ValueFromRemainingArguments", StringComparison.OrdinalIgnoreCase)) { - result.ValueFromRemainingArguments = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.ValueFromRemainingArguments = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else if (argumentName.Equals("HelpMessage", StringComparison.OrdinalIgnoreCase)) { @@ -1201,7 +1201,7 @@ namespace System.Management.Automation.Language } else if (argumentName.Equals("DontShow", StringComparison.OrdinalIgnoreCase)) { - result.DontShow = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.DontShow = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else { @@ -1214,9 +1214,9 @@ namespace System.Management.Automation.Language return result; } - static Attribute NewOutputTypeAttribute(AttributeAst ast) + private static Attribute NewOutputTypeAttribute(AttributeAst ast) { - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; OutputTypeAttribute result; if (ast.PositionalArguments.Count == 0) @@ -1266,7 +1266,7 @@ namespace System.Management.Automation.Language if (argumentName.Equals("ParameterSetName", StringComparison.OrdinalIgnoreCase)) { - result.ParameterSetName = _attrArgToStringArrayConverter.Target(_attrArgToStringArrayConverter, argValue); + result.ParameterSetName = s_attrArgToStringArrayConverter.Target(s_attrArgToStringArrayConverter, argValue); } else if (argumentName.Equals("ProviderCmdlet", StringComparison.OrdinalIgnoreCase)) { @@ -1283,11 +1283,11 @@ namespace System.Management.Automation.Language return result; } - static Attribute NewAliasAttribute(AttributeAst ast) + private static Attribute NewAliasAttribute(AttributeAst ast) { CheckNoNamedArgs(ast); - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; var args = new string[ast.PositionalArguments.Count]; for (int i = 0; i < ast.PositionalArguments.Count; i++) { @@ -1297,9 +1297,9 @@ namespace System.Management.Automation.Language return new AliasAttribute(args); } - static Attribute NewValidateSetAttribute(AttributeAst ast) + private static Attribute NewValidateSetAttribute(AttributeAst ast) { - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; var args = new string[ast.PositionalArguments.Count]; for (int i = 0; i < ast.PositionalArguments.Count; i++) { @@ -1314,7 +1314,7 @@ namespace System.Management.Automation.Language var argumentName = namedArg.ArgumentName; if (argumentName.Equals("IgnoreCase", StringComparison.OrdinalIgnoreCase)) { - result.IgnoreCase = _attrArgToBoolConverter.Target(_attrArgToBoolConverter, argValue); + result.IgnoreCase = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue); } else { @@ -1327,21 +1327,21 @@ namespace System.Management.Automation.Language return result; } - static Attribute NewDebuggerHiddenAttribute(AttributeAst ast) + private static Attribute NewDebuggerHiddenAttribute(AttributeAst ast) { CheckNoPositionalArgs(ast); CheckNoNamedArgs(ast); return new DebuggerHiddenAttribute(); } - static Attribute NewValidateNotNullOrEmptyAttribute(AttributeAst ast) + private static Attribute NewValidateNotNullOrEmptyAttribute(AttributeAst ast) { CheckNoPositionalArgs(ast); CheckNoNamedArgs(ast); return new ValidateNotNullOrEmptyAttribute(); } - static Attribute NewValidateNotNullAttribute(AttributeAst ast) + private static Attribute NewValidateNotNullAttribute(AttributeAst ast) { CheckNoPositionalArgs(ast); CheckNoNamedArgs(ast); @@ -1358,7 +1358,7 @@ namespace System.Management.Automation.Language } Func generator; - if (_builtinAttributeGenerator.TryGetValue(attributeType, out generator)) + if (s_builtinAttributeGenerator.TryGetValue(attributeType, out generator)) { return generator(attributeAst); } @@ -1371,7 +1371,7 @@ namespace System.Management.Automation.Language var delegateArgs = new object[totalArgCount + 1]; delegateArgs[0] = attributeType; - var cvv = new ConstantValueVisitor {AttributeArgument = true}; + var cvv = new ConstantValueVisitor { AttributeArgument = true }; int i = 1; for (int index = 0; index < attributeAst.PositionalArguments.Count; index++) { @@ -1531,21 +1531,21 @@ namespace System.Management.Automation.Language lock (this) { // Code written as part of a default value in a parameter is considered trusted - return Compiler.GetExpressionValue(this.Expression, true, context, sessionStateInternal, usingValues, ref _delegate, + return Compiler.GetExpressionValue(this.Expression, true, context, sessionStateInternal, usingValues, ref _delegate, ref _sequencePoints, ref _localsTupleType); } } } #endregion Parameter Metadata - + // This is the main entry point for turning an AST into compiled code. internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) { var body = scriptBlock.Ast; Diagnostics.Assert(body is ScriptBlockAst || body is FunctionDefinitionAst || body is FunctionMemberAst || body is CompilerGeneratedMemberFunctionAst, "Caller to verify ast is correct type."); - var ast = (Ast) body; + var ast = (Ast)body; Optimize = optimize; _compilingScriptCmdlet = scriptBlock.UsesCmdletBinding; @@ -1735,7 +1735,7 @@ namespace System.Management.Automation.Language }; if (usingValues != null) { - var boundParameters = new PSBoundParametersDictionary {ImplicitUsingParameters = usingValues}; + var boundParameters = new PSBoundParametersDictionary { ImplicitUsingParameters = usingValues }; functionContext._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters, context); } var result = lambda(functionContext); @@ -1778,19 +1778,19 @@ namespace System.Management.Automation.Language _loopTargets.Clear(); var exprs = new List(); - var temps = new List {_executionContextParameter, LocalVariablesParameter}; + var temps = new List { _executionContextParameter, LocalVariablesParameter }; GenerateFunctionProlog(exprs, temps, null); _sequencePoints.Add(expressionAst.Extent); exprs.Add(new UpdatePositionExpr(expressionAst.Extent, _sequencePoints.Count - 1, _debugSymbolDocument, checkBreakpoints: true)); var result = Compile(expressionAst).Cast(typeof(object)); exprs.Add(Expression.Label(_returnTarget, result)); var body = Expression.Block(new[] { _executionContextParameter, LocalVariablesParameter }, exprs); - var parameters = new[] { _functionContext }; + var parameters = new[] { _functionContext }; sequencePoints = _sequencePoints.ToArray(); return Expression.Lambda>(body, parameters).Compile(); } - class LoopGotoTargets + private class LoopGotoTargets { internal LoopGotoTargets(string label, LabelTarget breakLabel, LabelTarget continueLabel) { @@ -1812,7 +1812,7 @@ namespace System.Management.Automation.Language private readonly List _loopTargets = new List(); private bool _generatingWhileOrDoLoop; - enum CaptureAstContext + private enum CaptureAstContext { Condition, Enumerable, @@ -1823,7 +1823,7 @@ namespace System.Management.Automation.Language private delegate void MergeRedirectExprs(List exprs, List finallyExprs); private Expression CaptureAstResults( - Ast ast, + Ast ast, CaptureAstContext context, MergeRedirectExprs generateRedirectExprs = null) { @@ -1851,10 +1851,10 @@ namespace System.Management.Automation.Language var resultList = NewTemp(typeof(List), "resultList"); temps.Add(resultList); temps.Add(oldPipe); - exprs.Add(Expression.Assign(oldPipe, _getCurrentPipe)); + exprs.Add(Expression.Assign(oldPipe, s_getCurrentPipe)); exprs.Add(Expression.Assign(resultList, Expression.New(CachedReflectionInfo.ObjectList_ctor))); - exprs.Add(Expression.Assign(_getCurrentPipe, Expression.New(CachedReflectionInfo.Pipe_ctor, resultList))); - exprs.Add(Expression.Call(oldPipe, CachedReflectionInfo.Pipe_SetVariableListForTemporaryPipe, _getCurrentPipe)); + exprs.Add(Expression.Assign(s_getCurrentPipe, Expression.New(CachedReflectionInfo.Pipe_ctor, resultList))); + exprs.Add(Expression.Call(oldPipe, CachedReflectionInfo.Pipe_SetVariableListForTemporaryPipe, s_getCurrentPipe)); if (generateRedirectExprs != null) { // Add merge redirection expressions if delgate is provided. @@ -1864,39 +1864,39 @@ namespace System.Management.Automation.Language switch (context) { - case CaptureAstContext.AssignmentWithResultPreservation: - case CaptureAstContext.AssignmentWithoutResultPreservation: - result = Expression.Call(CachedReflectionInfo.PipelineOps_PipelineResult, resultList); + case CaptureAstContext.AssignmentWithResultPreservation: + case CaptureAstContext.AssignmentWithoutResultPreservation: + result = Expression.Call(CachedReflectionInfo.PipelineOps_PipelineResult, resultList); - // Clear the temporary pipe in case of exception, if we are not required to preserve the results - if (context == CaptureAstContext.AssignmentWithoutResultPreservation) - { - var catchExprs = new List + // Clear the temporary pipe in case of exception, if we are not required to preserve the results + if (context == CaptureAstContext.AssignmentWithoutResultPreservation) + { + var catchExprs = new List { Expression.Call(CachedReflectionInfo.PipelineOps_ClearPipe, resultList), Expression.Rethrow(), Expression.Constant(null, typeof (object)) }; - catches.Add(Expression.Catch(typeof(RuntimeException), Expression.Block(typeof(object), catchExprs))); - } + catches.Add(Expression.Catch(typeof(RuntimeException), Expression.Block(typeof(object), catchExprs))); + } - // PipelineResult might get skipped in some circumstances due to a FlowControlException thrown out, in which case - // we write to the oldPipe. This can happen in cases like: - // $(1;2;return 3) - finallyExprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_FlushPipe, oldPipe, resultList)); - break; - case CaptureAstContext.Condition: - result = DynamicExpression.Dynamic(PSPipelineResultToBoolBinder.Get(), typeof(bool), resultList); - break; - case CaptureAstContext.Enumerable: - result = resultList; - break; - default: - throw new ArgumentOutOfRangeException("context"); + // PipelineResult might get skipped in some circumstances due to a FlowControlException thrown out, in which case + // we write to the oldPipe. This can happen in cases like: + // $(1;2;return 3) + finallyExprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_FlushPipe, oldPipe, resultList)); + break; + case CaptureAstContext.Condition: + result = DynamicExpression.Dynamic(PSPipelineResultToBoolBinder.Get(), typeof(bool), resultList); + break; + case CaptureAstContext.Enumerable: + result = resultList; + break; + default: + throw new ArgumentOutOfRangeException("context"); } - finallyExprs.Add(Expression.Assign(_getCurrentPipe, oldPipe)); + finallyExprs.Add(Expression.Assign(s_getCurrentPipe, oldPipe)); exprs.Add(result); if (catches.Count > 0) @@ -1915,7 +1915,7 @@ namespace System.Management.Automation.Language } private Expression CaptureStatementResultsHelper( - StatementAst stmt, + StatementAst stmt, CaptureAstContext context, MergeRedirectExprs generateRedirectExprs) { @@ -1951,7 +1951,7 @@ namespace System.Management.Automation.Language } private Expression CaptureStatementResults( - StatementAst stmt, + StatementAst stmt, CaptureAstContext context, MergeRedirectExprs generateRedirectExprs = null) { @@ -1968,9 +1968,9 @@ namespace System.Management.Automation.Language if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, ast => ast is CommandAst, searchNestedScriptBlocks: false) != null) { var tmp = NewTemp(result.Type, "condTmp"); - result = Expression.Block(new [] { tmp }, + result = Expression.Block(new[] { tmp }, Expression.Assign(tmp, result), - _setDollarQuestionToTrue, + s_setDollarQuestionToTrue, tmp); } return result; @@ -2042,7 +2042,7 @@ namespace System.Management.Automation.Language return null; } - Expression> CompileNamedBlock(NamedBlockAst namedBlockAst, string funcName, ScriptBlockAst rootForDefiningTypes) + private Expression> CompileNamedBlock(NamedBlockAst namedBlockAst, string funcName, ScriptBlockAst rootForDefiningTypes) { IScriptExtent entryExtent = null; IScriptExtent exitExtent = null; @@ -2067,9 +2067,9 @@ namespace System.Management.Automation.Language return CompileSingleLambda(namedBlockAst.Statements, namedBlockAst.Traps, funcName, entryExtent, exitExtent, rootForDefiningTypes); } - Tuple, Type> CompileTrap(TrapStatementAst trap) + private Tuple, Type> CompileTrap(TrapStatementAst trap) { - var compiler = new Compiler(_sequencePoints) {_compilingTrap = true}; + var compiler = new Compiler(_sequencePoints) { _compilingTrap = true }; string funcName = _currentFunctionName + ""; if (trap.TrapType != null) { @@ -2090,7 +2090,7 @@ namespace System.Management.Automation.Language return Tuple.Create(lambda.Compile(), compiler.LocalVariablesTupleType); } - Expression> CompileSingleLambda(ReadOnlyCollection statements, + private Expression> CompileSingleLambda(ReadOnlyCollection statements, ReadOnlyCollection traps, string funcName, IScriptExtent entryExtent, @@ -2162,7 +2162,7 @@ namespace System.Management.Automation.Language CachedReflectionInfo.Debugger_ExitScriptFunction))); } - return Expression.Lambda>(body, funcName, new[] {_functionContext}); + return Expression.Lambda>(body, funcName, new[] { _functionContext }); } private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List exprs) @@ -2186,7 +2186,7 @@ namespace System.Management.Automation.Language rootForDefiningTypesAndUsings.FindAll(ast => ast is TypeDefinitionAst, true) .Cast() .ToArray(); - + if (typeAsts.Length > 0) { var assembly = DefinePowerShellTypes(rootForDefiningTypesAndUsings, typeAsts); @@ -2229,8 +2229,6 @@ namespace System.Management.Automation.Language trs = new TypeResolutionState( TypeOps.GetNamespacesForTypeResolutionState(usingStatements), assemblies); - - } exprs.Add(Expression.Call(CachedReflectionInfo.TypeOps_SetCurrentTypeResolutionState, Expression.Constant(trs), _executionContextParameter)); @@ -2421,7 +2419,7 @@ namespace System.Management.Automation.Language return null; } } - + private void GenerateFunctionProlog(List exprs, List temps, IScriptExtent entryExtent) { exprs.Add(Expression.Assign(_executionContextParameter, @@ -2436,7 +2434,7 @@ namespace System.Management.Automation.Language exprs.Add(Expression.Assign( Expression.Field(_functionContext, CachedReflectionInfo.FunctionContext__functionName), Expression.Constant(_currentFunctionName))); - + if (entryExtent != null) { _sequencePoints.Add(entryExtent); @@ -2455,8 +2453,8 @@ namespace System.Management.Automation.Language // Member functions don't write to the pipeline, they return values. // Set the default pipe to the null pipe, but remember the pipe parameter // so when we do compile the return statement, we can write to it's pipe. - exprs.Add(Expression.Assign(_returnPipe, _getCurrentPipe)); - exprs.Add(Expression.Assign(_getCurrentPipe, ExpressionCache.NullPipe)); + exprs.Add(Expression.Assign(_returnPipe, s_getCurrentPipe)); + exprs.Add(Expression.Assign(s_getCurrentPipe, ExpressionCache.NullPipe)); Diagnostics.Assert(_memberFunctionType.Type != null, "Member function type should not be null"); var ourThis = NewTemp(_memberFunctionType.Type, "this"); @@ -2705,7 +2703,7 @@ namespace System.Management.Automation.Language CompileTrappableExpression(exprList, statements[0]); exprList.Add(ExpressionCache.Empty); var expr = Expression.TryCatch(Expression.Block(exprList), _stmtCatchHandlers); - exprs.Add(expr); + exprs.Add(expr); } else { @@ -2747,7 +2745,7 @@ namespace System.Management.Automation.Language Expression.Goto(dispatchNextStatementTarget))); var expr = Expression.TryCatch(Expression.Block(tryBodyExprs), - new CatchBlock[] {_catchFlowControl, catchAll}); + new CatchBlock[] { s_catchFlowControl, catchAll }); exprs.Add(expr); exprs.Add(Expression.Label(dispatchTargets[statements.Count])); } @@ -2787,7 +2785,7 @@ namespace System.Management.Automation.Language if (pipeAst.PipelineElements.Count == 1 && pipeAst.PipelineElements[0] is CommandExpressionAst) { // A single expression - must set $? after the expression. - exprList.Add(_setDollarQuestionToTrue); + exprList.Add(s_setDollarQuestionToTrue); } } else @@ -2809,7 +2807,7 @@ namespace System.Management.Automation.Language pipeAst.PipelineElements[0] is CommandExpressionAst)) { // If the RHS of the assign was an expression, - exprList.Add(_setDollarQuestionToTrue); + exprList.Add(s_setDollarQuestionToTrue); } } } @@ -2862,12 +2860,12 @@ namespace System.Management.Automation.Language return this.VisitPipeline(dynamicKeywordAst.GenerateCommandCallPipelineAst()); } - private bool generatedCallToDefineWorkflows; + private bool _generatedCallToDefineWorkflows; public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { if (functionDefinitionAst.IsWorkflow) { - if (generatedCallToDefineWorkflows) + if (_generatedCallToDefineWorkflows) return ExpressionCache.Empty; var topAst = functionDefinitionAst.Parent; @@ -2876,7 +2874,7 @@ namespace System.Management.Automation.Language topAst = topAst.Parent; } - generatedCallToDefineWorkflows = true; + _generatedCallToDefineWorkflows = true; return Expression.Call(CachedReflectionInfo.FunctionOps_DefineWorkflows, _executionContextParameter, Expression.Constant(topAst, typeof(ScriptBlockAst))); @@ -3158,10 +3156,10 @@ namespace System.Management.Automation.Language resultList = NewTemp(typeof(List), "resultList"); temps.Add(resultList); temps.Add(oldPipe); - exprs.Add(Expression.Assign(oldPipe, _getCurrentPipe)); + exprs.Add(Expression.Assign(oldPipe, s_getCurrentPipe)); exprs.Add(Expression.Assign(resultList, Expression.New(CachedReflectionInfo.ObjectList_ctor))); - exprs.Add(Expression.Assign(_getCurrentPipe, Expression.New(CachedReflectionInfo.Pipe_ctor, resultList))); - exprs.Add(Expression.Call(oldPipe, CachedReflectionInfo.Pipe_SetVariableListForTemporaryPipe, _getCurrentPipe)); + exprs.Add(Expression.Assign(s_getCurrentPipe, Expression.New(CachedReflectionInfo.Pipe_ctor, resultList))); + exprs.Add(Expression.Call(oldPipe, CachedReflectionInfo.Pipe_SetVariableListForTemporaryPipe, s_getCurrentPipe)); } // We must generate the code for output redirection to a file before any merging redirections @@ -3181,16 +3179,16 @@ namespace System.Management.Automation.Language var redirectionExpr = NewTemp(typeof(FileRedirection), "fileRedirection"); temps.Add(redirectionExpr); exprs.Add(Expression.Assign(redirectionExpr, (Expression)compiledRedirection)); -/* - if (fileRedirectionAst.FromStream != RedirectionStream.Output && !(redirectionExpr is ConstantExpression)) - { - // We'll be reusing redirectionExpr, it's not constant, so save it in a temp. - var temp = Expression.Variable(redirectionExpr.Type); - temps.Add(temp); - exprs.Add(Expression.Assign(temp, redirectionExpr)); - redirectionExpr = temp; - } -*/ + /* + if (fileRedirectionAst.FromStream != RedirectionStream.Output && !(redirectionExpr is ConstantExpression)) + { + // We'll be reusing redirectionExpr, it's not constant, so save it in a temp. + var temp = Expression.Variable(redirectionExpr.Type); + temps.Add(temp); + exprs.Add(Expression.Assign(temp, redirectionExpr)); + redirectionExpr = temp; + } + */ exprs.Add(Expression.Assign( savedPipes, Expression.Call(redirectionExpr, CachedReflectionInfo.FileRedirection_BindForExpression, _functionContext))); @@ -3221,8 +3219,8 @@ namespace System.Management.Automation.Language bool shouldPreserveResultInCaseofException = parenExpr.ShouldPreserveOutputInCaseOfException(); result = CaptureAstResults( parenExpr.Pipeline, - shouldPreserveResultInCaseofException - ? CaptureAstContext.AssignmentWithResultPreservation + shouldPreserveResultInCaseofException + ? CaptureAstContext.AssignmentWithResultPreservation : CaptureAstContext.AssignmentWithoutResultPreservation, (mergeExprs, mergeFinallyExprs) => AddMergeRedirectionExpressions(commandExpr.Redirections, temps, mergeExprs, mergeFinallyExprs)); } @@ -3259,7 +3257,7 @@ namespace System.Management.Automation.Language } else { - exprs.Add(CallAddPipe(result, _getCurrentPipe)); + exprs.Add(CallAddPipe(result, s_getCurrentPipe)); // Make sure the result of the expression we return is AutomationNull.Value. exprs.Add(ExpressionCache.AutomationNullConstant); } @@ -3279,7 +3277,7 @@ namespace System.Management.Automation.Language // "hello" // } // before this change, running 'foo' will not write out 'hello'. - finallyExprs.Add(Expression.Assign(_getCurrentPipe, oldPipe)); + finallyExprs.Add(Expression.Assign(s_getCurrentPipe, oldPipe)); } if (finallyExprs.Count != 0) @@ -3292,7 +3290,7 @@ namespace System.Management.Automation.Language private void AddMergeRedirectionExpressions( ReadOnlyCollection redirections, List temps, - List exprs, + List exprs, List finallyExprs) { foreach (var mergingRedirectionAst in redirections.OfType()) @@ -3364,7 +3362,7 @@ namespace System.Management.Automation.Language { var splatTest = element; bool splatted = false; - + UsingExpressionAst usingExpression = element as UsingExpressionAst; if (usingExpression != null) { @@ -3372,7 +3370,7 @@ namespace System.Management.Automation.Language } VariableExpressionAst variableExpression = splatTest as VariableExpressionAst; - if(variableExpression != null) + if (variableExpression != null) { splatted = variableExpression.Splatted; } @@ -3450,7 +3448,7 @@ namespace System.Management.Automation.Language { return expr; } - return CallAddPipe(expr, _getCurrentPipe); + return CallAddPipe(expr, s_getCurrentPipe); } private bool ArgumentIsNotReallyArrayIfCommandIsNative(Ast arg) @@ -3614,7 +3612,7 @@ namespace System.Management.Automation.Language skipDefault = NewTemp(typeof(bool), "skipDefault"); temps.Add(skipDefault); } - + var switchBodyGenerator = GetSwitchBodyGenerator(switchStatementAst, avs, skipDefault); if ((switchStatementAst.Flags & SwitchFlags.File) != 0) @@ -3739,7 +3737,7 @@ namespace System.Management.Automation.Language { var clauseEvalBinder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags); exprs.Add(avs.SetNewValue(newValue)); - + if (skipDefault != null) { exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false))); @@ -3756,7 +3754,7 @@ namespace System.Management.Automation.Language Expression test; object constValue = ((bool)clause.Item1.Accept(iscvv)) ? clause.Item1.Accept(cvv) : null; if (constValue is ScriptBlock) - { + { var call = Expression.Call(Expression.Constant(constValue), CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs, /*useLocalScope=*/ ExpressionCache.Constant(true), @@ -3770,8 +3768,8 @@ namespace System.Management.Automation.Language else if (constValue != null) { SwitchFlags flags = switchStatementAst.Flags; - Expression conditionExpr = constValue is Regex || constValue is WildcardPattern - ? (Expression)Expression.Constant(constValue) + Expression conditionExpr = constValue is Regex || constValue is WildcardPattern + ? (Expression)Expression.Constant(constValue) : DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), (constValue is Type) ? Expression.Constant(constValue, typeof(Type)) @@ -3902,7 +3900,7 @@ namespace System.Management.Automation.Language exprs.Add(dataExpr); var block = Expression.Block( - new[] {oldLanguageMode}, + new[] { oldLanguageMode }, Expression.TryFinally( Expression.Block(exprs), Expression.Assign(languageModePropertyExpr, oldLanguageMode))); @@ -4003,7 +4001,7 @@ namespace System.Management.Automation.Language exprs.Add(enterLoop); var loopBodyExprs = new List(); - loopBodyExprs.Add(_callCheckForInterrupts); + loopBodyExprs.Add(s_callCheckForInterrupts); _loopTargets.Add(new LoopGotoTargets(loopLabel ?? "", breakLabel, continueLabel)); _generatingWhileOrDoLoop = true; @@ -4088,7 +4086,7 @@ namespace System.Management.Automation.Language _generatingWhileOrDoLoop = true; var loopBodyExprs = new List { - _callCheckForInterrupts, + s_callCheckForInterrupts, Compile(loopStatement.Body), ExpressionCache.Empty }; @@ -4236,7 +4234,7 @@ namespace System.Management.Automation.Language // } // } - Action, Expression> loopBodyGenerator = + Action, Expression> loopBodyGenerator = (exprs, newValue) => { exprs.Add(ReduceAssignment(forEachStatementAst.Variable, TokenKind.Equals, newValue)); @@ -4333,7 +4331,7 @@ namespace System.Management.Automation.Language // } // // This is a little convoluted because an automatic variable isn't necessarily set. - class AutomaticVarSaver + private class AutomaticVarSaver { private readonly Compiler _compiler; private readonly int _automaticVar; @@ -4342,9 +4340,9 @@ namespace System.Management.Automation.Language internal AutomaticVarSaver(Compiler compiler, VariablePath autoVarPath, int automaticVar) { - this._compiler = compiler; - this._autoVarPath = autoVarPath; - this._automaticVar = automaticVar; + _compiler = compiler; + _autoVarPath = autoVarPath; + _automaticVar = automaticVar; } internal IEnumerable GetTemps() @@ -4358,7 +4356,7 @@ namespace System.Management.Automation.Language var getValueExpr = _automaticVar < 0 ? Compiler.CallGetVariable(Expression.Constant(_autoVarPath), null) : _compiler.GetLocal(_automaticVar); - this._oldValue = _compiler.NewTemp(getValueExpr.Type, "old_" + _autoVarPath.UnqualifiedPath); + _oldValue = _compiler.NewTemp(getValueExpr.Type, "old_" + _autoVarPath.UnqualifiedPath); return Expression.Assign(_oldValue, getValueExpr); } @@ -4428,8 +4426,8 @@ namespace System.Management.Automation.Language rte); var catchExprs = new List { - Expression.Assign(oldrte, _currentExceptionBeingHandled), - Expression.Assign(_currentExceptionBeingHandled, rte), + Expression.Assign(oldrte, s_currentExceptionBeingHandled), + Expression.Assign(s_currentExceptionBeingHandled, rte), avs.SaveAutomaticVar(), avs.SetNewValue(errorRecord) }; @@ -4440,7 +4438,7 @@ namespace System.Management.Automation.Language Expression.Block(typeof(void), catchExprs), Expression.Block(typeof(void), avs.RestoreAutomaticVar(), - Expression.Assign(_currentExceptionBeingHandled, oldrte))); + Expression.Assign(s_currentExceptionBeingHandled, oldrte))); catches.Add(Expression.Catch(typeof(PipelineStoppedException), Expression.Rethrow())); catches.Add(Expression.Catch(rte, Expression.Block(avs.GetTemps().Append(oldrte).ToArray(), tf))); @@ -4503,7 +4501,7 @@ namespace System.Management.Automation.Language var c = tryStatementAst.CatchClauses[index]; if (c.IsCatchAll) { - catchTypes[i] = typeof (ExceptionHandlingOps.CatchAll); + catchTypes[i] = typeof(ExceptionHandlingOps.CatchAll); } else { @@ -4535,7 +4533,7 @@ namespace System.Management.Automation.Language } // Wrap the body in a void block so all cases have the same type. - var catchBody = Expression.Block(typeof (void), Compile(c.Body)); + var catchBody = Expression.Block(typeof(void), Compile(c.Body)); if (c.IsCatchAll) { @@ -4570,8 +4568,8 @@ namespace System.Management.Automation.Language var tf = Expression.TryFinally( Expression.Block( typeof(void), - Expression.Assign(oldexception, _currentExceptionBeingHandled), - Expression.Assign(_currentExceptionBeingHandled, exception), + Expression.Assign(oldexception, s_currentExceptionBeingHandled), + Expression.Assign(s_currentExceptionBeingHandled, exception), avs.SaveAutomaticVar(), // $_ is set in the call to ExceptionHandlingOps.FindMatchingHandler Expression.Switch( @@ -4582,7 +4580,7 @@ namespace System.Management.Automation.Language cases.ToArray())), Expression.Block( avs.RestoreAutomaticVar(), - Expression.Assign(_currentExceptionBeingHandled, oldexception))); + Expression.Assign(s_currentExceptionBeingHandled, oldexception))); catches.Add(Expression.Catch(typeof(PipelineStoppedException), Expression.Rethrow())); catches.Add(Expression.Catch(exception, Expression.Block(avs.GetTemps().Append(oldexception).ToArray(), tf))); @@ -4734,13 +4732,13 @@ namespace System.Management.Automation.Language } return Expression.Block(UpdatePosition(returnStatementAst.Pipeline), - Expression.Assign(_getCurrentPipe, _returnPipe), + Expression.Assign(s_getCurrentPipe, _returnPipe), returnValue, returnExpr); } - returnValue = assignmentStatementAst != null - ? CallAddPipe(CompileAssignment(assignmentStatementAst), _getCurrentPipe) + returnValue = assignmentStatementAst != null + ? CallAddPipe(CompileAssignment(assignmentStatementAst), s_getCurrentPipe) : Compile(pipe); return Expression.Block(returnValue, returnExpr); @@ -4767,7 +4765,7 @@ namespace System.Management.Automation.Language { // We should not preserve the partial output if exception is thrown when evaluating throwStmt.pipeline. Expression throwExpr = throwStatementAst.IsRethrow - ? _currentExceptionBeingHandled + ? s_currentExceptionBeingHandled : (throwStatementAst.Pipeline == null) ? ExpressionCache.NullConstant : CaptureStatementResults(throwStatementAst.Pipeline, @@ -4793,7 +4791,7 @@ namespace System.Management.Automation.Language Expression.Constant(CallSite>.Create( PSBinaryOperationBinder.Get(ExpressionType.Equal, ignoreCase, scalarCompare: true))), lhs.Cast(typeof(object)), - rhs.Cast(typeof(object))); + rhs.Cast(typeof(object))); } public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) @@ -4810,235 +4808,235 @@ namespace System.Management.Automation.Language switch (binaryExpressionAst.Operator) { - case TokenKind.And: - return Expression.AndAlso(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); - case TokenKind.Or: - return Expression.OrElse(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); - case TokenKind.Is: - case TokenKind.IsNot: - if (rhs is ConstantExpression && rhs.Type == typeof(Type)) - { - var isType = (Type)((ConstantExpression)rhs).Value; - if (!(isType == typeof(PSCustomObject)) && !(isType == typeof(PSObject))) + case TokenKind.And: + return Expression.AndAlso(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); + case TokenKind.Or: + return Expression.OrElse(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); + case TokenKind.Is: + case TokenKind.IsNot: + if (rhs is ConstantExpression && rhs.Type == typeof(Type)) { - lhs = lhs.Type.GetTypeInfo().IsValueType ? lhs : Expression.Call(CachedReflectionInfo.PSObject_Base, lhs); - if (binaryExpressionAst.Operator == TokenKind.Is) - return Expression.TypeIs(lhs, isType); - return Expression.Not(Expression.TypeIs(lhs, isType)); + var isType = (Type)((ConstantExpression)rhs).Value; + if (!(isType == typeof(PSCustomObject)) && !(isType == typeof(PSObject))) + { + lhs = lhs.Type.GetTypeInfo().IsValueType ? lhs : Expression.Call(CachedReflectionInfo.PSObject_Base, lhs); + if (binaryExpressionAst.Operator == TokenKind.Is) + return Expression.TypeIs(lhs, isType); + return Expression.Not(Expression.TypeIs(lhs, isType)); + } } - } - Expression result = Expression.Call(CachedReflectionInfo.TypeOps_IsInstance, lhs.Cast(typeof(object)), rhs.Cast(typeof(object))); - if (binaryExpressionAst.Operator == TokenKind.IsNot) - { - result = Expression.Not(result); - } - return result; + Expression result = Expression.Call(CachedReflectionInfo.TypeOps_IsInstance, lhs.Cast(typeof(object)), rhs.Cast(typeof(object))); + if (binaryExpressionAst.Operator == TokenKind.IsNot) + { + result = Expression.Not(result); + } + return result; - case TokenKind.As: - return Expression.Call(CachedReflectionInfo.TypeOps_AsOperator, lhs.Cast(typeof(object)), rhs.Convert(typeof(Type))); + case TokenKind.As: + return Expression.Call(CachedReflectionInfo.TypeOps_AsOperator, lhs.Cast(typeof(object)), rhs.Convert(typeof(Type))); - case TokenKind.DotDot: - return Expression.Call(CachedReflectionInfo.IntOps_Range, - lhs.Convert(typeof(int)), - rhs.Convert(typeof(int))); - case TokenKind.Multiply: - if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) - { - return Expression.Multiply(lhs, rhs); - } - binder = PSBinaryOperationBinder.Get(ExpressionType.Multiply); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Divide: - if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) - { - return Expression.Divide(lhs, rhs); - } - binder = PSBinaryOperationBinder.Get(ExpressionType.Divide); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Rem: - binder = PSBinaryOperationBinder.Get(ExpressionType.Modulo); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Plus: - if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) - { - return Expression.Add(lhs, rhs); - } - binder = PSBinaryOperationBinder.Get(ExpressionType.Add); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Minus: - if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) - { - return Expression.Subtract(lhs, rhs); - } - binder = PSBinaryOperationBinder.Get(ExpressionType.Subtract); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Format: - if (lhs.Type != typeof(string)) - { - lhs = DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), lhs, _executionContextParameter); - } - return Expression.Call(CachedReflectionInfo.StringOps_FormatOperator, lhs, rhs.Cast(typeof(object))); - case TokenKind.Xor: - return Expression.NotEqual(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); - case TokenKind.Shl: - binder = PSBinaryOperationBinder.Get(ExpressionType.LeftShift); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Shr: - binder = PSBinaryOperationBinder.Get(ExpressionType.RightShift); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Band: - binder = PSBinaryOperationBinder.Get(ExpressionType.And); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Bor: - binder = PSBinaryOperationBinder.Get(ExpressionType.Or); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Bxor: - binder = PSBinaryOperationBinder.Get(ExpressionType.ExclusiveOr); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Join: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_JoinOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object))); - case TokenKind.Ieq: - binder = PSBinaryOperationBinder.Get(ExpressionType.Equal); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Ine: - binder = PSBinaryOperationBinder.Get(ExpressionType.NotEqual); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Ige: - binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThanOrEqual); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Igt: - binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThan); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Ilt: - binder = PSBinaryOperationBinder.Get(ExpressionType.LessThan); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Ile: - binder = PSBinaryOperationBinder.Get(ExpressionType.LessThanOrEqual); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Ilike: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_LikeOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), - lhs.Cast(typeof(object)), - GetLikeRHSOperand(WildcardOptions.IgnoreCase, rhs).Cast(typeof(object)), - Expression.Constant(binaryExpressionAst.Operator)); - case TokenKind.Inotlike: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_LikeOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), - lhs.Cast(typeof(object)), - GetLikeRHSOperand(WildcardOptions.IgnoreCase, rhs).Cast(typeof(object)), - Expression.Constant(binaryExpressionAst.Operator)); - case TokenKind.Imatch: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_MatchOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(false), ExpressionCache.Constant(true)); - case TokenKind.Inotmatch: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_MatchOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(true), ExpressionCache.Constant(true)); - case TokenKind.Ireplace: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_ReplaceOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(true)); - case TokenKind.Icontains: - return GenerateCallContains(lhs, rhs, true); - case TokenKind.Inotcontains: - return Expression.Not(GenerateCallContains(lhs, rhs, true)); - case TokenKind.Iin: - return GenerateCallContains(rhs, lhs, true); - case TokenKind.Inotin: - return Expression.Not(GenerateCallContains(rhs, lhs, true)); - case TokenKind.Isplit: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_SplitOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(true)); - case TokenKind.Ceq: - binder = PSBinaryOperationBinder.Get(ExpressionType.Equal, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Cne: - binder = PSBinaryOperationBinder.Get(ExpressionType.NotEqual, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Cge: - binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThanOrEqual, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Cgt: - binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThan, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Clt: - binder = PSBinaryOperationBinder.Get(ExpressionType.LessThan, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Cle: - binder = PSBinaryOperationBinder.Get(ExpressionType.LessThanOrEqual, false); - return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); - case TokenKind.Clike: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_LikeOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), - lhs.Cast(typeof(object)), - GetLikeRHSOperand(WildcardOptions.None, rhs).Cast(typeof(object)), - Expression.Constant(binaryExpressionAst.Operator)); - case TokenKind.Cnotlike: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_LikeOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), - lhs.Cast(typeof(object)), - GetLikeRHSOperand(WildcardOptions.None, rhs).Cast(typeof(object)), - Expression.Constant(binaryExpressionAst.Operator)); - case TokenKind.Cmatch: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_MatchOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(false), ExpressionCache.Constant(false)); - case TokenKind.Cnotmatch: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_MatchOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(true), ExpressionCache.Constant(false)); - case TokenKind.Creplace: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_ReplaceOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(false)); - case TokenKind.Ccontains: - return GenerateCallContains(lhs, rhs, false); - case TokenKind.Cnotcontains: - return Expression.Not(GenerateCallContains(lhs, rhs, false)); - case TokenKind.Cin: - return GenerateCallContains(rhs, lhs, false); - case TokenKind.Cnotin: - return Expression.Not(GenerateCallContains(rhs, lhs, false)); - case TokenKind.Csplit: - // TODO: replace this with faster code - return Expression.Call( - CachedReflectionInfo.ParserOps_SplitOperator, - _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), - ExpressionCache.Constant(false)); + case TokenKind.DotDot: + return Expression.Call(CachedReflectionInfo.IntOps_Range, + lhs.Convert(typeof(int)), + rhs.Convert(typeof(int))); + case TokenKind.Multiply: + if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) + { + return Expression.Multiply(lhs, rhs); + } + binder = PSBinaryOperationBinder.Get(ExpressionType.Multiply); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Divide: + if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) + { + return Expression.Divide(lhs, rhs); + } + binder = PSBinaryOperationBinder.Get(ExpressionType.Divide); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Rem: + binder = PSBinaryOperationBinder.Get(ExpressionType.Modulo); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Plus: + if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) + { + return Expression.Add(lhs, rhs); + } + binder = PSBinaryOperationBinder.Get(ExpressionType.Add); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Minus: + if (lhs.Type == typeof(double) && rhs.Type == typeof(double)) + { + return Expression.Subtract(lhs, rhs); + } + binder = PSBinaryOperationBinder.Get(ExpressionType.Subtract); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Format: + if (lhs.Type != typeof(string)) + { + lhs = DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), lhs, _executionContextParameter); + } + return Expression.Call(CachedReflectionInfo.StringOps_FormatOperator, lhs, rhs.Cast(typeof(object))); + case TokenKind.Xor: + return Expression.NotEqual(lhs.Convert(typeof(bool)), rhs.Convert(typeof(bool))); + case TokenKind.Shl: + binder = PSBinaryOperationBinder.Get(ExpressionType.LeftShift); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Shr: + binder = PSBinaryOperationBinder.Get(ExpressionType.RightShift); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Band: + binder = PSBinaryOperationBinder.Get(ExpressionType.And); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Bor: + binder = PSBinaryOperationBinder.Get(ExpressionType.Or); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Bxor: + binder = PSBinaryOperationBinder.Get(ExpressionType.ExclusiveOr); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Join: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_JoinOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object))); + case TokenKind.Ieq: + binder = PSBinaryOperationBinder.Get(ExpressionType.Equal); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Ine: + binder = PSBinaryOperationBinder.Get(ExpressionType.NotEqual); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Ige: + binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThanOrEqual); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Igt: + binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThan); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Ilt: + binder = PSBinaryOperationBinder.Get(ExpressionType.LessThan); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Ile: + binder = PSBinaryOperationBinder.Get(ExpressionType.LessThanOrEqual); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Ilike: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_LikeOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), + lhs.Cast(typeof(object)), + GetLikeRHSOperand(WildcardOptions.IgnoreCase, rhs).Cast(typeof(object)), + Expression.Constant(binaryExpressionAst.Operator)); + case TokenKind.Inotlike: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_LikeOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), + lhs.Cast(typeof(object)), + GetLikeRHSOperand(WildcardOptions.IgnoreCase, rhs).Cast(typeof(object)), + Expression.Constant(binaryExpressionAst.Operator)); + case TokenKind.Imatch: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_MatchOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(false), ExpressionCache.Constant(true)); + case TokenKind.Inotmatch: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_MatchOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(true), ExpressionCache.Constant(true)); + case TokenKind.Ireplace: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_ReplaceOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(true)); + case TokenKind.Icontains: + return GenerateCallContains(lhs, rhs, true); + case TokenKind.Inotcontains: + return Expression.Not(GenerateCallContains(lhs, rhs, true)); + case TokenKind.Iin: + return GenerateCallContains(rhs, lhs, true); + case TokenKind.Inotin: + return Expression.Not(GenerateCallContains(rhs, lhs, true)); + case TokenKind.Isplit: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_SplitOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(true)); + case TokenKind.Ceq: + binder = PSBinaryOperationBinder.Get(ExpressionType.Equal, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Cne: + binder = PSBinaryOperationBinder.Get(ExpressionType.NotEqual, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Cge: + binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThanOrEqual, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Cgt: + binder = PSBinaryOperationBinder.Get(ExpressionType.GreaterThan, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Clt: + binder = PSBinaryOperationBinder.Get(ExpressionType.LessThan, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Cle: + binder = PSBinaryOperationBinder.Get(ExpressionType.LessThanOrEqual, false); + return DynamicExpression.Dynamic(binder, typeof(object), lhs, rhs); + case TokenKind.Clike: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_LikeOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), + lhs.Cast(typeof(object)), + GetLikeRHSOperand(WildcardOptions.None, rhs).Cast(typeof(object)), + Expression.Constant(binaryExpressionAst.Operator)); + case TokenKind.Cnotlike: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_LikeOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), + lhs.Cast(typeof(object)), + GetLikeRHSOperand(WildcardOptions.None, rhs).Cast(typeof(object)), + Expression.Constant(binaryExpressionAst.Operator)); + case TokenKind.Cmatch: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_MatchOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(false), ExpressionCache.Constant(false)); + case TokenKind.Cnotmatch: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_MatchOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(true), ExpressionCache.Constant(false)); + case TokenKind.Creplace: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_ReplaceOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(false)); + case TokenKind.Ccontains: + return GenerateCallContains(lhs, rhs, false); + case TokenKind.Cnotcontains: + return Expression.Not(GenerateCallContains(lhs, rhs, false)); + case TokenKind.Cin: + return GenerateCallContains(rhs, lhs, false); + case TokenKind.Cnotin: + return Expression.Not(GenerateCallContains(rhs, lhs, false)); + case TokenKind.Csplit: + // TODO: replace this with faster code + return Expression.Call( + CachedReflectionInfo.ParserOps_SplitOperator, + _executionContextParameter, Expression.Constant(binaryExpressionAst.ErrorPosition), lhs.Cast(typeof(object)), rhs.Cast(typeof(object)), + ExpressionCache.Constant(false)); } throw new InvalidOperationException("Unknown token in binary operator."); } - static Expression GetLikeRHSOperand(WildcardOptions options, Expression expr) + private static Expression GetLikeRHSOperand(WildcardOptions options, Expression expr) { var constExpr = expr as ConstantExpression; if (constExpr == null) @@ -5062,45 +5060,45 @@ namespace System.Management.Automation.Language ExpressionAst child = unaryExpressionAst.Child; switch (unaryExpressionAst.TokenKind) { - case TokenKind.Exclaim: - case TokenKind.Not: - return DynamicExpression.Dynamic(PSUnaryOperationBinder.Get(ExpressionType.Not), typeof(object), CompileExpressionOperand(child)); - case TokenKind.Minus: - return DynamicExpression.Dynamic(PSBinaryOperationBinder.Get(ExpressionType.Subtract), - typeof(object), ExpressionCache.Constant(0), CompileExpressionOperand(child)); - case TokenKind.Plus: - return DynamicExpression.Dynamic(PSBinaryOperationBinder.Get(ExpressionType.Add), - typeof(object), ExpressionCache.Constant(0), CompileExpressionOperand(child)); - case TokenKind.Bnot: - return DynamicExpression.Dynamic(PSUnaryOperationBinder.Get(ExpressionType.OnesComplement), - typeof(object), CompileExpressionOperand(child)); - case TokenKind.PlusPlus: - return CompileIncrementOrDecrement(child, 1, true); - case TokenKind.MinusMinus: - return CompileIncrementOrDecrement(child, -1, true); - case TokenKind.PostfixPlusPlus: - return CompileIncrementOrDecrement(child, 1, false); - case TokenKind.PostfixMinusMinus: - return CompileIncrementOrDecrement(child, -1, false); - case TokenKind.Join: - // TODO: replace this with faster code - return Expression.Call(CachedReflectionInfo.ParserOps_UnaryJoinOperator, - _executionContextParameter, - Expression.Constant(unaryExpressionAst.Extent), - (CompileExpressionOperand(child)).Cast(typeof(object))); - case TokenKind.Isplit: - case TokenKind.Csplit: - // TODO: replace this with faster code - return Expression.Call(CachedReflectionInfo.ParserOps_UnarySplitOperator, - _executionContextParameter, - Expression.Constant(unaryExpressionAst.Extent), - (CompileExpressionOperand(child)).Cast(typeof(object))); + case TokenKind.Exclaim: + case TokenKind.Not: + return DynamicExpression.Dynamic(PSUnaryOperationBinder.Get(ExpressionType.Not), typeof(object), CompileExpressionOperand(child)); + case TokenKind.Minus: + return DynamicExpression.Dynamic(PSBinaryOperationBinder.Get(ExpressionType.Subtract), + typeof(object), ExpressionCache.Constant(0), CompileExpressionOperand(child)); + case TokenKind.Plus: + return DynamicExpression.Dynamic(PSBinaryOperationBinder.Get(ExpressionType.Add), + typeof(object), ExpressionCache.Constant(0), CompileExpressionOperand(child)); + case TokenKind.Bnot: + return DynamicExpression.Dynamic(PSUnaryOperationBinder.Get(ExpressionType.OnesComplement), + typeof(object), CompileExpressionOperand(child)); + case TokenKind.PlusPlus: + return CompileIncrementOrDecrement(child, 1, true); + case TokenKind.MinusMinus: + return CompileIncrementOrDecrement(child, -1, true); + case TokenKind.PostfixPlusPlus: + return CompileIncrementOrDecrement(child, 1, false); + case TokenKind.PostfixMinusMinus: + return CompileIncrementOrDecrement(child, -1, false); + case TokenKind.Join: + // TODO: replace this with faster code + return Expression.Call(CachedReflectionInfo.ParserOps_UnaryJoinOperator, + _executionContextParameter, + Expression.Constant(unaryExpressionAst.Extent), + (CompileExpressionOperand(child)).Cast(typeof(object))); + case TokenKind.Isplit: + case TokenKind.Csplit: + // TODO: replace this with faster code + return Expression.Call(CachedReflectionInfo.ParserOps_UnarySplitOperator, + _executionContextParameter, + Expression.Constant(unaryExpressionAst.Extent), + (CompileExpressionOperand(child)).Cast(typeof(object))); } throw new InvalidOperationException("Unknown token in unary operator."); } - Expression CompileIncrementOrDecrement(ExpressionAst exprAst, int valueToAdd, bool prefix) + private Expression CompileIncrementOrDecrement(ExpressionAst exprAst, int valueToAdd, bool prefix) { var av = ((ISupportsAssignment)exprAst).GetAssignableValue(); List temps = new List(); @@ -5167,7 +5165,7 @@ namespace System.Management.Automation.Language // pure laziness here - we should construct the PSObject directly. Instead, we're relying on the conversion // to create the PSObject from an OrderedDictionary. childExpr = Expression.Block(typeof(OrderedDictionary), - new [] { temp }, + new[] { temp }, BuildHashtable(hashTableAst.KeyValuePairs, temp, ordered: true)); } } @@ -5238,7 +5236,7 @@ namespace System.Management.Automation.Language { string usingExprKey = PsUtils.GetUsingExpressionKey(usingExpression); return Expression.Call(CachedReflectionInfo.VariableOps_GetUsingValue, LocalVariablesParameter, - Expression.Constant(usingExprKey), + Expression.Constant(usingExprKey), ExpressionCache.Constant(usingExpression.RuntimeUsingIndex), _executionContextParameter); } @@ -5361,7 +5359,7 @@ namespace System.Management.Automation.Language string name = memberNameAst.Value; return DynamicExpression.Dynamic(PSGetMemberBinder.Get(name, _memberFunctionType, memberExpressionAst.Static), typeof(object), target); } - + var memberNameExpr = Compile(memberExpressionAst.Member); return DynamicExpression.Dynamic(PSGetDynamicMemberBinder.Get(_memberFunctionType, memberExpressionAst.Static), typeof(object), target, memberNameExpr); } @@ -5428,10 +5426,10 @@ namespace System.Management.Automation.Language public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { var constraints = GetInvokeMemberConstraints(invokeMemberExpressionAst); - + var target = CompileExpressionOperand(invokeMemberExpressionAst.Expression); var args = CompileInvocationArguments(invokeMemberExpressionAst.Arguments); - + var memberNameAst = invokeMemberExpressionAst.Member as StringConstantExpressionAst; if (memberNameAst != null) { @@ -5509,12 +5507,12 @@ namespace System.Management.Automation.Language for (int index = 0; index < keyValuePairs.Count; index++) { var keyValuePair = keyValuePairs[index]; - Expression key = Expression.Convert(Compile(keyValuePair.Item1), typeof (object)); + Expression key = Expression.Convert(Compile(keyValuePair.Item1), typeof(object)); // We should not preserve the partial output if exception is thrown when evaluating the value. Expression value = Expression.Convert( CaptureStatementResults(keyValuePair.Item2, - CaptureAstContext.AssignmentWithoutResultPreservation), typeof (object)); + CaptureAstContext.AssignmentWithoutResultPreservation), typeof(object)); Expression errorExtent = Expression.Constant(keyValuePair.Item1.Extent); yield return Expression.Call(CachedReflectionInfo.HashtableOps_AddKeyValuePair, @@ -5587,7 +5585,7 @@ namespace System.Management.Automation.Language var arrayLiteral = (index as ArrayLiteralAst); var constraints = CombineTypeConstraintForMethodResolution(GetTypeConstraintForMethodResolution(indexExpressionAst.Target), GetTypeConstraintForMethodResolution(index)); - + // An array literal is either: // $x[1,2] // or @@ -5617,19 +5615,19 @@ namespace System.Management.Automation.Language #endregion Expressions } - class MemberAssignableValue : IAssignableValue + internal class MemberAssignableValue : IAssignableValue { internal MemberExpressionAst MemberExpression { get; set; } private Expression CachedTarget { get; set; } private Expression CachedPropertyExpr { get; set; } - Expression GetTargetExpr(Compiler compiler) + private Expression GetTargetExpr(Compiler compiler) { return compiler.Compile(MemberExpression.Expression); } - Expression GetPropertyExpr(Compiler compiler) + private Expression GetPropertyExpr(Compiler compiler) { return compiler.Compile(MemberExpression.Member); } @@ -5672,7 +5670,7 @@ namespace System.Management.Automation.Language } } - class InvokeMemberAssignableValue : IAssignableValue + internal class InvokeMemberAssignableValue : IAssignableValue { internal InvokeMemberExpressionAst InvokeMemberExpressionAst { get; set; } @@ -5680,17 +5678,17 @@ namespace System.Management.Automation.Language private ParameterExpression _memberNameExprTemp; private IEnumerable _argExprTemps; - Expression GetTargetExpr(Compiler compiler) + private Expression GetTargetExpr(Compiler compiler) { return _targetExprTemp ?? compiler.Compile(InvokeMemberExpressionAst.Expression); } - Expression GetMemberNameExpr(Compiler compiler) + private Expression GetMemberNameExpr(Compiler compiler) { return _memberNameExprTemp ?? compiler.Compile(InvokeMemberExpressionAst.Member); } - IEnumerable GetArgumentExprs(Compiler compiler) + private IEnumerable GetArgumentExprs(Compiler compiler) { if (_argExprTemps != null) { @@ -5701,7 +5699,7 @@ namespace System.Management.Automation.Language ? Utils.EmptyArray() : (InvokeMemberExpressionAst.Arguments.Select(compiler.Compile)).ToArray(); } - + public Expression GetValue(Compiler compiler, List exprs, List temps) { var constraints = Compiler.GetInvokeMemberConstraints(InvokeMemberExpressionAst); @@ -5727,7 +5725,7 @@ namespace System.Management.Automation.Language var memberNameExpr = GetMemberNameExpr(compiler); _memberNameExprTemp = Expression.Variable(memberNameExpr.Type); - + exprs.Insert(exprsIndex, Expression.Assign(_memberNameExprTemp, memberNameExpr)); temps.Insert(tempsIndex, _memberNameExprTemp); @@ -5751,7 +5749,7 @@ namespace System.Management.Automation.Language } } - class IndexAssignableValue : IAssignableValue + internal class IndexAssignableValue : IAssignableValue { internal IndexExpressionAst IndexExpressionAst { get; set; } @@ -5764,12 +5762,12 @@ namespace System.Management.Automation.Language Compiler.GetTypeConstraintForMethodResolution(IndexExpressionAst.Index)); } - Expression GetTargetExpr(Compiler compiler) + private Expression GetTargetExpr(Compiler compiler) { return _targetExprTemp ?? compiler.Compile(IndexExpressionAst.Target); } - Expression GetIndexExpr(Compiler compiler) + private Expression GetIndexExpr(Compiler compiler) { return _indexExprTemp ?? compiler.Compile(IndexExpressionAst.Index); } @@ -5830,11 +5828,11 @@ namespace System.Management.Automation.Language setExpr = DynamicExpression.Dynamic(PSSetIndexBinder.Get(1, constraints), typeof(object), targetExpr, GetIndexExpr(compiler), temp); } - return Expression.Block(new[] {temp}, Expression.Assign(temp, rhs), setExpr, temp); + return Expression.Block(new[] { temp }, Expression.Assign(temp, rhs), setExpr, temp); } } - class ArrayAssignableValue : IAssignableValue + internal class ArrayAssignableValue : IAssignableValue { internal ArrayLiteralAst ArrayLiteral { get; set; } @@ -5875,11 +5873,11 @@ namespace System.Management.Automation.Language } // Add the temp as the last expression for chained assignment, i.e. $x = $y,$z = 1,2 exprs.Add(rhsTemp); - return Expression.Block(new [] { rhsTemp }, exprs); + return Expression.Block(new[] { rhsTemp }, exprs); } } - class PowerShellLoopExpression : Expression, Interpreter.IInstructionProvider + internal class PowerShellLoopExpression : Expression, Interpreter.IInstructionProvider { public override bool CanReduce { get { return true; } } public override Type Type { get { return typeof(void); } } @@ -5900,9 +5898,9 @@ namespace System.Management.Automation.Language public void AddInstructions(LightCompiler compiler) { EnterLoopInstruction enterLoop = null; - + compiler.PushLabelBlock(LabelScopeKind.Statement); - + // emit loop body: foreach (var expr in _exprs) { @@ -5924,7 +5922,7 @@ namespace System.Management.Automation.Language } } - class EnterLoopExpression : Expression, Interpreter.IInstructionProvider + internal class EnterLoopExpression : Expression, Interpreter.IInstructionProvider { public override bool CanReduce { get { return true; } } public override Type Type { get { return typeof(void); } } @@ -5954,7 +5952,7 @@ namespace System.Management.Automation.Language } } - class UpdatePositionExpr : Expression, Interpreter.IInstructionProvider + internal class UpdatePositionExpr : Expression, Interpreter.IInstructionProvider { public override bool CanReduce { get { return true; } } public override Type Type { get { return typeof(void); } } diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index 2679fdfa8..c150109db 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -11,19 +11,18 @@ using System.Reflection; namespace System.Management.Automation.Language { - /* * The IsGetPowerShellSafeValueVisitor class in SafeValues.cs used this class as the basis for implementation. * There is a number of similarities between these two classes, and changes (fixes) in this code * may need to be reflected in that class and vice versa */ - class IsConstantValueVisitor : ICustomAstVisitor + internal class IsConstantValueVisitor : ICustomAstVisitor { public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false) { try { - if ((bool)ast.Accept(new IsConstantValueVisitor {CheckingAttributeArgument = forAttribute, CheckingRequiresArgument = forRequires})) + if ((bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = forAttribute, CheckingRequiresArgument = forRequires })) { Ast parent = ast.Parent; while (parent != null) @@ -37,7 +36,7 @@ namespace System.Management.Automation.Language if (parent == null) { - constantValue = ast.Accept(new ConstantValueVisitor { AttributeArgument = forAttribute, RequiresArgument = forRequires}); + constantValue = ast.Accept(new ConstantValueVisitor { AttributeArgument = forAttribute, RequiresArgument = forRequires }); return true; } } @@ -126,13 +125,13 @@ namespace System.Management.Automation.Language switch (parent.Operator) { - case TokenKind.Divide: - case TokenKind.DivideEquals: - case TokenKind.Rem: - case TokenKind.RemainderEquals: - string name = varExpr.VariablePath.UnqualifiedPath; - return (name.Equals(SpecialVariables.False, StringComparison.OrdinalIgnoreCase) || - name.Equals(SpecialVariables.Null, StringComparison.OrdinalIgnoreCase)); + case TokenKind.Divide: + case TokenKind.DivideEquals: + case TokenKind.Rem: + case TokenKind.RemainderEquals: + string name = varExpr.VariablePath.UnqualifiedPath; + return (name.Equals(SpecialVariables.False, StringComparison.OrdinalIgnoreCase) || + name.Equals(SpecialVariables.Null, StringComparison.OrdinalIgnoreCase)); } return false; @@ -264,7 +263,7 @@ namespace System.Management.Automation.Language } } - class ConstantValueVisitor : ICustomAstVisitor + internal class ConstantValueVisitor : ICustomAstVisitor { internal bool AttributeArgument { get; set; } internal bool RequiresArgument { get; set; } @@ -274,14 +273,14 @@ namespace System.Management.Automation.Language private void CheckIsConstant(Ast ast, string msg) { Diagnostics.Assert( - (bool)ast.Accept(new IsConstantValueVisitor {CheckingAttributeArgument = this.AttributeArgument, CheckingRequiresArgument = RequiresArgument}), msg); + (bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = this.AttributeArgument, CheckingRequiresArgument = RequiresArgument }), msg); } private static object CompileAndInvoke(Ast ast) { try { - var compiler = new Compiler {CompilingConstantExpression = true}; + var compiler = new Compiler { CompilingConstantExpression = true }; return Expression.Lambda((Expression)ast.Accept(compiler)).Compile().DynamicInvoke(); } catch (TargetInvocationException tie) diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 8d52114f4..8355c7669 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -155,7 +155,7 @@ namespace System.Management.Automation.Language { } } - #region The printing code +#region The printing code private void Out(string s) { Out(Flow.None, s, Flow.None); @@ -215,9 +215,9 @@ namespace System.Management.Automation.Language { return flow; } - #endregion +#endregion - #region The AST Output +#region The AST Output // More proper would be to make this a virtual method on Action private static string FormatBinder(CallSiteBinder binder) { @@ -1180,7 +1180,7 @@ namespace System.Management.Automation.Language { } } - #endregion +#endregion } } #endif diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs index 391ee5f49..f58a63ca3 100644 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs @@ -21,10 +21,10 @@ namespace Microsoft.CodeAnalysis /// Represents the current Processor architecture /// public static readonly ProcessorArchitecture[] CurrentArchitectures = (IntPtr.Size == 4) - ? new []{ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86} - : new []{ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64}; + ? new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86 } + : new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64 }; - #region Interop +#region Interop private const int MAX_PATH = 260; @@ -81,7 +81,7 @@ namespace Microsoft.CodeAnalysis [DllImport("clr", CharSet = CharSet.Auto, PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); - #endregion +#endregion private const int S_OK = 0; private const int S_FALSE = 1; diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 3d42739a2..78ed50f3a 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -17,14 +17,14 @@ namespace System.Management.Automation.Language { internal class TypeDefiner { - private static int globalCounter = 0; - private static readonly object[] emptyArgArray = Utils.EmptyArray(); - static readonly CustomAttributeBuilder hiddenCustomAttributeBuilder = - new CustomAttributeBuilder(typeof(HiddenAttribute).GetConstructor(Type.EmptyTypes), emptyArgArray); + private static int s_globalCounter = 0; + private static readonly object[] s_emptyArgArray = Utils.EmptyArray(); + private static readonly CustomAttributeBuilder s_hiddenCustomAttributeBuilder = + new CustomAttributeBuilder(typeof(HiddenAttribute).GetConstructor(Type.EmptyTypes), s_emptyArgArray); - private static readonly string SessionStateKeeperFieldName = "__sessionStateKeeper"; + private static readonly string s_sessionStateKeeperFieldName = "__sessionStateKeeper"; internal static readonly string SessionStateFieldName = "__sessionState"; - private static readonly MethodInfo SessionStateKeeper_GetSessionState = + private static readonly MethodInfo s_sessionStateKeeper_GetSessionState = typeof(SessionStateKeeper).GetMethod("GetSessionState", BindingFlags.Instance | BindingFlags.Public); private static bool TryConvertArg(object arg, Type type, out object result, Parser parser, IScriptExtent errorExtent) @@ -42,8 +42,8 @@ namespace System.Management.Automation.Language } return true; } - - static CustomAttributeBuilder GetAttributeBuilder(Parser parser, AttributeAst attributeAst, AttributeTargets attributeTargets) + + private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, AttributeAst attributeAst, AttributeTargets attributeTargets) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); Diagnostics.Assert(attributeType != null, "Semantic checks should have verified attribute type exists"); @@ -53,7 +53,7 @@ namespace System.Management.Automation.Language (attributeType.GetTypeInfo().GetCustomAttribute(true).ValidOn & attributeTargets) != 0, "Semantic checks should have verified attribute usage"); var positionalArgs = new object[attributeAst.PositionalArguments.Count]; - var cvv = new ConstantValueVisitor {AttributeArgument = false}; + var cvv = new ConstantValueVisitor { AttributeArgument = false }; for (var i = 0; i < attributeAst.PositionalArguments.Count; i++) { var posArg = attributeAst.PositionalArguments[i]; @@ -136,7 +136,7 @@ namespace System.Management.Automation.Language "Semantic checks should have ensured names attribute argument exists"); arg = namedArg.Argument.Accept(cvv); - + var propertyInfo = members[0] as PropertyInfo; if (propertyInfo != null) { @@ -167,7 +167,7 @@ namespace System.Management.Automation.Language propertyInfoList.ToArray(), propertyArgs.ToArray(), fieldInfoList.ToArray(), fieldArgs.ToArray()); } - + internal static void DefineCustomAttributes(TypeBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { if (attributes != null) @@ -243,7 +243,7 @@ namespace System.Management.Automation.Language } } - class DefineTypeHelper + private class DefineTypeHelper { private readonly Parser _parser; internal readonly TypeDefinitionAst _typeDefinitionAst; @@ -278,11 +278,11 @@ namespace System.Management.Automation.Language _typeDefinitionAst.Type = _typeBuilder.AsType(); _fieldsToInitForMemberFunctions = new List>(); - _definedMethods = new Dictionary>>(StringComparer.OrdinalIgnoreCase); + _definedMethods = new Dictionary>>(StringComparer.OrdinalIgnoreCase); _definedProperties = new Dictionary(StringComparer.OrdinalIgnoreCase); _sessionStateField = _typeBuilder.DefineField(SessionStateFieldName, typeof(SessionStateInternal), FieldAttributes.Private); - _sessionStateKeeperField = _staticHelpersTypeBuilder.DefineField(SessionStateKeeperFieldName, typeof(SessionStateKeeper), FieldAttributes.Assembly | FieldAttributes.Static); + _sessionStateKeeperField = _staticHelpersTypeBuilder.DefineField(s_sessionStateKeeperFieldName, typeof(SessionStateKeeper), FieldAttributes.Assembly | FieldAttributes.Static); } /// @@ -382,7 +382,6 @@ namespace System.Management.Automation.Language } else { - if (interfaceType.GetTypeInfo().IsInterface) { interfaces.Add(interfaceType); @@ -435,7 +434,7 @@ namespace System.Management.Automation.Language else { FunctionMemberAst method = member as FunctionMemberAst; - Diagnostics.Assert(method != null, StringUtil.Format("Unexpected subtype of MemberAst '{0}'. Expect `{1}`", + Diagnostics.Assert(method != null, StringUtil.Format("Unexpected subtype of MemberAst '{0}'. Expect `{1}`", member.GetType().Name, typeof(FunctionMemberAst).GetType().Name)); if (method.IsConstructor) { @@ -560,12 +559,12 @@ namespace System.Management.Automation.Language hasValidateAttributes = true; break; } - } + } } // The last argument of DefineProperty is null, because the property has no parameters. PropertyBuilder property = _typeBuilder.DefineProperty(propertyMemberAst.Name, Reflection.PropertyAttributes.None, type, null); - + // Define the "get" accessor method. MethodBuilder getMethod = _typeBuilder.DefineMethod(String.Concat("get_", propertyMemberAst.Name), getSetAttributes, type, Type.EmptyTypes); ILGenerator getIlGen = getMethod.GetILGenerator(); @@ -581,7 +580,7 @@ namespace System.Management.Automation.Language getIlGen.Emit(OpCodes.Ldarg_0); getIlGen.Emit(OpCodes.Ldfld, backingField); getIlGen.Emit(OpCodes.Ret); - } + } // Define the "set" accessor method. MethodBuilder setMethod = _typeBuilder.DefineMethod(String.Concat("set_", propertyMemberAst.Name), getSetAttributes, null, new Type[] { type }); @@ -600,7 +599,7 @@ namespace System.Management.Automation.Language } setIlGen.Emit(OpCodes.Call, CachedReflectionInfo.ClassOps_ValidateSetProperty); } - + if (propertyMemberAst.IsStatic) { setIlGen.Emit(OpCodes.Ldarg_0); @@ -621,7 +620,7 @@ namespace System.Management.Automation.Language if (propertyMemberAst.IsHidden) { - property.SetCustomAttribute(hiddenCustomAttributeBuilder); + property.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } return property; @@ -678,7 +677,7 @@ namespace System.Management.Automation.Language private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) { - var parameters = ((IParameterMetadataProvider) functionMemberAst).Parameters; + var parameters = ((IParameterMetadataProvider)functionMemberAst).Parameters; if (parameters == null) { return PSTypeExtensions.EmptyTypes; @@ -777,7 +776,7 @@ namespace System.Management.Automation.Language DefineCustomAttributes(method, functionMemberAst.Attributes, _parser, AttributeTargets.Method); if (functionMemberAst.IsHidden) { - method.SetCustomAttribute(hiddenCustomAttributeBuilder); + method.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } var ilGenerator = method.GetILGenerator(); DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Count()), functionMemberAst.IsStatic, parameterTypes, returnType, @@ -793,7 +792,7 @@ namespace System.Management.Automation.Language DefineCustomAttributes(ctor, attributeAsts, _parser, AttributeTargets.Constructor); if (isHidden) { - ctor.SetCustomAttribute(hiddenCustomAttributeBuilder); + ctor.SetCustomAttribute(s_hiddenCustomAttributeBuilder); } var ilGenerator = ctor.GetILGenerator(); @@ -803,7 +802,7 @@ namespace System.Management.Automation.Language ilGenerator.Emit(OpCodes.Ldnull); ilGenerator.Emit(OpCodes.Ldfld, _sessionStateKeeperField); - ilGenerator.EmitCall(OpCodes.Call, SessionStateKeeper_GetSessionState, null); // load 'sessionState' on stack for Stfld call + ilGenerator.EmitCall(OpCodes.Call, s_sessionStateKeeper_GetSessionState, null); // load 'sessionState' on stack for Stfld call ilGenerator.Emit(OpCodes.Stfld, _sessionStateField); } @@ -814,7 +813,7 @@ namespace System.Management.Automation.Language private string GetMetaDataName(string name, int numberOfParameters) { - int currentId = Interlocked.Increment(ref globalCounter); + int currentId = Interlocked.Increment(ref s_globalCounter); string metaDataName = name + "_" + numberOfParameters + "_" + currentId; return metaDataName; } @@ -850,10 +849,10 @@ namespace System.Management.Automation.Language if (parameterCount > 0) { var parameters = ipmp.Parameters; - var local = ilGenerator.DeclareLocal(typeof (object[])); + var local = ilGenerator.DeclareLocal(typeof(object[])); EmitLdc(ilGenerator, parameterCount); // Create an array to hold all - ilGenerator.Emit(OpCodes.Newarr, typeof (object)); // of the parameters + ilGenerator.Emit(OpCodes.Newarr, typeof(object)); // of the parameters ilGenerator.Emit(OpCodes.Stloc, local); // Save array for repeated use int j = isStatic ? 0 : 1; for (int i = 0; i < parameterCount; i++, j++) @@ -896,7 +895,7 @@ namespace System.Management.Automation.Language } } - class DefineEnumHelper + private class DefineEnumHelper { private readonly Parser _parser; private readonly TypeDefinitionAst _enumDefinitionAst; @@ -950,7 +949,7 @@ namespace System.Management.Automation.Language // There won't be many nodes in our graph, so we just use a dictionary with a list of edges instead // of something cleaner. var graph = new Dictionary>>(); - + // Add all of our nodes to the graph foreach (var helper in defineEnumHelpers) { @@ -1072,7 +1071,6 @@ namespace System.Management.Automation.Language _parser.ReportError(enumerator.InitialValue.Extent, () => ParserStrings.CannotConvertValue, ToStringCodeMethods.Type(typeof(int))); } - } } } @@ -1111,7 +1109,7 @@ namespace System.Management.Automation.Language private static IEnumerable GetAssemblyAttributeBuilders() { - yield return new CustomAttributeBuilder(typeof(DynamicClassImplementationAssemblyAttribute).GetConstructor(Type.EmptyTypes), emptyArgArray); + yield return new CustomAttributeBuilder(typeof(DynamicClassImplementationAssemblyAttribute).GetConstructor(Type.EmptyTypes), s_emptyArgArray); } internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionAst[] typeDefinitions) @@ -1119,7 +1117,7 @@ namespace System.Management.Automation.Language Diagnostics.Assert(rootAst.Parent == null, "Caller should only define types from the root ast"); var definedTypes = new HashSet(StringComparer.OrdinalIgnoreCase); - + // First character is a special mark that allows us to cheaply ignore dynamic generated assemblies in ClrFacede.GetAssemblies() // Two replaces at the end are for not-allowed characters. They are replaced by similar-looking chars. string assemblyName = ClrFacade.FIRST_CHAR_PSASSEMBLY_MARK + (string.IsNullOrWhiteSpace(rootAst.Extent.File) @@ -1128,7 +1126,7 @@ namespace System.Management.Automation.Language .Replace('\\', (char)0x29f9) .Replace('/', (char)0x29f9) .Replace(':', (char)0x0589)); - + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndCollect, GetAssemblyAttributeBuilders()); var module = assembly.DefineDynamicModule(assemblyName); @@ -1187,7 +1185,7 @@ namespace System.Management.Automation.Language } } - helperType.GetField(SessionStateKeeperFieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, new SessionStateKeeper()); + helperType.GetField(s_sessionStateKeeperFieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, new SessionStateKeeper()); } catch (TypeLoadException e) { @@ -1198,8 +1196,6 @@ namespace System.Management.Automation.Language // Error checking should be moved/added to semantic checks. parser.ReportError(helper._typeDefinitionAst.Extent, () => ParserStrings.TypeCreationError, helper._typeBuilder.Name, e.Message); - - } } @@ -1212,7 +1208,7 @@ namespace System.Management.Automation.Language return assembly; } - + private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst) { // Only allocate a list if necessary - in the most common case, we don't need it. @@ -1247,7 +1243,7 @@ namespace System.Management.Automation.Language return string.Join(".", nameParts); } - private static OpCode[] _ldc = + private static OpCode[] s_ldc = { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 @@ -1255,9 +1251,9 @@ namespace System.Management.Automation.Language private static void EmitLdc(ILGenerator emitter, int c) { - if (c < _ldc.Length) + if (c < s_ldc.Length) { - emitter.Emit(_ldc[c]); + emitter.Emit(s_ldc[c]); } else { @@ -1265,16 +1261,16 @@ namespace System.Management.Automation.Language } } - private static OpCode[] _ldarg = + private static OpCode[] s_ldarg = { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 }; private static void EmitLdarg(ILGenerator emitter, int c) { - if (c < _ldarg.Length) + if (c < s_ldarg.Length) { - emitter.Emit(_ldarg[c]); + emitter.Emit(s_ldarg[c]); } else { diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 0cfc4dd70..041b4b99e 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -90,7 +90,7 @@ namespace System.Management.Automation.Language { var emptyExtent = new EmptyScriptExtent(); var errorMsg = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileReadError, e.Message); - errors = new[] {new ParseError(emptyExtent, "FileReadError", errorMsg)}; + errors = new[] { new ParseError(emptyExtent, "FileReadError", errorMsg) }; tokens = Utils.EmptyArray(); return new ScriptBlockAst(emptyExtent, null, new StatementBlockAst(emptyExtent, null, null), false); } @@ -120,7 +120,7 @@ namespace System.Management.Automation.Language tokens = tokenList.ToArray(); return result; } - string _keywordModuleName; + private string _keywordModuleName; /// @@ -132,7 +132,7 @@ namespace System.Management.Automation.Language /// The that represents the input script file. public static ScriptBlockAst ParseInput(string input, out Token[] tokens, out ParseError[] errors) { - return ParseInput(input, null /* fileName */, out tokens, out errors); + return ParseInput(input, null /* fileName */, out tokens, out errors); } /// @@ -271,7 +271,7 @@ namespace System.Management.Automation.Language var tokenizer = parser._tokenizer; tokenizer.Initialize(null, typename, null); Token unused; - var result = parser.TypeNameRule(allowAssemblyQualifiedNames:true, firstTypeNameToken:out unused); + var result = parser.TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out unused); SemanticChecks.CheckArrayTypeNameDepth(result, PositionUtilities.EmptyExtent, parser); if (!ignoreErrors && parser.ErrorList.Count > 0) @@ -555,18 +555,18 @@ namespace System.Management.Automation.Language } - internal void RequireStatementTerminator() - { - var terminatorToken = PeekToken(); - if (terminatorToken.Kind == TokenKind.NewLine || terminatorToken.Kind == TokenKind.Semi) - { - SkipToken(); - } - else if (terminatorToken.Kind != TokenKind.EndOfInput) - { - ReportIncompleteInput(terminatorToken.Extent, () => ParserStrings.MissingStatementTerminator); - } - } + internal void RequireStatementTerminator() + { + var terminatorToken = PeekToken(); + if (terminatorToken.Kind == TokenKind.NewLine || terminatorToken.Kind == TokenKind.Semi) + { + SkipToken(); + } + else if (terminatorToken.Kind != TokenKind.EndOfInput) + { + ReportIncompleteInput(terminatorToken.Extent, () => ParserStrings.MissingStatementTerminator); + } + } internal static IScriptExtent ExtentOf(IScriptExtent first, IScriptExtent last) { @@ -1039,7 +1039,7 @@ namespace System.Management.Automation.Language V3SkipNewlines(); Token firstTypeNameToken; - ITypeName typeName = TypeNameRule(allowAssemblyQualifiedNames:true, firstTypeNameToken:out firstTypeNameToken); + ITypeName typeName = TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out firstTypeNameToken); if (typeName == null) { // ErrorRecovery: Return null so we stop looking for attributes. @@ -1276,7 +1276,7 @@ namespace System.Management.Automation.Language // firstTypeNameToken is returned so we can mark it as an attribute if it turns out // that we've got a attribute instead of a type literal. firstTypeNameToken = typeName; - return FinishTypeNameRule(typeName, allowAssemblyQualifiedNames:allowAssemblyQualifiedNames); + return FinishTypeNameRule(typeName, allowAssemblyQualifiedNames: allowAssemblyQualifiedNames); } finally { @@ -1697,7 +1697,7 @@ namespace System.Management.Automation.Language extent = ExtentOf(startExtent, endExtent); CompleteScriptBlockBody(lCurly, ref extent, out scriptBlockExtent); - return new ScriptBlockAst(scriptBlockExtent, usingStatements, paramBlockAst, beginBlock, processBlock, endBlock, + return new ScriptBlockAst(scriptBlockExtent, usingStatements, paramBlockAst, beginBlock, processBlock, endBlock, dynamicParamBlock); } @@ -1850,7 +1850,7 @@ namespace System.Management.Automation.Language attributes[0].TypeName.FullName); } } - else if((token.TokenFlags & TokenFlags.Keyword) != 0) + else if ((token.TokenFlags & TokenFlags.Keyword) != 0) { foreach (var attr in attributes.Where(attr => !(attr is AttributeAst))) { @@ -1922,7 +1922,7 @@ namespace System.Management.Automation.Language statement = BlockStatementRule(token); break; case TokenKind.Configuration: - statement = ConfigurationStatementRule(attributes != null? attributes.OfType() : null, token); + statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); break; case TokenKind.From: case TokenKind.Define: @@ -2041,7 +2041,7 @@ namespace System.Management.Automation.Language if (token.Kind != TokenKind.NewLine && token.Kind != TokenKind.Semi) { ExpressionAst labelExpr; - bool disableCommaOperator = this._disableCommaOperator; + bool disableCommaOperator = _disableCommaOperator; try { _disableCommaOperator = true; @@ -2704,7 +2704,7 @@ namespace System.Management.Automation.Language if (IsConstantValueVisitor.IsConstant(configurationName, out outValue)) { simpleConfigurationNameValue = outValue as string; - if (simpleConfigurationNameValue == null || + if (simpleConfigurationNameValue == null || !System.Text.RegularExpressions.Regex.IsMatch(simpleConfigurationNameValue, "^[A-Za-z][A-Za-z0-9_./-]*$")) { // This is actually a semantics check, the syntax is fine at this point. @@ -2812,7 +2812,7 @@ namespace System.Management.Automation.Language // we'll catch the exception and report it as an error. ReportError(configurationKeywordToken.Extent, () => e.ToString()); return null; - } + } } finally { @@ -2984,12 +2984,12 @@ namespace System.Management.Automation.Language bodyAst, isMetaConfiguration ? ConfigurationType.Meta : ConfigurationType.Resource, configurationName) - { - LCurlyToken = lCurly, - ConfigurationToken = configurationToken, - CustomAttributes = customAttributes, - DefinedKeywords = DynamicKeyword.GetKeyword() - }; + { + LCurlyToken = lCurly, + ConfigurationToken = configurationToken, + CustomAttributes = customAttributes, + DefinedKeywords = DynamicKeyword.GetKeyword() + }; } catch (Exception e) { @@ -3023,11 +3023,10 @@ namespace System.Management.Automation.Language // this will flush any cached dynamic keyword tokens. var restorePoint = _tokenizer.GetRestorePoint(); Resync(restorePoint); - } } - Dictionary _configurationKeywordsDefinedInThisFile; + private Dictionary _configurationKeywordsDefinedInThisFile; /// /// Reads an argument expression for a keyword or keyword parameter. @@ -3153,7 +3152,6 @@ namespace System.Management.Automation.Language } else { - SkipNewlines(); pipeline = PipelineRule(); if (pipeline == null) @@ -3400,7 +3398,7 @@ namespace System.Management.Automation.Language } } } - catch(Exception e) + catch (Exception e) { ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPreParseException, keywordData.ResourceName, e.ToString()); return null; @@ -3441,7 +3439,7 @@ namespace System.Management.Automation.Language Token nameToken = NextToken(); if (nameToken.Kind == TokenKind.EndOfInput) { - UngetToken(nameToken); + UngetToken(nameToken); if (keywordData.NameMode == DynamicKeywordNameMode.NameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired) { @@ -3506,7 +3504,7 @@ namespace System.Management.Automation.Language } return null; } - + // Ok, we got a name expression, but we're expecting no name, so it's and error. if (keywordData.NameMode == DynamicKeywordNameMode.NoName) { @@ -3546,7 +3544,7 @@ namespace System.Management.Automation.Language if (lCurly.Kind == TokenKind.EndOfInput) { UngetToken(lCurly); - ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition ); + ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition); // Preserve the name expression for tab completion return originalInstanceName == null @@ -3567,7 +3565,7 @@ namespace System.Management.Automation.Language InvokeMemberExpressionAst instanceInvokeMemberExpressionAst = instanceName as InvokeMemberExpressionAst; - if (instanceInvokeMemberExpressionAst != null && + if (instanceInvokeMemberExpressionAst != null && instanceInvokeMemberExpressionAst.Arguments.Count == 1 && instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && // the last condition checks that there is no space between "method" name and '{' @@ -3588,8 +3586,8 @@ namespace System.Management.Automation.Language IScriptExtent errorExtent = ExtentOf(originalInstanceName, lCurly); var errorExpr = new ErrorExpressionAst(errorExtent); var memberExpr = new MemberExpressionAst(originalInstanceName.Extent, originalInstanceName, errorExpr, @static: false); - - return new ErrorStatementAst(errorExtent, new[] {memberExpr}); + + return new ErrorStatementAst(errorExtent, new[] { memberExpr }); } UngetToken(lCurly); @@ -3611,7 +3609,6 @@ namespace System.Management.Automation.Language var oldInConfiguraiton = _inConfiguration; try { - _inConfiguration = false; body = ScriptBlockExpressionRule(lCurly); } @@ -3694,7 +3691,7 @@ namespace System.Management.Automation.Language } } } - catch(Exception e) + catch (Exception e) { ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPostParseException, keywordData.Keyword, e.ToString()); return null; @@ -3838,7 +3835,7 @@ namespace System.Management.Automation.Language classNameToken.TokenFlags |= TokenFlags.TypeName; SkipNewlines(); - + // handle inheritance constraint. var oldTokenizerMode = _tokenizer.Mode; var superClassesList = new List(); @@ -3892,7 +3889,7 @@ namespace System.Management.Automation.Language List nestedAsts = null; MemberAst member; List members = new List(); - List astsOnError=null; + List astsOnError = null; while ((member = ClassMemberRule(name.Value, out astsOnError)) != null || astsOnError != null) { @@ -3912,7 +3909,7 @@ namespace System.Management.Automation.Language } } - var rCurly = NextToken(); + var rCurly = NextToken(); if (rCurly.Kind != TokenKind.RCurly) { UngetToken(rCurly); @@ -3943,7 +3940,7 @@ namespace System.Management.Automation.Language { return new ErrorStatementAst(extent, nestedAsts); } - + return classDefn; } finally @@ -4053,29 +4050,29 @@ namespace System.Management.Automation.Language break; #endif - case TokenKind.Hidden: - if (hiddenToken != null) - { - ReportError(token.Extent, () => ParserStrings.DuplicateQualifier, token.Text); - } - hiddenToken = token; - lastAttribute = token; - SkipToken(); - break; + case TokenKind.Hidden: + if (hiddenToken != null) + { + ReportError(token.Extent, () => ParserStrings.DuplicateQualifier, token.Text); + } + hiddenToken = token; + lastAttribute = token; + SkipToken(); + break; - case TokenKind.Static: - if (staticToken != null) - { - ReportError(token.Extent, () => ParserStrings.DuplicateQualifier, token.Text); - } - staticToken = token; - lastAttribute = token; - SkipToken(); - break; + case TokenKind.Static: + if (staticToken != null) + { + ReportError(token.Extent, () => ParserStrings.DuplicateQualifier, token.Text); + } + staticToken = token; + lastAttribute = token; + SkipToken(); + break; - default: - scanningAttributes = false; - break; + default: + scanningAttributes = false; + break; } } @@ -4188,7 +4185,7 @@ namespace System.Management.Automation.Language { return; } - + if (astsOnError == null) { astsOnError = new List(); @@ -4376,34 +4373,34 @@ namespace System.Management.Automation.Language bool aliasRequired = false; switch (directiveToken.Kind) { - case TokenKind.Namespace: - kind = UsingStatementKind.Namespace; - aliasAllowed = true; - break; + case TokenKind.Namespace: + kind = UsingStatementKind.Namespace; + aliasAllowed = true; + break; - case TokenKind.Type: - kind = UsingStatementKind.Type; - aliasRequired = true; - break; + case TokenKind.Type: + kind = UsingStatementKind.Type; + aliasRequired = true; + break; - case TokenKind.Module: - kind = UsingStatementKind.Module; - aliasAllowed = true; - break; + case TokenKind.Module: + kind = UsingStatementKind.Module; + aliasAllowed = true; + break; - case TokenKind.Command: - kind = UsingStatementKind.Command; - aliasRequired = true; - break; + case TokenKind.Command: + kind = UsingStatementKind.Command; + aliasRequired = true; + break; - case TokenKind.Assembly: - kind = UsingStatementKind.Assembly; - break; + case TokenKind.Assembly: + kind = UsingStatementKind.Assembly; + break; - default: - UngetToken(directiveToken); - ReportIncompleteInput(After(usingToken), () => ParserStrings.MissingUsingStatementDirective); - return new ErrorStatementAst(usingToken.Extent); + default: + UngetToken(directiveToken); + ReportIncompleteInput(After(usingToken), () => ParserStrings.MissingUsingStatementDirective); + return new ErrorStatementAst(usingToken.Extent); } var itemToken = NextToken(); @@ -4413,10 +4410,10 @@ namespace System.Management.Automation.Language case TokenKind.NewLine: // Example, using module ,FooBar case TokenKind.Comma: - { - ReportIncompleteInput(After(directiveToken), () => ParserStrings.MissingUsingItemName); - return new ErrorStatementAst(ExtentOf(usingToken, directiveToken)); - } + { + ReportIncompleteInput(After(directiveToken), () => ParserStrings.MissingUsingItemName); + return new ErrorStatementAst(ExtentOf(usingToken, directiveToken)); + } } var itemAst = GetCommandArgument(CommandArgumentContext.CommandArgument, itemToken); @@ -4458,17 +4455,17 @@ namespace System.Management.Automation.Language return new ErrorStatementAst(ExtentOf(usingToken, equalsToken)); } - var aliasAst = GetCommandArgument(CommandArgumentContext.CommandArgument, aliasToken); + var aliasAst = GetCommandArgument(CommandArgumentContext.CommandArgument, aliasToken); if (kind == UsingStatementKind.Module && aliasAst is HashtableAst) { htAst = (HashtableAst)aliasAst; } - else if (!(aliasAst is StringConstantExpressionAst)) - { - return new ErrorStatementAst(ExtentOf(usingToken, aliasAst), new Ast[] {itemAst, aliasAst}); - } + else if (!(aliasAst is StringConstantExpressionAst)) + { + return new ErrorStatementAst(ExtentOf(usingToken, aliasAst), new Ast[] { itemAst, aliasAst }); + } - RequireStatementTerminator(); + RequireStatementTerminator(); if (htAst == null) { @@ -4490,11 +4487,11 @@ namespace System.Management.Automation.Language if (aliasRequired) { ReportIncompleteInput(After(itemToken), () => ParserStrings.MissingEqualsInUsingAlias); - return new ErrorStatementAst(ExtentOf(usingToken, itemAst), new Ast[] {itemAst}); + return new ErrorStatementAst(ExtentOf(usingToken, itemAst), new Ast[] { itemAst }); } } - RequireStatementTerminator(); + RequireStatementTerminator(); if (htAst == null) { @@ -4599,8 +4596,8 @@ namespace System.Management.Automation.Language var functionName = functionNameToken.Text; List parameters; Token lParen = this.PeekToken(); - - IScriptExtent endErrorStatement = null; + + IScriptExtent endErrorStatement = null; Token rParen = null; if (lParen.Kind == TokenKind.LParen) @@ -4651,7 +4648,6 @@ namespace System.Management.Automation.Language endErrorStatement = baseToken.Extent; ReportIncompleteInput(After(baseToken), () => ParserStrings.MissingMethodParameterList); } - } else { @@ -4716,7 +4712,7 @@ namespace System.Management.Automation.Language ScriptBlockAst scriptBlock = ScriptBlockRule(lCurly, false, baseCtorCallStatement); var result = new FunctionDefinitionAst(ExtentOf(functionNameToken, scriptBlock), /*isFilter:*/false, /*isWorkflow:*/false, functionNameToken, parameters, scriptBlock); - + return result; } finally @@ -4734,7 +4730,7 @@ namespace System.Management.Automation.Language //G //G function-name: //G command-argument - + SkipNewlines(); Token functionNameToken = NextToken(); @@ -4774,7 +4770,7 @@ namespace System.Management.Automation.Language // A function name that matches a keyword isn't really a keyword, so don't color it that way functionNameToken.TokenFlags &= ~TokenFlags.Keyword; - IScriptExtent endErrorStatement; + IScriptExtent endErrorStatement; Token rParen; var parameters = this.FunctionParameterDeclarationRule(out endErrorStatement, out rParen); @@ -4845,7 +4841,7 @@ namespace System.Management.Automation.Language ReportIncompleteInput(After(endErrorStatement), () => ParserStrings.MissingEndParenthesisInFunctionParameterList); } SkipNewlines(); - } + } return parameters; } @@ -5432,7 +5428,7 @@ namespace System.Management.Automation.Language } [Flags] - enum CommandArgumentContext + private enum CommandArgumentContext { CommandName = 0x01, CommandNameAfterInvocationOperator = 0x02 | CommandName, @@ -6153,7 +6149,6 @@ namespace System.Management.Automation.Language { expr = new TypeExpressionAst(lastAttribute.Extent, lastAttribute.TypeName); } - } for (int i = attributes.Count - 2; i >= 0; --i) @@ -6676,7 +6671,7 @@ namespace System.Management.Automation.Language //G invoke-param-list: //G '(' invoke-param-paren-list //G script-block - + IScriptExtent lastExtent = null; List arguments; @@ -6862,15 +6857,17 @@ namespace System.Management.Automation.Language private static object[] arrayOfOneArg { - get { return _arrayOfOneArg ?? (_arrayOfOneArg = new object[1]); } + get { return t_arrayOfOneArg ?? (t_arrayOfOneArg = new object[1]); } } - [ThreadStatic] private static object[] _arrayOfOneArg; + [ThreadStatic] + private static object[] t_arrayOfOneArg; private static object[] arrayOfTwoArgs { - get { return _arrayOfTwoArgs ?? (_arrayOfTwoArgs = new object[2]); } + get { return t_arrayOfTwoArgs ?? (t_arrayOfTwoArgs = new object[2]); } } - [ThreadStatic] private static object[] _arrayOfTwoArgs; + [ThreadStatic] + private static object[] t_arrayOfTwoArgs; internal bool ReportIncompleteInput(IScriptExtent extent, Expression> errorExpr) { @@ -6978,10 +6975,10 @@ namespace System.Management.Automation.Language Diagnostics.Assert(!string.IsNullOrEmpty(message), "can't have a null error message"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "can't have a null error id"); - this._extent = extent; - this._errorId = errorId; - this._message = message; - this._incompleteInput = incompleteInput; + _extent = extent; + _errorId = errorId; + _message = message; + _incompleteInput = incompleteInput; } /// @@ -7018,7 +7015,7 @@ namespace System.Management.Automation.Language // Guid is {eba789d9-533b-58d4-cd1f-2e6520e3a9c2} [EventSource(Name = "Microsoft-PowerShell-Parser")] - class ParserEventSource : EventSource + internal class ParserEventSource : EventSource { internal static ParserEventSource Log = new ParserEventSource(); internal const int MaxScriptLengthToLog = 50; diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 0a295ecd8..05c905267 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -115,18 +115,18 @@ namespace System.Management.Automation.Language /// public static IScriptPosition EmptyPosition { - get { return emptyPosition; } + get { return s_emptyPosition; } } - private readonly static IScriptPosition emptyPosition = new EmptyScriptPosition(); + private readonly static IScriptPosition s_emptyPosition = new EmptyScriptPosition(); /// /// Return a unique extent repesenting an empty or missing extent. /// public static IScriptExtent EmptyExtent { - get { return emptyExtent; } + get { return s_emptyExtent; } } - private static readonly IScriptExtent emptyExtent = new EmptyScriptExtent(); + private static readonly IScriptExtent s_emptyExtent = new EmptyScriptExtent(); /// /// Return a message that looks like: @@ -277,11 +277,11 @@ namespace System.Management.Automation.Language { return start; } - if (start == emptyExtent) + if (start == s_emptyExtent) { return end; } - if (end == emptyExtent) + if (end == s_emptyExtent) { return start; } @@ -378,8 +378,8 @@ namespace System.Management.Automation.Language internal PositionHelper(string filename, string scriptText) { - this._filename = filename; - this._scriptText = scriptText; + _filename = filename; + _scriptText = scriptText; } internal string ScriptText @@ -432,7 +432,7 @@ namespace System.Management.Automation.Language internal InternalScriptPosition(PositionHelper _positionHelper, int offset) { this._positionHelper = _positionHelper; - this._offset = offset; + _offset = offset; } public string File { get { return _positionHelper.File; } } @@ -443,7 +443,7 @@ namespace System.Management.Automation.Language internal InternalScriptPosition CloneWithNewOffset(int offset) { - return new InternalScriptPosition(_positionHelper, offset); + return new InternalScriptPosition(_positionHelper, offset); } public string GetFullScript() @@ -461,8 +461,8 @@ namespace System.Management.Automation.Language internal InternalScriptExtent(PositionHelper _positionHelper, int startOffset, int endOffset) { this._positionHelper = _positionHelper; - this._startOffset = startOffset; - this._endOffset = endOffset; + _startOffset = startOffset; + _endOffset = endOffset; } public string File @@ -602,20 +602,20 @@ namespace System.Management.Automation.Language [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public ScriptPosition(string scriptName, int scriptLineNumber, int offsetInLine, string line) { - this._scriptName = scriptName; - this._scriptLineNumber = scriptLineNumber; - this._offsetInLine = offsetInLine; + _scriptName = scriptName; + _scriptLineNumber = scriptLineNumber; + _offsetInLine = offsetInLine; if (string.IsNullOrEmpty(line)) { - this._line = String.Empty; + _line = String.Empty; } else { - this._line = line; + _line = line; } } - + /// /// Creates a new script position, which represents a point in a script /// @@ -633,7 +633,7 @@ namespace System.Management.Automation.Language string fullScript) : this(scriptName, scriptLineNumber, offsetInLine, line) { - this._fullScript = fullScript; + _fullScript = fullScript; } /// @@ -677,7 +677,6 @@ namespace System.Management.Automation.Language private ScriptExtent() { - } /// @@ -685,8 +684,8 @@ namespace System.Management.Automation.Language /// public ScriptExtent(ScriptPosition startPosition, ScriptPosition endPosition) { - this._startPosition = startPosition; - this._endPosition = endPosition; + _startPosition = startPosition; + _endPosition = endPosition; } /// @@ -776,7 +775,7 @@ namespace System.Management.Automation.Language int endLineNumber = RemotingDecoder.GetPropertyValue(serializedScriptExtent, "ScriptExtent_EndLineNumber"); int endColumnNumber = RemotingDecoder.GetPropertyValue(serializedScriptExtent, "ScriptExtent_EndColumnNumber"); - ScriptPosition startPosition = new ScriptPosition(file, startLineNumber, startColumnNumber, null ); + ScriptPosition startPosition = new ScriptPosition(file, startLineNumber, startColumnNumber, null); ScriptPosition endPosition = new ScriptPosition(file, endLineNumber, endColumnNumber, null); _startPosition = startPosition; diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 1374b6acd..b5f2b0d72 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -35,9 +35,10 @@ using System.Management.Automation.Internal; * o VisitHashtable may be safe if its components are safe * */ + namespace System.Management.Automation.Language { - class IsSafeValueVisitor : ICustomAstVisitor + internal class IsSafeValueVisitor : ICustomAstVisitor { public static bool IsAstSafe(Ast ast, GetSafeValueVisitor.SafeValueContext safeValueContext) { @@ -51,7 +52,7 @@ namespace System.Management.Automation.Language internal IsSafeValueVisitor(GetSafeValueVisitor.SafeValueContext safeValueContext) { - this._safeValueContext = safeValueContext; + _safeValueContext = safeValueContext; } // This is a check of the number of visits @@ -64,7 +65,7 @@ namespace System.Management.Automation.Language // what we can verify. private GetSafeValueVisitor.SafeValueContext _safeValueContext; - public object VisitErrorStatement(ErrorStatementAst errorStatementAst) {return false;} + public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } @@ -111,7 +112,7 @@ namespace System.Management.Automation.Language foreach (var nestedExpression in expandableStringExpressionAst.NestedExpressions) { _visitCount++; - if (! (bool)nestedExpression.Accept(this)) + if (!(bool)nestedExpression.Accept(this)) { isSafe = false; break; @@ -119,7 +120,7 @@ namespace System.Management.Automation.Language } return isSafe; } - + public object VisitStatementBlock(StatementBlockAst statementBlockAst) { bool isSafe = true; @@ -157,7 +158,7 @@ namespace System.Management.Automation.Language public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { bool unaryExpressionIsSafe = unaryExpressionAst.TokenKind.HasTrait(TokenFlags.CanConstantFold) && - ! unaryExpressionAst.TokenKind.HasTrait(TokenFlags.DisallowedInRestrictedMode) && + !unaryExpressionAst.TokenKind.HasTrait(TokenFlags.DisallowedInRestrictedMode) && (bool)unaryExpressionAst.Child.Accept(this); if (unaryExpressionIsSafe) { @@ -271,7 +272,7 @@ namespace System.Management.Automation.Language { // Returning a ScriptBlock instance itself is OK, bad stuff only happens // when invoking one (which is blocked) - return true; + return true; } public object VisitParenExpression(ParenExpressionAst parenExpressionAst) @@ -285,7 +286,7 @@ namespace System.Management.Automation.Language * except in the case of handling the unary operator * ExecutionContext is provided to ensure we can resolve variables */ - class GetSafeValueVisitor : ICustomAstVisitor + internal class GetSafeValueVisitor : ICustomAstVisitor { internal enum SafeValueContext { @@ -299,7 +300,7 @@ namespace System.Management.Automation.Language public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext) { - _context = context; + s_context = context; if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) { return ast.Accept(new GetSafeValueVisitor()); @@ -312,7 +313,7 @@ namespace System.Management.Automation.Language throw PSTraceSource.NewArgumentException("ast"); } - private static ExecutionContext _context; + private static ExecutionContext s_context; public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { throw PSTraceSource.NewArgumentException("ast"); } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { throw PSTraceSource.NewArgumentException("ast"); } @@ -378,7 +379,6 @@ namespace System.Management.Automation.Language return null; } return offset >= 0 ? targetArray[offset] : targetArray[targetArray.Length + offset]; - } var targetHashtable = target as Hashtable; if (targetHashtable != null) @@ -393,7 +393,7 @@ namespace System.Management.Automation.Language private object GetIndexedValueFromTarget(object target, object index) { var indexArray = index as object[]; - return indexArray != null ? ((object[]) indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); + return indexArray != null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) @@ -414,9 +414,9 @@ namespace System.Management.Automation.Language object[] safeValues = new object[expandableStringExpressionAst.NestedExpressions.Count]; // retrieve OFS, and if it doesn't exist set it to space string ofs = null; - if ( _context != null ) + if (s_context != null) { - ofs = _context.SessionState.PSVariable.GetValue("OFS") as string; + ofs = s_context.SessionState.PSVariable.GetValue("OFS") as string; } if (ofs == null) { @@ -527,9 +527,9 @@ namespace System.Management.Automation.Language public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { - if ( _context != null ) + if (s_context != null) { - return Compiler.GetExpressionValue(unaryExpressionAst, true, _context, null); + return Compiler.GetExpressionValue(unaryExpressionAst, true, s_context, null); } else { @@ -541,9 +541,9 @@ namespace System.Management.Automation.Language { // at this point, we know we're safe because we checked both the type and the child, // so now we can just call the compiler and indicate that it's trusted (at this point) - if ( _context != null ) + if (s_context != null) { - return Compiler.GetExpressionValue(convertExpressionAst, true, _context, null); + return Compiler.GetExpressionValue(convertExpressionAst, true, s_context, null); } else { @@ -599,9 +599,9 @@ namespace System.Management.Automation.Language return Path.GetDirectoryName(scriptFileName); } - if (_context != null) + if (s_context != null) { - return VariableOps.GetVariableValue(variableExpressionAst.VariablePath, _context, variableExpressionAst); + return VariableOps.GetVariableValue(variableExpressionAst.VariablePath, s_context, variableExpressionAst); } throw PSTraceSource.NewArgumentException("ast"); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 7feafc345..e64ea3c28 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -19,17 +19,17 @@ namespace System.Management.Automation.Language internal class SemanticChecks : AstVisitor2, IAstPostVisitHandler { private readonly Parser _parser; - private static readonly IsConstantValueVisitor _isConstantAttributeArgVisitor = new IsConstantValueVisitor + private static readonly IsConstantValueVisitor s_isConstantAttributeArgVisitor = new IsConstantValueVisitor { CheckingAttributeArgument = true, }; - private static readonly IsConstantValueVisitor _isConstantAttributeArgForClassVisitor = new IsConstantValueVisitor + private static readonly IsConstantValueVisitor s_isConstantAttributeArgForClassVisitor = new IsConstantValueVisitor { CheckingAttributeArgument = true, CheckingClassAttributeArguments = true }; private readonly Stack _memberScopeStack; - private readonly Stack _scopeStack; + private readonly Stack _scopeStack; internal static void CheckAst(Parser parser, ScriptBlockAst ast) { @@ -43,9 +43,9 @@ namespace System.Management.Automation.Language private SemanticChecks(Parser parser) { - this._parser = parser; - this._memberScopeStack = new Stack(); - this._scopeStack = new Stack(); + _parser = parser; + _memberScopeStack = new Stack(); + _scopeStack = new Stack(); } private bool AnalyzingStaticMember() @@ -149,15 +149,15 @@ namespace System.Management.Automation.Language else if (parent is ParameterAst && _memberScopeStack.Peek() is FunctionMemberAst) { checkingAttributeOnClass = true; - + // TODO: we aren't actually generating any attributes in the class metadata attributeTargets = AttributeTargets.Parameter; } } var constantValueVisitor = checkingAttributeOnClass - ? _isConstantAttributeArgForClassVisitor - : _isConstantAttributeArgVisitor; + ? s_isConstantAttributeArgForClassVisitor + : s_isConstantAttributeArgVisitor; if (checkingAttributeOnClass) { @@ -241,9 +241,9 @@ namespace System.Management.Automation.Language } private static string GetValidNamedAttributeProperties(Type attributeType) - { + { var propertyNames = new List(); - PropertyInfo [] properties = attributeType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); + PropertyInfo[] properties = attributeType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy); for (int i = 0; i < properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; @@ -301,7 +301,7 @@ namespace System.Management.Automation.Language CheckArrayTypeNameDepth(typeExpressionAst.TypeName, typeExpressionAst.Extent, _parser); // If this is access to the [Type] class, it may be suspicious - if(typeof(Type) == typeExpressionAst.TypeName.GetReflectionType()) + if (typeof(Type) == typeExpressionAst.TypeName.GetReflectionType()) { MarkAstParentsAsSuspicious(typeExpressionAst); } @@ -313,7 +313,7 @@ namespace System.Management.Automation.Language { int count = 0; ITypeName type = typeName; - while ((type is TypeName)==false) + while ((type is TypeName) == false) { count++; if (count > 200) @@ -323,7 +323,7 @@ namespace System.Management.Automation.Language } if (type is ArrayTypeName) { - type = ((ArrayTypeName) type).ElementType; + type = ((ArrayTypeName)type).ElementType; } else { @@ -346,7 +346,7 @@ namespace System.Management.Automation.Language } if (dscResourceAttibuteAst != null) { - DscResourceChecker.CheckType(this._parser, typeDefinitionAst, dscResourceAttibuteAst); + DscResourceChecker.CheckType(_parser, typeDefinitionAst, dscResourceAttibuteAst); } return AstVisitAction.Continue; @@ -526,7 +526,7 @@ namespace System.Management.Automation.Language /// /// BreakStatementAst or ContinueStatementAst /// label name. Can be null - void CheckLabelExists(StatementAst ast, string label) + private void CheckLabelExists(StatementAst ast, string label) { if (String.IsNullOrEmpty(label)) { @@ -561,7 +561,7 @@ namespace System.Management.Automation.Language /// If label is null, either it's a break/continue to an unknown label /// (and unknown does not mean not specified, it means it's an expression we can't evaluate) or we have a return statement. /// - void CheckForFlowOutOfFinally(Ast ast, string label) + private void CheckForFlowOutOfFinally(Ast ast, string label) { Ast parent; for (parent = ast.Parent; parent != null; parent = parent.Parent) @@ -591,12 +591,12 @@ namespace System.Management.Automation.Language { _parser.ReportError(ast.Extent, () => ParserStrings.ControlLeavingFinally); break; - } + } } } } - static string GetLabel(ExpressionAst expr) + private static string GetLabel(ExpressionAst expr) { // We only return null from this method if the label is unknown. If no label is specified, // we just use the empty string. @@ -627,7 +627,7 @@ namespace System.Management.Automation.Language return AstVisitAction.Continue; } - void CheckForReturnStatement(ReturnStatementAst ast) + private void CheckForReturnStatement(ReturnStatementAst ast) { var functionMemberAst = _memberScopeStack.Peek() as FunctionMemberAst; if (functionMemberAst == null) @@ -638,14 +638,14 @@ namespace System.Management.Automation.Language { if (functionMemberAst.IsReturnTypeVoid()) { - this._parser.ReportError(ast.Extent, () => ParserStrings.VoidMethodHasReturn); + _parser.ReportError(ast.Extent, () => ParserStrings.VoidMethodHasReturn); } } else { if (!functionMemberAst.IsReturnTypeVoid()) { - this._parser.ReportError(ast.Extent, () => ParserStrings.NonVoidMethodMissingReturnValue); + _parser.ReportError(ast.Extent, () => ParserStrings.NonVoidMethodMissingReturnValue); } } } @@ -744,7 +744,6 @@ namespace System.Management.Automation.Language if (expectedType != lastConvertType) { _parser.ReportError(ast.Extent, () => ParserStrings.AssignmentStatementToAutomaticNotSupported, varPath.UnqualifiedPath, expectedType); - } break; } @@ -796,14 +795,14 @@ namespace System.Management.Automation.Language { switch (unaryExpressionAst.TokenKind) { - case TokenKind.PlusPlus: - case TokenKind.PostfixPlusPlus: - case TokenKind.MinusMinus: - case TokenKind.PostfixMinusMinus: - CheckAssignmentTarget(unaryExpressionAst.Child, false, - ast => _parser.ReportError(ast.Extent, () => ParserStrings.OperatorRequiresVariableOrProperty, - unaryExpressionAst.TokenKind.Text())); - break; + case TokenKind.PlusPlus: + case TokenKind.PostfixPlusPlus: + case TokenKind.MinusMinus: + case TokenKind.PostfixMinusMinus: + CheckAssignmentTarget(unaryExpressionAst.Child, false, + ast => _parser.ReportError(ast.Extent, () => ParserStrings.OperatorRequiresVariableOrProperty, + unaryExpressionAst.TokenKind.Text())); + break; } return AstVisitAction.Continue; @@ -928,7 +927,7 @@ namespace System.Management.Automation.Language var indexExpr = exprAst as IndexExpressionAst; if (indexExpr != null) { - if (!IsValidAttributeArgument(indexExpr.Index, _isConstantAttributeArgVisitor)) + if (!IsValidAttributeArgument(indexExpr.Index, s_isConstantAttributeArgVisitor)) { return indexExpr.Index; } @@ -1038,7 +1037,7 @@ namespace System.Management.Automation.Language public override AstVisitAction VisitMemberExpression(MemberExpressionAst memberExpressionAst) { - CheckMemberAccess(memberExpressionAst); + CheckMemberAccess(memberExpressionAst); return AstVisitAction.Continue; } @@ -1059,7 +1058,7 @@ namespace System.Management.Automation.Language TypeExpressionAst typeExpression = ast.Expression as TypeExpressionAst; // If this is static access on a variable, it may be suspicious - if(ast.Static && (typeExpression == null)) + if (ast.Static && (typeExpression == null)) { MarkAstParentsAsSuspicious(ast); } @@ -1159,9 +1158,9 @@ namespace System.Management.Automation.Language public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatementAst) { - bool usingKindSupported = usingStatementAst.UsingStatementKind == UsingStatementKind.Namespace || - usingStatementAst.UsingStatementKind == UsingStatementKind.Assembly || - usingStatementAst.UsingStatementKind == UsingStatementKind.Module; + bool usingKindSupported = usingStatementAst.UsingStatementKind == UsingStatementKind.Namespace || + usingStatementAst.UsingStatementKind == UsingStatementKind.Assembly || + usingStatementAst.UsingStatementKind == UsingStatementKind.Module; if (!usingKindSupported || usingStatementAst.Alias != null) { @@ -1169,7 +1168,7 @@ namespace System.Management.Automation.Language } return AstVisitAction.Continue; - } + } public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) { @@ -1233,7 +1232,7 @@ namespace System.Management.Automation.Language _parser.ReportError(propName.Extent, () => ParserStrings.InvalidInstanceProperty, propName.Value, - string.Join("', '", keyword.Properties.Keys.OrderBy(key=>key, StringComparer.OrdinalIgnoreCase))); + string.Join("', '", keyword.Properties.Keys.OrderBy(key => key, StringComparer.OrdinalIgnoreCase))); } } } @@ -1435,7 +1434,6 @@ namespace System.Management.Automation.Language { var propertyMemberAst = (PropertyMemberAst)member; CheckKey(parser, propertyMemberAst, ref hasKey); - } } if (baseTypeDefinitionAst.BaseTypes != null && (!hasSet || !hasGet || !hasTest || !hasKey)) @@ -1457,25 +1455,25 @@ namespace System.Management.Automation.Language return; } if (functionMemberAst.Name.Equals("Get", StringComparison.OrdinalIgnoreCase) && - functionMemberAst.Parameters.Count == 0 ) + functionMemberAst.Parameters.Count == 0) { - if (functionMemberAst.ReturnType != null) - { - // Return type is of the class we're defined in - //it must return the class type, or array of the class type. - var arrayTypeName = functionMemberAst.ReturnType.TypeName as ArrayTypeName; - var typeName = - (arrayTypeName != null ? arrayTypeName.ElementType : functionMemberAst.ReturnType.TypeName) as - TypeName; - if (typeName == null || typeName._typeDefinitionAst != functionMemberAst.Parent) - { - parser.ReportError(functionMemberAst.Extent, () => ParserStrings.DscResourceInvalidGetMethod, ((TypeDefinitionAst)functionMemberAst.Parent).Name); - } - } - else - { - parser.ReportError(functionMemberAst.Extent, () => ParserStrings.DscResourceInvalidGetMethod, ((TypeDefinitionAst)functionMemberAst.Parent).Name); - } + if (functionMemberAst.ReturnType != null) + { + // Return type is of the class we're defined in + //it must return the class type, or array of the class type. + var arrayTypeName = functionMemberAst.ReturnType.TypeName as ArrayTypeName; + var typeName = + (arrayTypeName != null ? arrayTypeName.ElementType : functionMemberAst.ReturnType.TypeName) as + TypeName; + if (typeName == null || typeName._typeDefinitionAst != functionMemberAst.Parent) + { + parser.ReportError(functionMemberAst.Extent, () => ParserStrings.DscResourceInvalidGetMethod, ((TypeDefinitionAst)functionMemberAst.Parent).Name); + } + } + else + { + parser.ReportError(functionMemberAst.Extent, () => ParserStrings.DscResourceInvalidGetMethod, ((TypeDefinitionAst)functionMemberAst.Parent).Name); + } //Set hasGet to true to stop look up; it may have invalid get hasGet = true; return; @@ -1494,7 +1492,6 @@ namespace System.Management.Automation.Language functionMemberAst.Parameters.Count == 0 && functionMemberAst.ReturnType != null && functionMemberAst.ReturnType.TypeName.GetReflectionType() == typeof(bool)); - } /// /// Check if it is a Set method with correct return type and signature @@ -1530,7 +1527,7 @@ namespace System.Management.Automation.Language && LanguagePrimitives.IsTrue(attrArgValue)) { hasKey = true; - + bool keyPropertyTypeAllowed = false; var propertyType = propertyMemberAst.PropertyType; if (propertyType != null) @@ -1540,8 +1537,8 @@ namespace System.Management.Automation.Language { var type = typeName.GetReflectionType(); if (type != null) - { - keyPropertyTypeAllowed = type == typeof (string) || type.IsInteger(); + { + keyPropertyTypeAllowed = type == typeof(string) || type.IsInteger(); } else { @@ -1558,7 +1555,7 @@ namespace System.Management.Automation.Language parser.ReportError(propertyMemberAst.Extent, () => ParserStrings.DscResourceInvalidKeyProperty); } return; - } + } } } } @@ -1566,7 +1563,7 @@ namespace System.Management.Automation.Language } } - class RestrictedLanguageChecker : AstVisitor + internal class RestrictedLanguageChecker : AstVisitor { private readonly Parser _parser; private readonly IEnumerable _allowedCommands; @@ -1576,8 +1573,8 @@ namespace System.Management.Automation.Language internal RestrictedLanguageChecker(Parser parser, IEnumerable allowedCommands, IEnumerable allowedVariables, bool allowEnvironmentVariables) { - this._parser = parser; - this._allowedCommands = allowedCommands; + _parser = parser; + _allowedCommands = allowedCommands; if (allowedVariables != null) { @@ -1591,15 +1588,15 @@ namespace System.Management.Automation.Language else { // Allowed variables are the union of the default variables plus any the caller has passed in. - this._allowedVariables = new HashSet(_defaultAllowedVariables).Union(allowedVariablesList); + _allowedVariables = new HashSet(s_defaultAllowedVariables).Union(allowedVariablesList); } } else { - this._allowedVariables = _defaultAllowedVariables; + _allowedVariables = s_defaultAllowedVariables; } - this._allowEnvironmentVariables = allowEnvironmentVariables; + _allowEnvironmentVariables = allowEnvironmentVariables; } private bool FoundError @@ -1681,7 +1678,7 @@ namespace System.Management.Automation.Language // If we couldn't resolve the type, then it's definitely an error. if (type == null || ((type.IsArray ? type.GetElementType() : type).GetTypeCode() == TypeCode.Object)) { - ReportError(ast, () => ParserStrings.TypeNotAllowedInDataSection, typename.FullName); + ReportError(ast, () => ParserStrings.TypeNotAllowedInDataSection, typename.FullName); } } @@ -1989,7 +1986,7 @@ namespace System.Management.Automation.Language return AstVisitAction.Continue; } - private static readonly HashSet _defaultAllowedVariables = new HashSet(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet s_defaultAllowedVariables = new HashSet(StringComparer.OrdinalIgnoreCase) {"PSCulture", "PSUICulture", "true", "false", "null"}; public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) @@ -2008,7 +2005,7 @@ namespace System.Management.Automation.Language } string resourceArg; - if (ReferenceEquals(_allowedVariables, _defaultAllowedVariables)) + if (ReferenceEquals(_allowedVariables, s_defaultAllowedVariables)) { resourceArg = ParserStrings.DefaultAllowedVariablesInDataSection; } @@ -2023,7 +2020,7 @@ namespace System.Management.Automation.Language first = false; else argBuilder.Append(", "); - + argBuilder.Append("$"); argBuilder.Append(varName); } diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 500f81487..3e2855bcc 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -14,15 +14,15 @@ using System.IO; namespace System.Management.Automation.Language { - enum ScopeType - { - Type, // class or enum - Method, // class method - Function, // function - ScriptBlock // script or anonymous script block - } + internal enum ScopeType + { + Type, // class or enum + Method, // class method + Function, // function + ScriptBlock // script or anonymous script block + } - class TypeLookupResult + internal class TypeLookupResult { public TypeLookupResult(TypeDefinitionAst type = null) { @@ -38,10 +38,10 @@ namespace System.Management.Automation.Language } } - class Scope + internal class Scope { internal Ast _ast; - internal ScopeType _scopeType; + internal ScopeType _scopeType; /// /// TypeTable maps namespace (currently it's module name) to the types under this namespace. /// For the types defined in the current namespace (module) we use CURRENT_NAMESPACE as a namespace. @@ -51,8 +51,8 @@ namespace System.Management.Automation.Language internal Scope(IParameterMetadataProvider ast, ScopeType scopeType) { - _ast = (Ast) ast; - _scopeType = scopeType; + _ast = (Ast)ast; + _scopeType = scopeType; _typeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); _variableTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } @@ -60,7 +60,7 @@ namespace System.Management.Automation.Language internal Scope(TypeDefinitionAst typeDefinition) { _ast = typeDefinition; - _scopeType = ScopeType.Type; + _scopeType = ScopeType.Type; _typeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); _variableTable = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var member in typeDefinition.Members) @@ -154,7 +154,7 @@ namespace System.Management.Automation.Language } } - class SymbolTable + internal class SymbolTable { internal readonly List _scopes; internal readonly Parser _parser; @@ -259,32 +259,32 @@ namespace System.Management.Automation.Language return null; } - public bool IsInMethodScope() - { - return _scopes[_scopes.Count - 1]._scopeType == ScopeType.Method; - } + public bool IsInMethodScope() + { + return _scopes[_scopes.Count - 1]._scopeType == ScopeType.Method; + } } - class SymbolResolver : AstVisitor2, IAstPostVisitHandler + internal class SymbolResolver : AstVisitor2, IAstPostVisitHandler { private readonly SymbolResolvePostActionVisitor _symbolResolvePostActionVisitor; internal readonly SymbolTable _symbolTable; internal readonly Parser _parser; internal readonly TypeResolutionState _typeResolutionState; - [ThreadStatic] - private static PowerShell _usingStatementResolvePowerShell; + [ThreadStatic] + private static PowerShell t_usingStatementResolvePowerShell; private static PowerShell UsingStatementResolvePowerShell { get { // The goal is to re-use runspaces, because creating runspace is an expensive part in creating PowerShell instance. - if (_usingStatementResolvePowerShell == null) + if (t_usingStatementResolvePowerShell == null) { if (Runspace.DefaultRunspace != null) { - _usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); + t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } else { @@ -294,16 +294,16 @@ namespace System.Management.Automation.Language var sessionStateProviderEntry = new SessionStateProviderEntry(FileSystemProvider.ProviderName, typeof(FileSystemProvider), null); var snapin = PSSnapInReader.ReadEnginePSSnapIns().FirstOrDefault(snapIn => snapIn.Name.Equals("Microsoft.PowerShell.Core", StringComparison.OrdinalIgnoreCase)); sessionStateProviderEntry.SetPSSnapIn(snapin); - iss.Providers.Add(sessionStateProviderEntry); - _usingStatementResolvePowerShell = PowerShell.Create(iss); + iss.Providers.Add(sessionStateProviderEntry); + t_usingStatementResolvePowerShell = PowerShell.Create(iss); } } - else if (Runspace.DefaultRunspace != null && _usingStatementResolvePowerShell.Runspace != Runspace.DefaultRunspace) + else if (Runspace.DefaultRunspace != null && t_usingStatementResolvePowerShell.Runspace != Runspace.DefaultRunspace) { - _usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); + t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } - return _usingStatementResolvePowerShell; + return t_usingStatementResolvePowerShell; } } @@ -312,7 +312,7 @@ namespace System.Management.Automation.Language _symbolTable = new SymbolTable(parser); _parser = parser; _typeResolutionState = typeResolutionState; - _symbolResolvePostActionVisitor = new SymbolResolvePostActionVisitor {_symbolResolver = this}; + _symbolResolvePostActionVisitor = new SymbolResolvePostActionVisitor { _symbolResolver = this }; } internal static void ResolveSymbols(Parser parser, ScriptBlockAst scriptBlockAst) @@ -330,7 +330,7 @@ namespace System.Management.Automation.Language Diagnostics.Assert(resolver._symbolTable._scopes.Count == 0, "Somebody missed removing a scope"); } - public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) + public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { _symbolTable.EnterScope(typeDefinitionAst); return AstVisitAction.Continue; @@ -390,17 +390,17 @@ namespace System.Management.Automation.Language var propertyMember = ast as PropertyMemberAst; if (propertyMember != null) { - if (propertyMember.IsStatic) - { + if (propertyMember.IsStatic) + { var typeAst = _symbolTable.GetCurrentTypeDefinitionAst(); Diagnostics.Assert(typeAst != null, "Method scopes can exist only inside type definitions."); _parser.ReportError(variableExpressionAst.Extent, () => ParserStrings.MissingTypeInStaticPropertyAssignment, String.Format(CultureInfo.InvariantCulture, "[{0}]::", typeAst.Name), propertyMember.Name); - } - else - { + } + else + { _parser.ReportError(variableExpressionAst.Extent, () => ParserStrings.MissingThis, "$this.", propertyMember.Name); - } + } } } } @@ -439,7 +439,7 @@ namespace System.Management.Automation.Language exception = null; wildcardCharactersUsed = false; isConstant = true; - + // fullyQualifiedName can be string or hashtable object fullyQualifiedName; if (usingStatementAst.ModuleSpecification != null) @@ -608,7 +608,7 @@ namespace System.Management.Automation.Language if (classDefn != null && classDefn.IsAmbiguous()) { - _parser.ReportError(typeName.Extent, () => ParserStrings.AmbiguousTypeReference, + _parser.ReportError(typeName.Extent, () => ParserStrings.AmbiguousTypeReference, typeName.Name, GetModuleQualifiedName(classDefn.ExternalNamespaces[0], typeName.Name), GetModuleQualifiedName(classDefn.ExternalNamespaces[1], typeName.Name)); @@ -617,7 +617,7 @@ namespace System.Management.Automation.Language { typeName.SetTypeDefinition(classDefn.Type); } - else + else { Exception e; TypeResolutionState trs = genericArgumentCount > 0 || isAttribute @@ -687,7 +687,7 @@ namespace System.Management.Automation.Language } } - class SymbolResolvePostActionVisitor : DefaultCustomAstVisitor2 + internal class SymbolResolvePostActionVisitor : DefaultCustomAstVisitor2 { internal SymbolResolver _symbolResolver; diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index ae934df9f..ec723cd78 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -87,7 +87,7 @@ namespace System.Management.Automation.Language // accelerator for the common case, when we are not interested in ambiguity exception. return targetType; } - + // .NET has forward notation for types, when they declared in one assembly and implemented in another one. // We want to support both scenarios: // 1) When we pass assembly with declared forwarded type (CoreCLR) @@ -293,7 +293,6 @@ namespace System.Management.Automation.Language if (context != null) { currentScope = context.EngineSessionState.CurrentScope; - } // If this is TypeDefinition we should not cache anything in TypeCache. @@ -448,13 +447,13 @@ namespace System.Management.Automation.Language /// internal class TypeResolutionState { - internal static readonly string[] systemNamespace = {"System"}; + internal static readonly string[] systemNamespace = { "System" }; internal static readonly Assembly[] emptyAssemblies = Utils.EmptyArray(); internal static readonly TypeResolutionState UsingSystem = new TypeResolutionState(); internal readonly string[] namespaces; internal readonly Assembly[] assemblies; - private readonly HashSet typesDefined; + private readonly HashSet _typesDefined; internal readonly int genericArgumentCount; internal readonly bool attribute; @@ -471,32 +470,32 @@ namespace System.Management.Automation.Language /// internal TypeResolutionState CloneWithAddTypesDefined(IEnumerable types) { - var newTypesDefined = new HashSet(this.typesDefined, StringComparer.OrdinalIgnoreCase); + var newTypesDefined = new HashSet(_typesDefined, StringComparer.OrdinalIgnoreCase); foreach (var type in types) { - newTypesDefined.Add(type); + newTypesDefined.Add(type); } - + return new TypeResolutionState(this, newTypesDefined); } internal bool ContainsTypeDefined(string type) { - return this.typesDefined.Contains(type); + return _typesDefined.Contains(type); } internal TypeResolutionState(string[] namespaces, Assembly[] assemblies) { this.namespaces = namespaces ?? systemNamespace; this.assemblies = assemblies ?? emptyAssemblies; - this.typesDefined = new HashSet(StringComparer.OrdinalIgnoreCase); + _typesDefined = new HashSet(StringComparer.OrdinalIgnoreCase); } internal TypeResolutionState(TypeResolutionState other, int genericArgumentCount, bool attribute) { this.namespaces = other.namespaces; this.assemblies = other.assemblies; - this.typesDefined = other.typesDefined; + _typesDefined = other._typesDefined; this.genericArgumentCount = genericArgumentCount; this.attribute = attribute; } @@ -505,7 +504,7 @@ namespace System.Management.Automation.Language { this.namespaces = other.namespaces; this.assemblies = other.assemblies; - this.typesDefined = typesDefined; + _typesDefined = typesDefined; this.genericArgumentCount = other.genericArgumentCount; this.attribute = other.attribute; } @@ -573,10 +572,10 @@ namespace System.Management.Automation.Language return false; } - if (this.typesDefined.Count != other.typesDefined.Count) + if (_typesDefined.Count != other._typesDefined.Count) return false; - return this.typesDefined.SetEquals(other.typesDefined); + return _typesDefined.SetEquals(other._typesDefined); } public override int GetHashCode() @@ -591,7 +590,7 @@ namespace System.Management.Automation.Language { result = Utils.CombineHashCodes(result, this.assemblies[i].GetHashCode()); } - foreach (var t in typesDefined) + foreach (var t in _typesDefined) { result = Utils.CombineHashCodes(result, t.GetHashCode()); } @@ -601,7 +600,7 @@ namespace System.Management.Automation.Language internal class TypeCache { - class KeyComparer : IEqualityComparer> + private class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -615,18 +614,18 @@ namespace System.Management.Automation.Language } } - private static readonly ConcurrentDictionary, Type> _cache = new ConcurrentDictionary, Type>(new KeyComparer()); + private static readonly ConcurrentDictionary, Type> s_cache = new ConcurrentDictionary, Type>(new KeyComparer()); internal static Type Lookup(ITypeName typeName, TypeResolutionState typeResolutionState) { Type result; - _cache.TryGetValue(Tuple.Create(typeName, typeResolutionState), out result); + s_cache.TryGetValue(Tuple.Create(typeName, typeResolutionState), out result); return result; } internal static void Add(ITypeName typeName, TypeResolutionState typeResolutionState, Type type) { - _cache.GetOrAdd(Tuple.Create(typeName, typeResolutionState), type); + s_cache.GetOrAdd(Tuple.Create(typeName, typeResolutionState), type); } } } @@ -761,11 +760,11 @@ namespace System.Management.Automation // users can add to user added accelerators (but not currently remove any.) Keeping a seperate // list allows us to add removing in the future w/o worrying about breaking the builtins. - internal static Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); + internal static Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); // We expose this one publicly for programmatic access to our type accelerator table, but it is // otherwise unused (so changes to this dictionary don't affect internals.) - private static Dictionary allTypeAccelerators; + private static Dictionary s_allTypeAccelerators; static TypeAccelerators() { @@ -783,19 +782,19 @@ namespace System.Management.Automation // Add additional utility types that are useful as type accelerators, but aren't // fundamentally "core language", or may be unsafe to expose to untrusted input. - builtinTypeAccelerators.Add("scriptblock", typeof(ScriptBlock)); - builtinTypeAccelerators.Add("psvariable", typeof(PSVariable)); - builtinTypeAccelerators.Add("type", typeof(Type)); - builtinTypeAccelerators.Add("psmoduleinfo", typeof(PSModuleInfo)); - builtinTypeAccelerators.Add("powershell", typeof(PowerShell)); - builtinTypeAccelerators.Add("runspacefactory", typeof(RunspaceFactory)); - builtinTypeAccelerators.Add("runspace", typeof(Runspace)); - builtinTypeAccelerators.Add("initialsessionstate", typeof(InitialSessionState)); - builtinTypeAccelerators.Add("psscriptmethod", typeof(PSScriptMethod)); - builtinTypeAccelerators.Add("psscriptproperty", typeof(PSScriptProperty)); - builtinTypeAccelerators.Add("psnoteproperty", typeof(PSNoteProperty)); - builtinTypeAccelerators.Add("psaliasproperty", typeof(PSAliasProperty)); - builtinTypeAccelerators.Add("psvariableproperty", typeof(PSVariableProperty)); + builtinTypeAccelerators.Add("scriptblock", typeof(ScriptBlock)); + builtinTypeAccelerators.Add("psvariable", typeof(PSVariable)); + builtinTypeAccelerators.Add("type", typeof(Type)); + builtinTypeAccelerators.Add("psmoduleinfo", typeof(PSModuleInfo)); + builtinTypeAccelerators.Add("powershell", typeof(PowerShell)); + builtinTypeAccelerators.Add("runspacefactory", typeof(RunspaceFactory)); + builtinTypeAccelerators.Add("runspace", typeof(Runspace)); + builtinTypeAccelerators.Add("initialsessionstate", typeof(InitialSessionState)); + builtinTypeAccelerators.Add("psscriptmethod", typeof(PSScriptMethod)); + builtinTypeAccelerators.Add("psscriptproperty", typeof(PSScriptProperty)); + builtinTypeAccelerators.Add("psnoteproperty", typeof(PSNoteProperty)); + builtinTypeAccelerators.Add("psaliasproperty", typeof(PSAliasProperty)); + builtinTypeAccelerators.Add("psvariableproperty", typeof(PSVariableProperty)); } internal static string FindBuiltinAccelerator(Type type) @@ -818,9 +817,9 @@ namespace System.Management.Automation public static void Add(string typeName, Type type) { userTypeAccelerators[typeName] = type; - if (allTypeAccelerators != null) + if (s_allTypeAccelerators != null) { - allTypeAccelerators[typeName] = type; + s_allTypeAccelerators[typeName] = type; } } @@ -832,9 +831,9 @@ namespace System.Management.Automation public static bool Remove(string typeName) { userTypeAccelerators.Remove(typeName); - if (allTypeAccelerators != null) + if (s_allTypeAccelerators != null) { - allTypeAccelerators.Remove(typeName); + s_allTypeAccelerators.Remove(typeName); } return true; } @@ -854,13 +853,13 @@ namespace System.Management.Automation { get { - if (allTypeAccelerators == null) + if (s_allTypeAccelerators == null) { - allTypeAccelerators = new Dictionary(StringComparer.OrdinalIgnoreCase); - FillCache(allTypeAccelerators); + s_allTypeAccelerators = new Dictionary(StringComparer.OrdinalIgnoreCase); + FillCache(s_allTypeAccelerators); } - return allTypeAccelerators; + return s_allTypeAccelerators; } } diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 2bff3ec1f..44dc31bd7 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -11,7 +11,7 @@ using System.Reflection; namespace System.Management.Automation.Language { - static class VariablePathExtentions + internal static class VariablePathExtentions { static internal bool IsAnyLocal(this VariablePath variablePath) { @@ -36,10 +36,10 @@ namespace System.Management.Automation.Language public List AssociatedAsts { get; private set; } } - class FindAllVariablesVisitor : AstVisitor + internal class FindAllVariablesVisitor : AstVisitor { - private static readonly HashSet hashOfPessimizingCmdlets = new HashSet(StringComparer.OrdinalIgnoreCase); - private static readonly string[] pessimizingCmdlets = new string[] + private static readonly HashSet s_hashOfPessimizingCmdlets = new HashSet(StringComparer.OrdinalIgnoreCase); + private static readonly string[] s_pessimizingCmdlets = new string[] { "New-Variable", "Remove-Variable", @@ -58,9 +58,9 @@ namespace System.Management.Automation.Language static FindAllVariablesVisitor() { - foreach (var cmdlet in pessimizingCmdlets) + foreach (var cmdlet in s_pessimizingCmdlets) { - hashOfPessimizingCmdlets.Add(cmdlet); + s_hashOfPessimizingCmdlets.Add(cmdlet); } } @@ -111,9 +111,9 @@ namespace System.Management.Automation.Language private readonly Dictionary _variables = new Dictionary(StringComparer.OrdinalIgnoreCase); - FindAllVariablesVisitor(bool disableOptimizations, bool scriptCmdlet) + private FindAllVariablesVisitor(bool disableOptimizations, bool scriptCmdlet) { - this._disableOptimizations = disableOptimizations; + _disableOptimizations = disableOptimizations; var automaticVariables = SpecialVariables.AutomaticVariables; Diagnostics.Assert(Array.IndexOf(automaticVariables, SpecialVariables.Underbar) == (int)AutomaticVariable.Underbar, @@ -249,7 +249,7 @@ namespace System.Management.Automation.Language public override AstVisitAction VisitCommand(CommandAst commandAst) { var commandName = commandAst.CommandElements[0] as StringConstantExpressionAst; - if (commandName != null && hashOfPessimizingCmdlets.Contains(commandName.Value)) + if (commandName != null && s_hashOfPessimizingCmdlets.Contains(commandName.Value)) { // TODO: psuedo-bind the command invocation to figure out the variable and only force that variable to be unoptimized _disableOptimizations = true; @@ -311,7 +311,7 @@ namespace System.Management.Automation.Language } } - class VariableAnalysis : ICustomAstVisitor + internal class VariableAnalysis : ICustomAstVisitor { // Tuple slots start at index 0. >= 0 means a variable is allocated in the tuple. -1 means we don't // we haven't analyzed a specific use of a variable and don't know what slot it might be assigned to yet. @@ -326,7 +326,7 @@ namespace System.Management.Automation.Language // in these cases, we rely on the setter PSVariable.Value to handle those attributes. internal const int ForceDynamic = -2; - class LoopGotoTargets + private class LoopGotoTargets { internal LoopGotoTargets(string label, Block breakTarget, Block continueTarget) { @@ -339,7 +339,7 @@ namespace System.Management.Automation.Language internal Block ContinueTarget { get; private set; } } - class Block + private class Block { internal readonly List _asts = new List(); private readonly List _successors = new List(); @@ -348,7 +348,7 @@ namespace System.Management.Automation.Language internal object _visitData; internal bool _throws; internal bool _returns; - internal bool _unreachable { get; private set; } + internal bool _unreachable { get; private set; } // Only Entry block, that can be constructed via NewEntryBlock() is reachable initially. // all other blocks are unreachable. @@ -422,7 +422,7 @@ namespace System.Management.Automation.Language } } - class AssignmentTarget : Ast + private class AssignmentTarget : Ast { internal readonly ExpressionAst _targetAst; internal readonly string _variableName; @@ -481,16 +481,16 @@ namespace System.Management.Automation.Language // constant though - it only contains variable names known to _always_ be allscope. For other names, we need a special // check before choosing to run the optimized code or unoptimized (dotted) version which will correctly handle allscope // assignments. - private readonly static ConcurrentDictionary _allScopeVariables = new ConcurrentDictionary(1, 16, StringComparer.OrdinalIgnoreCase); + private readonly static ConcurrentDictionary s_allScopeVariables = new ConcurrentDictionary(1, 16, StringComparer.OrdinalIgnoreCase); internal static void NoteAllScopeVariable(string variableName) { - _allScopeVariables.GetOrAdd(variableName, true); + s_allScopeVariables.GetOrAdd(variableName, true); } internal static bool AnyVariablesCouldBeAllScope(Dictionary variableNames) { - return variableNames.Any(keyValuePair => _allScopeVariables.ContainsKey(keyValuePair.Key)); + return variableNames.Any(keyValuePair => s_allScopeVariables.ContainsKey(keyValuePair.Key)); } private Dictionary _variables; @@ -571,7 +571,7 @@ namespace System.Management.Automation.Language va.AnalyzeImpl(ast, false, false); return va._exitBlock._predecessors.All(b => b._returns || b._throws || b._unreachable); } - + private Tuple> AnalyzeImpl(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet) { _variables = FindAllVariablesVisitor.Visit(ast, disableOptimizations, scriptCmdlet, out _localsAllocated, out _disableOptimizations); @@ -865,7 +865,7 @@ namespace System.Management.Automation.Language var analysisDetails = _variables[variableName]; if (analysisDetails.LocalTupleIndex == VariableAnalysis.Unanalyzed) { - analysisDetails.LocalTupleIndex = _disableOptimizations || _allScopeVariables.ContainsKey(variableName) + analysisDetails.LocalTupleIndex = _disableOptimizations || s_allScopeVariables.ContainsKey(variableName) ? VariableAnalysis.ForceDynamic : _localsAllocated++; } @@ -996,7 +996,7 @@ namespace System.Management.Automation.Language return VisitStatementBlock(statementBlockAst.Statements); } - object VisitStatementBlock(ReadOnlyCollection statements) + private object VisitStatementBlock(ReadOnlyCollection statements) { foreach (var stmt in statements) { @@ -1336,7 +1336,7 @@ namespace System.Management.Automation.Language if (finallyFirstBlock != null) { lastBlockInTry.FlowsTo(finallyFirstBlock); - + _currentBlock = finallyFirstBlock; tryStatementAst.Finally.Accept(this); _currentBlock.FlowsTo(afterTry); diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index f08415b64..28b9e6240 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -73,7 +73,6 @@ namespace System.Management.Automation.Language Tuple GetWithInputHandlingForInvokeCommandWithUsingExpression(Tuple, string> usingVariablesTuple); #endregion Remoting/Invoke Command - } /// @@ -197,7 +196,7 @@ namespace System.Management.Automation.Language try { ExecutionContext context = null; - if(System.Management.Automation.Runspaces.Runspace.DefaultRunspace != null) + if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace != null) { context = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.ExecutionContext; } @@ -770,13 +769,13 @@ namespace System.Management.Automation.Language /// public class ScriptBlockAst : Ast, IParameterMetadataProvider { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyUsingStatementList = + private static readonly ReadOnlyCollection s_emptyUsingStatementList = Utils.EmptyReadOnlyCollection(); internal bool HadErrors { get; set; } - internal bool IsConfiguration { get; private set; } + internal bool IsConfiguration { get; private set; } internal bool PostParseChecksPerformed { get; set; } /// @@ -813,7 +812,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } if (paramBlock != null) @@ -1021,7 +1020,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } if (statements == null) @@ -1056,7 +1055,7 @@ namespace System.Management.Automation.Language } else { - this.UsingStatements = EmptyUsingStatementList; + this.UsingStatements = s_emptyUsingStatementList; } } @@ -1178,10 +1177,10 @@ namespace System.Management.Automation.Language var scriptBlockAst = new ScriptBlockAst(this.Extent, newUsingStatements, newAttributes, newParamBlock, newBeginBlock, newProcessBlock, newEndBlock, newDynamicParamBlock) - { - IsConfiguration = this.IsConfiguration, - ScriptRequirements = this.ScriptRequirements - }; + { + IsConfiguration = this.IsConfiguration, + ScriptRequirements = this.ScriptRequirements + }; return scriptBlockAst; } @@ -1201,9 +1200,9 @@ namespace System.Management.Automation.Language internal string ToStringForSerialization(Tuple, string> usingVariablesTuple, int initialStartOffset, int initialEndOffset) { - Diagnostics.Assert(usingVariablesTuple.Item1 != null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), + Diagnostics.Assert(usingVariablesTuple.Item1 != null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), "Caller makes sure the value passed in is not null or empty"); - Diagnostics.Assert(initialStartOffset < initialEndOffset && initialStartOffset >= this.Extent.StartOffset && initialEndOffset <= this.Extent.EndOffset, + Diagnostics.Assert(initialStartOffset < initialEndOffset && initialStartOffset >= this.Extent.StartOffset && initialEndOffset <= this.Extent.EndOffset, "Caller makes sure the section is within the ScriptBlockAst"); List usingVars = usingVariablesTuple.Item1; // A list of using variables @@ -1405,7 +1404,7 @@ namespace System.Management.Automation.Language var attributeAst = Attributes[index]; yield return Compiler.GetAttribute(attributeAst); } - + if (ParamBlock != null) { for (int index = 0; index < ParamBlock.Attributes.Count; index++) @@ -1452,7 +1451,7 @@ namespace System.Management.Automation.Language return new Tuple(paramText, scriptBlockText); } - string GetWithInputHandlingForInvokeCommandImpl(Tuple, string> usingVariablesTuple) + private string GetWithInputHandlingForInvokeCommandImpl(Tuple, string> usingVariablesTuple) { // do not add "$input |" to complex pipelines string unused1; @@ -1569,9 +1568,9 @@ namespace System.Management.Automation.Language [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")] public class ParamBlockAst : Ast { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyParameterList = + private static readonly ReadOnlyCollection s_emptyParameterList = Utils.EmptyReadOnlyCollection(); /// @@ -1593,7 +1592,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } if (parameters != null) @@ -1603,7 +1602,7 @@ namespace System.Management.Automation.Language } else { - this.Parameters = EmptyParameterList; + this.Parameters = s_emptyParameterList; } } @@ -1807,8 +1806,8 @@ namespace System.Management.Automation.Language // For explicitly named block, the Extent of the StatementBlockAst is not // the same as the Extent of the NamedBlockAst. In this case, reconstruct // the Extent of the StatementBlockAst from openExtent/closeExtent. - var openExtent = (InternalScriptExtent) this.OpenCurlyExtent; - var closeExtent = (InternalScriptExtent) this.CloseCurlyExtent; + var openExtent = (InternalScriptExtent)this.OpenCurlyExtent; + var closeExtent = (InternalScriptExtent)this.CloseCurlyExtent; statementBlockExtent = new InternalScriptExtent(openExtent.PositionHelper, openExtent.StartOffset, closeExtent.EndOffset); } @@ -1980,9 +1979,9 @@ namespace System.Management.Automation.Language /// public class AttributeAst : AttributeBaseAst { - private static readonly ReadOnlyCollection EmptyPositionalArguments = + private static readonly ReadOnlyCollection s_emptyPositionalArguments = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyNamedAttributeArguments = + private static readonly ReadOnlyCollection s_emptyNamedAttributeArguments = Utils.EmptyReadOnlyCollection(); /// @@ -2008,7 +2007,7 @@ namespace System.Management.Automation.Language } else { - this.PositionalArguments = EmptyPositionalArguments; + this.PositionalArguments = s_emptyPositionalArguments; } if (namedArguments != null) @@ -2018,7 +2017,7 @@ namespace System.Management.Automation.Language } else { - this.NamedArguments = EmptyNamedAttributeArguments; + this.NamedArguments = s_emptyNamedAttributeArguments; } } @@ -2149,7 +2148,7 @@ namespace System.Management.Automation.Language /// public class ParameterAst : Ast { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); /// @@ -2180,7 +2179,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } this.Name = name; SetParent(name); @@ -2307,7 +2306,6 @@ namespace System.Management.Automation.Language newParamText.Append(paramText.Substring(startOffset, astStartOffset - startOffset)); newParamText.Append(newVarName); startOffset = astEndOffset; - } while (orderedUsingVar.MoveNext()); if (startOffset == 0) @@ -2365,7 +2363,7 @@ namespace System.Management.Automation.Language /// public class StatementBlockAst : Ast { - private static ReadOnlyCollection emptyStatementCollection = Utils.EmptyReadOnlyCollection(); + private static ReadOnlyCollection s_emptyStatementCollection = Utils.EmptyReadOnlyCollection(); /// /// Construct a statement block. @@ -2388,7 +2386,7 @@ namespace System.Management.Automation.Language } else { - this.Statements = emptyStatementCollection; + this.Statements = s_emptyStatementCollection; } if (traps != null && traps.Any()) @@ -2513,11 +2511,11 @@ namespace System.Management.Automation.Language /// public class TypeDefinitionAst : StatementAst { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyMembersCollection = + private static readonly ReadOnlyCollection s_emptyMembersCollection = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyBaseTypesCollection = + private static readonly ReadOnlyCollection s_emptyBaseTypesCollection = Utils.EmptyReadOnlyCollection(); /// @@ -2544,7 +2542,7 @@ namespace System.Management.Automation.Language } else { - Attributes = EmptyAttributeList; + Attributes = s_emptyAttributeList; } if (members != null && members.Any()) @@ -2554,7 +2552,7 @@ namespace System.Management.Automation.Language } else { - Members = EmptyMembersCollection; + Members = s_emptyMembersCollection; } if (baseTypes != null && baseTypes.Any()) @@ -2564,7 +2562,7 @@ namespace System.Management.Automation.Language } else { - BaseTypes = EmptyBaseTypesCollection; + BaseTypes = s_emptyBaseTypesCollection; } this.Name = name; @@ -3012,7 +3010,7 @@ namespace System.Management.Automation.Language /// public class PropertyMemberAst : MemberAst { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); /// @@ -3052,7 +3050,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } PropertyAttributes = propertyAttributes; InitialValue = initialValue; @@ -3201,9 +3199,9 @@ namespace System.Management.Automation.Language /// public class FunctionMemberAst : MemberAst, IParameterMetadataProvider { - private static readonly ReadOnlyCollection EmptyAttributeList = + private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); - private static readonly ReadOnlyCollection EmptyParameterList = + private static readonly ReadOnlyCollection s_emptyParameterList = Utils.EmptyReadOnlyCollection(); private readonly FunctionDefinitionAst _functionDefinitionAst; @@ -3243,7 +3241,7 @@ namespace System.Management.Automation.Language } else { - this.Attributes = EmptyAttributeList; + this.Attributes = s_emptyAttributeList; } _functionDefinitionAst = functionDefinitionAst; @@ -3259,7 +3257,7 @@ namespace System.Management.Automation.Language /// /// The attributes specified on the method. This property is never null. /// - public ReadOnlyCollection Attributes { get; private set; } + public ReadOnlyCollection Attributes { get; private set; } /// /// The ast representing the return type for the method. This property may be null if no return type was specified. @@ -3269,8 +3267,9 @@ namespace System.Management.Automation.Language /// /// The parameters specified immediately after the function name. This property is never null. /// - public ReadOnlyCollection Parameters { - get { return _functionDefinitionAst.Parameters ?? EmptyParameterList; } + public ReadOnlyCollection Parameters + { + get { return _functionDefinitionAst.Parameters ?? s_emptyParameterList; } } /// @@ -3406,20 +3405,20 @@ namespace System.Management.Automation.Language RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding) { - return ((IParameterMetadataProvider) _functionDefinitionAst).GetParameterMetadata(automaticPositions, ref usesCmdletBinding); + return ((IParameterMetadataProvider)_functionDefinitionAst).GetParameterMetadata(automaticPositions, ref usesCmdletBinding); } IEnumerable IParameterMetadataProvider.GetScriptBlockAttributes() { - return ((IParameterMetadataProvider) _functionDefinitionAst).GetScriptBlockAttributes(); + return ((IParameterMetadataProvider)_functionDefinitionAst).GetScriptBlockAttributes(); } bool IParameterMetadataProvider.UsesCmdletBinding() { - return ((IParameterMetadataProvider) _functionDefinitionAst).UsesCmdletBinding(); + return ((IParameterMetadataProvider)_functionDefinitionAst).UsesCmdletBinding(); } - PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, + PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, bool filterNonUsingVariables, bool? createLocalScope, params object[] args) { // OK? I think this isn't reachable @@ -3840,7 +3839,7 @@ namespace System.Management.Automation.Language Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCommandWithUsingExpression( Tuple, string> usingVariablesTuple) { - Tuple result = + Tuple result = ((IParameterMetadataProvider)Body).GetWithInputHandlingForInvokeCommandWithUsingExpression(usingVariablesTuple); if (Parameters == null) @@ -3991,7 +3990,7 @@ namespace System.Management.Automation.Language /// public class DataStatementAst : StatementAst { - private static readonly ExpressionAst[] EmptyCommandsAllowed = Utils.EmptyArray(); + private static readonly ExpressionAst[] s_emptyCommandsAllowed = Utils.EmptyArray(); /// /// Construct a data statement. @@ -4028,7 +4027,7 @@ namespace System.Management.Automation.Language } else { - this.CommandsAllowed = new ReadOnlyCollection(EmptyCommandsAllowed); + this.CommandsAllowed = new ReadOnlyCollection(s_emptyCommandsAllowed); } this.Body = body; SetParent(body); @@ -4086,7 +4085,7 @@ namespace System.Management.Automation.Language #endregion Visitors #region Code Generation Details - + private int _tupleIndex = VariableAnalysis.Unanalyzed; internal int TupleIndex { @@ -4296,7 +4295,7 @@ namespace System.Management.Automation.Language if (this.ThrottleLimit != null) { var newThrottleLimit = CopyElement(this.ThrottleLimit); - return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newThrottleLimit, + return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newThrottleLimit, newVariable, newExpression, newBody); } @@ -4633,7 +4632,7 @@ namespace System.Management.Automation.Language /// public class SwitchStatementAst : LabeledStatementAst { - private static readonly SwitchClause[] EmptyClauseArray = Utils.EmptyArray(); + private static readonly SwitchClause[] s_emptyClauseArray = Utils.EmptyArray(); /// /// Construct a switch statement. @@ -4670,7 +4669,7 @@ namespace System.Management.Automation.Language this.Flags = flags; this.Clauses = new ReadOnlyCollection( - (clauses != null && clauses.Any()) ? clauses.ToArray() : EmptyClauseArray); + (clauses != null && clauses.Any()) ? clauses.ToArray() : s_emptyClauseArray); SetParents(Clauses); if (@default != null) { @@ -4703,7 +4702,7 @@ namespace System.Management.Automation.Language { var newCondition = CopyElement(this.Condition); var newDefault = CopyElement(this.Default); - + List newClauses = null; if (this.Clauses.Count > 0) { @@ -4779,7 +4778,7 @@ namespace System.Management.Automation.Language /// public class CatchClauseAst : Ast { - private readonly static ReadOnlyCollection EmptyCatchTypes = + private readonly static ReadOnlyCollection s_emptyCatchTypes = Utils.EmptyReadOnlyCollection(); /// @@ -4806,7 +4805,7 @@ namespace System.Management.Automation.Language } else { - this.CatchTypes = EmptyCatchTypes; + this.CatchTypes = s_emptyCatchTypes; } this.Body = body; @@ -4876,7 +4875,7 @@ namespace System.Management.Automation.Language /// public class TryStatementAst : StatementAst { - private readonly static ReadOnlyCollection EmptyCatchClauses = + private readonly static ReadOnlyCollection s_emptyCatchClauses = Utils.EmptyReadOnlyCollection(); /// @@ -4921,7 +4920,7 @@ namespace System.Management.Automation.Language } else { - this.CatchClauses = EmptyCatchClauses; + this.CatchClauses = s_emptyCatchClauses; } if (@finally != null) @@ -5709,10 +5708,10 @@ namespace System.Management.Automation.Language /// public abstract class CommandBaseAst : StatementAst { - private static readonly ReadOnlyCollection EmptyRedirections = + private static readonly ReadOnlyCollection s_emptyRedirections = Utils.EmptyReadOnlyCollection(); - internal const int MaxRedirections = (int) RedirectionStream.Information + 1; + internal const int MaxRedirections = (int)RedirectionStream.Information + 1; /// /// Initialize the common fields of a command. @@ -5732,7 +5731,7 @@ namespace System.Management.Automation.Language } else { - this.Redirections = EmptyRedirections; + this.Redirections = s_emptyRedirections; } } @@ -5828,9 +5827,9 @@ namespace System.Management.Automation.Language var newCommandElements = CopyElements(this.CommandElements); var newRedirections = CopyElements(this.Redirections); return new CommandAst(this.Extent, newCommandElements, this.InvocationOperator, newRedirections) - { - DefiningKeyword = this.DefiningKeyword - }; + { + DefiningKeyword = this.DefiningKeyword + }; } internal override IEnumerable GetInferredType(CompletionContext context) @@ -6380,26 +6379,26 @@ namespace System.Management.Automation.Language return Left.GetInferredType(context); } - /// - /// Return all of the expressions assigned by the assignment statement. Typically - /// it's just a variable expression, but if is an , - /// then all of the elements are assigned. - /// - /// All of the expressions assigned by the assignment statement. - public IEnumerable GetAssignmentTargets() - { - var arrayExpression = Left as ArrayLiteralAst; - if (arrayExpression != null) - { - foreach (var element in arrayExpression.Elements) - { - yield return element; - } - yield break; - } + /// + /// Return all of the expressions assigned by the assignment statement. Typically + /// it's just a variable expression, but if is an , + /// then all of the elements are assigned. + /// + /// All of the expressions assigned by the assignment statement. + public IEnumerable GetAssignmentTargets() + { + var arrayExpression = Left as ArrayLiteralAst; + if (arrayExpression != null) + { + foreach (var element in arrayExpression.Elements) + { + yield return element; + } + yield break; + } - yield return Left; - } + yield return Left; + } #region Visitors internal override object Accept(ICustomAstVisitor visitor) @@ -6615,7 +6614,7 @@ namespace System.Management.Automation.Language var resourceBody = (from stm in bodyStatements where !IsImportCommand(stm, resourceModulePairsToImport) select (StatementAst)stm.Copy()).ToList(); cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); - + var scriptBlockBody = new ScriptBlockAst(Body.Extent, CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), null, @@ -6714,7 +6713,6 @@ namespace System.Management.Automation.Language SetParent(returnPipelineAst); return returnPipelineAst; - } #endregion @@ -6754,7 +6752,7 @@ namespace System.Management.Automation.Language if ((paramName.Length <= nameParam.Length) && (paramName.Equals(nameParam.Substring(0, paramName.Length), StringComparison.OrdinalIgnoreCase))) { resourceNames = paramValue; - } + } // Since both parameters -ModuleName and -ModuleVersion has same start string i.e. Module so we will try to resolve it to -ModuleName // if user specifies like -Module if ((paramName.Length <= moduleNameParam.Length) && (paramName.Equals(moduleNameParam.Substring(0, paramName.Length), StringComparison.OrdinalIgnoreCase))) @@ -6767,7 +6765,7 @@ namespace System.Management.Automation.Language } } - string[] resourceNamesTyped = new [] {"*"}; + string[] resourceNamesTyped = new[] { "*" }; ModuleSpecification[] moduleNamesTyped = null; Version moduleVersionTyped = null; @@ -6837,9 +6835,9 @@ namespace System.Management.Automation.Language { get { - if (_configurationBuildInParameters == null) + if (s_configurationBuildInParameters == null) { - _configurationBuildInParameters = new List(); + s_configurationBuildInParameters = new List(); Token[] tokens; ParseError[] errors; @@ -6848,57 +6846,55 @@ namespace System.Management.Automation.Language { foreach (var parameterAst in sba.ParamBlock.Parameters) { - _configurationBuildInParameters.Add((ParameterAst)parameterAst.Copy()); + s_configurationBuildInParameters.Add((ParameterAst)parameterAst.Copy()); } } - } - return _configurationBuildInParameters; + return s_configurationBuildInParameters; } } - private static List _configurationBuildInParameters; + private static List s_configurationBuildInParameters; private static IEnumerable ConfigurationBuildInParameterAttribAsts { get { - if (_configurationBuildInParameterAttrAsts == null) + if (s_configurationBuildInParameterAttrAsts == null) { - _configurationBuildInParameterAttrAsts = new List(); + s_configurationBuildInParameterAttrAsts = new List(); Token[] tokens; ParseError[] errors; var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors); if (sba != null) { - if (_configurationBuildInParameters == null) + if (s_configurationBuildInParameters == null) { - _configurationBuildInParameters = new List(); + s_configurationBuildInParameters = new List(); foreach (var parameterAst in sba.ParamBlock.Parameters) { - _configurationBuildInParameters.Add((ParameterAst)parameterAst.Copy()); + s_configurationBuildInParameters.Add((ParameterAst)parameterAst.Copy()); } } foreach (var attribAst in sba.ParamBlock.Attributes) { - _configurationBuildInParameterAttrAsts.Add((AttributeAst)attribAst.Copy()); + s_configurationBuildInParameterAttrAsts.Add((AttributeAst)attribAst.Copy()); } } - } - return _configurationBuildInParameterAttrAsts; + return s_configurationBuildInParameterAttrAsts; } } - private static List _configurationBuildInParameterAttrAsts; + private static List s_configurationBuildInParameterAttrAsts; private static IEnumerable ConfigurationExtraParameterStatements { get { - if (_configurationExtraParameterStatements == null) + if (s_configurationExtraParameterStatements == null) { - _configurationExtraParameterStatements = new List(); + s_configurationExtraParameterStatements = new List(); Token[] tokens; ParseError[] errors; var sba = Parser.ParseInput(@" @@ -6913,15 +6909,14 @@ namespace System.Management.Automation.Language { foreach (var statementAst in sba.EndBlock.Statements) { - _configurationExtraParameterStatements.Add((StatementAst)statementAst.Copy()); + s_configurationExtraParameterStatements.Add((StatementAst)statementAst.Copy()); } } - } - return _configurationExtraParameterStatements; + return s_configurationExtraParameterStatements; } } - private static List _configurationExtraParameterStatements; + private static List s_configurationExtraParameterStatements; #endregion } @@ -7110,7 +7105,7 @@ namespace System.Management.Automation.Language FunctionName.Extent, "InstanceName", InstanceName, - FunctionName.Extent)); + FunctionName.Extent)); } // @@ -7153,7 +7148,7 @@ namespace System.Management.Automation.Language // Construct the real parameters if Hashtable is valid foreach (var keyValueTuple in hashtable.KeyValuePairs) { - var propName = (StringConstantExpressionAst) keyValueTuple.Item1; + var propName = (StringConstantExpressionAst)keyValueTuple.Item1; ExpressionAst propValue = new SubExpressionAst( FunctionName.Extent, new StatementBlockAst( @@ -7194,7 +7189,7 @@ namespace System.Management.Automation.Language FunctionName.Extent, new TypeName( FunctionName.Extent, - typeof (System.Management.Automation.Language.DynamicKeyword).FullName)), + typeof(System.Management.Automation.Language.DynamicKeyword).FullName)), new StringConstantExpressionAst( FunctionName.Extent, "GetKeyword", @@ -7712,7 +7707,7 @@ namespace System.Management.Automation.Language #region Code Generation Details - ISupportsAssignment GetActualAssignableAst() + private ISupportsAssignment GetActualAssignableAst() { ExpressionAst child = this; var childAttributeAst = child as AttributedExpressionAst; @@ -7726,7 +7721,7 @@ namespace System.Management.Automation.Language return (ISupportsAssignment)child; } - List GetAttributes() + private List GetAttributes() { var attributes = new List(); var childAttributeAst = this; @@ -8271,10 +8266,10 @@ namespace System.Management.Automation.Language /// The arguments to pass to the ctor. public BaseCtorInvokeMemberExpressionAst(IScriptExtent baseKeywordExtent, IScriptExtent baseCallExtent, IEnumerable arguments) : base( - baseCallExtent, - new VariableExpressionAst(baseKeywordExtent, "this", false), - new StringConstantExpressionAst(baseKeywordExtent, ".ctor", StringConstantType.BareWord), - arguments, + baseCallExtent, + new VariableExpressionAst(baseKeywordExtent, "this", false), + new StringConstantExpressionAst(baseKeywordExtent, ".ctor", StringConstantType.BareWord), + arguments, @static: false) { } @@ -8651,7 +8646,7 @@ namespace System.Management.Automation.Language throw PSTraceSource.NewArgumentException("genericArguments"); } - this._extent = extent; + _extent = extent; this.TypeName = genericTypeName; this.GenericArguments = new ReadOnlyCollection(genericArguments.ToArray()); @@ -8854,7 +8849,6 @@ namespace System.Management.Automation.Language type = genericTypeInfo.MakeGenericType((from arg in GenericArguments select arg.GetReflectionType()).ToArray()); Interlocked.CompareExchange(ref _cachedType, type, null); } - } return type; } @@ -8942,7 +8936,7 @@ namespace System.Management.Automation.Language throw PSTraceSource.NewArgumentException("rank"); } - this._extent = extent; + _extent = extent; this.Rank = rank; this.ElementType = elementType; } @@ -9133,7 +9127,7 @@ namespace System.Management.Automation.Language throw PSTraceSource.NewArgumentNullException("type"); } - this._type = type; + _type = type; } /// @@ -9274,7 +9268,7 @@ namespace System.Management.Automation.Language #endregion Visitors } - + /// /// The ast representing a variable reference, either normal references, e.g. $true, or splatted references /// @PSBoundParameters. @@ -9587,7 +9581,7 @@ namespace System.Management.Automation.Language } else { - ok = ! this.Splatted + ok = !this.Splatted && this.IsConstantVariable(); } } @@ -9616,7 +9610,7 @@ namespace System.Management.Automation.Language { string[] variableParameters = new string[] { "PV", "PipelineVariable", "OV", "OutVariable" }; StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, variableParameters); - + if (bindingResult != null) { ParameterBindingResult parameterBindingResult; @@ -9625,7 +9619,7 @@ namespace System.Management.Automation.Language { if (bindingResult.BoundParameters.TryGetValue(commandVariableParameter, out parameterBindingResult)) { - if(String.Equals(VariablePath.UnqualifiedPath, (string)parameterBindingResult.ConstantValue, StringComparison.OrdinalIgnoreCase)) + if (String.Equals(VariablePath.UnqualifiedPath, (string)parameterBindingResult.ConstantValue, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -10037,9 +10031,9 @@ namespace System.Management.Automation.Language /// the nested tokens. This method is internal mainly so we can avoid validating . /// internal ExpandableStringExpressionAst(Token token, string value, string formatString, IEnumerable nestedExpressions) - : this(token.Extent, value, formatString, + : this(token.Extent, value, formatString, StringConstantExpressionAst - .MapTokenKindToStringContantKind(token), + .MapTokenKindToStringContantKind(token), nestedExpressions) { } @@ -10291,7 +10285,7 @@ namespace System.Management.Automation.Language /// public class HashtableAst : ExpressionAst { - private static readonly ReadOnlyCollection EmptyKeyValuePairs = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyKeyValuePairs = Utils.EmptyReadOnlyCollection(); /// /// Construct a hash literal ast. @@ -10312,7 +10306,7 @@ namespace System.Management.Automation.Language } else { - this.KeyValuePairs = EmptyKeyValuePairs; + this.KeyValuePairs = s_emptyKeyValuePairs; } } @@ -10591,7 +10585,6 @@ namespace System.Management.Automation.Language return visitor.CheckForPostAction(this, action); } - #endregion Visitors } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index f45643393..06eafcc6b 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -45,7 +45,7 @@ namespace System.Management.Automation.Language /// Tokens with this kind are always instances of . /// Parameter = 3, - + /// /// Any numerical literal token. /// Tokens with this kind are always instances of . @@ -728,7 +728,7 @@ namespace System.Management.Automation.Language /// public static class TokenTraits { - private readonly static TokenFlags[] _staticTokenFlags = new TokenFlags[] + private readonly static TokenFlags[] s_staticTokenFlags = new TokenFlags[] { #region Flags for unclassified tokens @@ -923,11 +923,10 @@ namespace System.Management.Automation.Language /* Hidden */ TokenFlags.Keyword, /* Base */ TokenFlags.Keyword, - #endregion Flags for keywords }; - private static readonly string[] _tokenText = new string[] + private static readonly string[] s_tokenText = new string[] { #region Text for unclassified tokens @@ -1128,9 +1127,9 @@ namespace System.Management.Automation.Language #if DEBUG static TokenTraits() { - Diagnostics.Assert(_staticTokenFlags.Length == ((int)TokenKind.Base + 1), + Diagnostics.Assert(s_staticTokenFlags.Length == ((int)TokenKind.Base + 1), "Table size out of sync with enum - _staticTokenFlags"); - Diagnostics.Assert(_tokenText.Length == ((int)TokenKind.Base + 1), + Diagnostics.Assert(s_tokenText.Length == ((int)TokenKind.Base + 1), "Table size out of sync with enum - _tokenText"); // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), @@ -1141,7 +1140,7 @@ namespace System.Management.Automation.Language "Table out of sync with enum - flags Sequence"); Diagnostics.Assert(GetTraits(TokenKind.Shr) == (TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison | TokenFlags.CanConstantFold), "Table out of sync with enum - flags Shr"); - Diagnostics.Assert(_tokenText[(int)TokenKind.Shr].Equals("-shr", StringComparison.OrdinalIgnoreCase), + Diagnostics.Assert(s_tokenText[(int)TokenKind.Shr].Equals("-shr", StringComparison.OrdinalIgnoreCase), "Table out of sync with enum - text Shr"); } #endif @@ -1151,7 +1150,7 @@ namespace System.Management.Automation.Language /// public static TokenFlags GetTraits(this TokenKind kind) { - return _staticTokenFlags[(int)kind]; + return s_staticTokenFlags[(int)kind]; } /// @@ -1165,7 +1164,7 @@ namespace System.Management.Automation.Language internal static int GetBinaryPrecedence(this TokenKind kind) { Diagnostics.Assert(HasTrait(kind, TokenFlags.BinaryOperator), "Token doesn't have binary precedence."); - return (int)(_staticTokenFlags[(int)kind] & TokenFlags.BinaryPrecedenceMask); + return (int)(s_staticTokenFlags[(int)kind] & TokenFlags.BinaryPrecedenceMask); } /// @@ -1173,7 +1172,7 @@ namespace System.Management.Automation.Language /// public static string Text(this TokenKind kind) { - return _tokenText[(int) kind]; + return s_tokenText[(int)kind]; } } @@ -1188,9 +1187,9 @@ namespace System.Management.Automation.Language internal Token(InternalScriptExtent scriptExtent, TokenKind kind, TokenFlags tokenFlags) { - this._scriptExtent = scriptExtent; - this._kind = kind; - this._tokenFlags = tokenFlags | kind.GetTraits(); + _scriptExtent = scriptExtent; + _kind = kind; + _tokenFlags = tokenFlags | kind.GetTraits(); } internal void SetIsCommandArgument() @@ -1252,7 +1251,7 @@ namespace System.Management.Automation.Language internal NumberToken(InternalScriptExtent scriptExtent, object value, TokenFlags tokenFlags) : base(scriptExtent, TokenKind.Number, tokenFlags) { - this._value = value; + _value = value; } internal override string ToDebugString(int indent) @@ -1337,12 +1336,12 @@ namespace System.Management.Automation.Language /// public abstract class StringToken : Token { - readonly string _value; + private readonly string _value; internal StringToken(InternalScriptExtent scriptExtent, TokenKind kind, TokenFlags tokenFlags, string value) : base(scriptExtent, kind, tokenFlags) { - this._value = value; + _value = value; } /// @@ -1381,10 +1380,10 @@ namespace System.Management.Automation.Language { if (nestedTokens != null && nestedTokens.Count > 0) { - this._nestedTokens = new ReadOnlyCollection(nestedTokens.ToArray()); + _nestedTokens = new ReadOnlyCollection(nestedTokens.ToArray()); } - this._formatString = formatString; + _formatString = formatString; } internal static void ToDebugString(ReadOnlyCollection nestedTokens, @@ -1436,7 +1435,7 @@ namespace System.Management.Automation.Language internal LabelToken(InternalScriptExtent scriptExtent, TokenFlags tokenFlags, string labelText) : base(scriptExtent, TokenKind.Label, tokenFlags) { - this._labelText = labelText; + _labelText = labelText; } /// diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index bb2d39b2c..ddab62b50 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -42,7 +42,6 @@ namespace System.Management.Automation.Language /// Name may be optionally present, expression or bare word /// OptionalName = 4, - }; /// @@ -77,14 +76,15 @@ namespace System.Management.Automation.Language /// private static Dictionary DynamicKeywords { - get { - return _dynamicKeywords ?? - (_dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase)); + get + { + return t_dynamicKeywords ?? + (t_dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } [ThreadStatic] - private static Dictionary _dynamicKeywords; + private static Dictionary t_dynamicKeywords; /// /// stack of DynamicKeywords Cache @@ -94,19 +94,19 @@ namespace System.Management.Automation.Language { get { - return _dynamicKeywordsStack ?? - (_dynamicKeywordsStack = new Stack>()); + return t_dynamicKeywordsStack ?? + (t_dynamicKeywordsStack = new Stack>()); } } [ThreadStatic] - private static Stack> _dynamicKeywordsStack; + private static Stack> t_dynamicKeywordsStack; /// /// Reset the keyword table to a new empty collection. /// public static void Reset() { - _dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase); + t_dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase); } /// @@ -114,7 +114,7 @@ namespace System.Management.Automation.Language /// public static void Push() { - DynamicKeywordsStack.Push(_dynamicKeywords); + DynamicKeywordsStack.Push(t_dynamicKeywords); Reset(); } @@ -123,7 +123,7 @@ namespace System.Management.Automation.Language /// public static void Pop() { - _dynamicKeywords = DynamicKeywordsStack.Pop(); + t_dynamicKeywords = DynamicKeywordsStack.Pop(); } /// @@ -214,15 +214,15 @@ namespace System.Management.Automation.Language throw e; } - return HiddenDynamicKeywords.Contains(name); + return s_hiddenDynamicKeywords.Contains(name); } /// /// A set of dynamic keywords that are not supposed to be used in script directly. /// They are for internal use only. /// - private static readonly HashSet HiddenDynamicKeywords = - new HashSet(StringComparer.OrdinalIgnoreCase) {"MSFT_Credential"}; + private static readonly HashSet s_hiddenDynamicKeywords = + new HashSet(StringComparer.OrdinalIgnoreCase) { "MSFT_Credential" }; #endregion @@ -320,24 +320,26 @@ namespace System.Management.Automation.Language /// public Dictionary Properties { - get { + get + { return _properties ?? (_properties = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } - Dictionary _properties; + private Dictionary _properties; /// /// A list of the parameters allowed for this constuctor. /// public Dictionary Parameters { - get { + get + { return _parameters ?? (_parameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } } - Dictionary _parameters; + private Dictionary _parameters; /// /// A custom function that gets executed at parsing time before parsing dynamickeyword block @@ -375,7 +377,7 @@ namespace System.Management.Automation.Language (ConfigurationType != ConfigurationType.Meta && !keyword.IsMetaDSCResource())); } - private static Dictionary> _excludeKeywords = new Dictionary>(StringComparer.OrdinalIgnoreCase) + private static Dictionary> s_excludeKeywords = new Dictionary>(StringComparer.OrdinalIgnoreCase) { {@"Node", new List {@"Node"}}, }; @@ -392,7 +394,7 @@ namespace System.Management.Automation.Language if (String.Compare(keywordName, @"Node", StringComparison.OrdinalIgnoreCase) == 0) { List excludeKeywords; - if (_excludeKeywords.TryGetValue(keywordName, out excludeKeywords)) + if (s_excludeKeywords.TryGetValue(keywordName, out excludeKeywords)) { return allowedKeywords.Where(k => !excludeKeywords.Contains(k.Keyword)); } @@ -425,7 +427,7 @@ namespace System.Management.Automation.Language { get { return _attributes ?? (_attributes = new List()); } } - List _attributes; + private List _attributes; /// /// List of strings that may be used as values for this property. @@ -434,7 +436,7 @@ namespace System.Management.Automation.Language { get { return _values ?? (_values = new List()); } } - List _values; + private List _values; /// /// Mapping the descriptive values to the actual values @@ -500,9 +502,9 @@ namespace System.Management.Automation.Language [DebuggerDisplay("Mode = {Mode}; Script = {_script}")] internal class Tokenizer { - readonly private static Dictionary _keywordTable + readonly private static Dictionary s_keywordTable = new Dictionary(StringComparer.OrdinalIgnoreCase); - readonly private static Dictionary _operatorTable + readonly private static Dictionary s_operatorTable = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly Parser _parser; @@ -524,7 +526,7 @@ namespace System.Management.Automation.Language #region Tables for initialization - readonly private static string[] _keywordText = new string[] { + readonly private static string[] s_keywordText = new string[] { /*1*/ "elseif", "if", "else", "switch", /*1*/ /*2*/ "foreach", "from", "in", "for", /*2*/ /*3*/ "while", "until", "do", "try", /*3*/ @@ -540,7 +542,7 @@ namespace System.Management.Automation.Language /*D*/ "base", /*D*/ }; - readonly private static TokenKind[] _keywordTokenKind = new TokenKind[] { + readonly private static TokenKind[] s_keywordTokenKind = new TokenKind[] { /*1*/ TokenKind.ElseIf, TokenKind.If, TokenKind.Else, TokenKind.Switch, /*1*/ /*2*/ TokenKind.Foreach, TokenKind.From, TokenKind.In, TokenKind.For, /*2*/ /*3*/ TokenKind.While, TokenKind.Until, TokenKind.Do, TokenKind.Try, /*3*/ @@ -575,7 +577,7 @@ namespace System.Management.Automation.Language /*16*/ "join", "shl", "shr", /*16*/ }; - readonly static TokenKind[] _operatorTokenKind = new TokenKind[] { + private readonly static TokenKind[] s_operatorTokenKind = new TokenKind[] { /*1*/ TokenKind.Bnot, TokenKind.Not, TokenKind.Ieq, TokenKind.Ieq, /*1*/ /*2*/ TokenKind.Ceq, TokenKind.Ine, TokenKind.Ine, TokenKind.Cne, /*2*/ /*3*/ TokenKind.Ige, TokenKind.Ige, TokenKind.Cge, TokenKind.Igt, /*3*/ @@ -598,17 +600,17 @@ namespace System.Management.Automation.Language static Tokenizer() { - Diagnostics.Assert(_keywordText.Length == _keywordTokenKind.Length, "Keyword table sizes must match"); - Diagnostics.Assert(_operatorText.Length == _operatorTokenKind.Length, "Operator table sizes must match"); + Diagnostics.Assert(s_keywordText.Length == s_keywordTokenKind.Length, "Keyword table sizes must match"); + Diagnostics.Assert(_operatorText.Length == s_operatorTokenKind.Length, "Operator table sizes must match"); - for (int i = 0; i < _keywordText.Length; ++i) + for (int i = 0; i < s_keywordText.Length; ++i) { - _keywordTable.Add(_keywordText[i], _keywordTokenKind[i]); + s_keywordTable.Add(s_keywordText[i], s_keywordTokenKind[i]); } for (int i = 0; i < _operatorText.Length; ++i) { - _operatorTable.Add(_operatorText[i], _operatorTokenKind[i]); + s_operatorTable.Add(_operatorText[i], s_operatorTokenKind[i]); } // The real signature (in mshsip.cpp) has spaces, but we ignore whitespace when looking @@ -619,13 +621,13 @@ namespace System.Management.Automation.Language beginSig.Aggregate(0, (current, t) => current + t); // Spot check to help make sure the arrays are in sync - Diagnostics.Assert(_keywordTable["using"] == TokenKind.Using, "Keyword table out of sync w/ enum"); - Diagnostics.Assert(_operatorTable["join"] == TokenKind.Join, "Operator table out of sync w/ enum"); + Diagnostics.Assert(s_keywordTable["using"] == TokenKind.Using, "Keyword table out of sync w/ enum"); + Diagnostics.Assert(s_operatorTable["join"] == TokenKind.Join, "Operator table out of sync w/ enum"); } internal Tokenizer(Parser parser) { - this._parser = parser; + _parser = parser; } internal TokenizerMode Mode { get; set; } @@ -633,7 +635,7 @@ namespace System.Management.Automation.Language internal bool WantSimpleName { get; set; } internal bool InWorkflowContext { get; set; } internal List TokenList { get; set; } - internal Token FirstToken { get; private set; } + internal Token FirstToken { get; private set; } internal Token LastToken { get; private set; } private List RequiresTokens { get; set; } @@ -644,22 +646,22 @@ namespace System.Management.Automation.Language internal void Initialize(string fileName, string input, List tokenList) { - this._positionHelper = new PositionHelper(fileName, input); - this._script = input; + _positionHelper = new PositionHelper(fileName, input); + _script = input; this.TokenList = tokenList; this.FirstToken = null; this.LastToken = null; this.RequiresTokens = null; - this._beginSignatureExtent = null; + _beginSignatureExtent = null; - List lineStartMap = new List(100) {0}; + List lineStartMap = new List(100) { 0 }; for (int i = 0; i < input.Length; ++i) { char c = input[i]; - + if (c == '\r') { - if ((i+1) < input.Length && input[i+1] == '\n') + if ((i + 1) < input.Length && input[i + 1] == '\n') { i += 1; } @@ -676,10 +678,11 @@ namespace System.Management.Automation.Language _positionHelper.LineStartMap = lineStartMap.ToArray(); } - + internal TokenizerState StartNestedScan(UnscannedSubExprToken nestedText) { - TokenizerState ts = new TokenizerState { + TokenizerState ts = new TokenizerState + { CurrentIndex = _currentIndex, NestedTokensAdjustment = _nestedTokensAdjustment, Script = _script, @@ -715,7 +718,7 @@ namespace System.Management.Automation.Language private char GetChar() { Diagnostics.Assert(0 <= _currentIndex, "GetChar reading before start of input."); - Diagnostics.Assert(_currentIndex <= _script.Length+1, "GetChar reading after end of input."); + Diagnostics.Assert(_currentIndex <= _script.Length + 1, "GetChar reading after end of input."); // Increment _currentIndex, even if it goes over the Length so callers can call UngetChar to unget EOF. int current = _currentIndex++; @@ -758,7 +761,7 @@ namespace System.Management.Automation.Language internal static bool IsKeyword(string str) { - if (_keywordTable.ContainsKey(str)) + if (s_keywordTable.ContainsKey(str)) { return true; } @@ -772,84 +775,84 @@ namespace System.Management.Automation.Language internal void SkipNewlines(bool skipSemis, bool v3) { - // We normally don't create any tokens here, but the V2 tokenizer api returns newline tokens, - // so we create them when asked to create them. + // We normally don't create any tokens here, but the V2 tokenizer api returns newline tokens, + // so we create them when asked to create them. - again: + again: char c = GetChar(); switch (c) { - case ' ': - case '\t': - case '\f': - case '\v': - case SpecialChars.NoBreakSpace: - case SpecialChars.NextLine: - SkipWhiteSpace(); - goto again; + case ' ': + case '\t': + case '\f': + case '\v': + case SpecialChars.NoBreakSpace: + case SpecialChars.NextLine: + SkipWhiteSpace(); + goto again; - case '\r': - case '\n': - if (v3) _parser.NoteV3FeatureUsed(); - if (TokenList != null) - { - _tokenStart = _currentIndex - 1; - ScanNewline(c); - NewToken(TokenKind.NewLine); - } - goto again; - - case ';': - if (skipSemis) - { + case '\r': + case '\n': + if (v3) _parser.NoteV3FeatureUsed(); if (TokenList != null) { _tokenStart = _currentIndex - 1; - NewToken(TokenKind.Semi); + ScanNewline(c); + NewToken(TokenKind.NewLine); } goto again; - } - break; - case '#': - _tokenStart = _currentIndex - 1; - ScanLineComment(); - goto again; + case ';': + if (skipSemis) + { + if (TokenList != null) + { + _tokenStart = _currentIndex - 1; + NewToken(TokenKind.Semi); + } + goto again; + } + break; - case '<': - if (PeekChar() == '#') - { + case '#': _tokenStart = _currentIndex - 1; - SkipChar(); - ScanBlockComment(); + ScanLineComment(); goto again; - } - break; - - case '`': - char c1 = GetChar(); - if (c1 == '\n' || c1 == '\r') - { - _tokenStart = _currentIndex - 2; - ScanNewline(c1); - NewToken(TokenKind.LineContinuation); - goto again; - } - if (char.IsWhiteSpace(c1)) - { - SkipWhiteSpace(); - goto again; - } - UngetChar(); - break; - default: - if (c.IsWhitespace()) - { - SkipWhiteSpace(); - goto again; - } - break; + case '<': + if (PeekChar() == '#') + { + _tokenStart = _currentIndex - 1; + SkipChar(); + ScanBlockComment(); + goto again; + } + break; + + case '`': + char c1 = GetChar(); + if (c1 == '\n' || c1 == '\r') + { + _tokenStart = _currentIndex - 2; + ScanNewline(c1); + NewToken(TokenKind.LineContinuation); + goto again; + } + if (char.IsWhiteSpace(c1)) + { + SkipWhiteSpace(); + goto again; + } + UngetChar(); + break; + + default: + if (c.IsWhitespace()) + { + SkipWhiteSpace(); + goto again; + } + break; } UngetChar(); } @@ -984,7 +987,7 @@ namespace System.Management.Automation.Language private void ReportError(int errorOffset, Expression> message, params object[] args) { - _parser.ReportError(NewScriptExtent(errorOffset, errorOffset+1), message, args); + _parser.ReportError(NewScriptExtent(errorOffset, errorOffset + 1), message, args); } private void ReportError(IScriptExtent extent, Expression> message) @@ -1037,7 +1040,7 @@ namespace System.Management.Automation.Language if (_skippedCharOffsets[i]) { end += 1; - } + } } } return new InternalScriptExtent(_positionHelper, start, end); @@ -1053,7 +1056,7 @@ namespace System.Management.Automation.Language return SaveToken(new Token(CurrentExtent(), TokenKind.Comment, TokenFlags.None)); } - private T SaveToken(T token) where T: Token + private T SaveToken(T token) where T : Token { if (TokenList != null) { @@ -1064,19 +1067,19 @@ namespace System.Management.Automation.Language // for the special variables $$ and $^. switch (token.Kind) { - case TokenKind.NewLine: - case TokenKind.LineContinuation: - case TokenKind.Comment: - case TokenKind.EndOfInput: - // Don't remember these tokens, they aren't useful in $$ and $^. - break; - default: - if (FirstToken == null) - { - FirstToken = token; - } - LastToken = token; - break; + case TokenKind.NewLine: + case TokenKind.LineContinuation: + case TokenKind.Comment: + case TokenKind.EndOfInput: + // Don't remember these tokens, they aren't useful in $$ and $^. + break; + default: + if (FirstToken == null) + { + FirstToken = token; + } + LastToken = token; + break; } return token; } @@ -1182,7 +1185,7 @@ namespace System.Management.Automation.Language continue; } - if (_script[i] == '<' && (i+1) < _script.Length && _script[i+1] == '#') + if (_script[i] == '<' && (i + 1) < _script.Length && _script[i + 1] == '#') { i = SkipBlockComment(i + 2) - 1; continue; @@ -1190,7 +1193,7 @@ namespace System.Management.Automation.Language if (!_script[i].IsWhitespace()) { - return false; + return false; } } return true; @@ -1217,7 +1220,7 @@ namespace System.Management.Automation.Language { char c = _script[i]; - if (c == '#' && (i+1) < _script.Length && _script[i+1] == '>') + if (c == '#' && (i + 1) < _script.Length && _script[i + 1] == '>') { return i + 2; } @@ -1230,15 +1233,15 @@ namespace System.Management.Automation.Language { switch (c) { - case '0': return '\0'; - case 'a': return '\a'; - case 'b': return '\b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'v': return '\v'; - default : return c; + case '0': return '\0'; + case 'a': return '\a'; + case 'b': return '\b'; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + default: return c; } } @@ -1274,100 +1277,106 @@ namespace System.Management.Automation.Language switch (c) { - case 'e': case 'E': - if (requiresMatchState == 1 || requiresMatchState == 6) - requiresMatchState += 1; - else - requiresMatchState = -1; - break; - case 'i': case 'I': - if (requiresMatchState == 4) - requiresMatchState += 1; - else - requiresMatchState = -1; - break; - case 'q': case 'Q': - if (requiresMatchState == 2) - requiresMatchState += 1; - else - requiresMatchState = -1; - break; - case 'r': case 'R': - if (requiresMatchState == 0 || requiresMatchState == 5) - requiresMatchState += 1; - else - requiresMatchState = -1; - break; - case 's': case 'S': - if (requiresMatchState == 7) - matchedRequires = true; - else - requiresMatchState = -1; - break; - case 'u': case 'U': - if (requiresMatchState == 3) - requiresMatchState += 1; - else - requiresMatchState = -1; - break; - case '\0': - if (AtEof()) - { - goto case '\n'; - } - goto default; - case '\r': - case '\n': - UngetChar(); + case 'e': + case 'E': + if (requiresMatchState == 1 || requiresMatchState == 6) + requiresMatchState += 1; + else + requiresMatchState = -1; + break; + case 'i': + case 'I': + if (requiresMatchState == 4) + requiresMatchState += 1; + else + requiresMatchState = -1; + break; + case 'q': + case 'Q': + if (requiresMatchState == 2) + requiresMatchState += 1; + else + requiresMatchState = -1; + break; + case 'r': + case 'R': + if (requiresMatchState == 0 || requiresMatchState == 5) + requiresMatchState += 1; + else + requiresMatchState = -1; + break; + case 's': + case 'S': + if (requiresMatchState == 7) + matchedRequires = true; + else + requiresMatchState = -1; + break; + case 'u': + case 'U': + if (requiresMatchState == 3) + requiresMatchState += 1; + else + requiresMatchState = -1; + break; + case '\0': + if (AtEof()) + { + goto case '\n'; + } + goto default; + case '\r': + case '\n': + UngetChar(); - // The token similarity threshold was chosen by instrumenting the tokenizer and - // analyzing every comment from PoshCode, Technet Script Center, and Windows. - // - // The closest comments above "10" had a score of 11, which are marginal and - // appropriately close to being tricky. - // - // # END BEGIN SCRIPT BLOCK - // # SET TEXT SIGNATURE - // - // Below 11 were only actual signature blocks: - // - // # SIG # END SIGNATURE BLOCK - // # SIG # BEGIN SIGNATURE BLOCK - // - // There were only 279 (out of 269,387) comments with a similarity of 11,12,13,14, or 15. - // At a similarity of 16-77, there were thousands of comments per similarity bucket. - // - // System.IO.File.AppendAllText(@"c:\temp\signature_similarity.txt", "" + sawBeginTokenSimilarity + ":" + commentLineComparison); - - const string beginSignatureTextNoSpace = "sig#beginsignatureblock\n"; - const int beginTokenSimilarityThreshold = 10; - - // Quick exit - the comment line is more than 'threshold' longer. Therefore, - // its similarity will be over the threshold. - if (commentLine.Length > (beginSignatureTextNoSpace.Length + beginTokenSimilarityThreshold)) - { - sawBeginSig = false; - } - else - { - // Perf note - the GetStringSimilarity function is able to evaluate approximately 50kb of pure comments - // (1000 lines, each of length between 10 and 80 characters) in about 40ms, compared to 6ms it took to - // doing the error-prone hashing approach we had implemented before. + // The token similarity threshold was chosen by instrumenting the tokenizer and + // analyzing every comment from PoshCode, Technet Script Center, and Windows. // - // The average script is 14% comments and parses in about 5.05 ms with this algorithm, - // about 4.45 ms with the more simplistic algorithm. - // - string commentLineComparison = commentLine.ToString().ToLowerInvariant(); + // The closest comments above "10" had a score of 11, which are marginal and + // appropriately close to being tricky. + // + // # END BEGIN SCRIPT BLOCK + // # SET TEXT SIGNATURE + // + // Below 11 were only actual signature blocks: + // + // # SIG # END SIGNATURE BLOCK + // # SIG # BEGIN SIGNATURE BLOCK + // + // There were only 279 (out of 269,387) comments with a similarity of 11,12,13,14, or 15. + // At a similarity of 16-77, there were thousands of comments per similarity bucket. + // + // System.IO.File.AppendAllText(@"c:\temp\signature_similarity.txt", "" + sawBeginTokenSimilarity + ":" + commentLineComparison); - int sawBeginTokenSimilarity = GetStringSimilarity(commentLineComparison, beginSignatureTextNoSpace); - sawBeginSig = sawBeginTokenSimilarity < beginTokenSimilarityThreshold; - } + const string beginSignatureTextNoSpace = "sig#beginsignatureblock\n"; + const int beginTokenSimilarityThreshold = 10; - Release(commentLine); - return; - default: - requiresMatchState = -1; - break; + // Quick exit - the comment line is more than 'threshold' longer. Therefore, + // its similarity will be over the threshold. + if (commentLine.Length > (beginSignatureTextNoSpace.Length + beginTokenSimilarityThreshold)) + { + sawBeginSig = false; + } + else + { + // Perf note - the GetStringSimilarity function is able to evaluate approximately 50kb of pure comments + // (1000 lines, each of length between 10 and 80 characters) in about 40ms, compared to 6ms it took to + // doing the error-prone hashing approach we had implemented before. + // + // The average script is 14% comments and parses in about 5.05 ms with this algorithm, + // about 4.45 ms with the more simplistic algorithm. + // + string commentLineComparison = commentLine.ToString().ToLowerInvariant(); + + int sawBeginTokenSimilarity = GetStringSimilarity(commentLineComparison, beginSignatureTextNoSpace); + sawBeginSig = sawBeginTokenSimilarity < beginTokenSimilarityThreshold; + } + + Release(commentLine); + return; + default: + requiresMatchState = -1; + break; } } } @@ -1376,21 +1385,21 @@ namespace System.Management.Automation.Language #region Object reuse - private readonly Queue stringBuilders = new Queue(); + private readonly Queue _stringBuilders = new Queue(); private StringBuilder GetStringBuilder() { - return stringBuilders.Count == 0 ? new StringBuilder() : stringBuilders.Dequeue(); + return _stringBuilders.Count == 0 ? new StringBuilder() : _stringBuilders.Dequeue(); } private void Release(StringBuilder sb) { // We don't want to cache too much, so limit to 10 string builders // and don't keep any that have > 1kb - if (stringBuilders.Count < 10 && sb.Capacity < 1024) + if (_stringBuilders.Count < 10 && sb.Capacity < 1024) { sb.Clear(); - stringBuilders.Enqueue(sb); + _stringBuilders.Enqueue(sb); } } @@ -1575,38 +1584,38 @@ namespace System.Management.Automation.Language if (snapinName != null) { Diagnostics.Assert(PSSnapInInfo.IsPSSnapinIdValid(snapinName), "we shouldn't set snapinName if it wasn't valid"); - requiredSnapins.Add(new PSSnapInSpecification(snapinName) {Version = snapinVersion}); + requiredSnapins.Add(new PSSnapInSpecification(snapinName) { Version = snapinVersion }); } } } return new ScriptRequirements - { - RequiredApplicationId = requiredShellId, - RequiredPSVersion = requiredVersion, - RequiredPSEditions = requiredEditions != null + { + RequiredApplicationId = requiredShellId, + RequiredPSVersion = requiredVersion, + RequiredPSEditions = requiredEditions != null ? new ReadOnlyCollection(requiredEditions) : ScriptRequirements.EmptyEditionCollection, - RequiresPSSnapIns = requiredSnapins != null + RequiresPSSnapIns = requiredSnapins != null ? new ReadOnlyCollection(requiredSnapins) : ScriptRequirements.EmptySnapinCollection, - RequiredAssemblies = requiredAssemblies != null + RequiredAssemblies = requiredAssemblies != null ? new ReadOnlyCollection(requiredAssemblies) : ScriptRequirements.EmptyAssemblyCollection, - RequiredModules = requiredModules != null + RequiredModules = requiredModules != null ? new ReadOnlyCollection(requiredModules) : ScriptRequirements.EmptyModuleCollection, - IsElevationRequired = requiresElevation + IsElevationRequired = requiresElevation }; } - const string shellIDToken = "shellid"; - const string PSSnapinToken = "pssnapin"; - const string versionToken = "version"; - const string editionToken = "psedition"; - const string assemblyToken = "assembly"; - const string modulesToken = "modules"; - const string elevationToken = "runasadministrator"; + private const string shellIDToken = "shellid"; + private const string PSSnapinToken = "pssnapin"; + private const string versionToken = "version"; + private const string editionToken = "psedition"; + private const string assemblyToken = "assembly"; + private const string modulesToken = "modules"; + private const string elevationToken = "runasadministrator"; private void HandleRequiresParameter(CommandParameterAst parameter, ReadOnlyCollection commandElements, @@ -1632,7 +1641,7 @@ namespace System.Management.Automation.Language } return; } - + if (argumentAst == null) { ReportError(parameter.Extent, () => ParserStrings.ParameterRequiresArgument, parameter.ParameterName); @@ -1804,7 +1813,7 @@ namespace System.Management.Automation.Language if (requiredEditions == null) requiredEditions = new List(); - var edition = (string) arg; + var edition = (string)arg; if (!Utils.IsValidPSEditionValue(edition)) { ReportError(argumentAst.Extent, () => ParserStrings.RequiresPSEditionInvalid, editionToken); @@ -1918,50 +1927,50 @@ namespace System.Management.Automation.Language char c = GetChar(); switch (c) { - case '(': - sb.Append(c); - ++parenCount; - break; - - case ')': - sb.Append(c); - if (--parenCount == 0) - { - scanning = false; - } - break; - - case '`': - case '"': - case SpecialChars.QuoteDoubleLeft: - case SpecialChars.QuoteDoubleRight: - case SpecialChars.QuoteLowDoubleLeft: - char c1 = PeekChar(); - if (!hereString && c1.IsDoubleQuote()) - { - SkipChar(); - sb.Append(c1); - skippedCharOffsets.Add(_currentIndex - 2 + _nestedTokensAdjustment); - } - else - { + case '(': sb.Append(c); - } - break; + ++parenCount; + break; - case '\0': - if (!AtEof()) - goto default; + case ')': + sb.Append(c); + if (--parenCount == 0) + { + scanning = false; + } + break; - UngetChar(); - ReportIncompleteInput(_tokenStart, () => ParserStrings.IncompleteDollarSubexpressionReference); - flags = TokenFlags.TokenInError; - scanning = false; - break; + case '`': + case '"': + case SpecialChars.QuoteDoubleLeft: + case SpecialChars.QuoteDoubleRight: + case SpecialChars.QuoteLowDoubleLeft: + char c1 = PeekChar(); + if (!hereString && c1.IsDoubleQuote()) + { + SkipChar(); + sb.Append(c1); + skippedCharOffsets.Add(_currentIndex - 2 + _nestedTokensAdjustment); + } + else + { + sb.Append(c); + } + break; - default: - sb.Append(c); - break; + case '\0': + if (!AtEof()) + goto default; + + UngetChar(); + ReportIncompleteInput(_tokenStart, () => ParserStrings.IncompleteDollarSubexpressionReference); + flags = TokenFlags.TokenInError; + scanning = false; + break; + + default: + sb.Append(c); + break; } } @@ -2313,7 +2322,7 @@ namespace System.Management.Automation.Language } continue; } - + if (c == '$') { if (ScanDollarInStringExpandable(sb, formatSb, true, nestedTokens)) @@ -2348,7 +2357,7 @@ namespace System.Management.Automation.Language UngetChar(); if (falseFooterOffset != -1) { - ReportIncompleteInput(falseFooterOffset, () => ParserStrings.WhitespaceBeforeHereStringFooter); + ReportIncompleteInput(falseFooterOffset, () => ParserStrings.WhitespaceBeforeHereStringFooter); } else { @@ -2357,7 +2366,7 @@ namespace System.Management.Automation.Language flags = TokenFlags.TokenInError; break; } - } + } } return NewStringExpandableToken(GetStringAndRelease(sb), GetStringAndRelease(formatSb), TokenKind.HereStringExpandable, nestedTokens, flags); @@ -2387,51 +2396,51 @@ namespace System.Management.Automation.Language switch (c) { - case '}': - goto end_braced_variable_scan; - case '`': - { - char c1 = GetChar(); - if (c1 == '\0' && AtEof()) - { - UngetChar(); + case '}': goto end_braced_variable_scan; - } - c = Backtick(c1); - break; - } - case '"': - case SpecialChars.QuoteDoubleLeft: - case SpecialChars.QuoteDoubleRight: - case SpecialChars.QuoteLowDoubleLeft: - if (inStringExpandable) - { - char c1 = GetChar(); - if (c1 == '\0' && AtEof()) + case '`': + { + char c1 = GetChar(); + if (c1 == '\0' && AtEof()) + { + UngetChar(); + goto end_braced_variable_scan; + } + c = Backtick(c1); + break; + } + case '"': + case SpecialChars.QuoteDoubleLeft: + case SpecialChars.QuoteDoubleRight: + case SpecialChars.QuoteLowDoubleLeft: + if (inStringExpandable) + { + char c1 = GetChar(); + if (c1 == '\0' && AtEof()) + { + UngetChar(); + goto end_braced_variable_scan; + } + if (c1.IsDoubleQuote()) + { + c = c1; + } + else + { + UngetChar(); + } + } + break; + case '{': + ReportError(_currentIndex, () => ParserStrings.OpenBraceNeedsToBeBackTickedInVariableName); + break; + case '\0': + if (AtEof()) { UngetChar(); goto end_braced_variable_scan; } - if (c1.IsDoubleQuote()) - { - c = c1; - } - else - { - UngetChar(); - } - } - break; - case '{': - ReportError(_currentIndex, () => ParserStrings.OpenBraceNeedsToBeBackTickedInVariableName); - break; - case '\0': - if (AtEof()) - { - UngetChar(); - goto end_braced_variable_scan; - } - break; + break; } sb.Append(c); @@ -2501,59 +2510,126 @@ namespace System.Management.Automation.Language c = GetChar(); switch (c) { - case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': - case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': - case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': - case '_': case '?': - sb.Append(c); - break; - - case ':': - if (PeekChar() == ':') - { - // Something like $a::b is static member access - UngetChar(); - scanning = false; - } - else - { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '_': + case '?': sb.Append(c); - } - break; + break; - case '\0': case '\t': case '\r': case '\n': case ' ': case '&': case '(': case ')': - case ',': case ';': case '{': case '}': case '|': + case ':': + if (PeekChar() == ':') + { + // Something like $a::b is static member access + UngetChar(); + scanning = false; + } + else + { + sb.Append(c); + } + break; + + case '\0': + case '\t': + case '\r': + case '\n': + case ' ': + case '&': + case '(': + case ')': + case ',': + case ';': + case '{': + case '}': + case '|': // The above cases would also be handled correctly below in the default case, // but we can avoid extra checks on some of these characters which commonly // occur after a variable. - case '.': - case '[': - // Something like $a.b or $a[1]. - UngetChar(); - scanning = false; - break; - - default: - if (Char.IsLetterOrDigit(c)) - { - sb.Append(c); - } - else if (InCommandMode() && !c.ForceStartNewToken()) - { - _currentIndex = _tokenStart; - sb.Clear(); - return ScanGenericToken(sb); - } - else - { + case '.': + case '[': + // Something like $a.b or $a[1]. UngetChar(); scanning = false; - } - break; + break; + + default: + if (Char.IsLetterOrDigit(c)) + { + sb.Append(c); + } + else if (InCommandMode() && !c.ForceStartNewToken()) + { + _currentIndex = _tokenStart; + sb.Clear(); + return ScanGenericToken(sb); + } + else + { + UngetChar(); + scanning = false; + } + break; } } } @@ -2603,63 +2679,118 @@ namespace System.Management.Automation.Language switch (c) { - case '{': case '}': case '(': case ')': case ';': case ',': case '|': case '&': - case '.': case '[': - case '\r': case '\n': - case '\0': - UngetChar(); - scanning = false; - break; - - case ':': - scanning = false; - sawColonAtEnd = true; - if (!InCommandMode()) - { - UngetChar(); - } - break; - - case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': - case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': - sb.Append(c); - break; - - case '\'': - case SpecialChars.QuoteSingleLeft: - case SpecialChars.QuoteSingleRight: - case SpecialChars.QuoteSingleBase: - case SpecialChars.QuoteReversed: - case '"': - case SpecialChars.QuoteDoubleLeft: - case SpecialChars.QuoteDoubleRight: - case SpecialChars.QuoteLowDoubleLeft: - if (InCommandMode()) - { - // Quotes are never part of a parameter. Treat the token as an argument. - UngetChar(); - sb.Insert(0, _script[_tokenStart]); // Insert the '-' that we skipped. - return ScanGenericToken(sb); - } - UngetChar(); - scanning = false; - break; - - default: - if (InCommandMode()) - { - sb.Append(c); - } - else - { + case '{': + case '}': + case '(': + case ')': + case ';': + case ',': + case '|': + case '&': + case '.': + case '[': + case '\r': + case '\n': + case '\0': UngetChar(); scanning = false; - } - break; + break; + + case ':': + scanning = false; + sawColonAtEnd = true; + if (!InCommandMode()) + { + UngetChar(); + } + break; + + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + sb.Append(c); + break; + + case '\'': + case SpecialChars.QuoteSingleLeft: + case SpecialChars.QuoteSingleRight: + case SpecialChars.QuoteSingleBase: + case SpecialChars.QuoteReversed: + case '"': + case SpecialChars.QuoteDoubleLeft: + case SpecialChars.QuoteDoubleRight: + case SpecialChars.QuoteLowDoubleLeft: + if (InCommandMode()) + { + // Quotes are never part of a parameter. Treat the token as an argument. + UngetChar(); + sb.Insert(0, _script[_tokenStart]); // Insert the '-' that we skipped. + return ScanGenericToken(sb); + } + UngetChar(); + scanning = false; + break; + + default: + if (InCommandMode()) + { + sb.Append(c); + } + else + { + UngetChar(); + scanning = false; + } + break; } } @@ -2668,7 +2799,7 @@ namespace System.Management.Automation.Language if (InExpressionMode()) { TokenKind operatorKind; - if (_operatorTable.TryGetValue(str, out operatorKind)) + if (s_operatorTable.TryGetValue(str, out operatorKind)) { return NewToken(operatorKind); } @@ -3277,63 +3408,63 @@ namespace System.Management.Automation.Language char c = GetChar(); switch (c) { - case ' ': - case '\t': - case '\f': - case '\v': - case SpecialChars.NoBreakSpace: - case SpecialChars.NextLine: - resyncIfMemberAccess = true; - SkipWhiteSpace(); - goto again; - - case '#': - resyncIfMemberAccess = true; - ScanLineComment(); - goto again; - - case '<': - if (PeekChar() == '#') - { - // We resync if we find any whitespace, but only if the whitespace occurs after a - // multi-line comment (rationale: backwards compatibility.) - resyncIfMemberAccess = false; - SkipChar(); - ScanBlockComment(); - goto again; - } - UngetChar(); - break; - - case '[': - return NewToken(TokenKind.LBracket); - - case '.': - case ':': - // We don't call resync here unless we might have a member access token, in which case - // we want to rescan the comments to ensure there is no whitespace between the expression - // and the member access token. The resync here should rarely do much other than move - // the _currentIndex because there will rarely be any comment tokens after the closing ']' - // in an attribute and the member access token. - if (resyncIfMemberAccess) - { - Resync(resyncPoint); - } - else - { - UngetChar(); - } - break; - - default: - if (c.IsWhitespace()) - { + case ' ': + case '\t': + case '\f': + case '\v': + case SpecialChars.NoBreakSpace: + case SpecialChars.NextLine: resyncIfMemberAccess = true; SkipWhiteSpace(); goto again; - } - UngetChar(); - break; + + case '#': + resyncIfMemberAccess = true; + ScanLineComment(); + goto again; + + case '<': + if (PeekChar() == '#') + { + // We resync if we find any whitespace, but only if the whitespace occurs after a + // multi-line comment (rationale: backwards compatibility.) + resyncIfMemberAccess = false; + SkipChar(); + ScanBlockComment(); + goto again; + } + UngetChar(); + break; + + case '[': + return NewToken(TokenKind.LBracket); + + case '.': + case ':': + // We don't call resync here unless we might have a member access token, in which case + // we want to rescan the comments to ensure there is no whitespace between the expression + // and the member access token. The resync here should rarely do much other than move + // the _currentIndex because there will rarely be any comment tokens after the closing ']' + // in an attribute and the member access token. + if (resyncIfMemberAccess) + { + Resync(resyncPoint); + } + else + { + UngetChar(); + } + break; + + default: + if (c.IsWhitespace()) + { + resyncIfMemberAccess = true; + SkipWhiteSpace(); + goto again; + } + UngetChar(); + break; } return null; @@ -3413,7 +3544,7 @@ namespace System.Management.Automation.Language TokenKind tokenKind; var ident = GetStringAndRelease(sb); sb = null; - if (_keywordTable.TryGetValue(ident, out tokenKind)) + if (s_keywordTable.TryGetValue(ident, out tokenKind)) { if (tokenKind != TokenKind.InlineScript || InWorkflowContext) return NewToken(tokenKind); @@ -3439,19 +3570,19 @@ namespace System.Management.Automation.Language switch (c) { - case '.': - case '`': - case '_': - case '+': - case '#': - case '\\': - continue; - default: - if (char.IsLetterOrDigit(c)) - { + case '.': + case '`': + case '_': + case '+': + case '#': + case '\\': continue; - } - break; + default: + if (char.IsLetterOrDigit(c)) + { + continue; + } + break; } UngetChar(); @@ -3587,349 +3718,404 @@ namespace System.Management.Automation.Language char c = GetChar(); switch (c) { - case ' ': - case '\t': - case '\f': - case '\v': - case SpecialChars.NoBreakSpace: - case SpecialChars.NextLine: - SkipWhiteSpace(); - goto again; - - case '\'': - case SpecialChars.QuoteSingleLeft: - case SpecialChars.QuoteSingleRight: - case SpecialChars.QuoteSingleBase: - case SpecialChars.QuoteReversed: - return ScanStringLiteral(); - - case '"': - case SpecialChars.QuoteDoubleLeft: - case SpecialChars.QuoteDoubleRight: - case SpecialChars.QuoteLowDoubleLeft: - return ScanStringExpandable(); - - case '@': - // Could be start of hash literal, array operator, multi-line string, splatted variable - c1 = GetChar(); - if (c1 == '{') - { - return NewToken(TokenKind.AtCurly); - } - if (c1 == '(') - { - return NewToken(TokenKind.AtParen); - } - if (c1.IsSingleQuote()) - { - return ScanHereStringLiteral(); - } - if (c1.IsDoubleQuote()) - { - return ScanHereStringExpandable(); - } - UngetChar(); - if (c1.IsVariableStart()) - { - return ScanVariable(true, false); - } - - ReportError(_currentIndex - 1, () => ParserStrings.UnrecognizedToken); - return NewToken(TokenKind.Unknown); - - case '#': - ScanLineComment(); - goto again; - - case '\r': - case '\n': - ScanNewline(c); - return NewToken(TokenKind.NewLine); - - case '`': - c1 = GetChar(); - if (c1 == '\n' || c1 == '\r') - { - ScanNewline(c1); - NewToken(TokenKind.LineContinuation); - goto again; - } - if (char.IsWhiteSpace(c1)) - { + case ' ': + case '\t': + case '\f': + case '\v': + case SpecialChars.NoBreakSpace: + case SpecialChars.NextLine: SkipWhiteSpace(); goto again; - } - if (c1 == '\0' && AtEof()) - { - ReportIncompleteInput(_currentIndex, () => ParserStrings.IncompleteString); - // Unget the EOF so we can return an EOF token. + case '\'': + case SpecialChars.QuoteSingleLeft: + case SpecialChars.QuoteSingleRight: + case SpecialChars.QuoteSingleBase: + case SpecialChars.QuoteReversed: + return ScanStringLiteral(); + + case '"': + case SpecialChars.QuoteDoubleLeft: + case SpecialChars.QuoteDoubleRight: + case SpecialChars.QuoteLowDoubleLeft: + return ScanStringExpandable(); + + case '@': + // Could be start of hash literal, array operator, multi-line string, splatted variable + c1 = GetChar(); + if (c1 == '{') + { + return NewToken(TokenKind.AtCurly); + } + if (c1 == '(') + { + return NewToken(TokenKind.AtParen); + } + if (c1.IsSingleQuote()) + { + return ScanHereStringLiteral(); + } + if (c1.IsDoubleQuote()) + { + return ScanHereStringExpandable(); + } UngetChar(); + if (c1.IsVariableStart()) + { + return ScanVariable(true, false); + } + + ReportError(_currentIndex - 1, () => ParserStrings.UnrecognizedToken); + return NewToken(TokenKind.Unknown); + + case '#': + ScanLineComment(); goto again; - } - return ScanGenericToken(Backtick(c1)); + case '\r': + case '\n': + ScanNewline(c); + return NewToken(TokenKind.NewLine); - case '=': - return CheckOperatorInCommandMode(c, TokenKind.Equals); + case '`': + c1 = GetChar(); + if (c1 == '\n' || c1 == '\r') + { + ScanNewline(c1); + NewToken(TokenKind.LineContinuation); + goto again; + } + if (char.IsWhiteSpace(c1)) + { + SkipWhiteSpace(); + goto again; + } + if (c1 == '\0' && AtEof()) + { + ReportIncompleteInput(_currentIndex, () => ParserStrings.IncompleteString); - case '+': - c1 = PeekChar(); - if (c1 == '+') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.PlusPlus); - } - if (c1 == '=') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.PlusEquals); - } - if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) - { - return ScanNumber(c); - } - return CheckOperatorInCommandMode(c, TokenKind.Plus); + // Unget the EOF so we can return an EOF token. + UngetChar(); + goto again; + } - case '-': - case SpecialChars.EmDash: - case SpecialChars.EnDash: - case SpecialChars.HorizontalBar: - c1 = PeekChar(); - if (c1.IsDash()) - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.MinusMinus); - } - if (c1 == '=') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.MinusEquals); - } - if (char.IsLetter(c1) || c1 == '_' || c1 == '?') - { - return ScanParameter(); - } - if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) - { - return ScanNumber(c); - } - return CheckOperatorInCommandMode(c, TokenKind.Minus); + return ScanGenericToken(Backtick(c1)); - case '*': - c1 = PeekChar(); - if (c1 == '=') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.MultiplyEquals); - } - if (c1 == '>') - { - SkipChar(); + case '=': + return CheckOperatorInCommandMode(c, TokenKind.Equals); + + case '+': c1 = PeekChar(); + if (c1 == '+') + { + SkipChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.PlusPlus); + } + if (c1 == '=') + { + SkipChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.PlusEquals); + } + if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) + { + return ScanNumber(c); + } + return CheckOperatorInCommandMode(c, TokenKind.Plus); + + case '-': + case SpecialChars.EmDash: + case SpecialChars.EnDash: + case SpecialChars.HorizontalBar: + c1 = PeekChar(); + if (c1.IsDash()) + { + SkipChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.MinusMinus); + } + if (c1 == '=') + { + SkipChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.MinusEquals); + } + if (char.IsLetter(c1) || c1 == '_' || c1 == '?') + { + return ScanParameter(); + } + if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.')) + { + return ScanNumber(c); + } + return CheckOperatorInCommandMode(c, TokenKind.Minus); + + case '*': + c1 = PeekChar(); + if (c1 == '=') + { + SkipChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.MultiplyEquals); + } if (c1 == '>') - { - SkipChar(); - return NewFileRedirectionToken(0, append: true, fromSpecifiedExplicitly: false); - } - if (c1 == '&') { SkipChar(); c1 = PeekChar(); - if (c1 == '1') + if (c1 == '>') { SkipChar(); - return NewMergingRedirectionToken(0, 1); + return NewFileRedirectionToken(0, append: true, fromSpecifiedExplicitly: false); } - UngetChar(); + if (c1 == '&') + { + SkipChar(); + c1 = PeekChar(); + if (c1 == '1') + { + SkipChar(); + return NewMergingRedirectionToken(0, 1); + } + UngetChar(); + } + + return NewFileRedirectionToken(0, append: false, fromSpecifiedExplicitly: false); } - return NewFileRedirectionToken(0, append: false, fromSpecifiedExplicitly: false); - } + return CheckOperatorInCommandMode(c, TokenKind.Multiply); - return CheckOperatorInCommandMode(c, TokenKind.Multiply); - - case '/': - c1 = PeekChar(); - if (c1 == '=') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.DivideEquals); - } - return CheckOperatorInCommandMode(c, TokenKind.Divide); - - case '%': - c1 = PeekChar(); - if (c1 == '=') - { - SkipChar(); - return CheckOperatorInCommandMode(c, c1, TokenKind.RemainderEquals); - } - return CheckOperatorInCommandMode(c, TokenKind.Rem); - - case '$': - if (PeekChar() == '(') - { - SkipChar(); - return NewToken(TokenKind.DollarParen); - } - return ScanVariable(false, false); - - case '<': - if (PeekChar() == '#') - { - SkipChar(); - ScanBlockComment(); - goto again; - } - return NewInputRedirectionToken(); - - case '>': - if (PeekChar() == '>') - { - SkipChar(); - return NewFileRedirectionToken(1, append: true, fromSpecifiedExplicitly: false); - } - return NewFileRedirectionToken(1, append: false, fromSpecifiedExplicitly: false); - - case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': - case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': - return ScanIdentifier(c); - - case '(': - return NewToken(TokenKind.LParen); - case ')': - return NewToken(TokenKind.RParen); - case '[': - if (InCommandMode() && !PeekChar().ForceStartNewToken()) - { - return ScanGenericToken('['); - } - return NewToken(TokenKind.LBracket); - case ']': - return NewToken(TokenKind.RBracket); - case '{': - return NewToken(TokenKind.LCurly); - case '}': - return NewToken(TokenKind.RCurly); - case '.': - return ScanDot(); - case ';': - return NewToken(TokenKind.Semi); - case ',': - return NewToken(TokenKind.Comma); - - case '0': case '7': case '8': case '9': - return ScanNumber(c); - - case '1': case '2': case '3': case '4': case '5': case '6': - if (PeekChar() == '>') - { - SkipChar(); + case '/': c1 = PeekChar(); - if (c1 == '>') + if (c1 == '=') { SkipChar(); - return NewFileRedirectionToken(c - '0', append: true, fromSpecifiedExplicitly: true); + return CheckOperatorInCommandMode(c, c1, TokenKind.DivideEquals); } - if (c1 == '&') + return CheckOperatorInCommandMode(c, TokenKind.Divide); + + case '%': + c1 = PeekChar(); + if (c1 == '=') { SkipChar(); - c1 = PeekChar(); - if (c1 == '1' || c1 == '2') - { - SkipChar(); - return NewMergingRedirectionToken(c - '0', c1 - '0'); - } - UngetChar(); + return CheckOperatorInCommandMode(c, c1, TokenKind.RemainderEquals); } + return CheckOperatorInCommandMode(c, TokenKind.Rem); - return NewFileRedirectionToken(c - '0', append: false, fromSpecifiedExplicitly: true); - } - return ScanNumber(c); - - case '&': - if (PeekChar() == '&') - { - SkipChar(); - return NewToken(TokenKind.AndAnd); - } - return NewToken(TokenKind.Ampersand); - - case '|': - if (PeekChar() == '|') - { - SkipChar(); - return NewToken(TokenKind.OrOr); - } - return NewToken(TokenKind.Pipe); - - case '!': - c1 = PeekChar(); - if ((InCommandMode() && !c1.ForceStartNewToken()) || - (InExpressionMode() && c1.IsIndentifierStart())) - { - return ScanGenericToken(c); - } - - if (InExpressionMode() && (char.IsDigit(c1) || c1 == '.')) - { - bool hex, real; - char suffix; - long multiplier; - - // check if the next token is actually a number - string strNum = ScanNumberHelper(c, out hex, out real, out suffix, out multiplier); - // rescan characters after the check - _currentIndex = _tokenStart; - c = GetChar(); - - if (strNum == null) { return ScanGenericToken(c); } - } - - return NewToken(TokenKind.Exclaim); - - case ':': - if (PeekChar() == ':') - { - SkipChar(); - if (InCommandMode() && !WantSimpleName && !PeekChar().ForceStartNewToken()) + case '$': + if (PeekChar() == '(') { - var sb = GetStringBuilder(); - sb.Append("::"); - return ScanGenericToken(sb); + SkipChar(); + return NewToken(TokenKind.DollarParen); } - return NewToken(TokenKind.ColonColon); - } - if (InCommandMode()) - { - return ScanLabel(); - } - return this.NewToken(TokenKind.Colon); + return ScanVariable(false, false); - case '\0': - if (AtEof()) - { - return SaveToken(new Token(NewScriptExtent(_tokenStart + 1, _tokenStart + 1), TokenKind.EndOfInput, TokenFlags.None)); - } - return ScanGenericToken(c); + case '<': + if (PeekChar() == '#') + { + SkipChar(); + ScanBlockComment(); + goto again; + } + return NewInputRedirectionToken(); - default: - if (c.IsWhitespace()) - { - SkipWhiteSpace(); - goto again; - } + case '>': + if (PeekChar() == '>') + { + SkipChar(); + return NewFileRedirectionToken(1, append: true, fromSpecifiedExplicitly: false); + } + return NewFileRedirectionToken(1, append: false, fromSpecifiedExplicitly: false); - if (char.IsLetter(c)) - { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case '_': return ScanIdentifier(c); - } - return ScanGenericToken(c); + + case '(': + return NewToken(TokenKind.LParen); + case ')': + return NewToken(TokenKind.RParen); + case '[': + if (InCommandMode() && !PeekChar().ForceStartNewToken()) + { + return ScanGenericToken('['); + } + return NewToken(TokenKind.LBracket); + case ']': + return NewToken(TokenKind.RBracket); + case '{': + return NewToken(TokenKind.LCurly); + case '}': + return NewToken(TokenKind.RCurly); + case '.': + return ScanDot(); + case ';': + return NewToken(TokenKind.Semi); + case ',': + return NewToken(TokenKind.Comma); + + case '0': + case '7': + case '8': + case '9': + return ScanNumber(c); + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + if (PeekChar() == '>') + { + SkipChar(); + c1 = PeekChar(); + if (c1 == '>') + { + SkipChar(); + return NewFileRedirectionToken(c - '0', append: true, fromSpecifiedExplicitly: true); + } + if (c1 == '&') + { + SkipChar(); + c1 = PeekChar(); + if (c1 == '1' || c1 == '2') + { + SkipChar(); + return NewMergingRedirectionToken(c - '0', c1 - '0'); + } + UngetChar(); + } + + return NewFileRedirectionToken(c - '0', append: false, fromSpecifiedExplicitly: true); + } + return ScanNumber(c); + + case '&': + if (PeekChar() == '&') + { + SkipChar(); + return NewToken(TokenKind.AndAnd); + } + return NewToken(TokenKind.Ampersand); + + case '|': + if (PeekChar() == '|') + { + SkipChar(); + return NewToken(TokenKind.OrOr); + } + return NewToken(TokenKind.Pipe); + + case '!': + c1 = PeekChar(); + if ((InCommandMode() && !c1.ForceStartNewToken()) || + (InExpressionMode() && c1.IsIndentifierStart())) + { + return ScanGenericToken(c); + } + + if (InExpressionMode() && (char.IsDigit(c1) || c1 == '.')) + { + bool hex, real; + char suffix; + long multiplier; + + // check if the next token is actually a number + string strNum = ScanNumberHelper(c, out hex, out real, out suffix, out multiplier); + // rescan characters after the check + _currentIndex = _tokenStart; + c = GetChar(); + + if (strNum == null) { return ScanGenericToken(c); } + } + + return NewToken(TokenKind.Exclaim); + + case ':': + if (PeekChar() == ':') + { + SkipChar(); + if (InCommandMode() && !WantSimpleName && !PeekChar().ForceStartNewToken()) + { + var sb = GetStringBuilder(); + sb.Append("::"); + return ScanGenericToken(sb); + } + return NewToken(TokenKind.ColonColon); + } + if (InCommandMode()) + { + return ScanLabel(); + } + return this.NewToken(TokenKind.Colon); + + case '\0': + if (AtEof()) + { + return SaveToken(new Token(NewScriptExtent(_tokenStart + 1, _tokenStart + 1), TokenKind.EndOfInput, TokenFlags.None)); + } + return ScanGenericToken(c); + + default: + if (c.IsWhitespace()) + { + SkipWhiteSpace(); + goto again; + } + + if (char.IsLetter(c)) + { + return ScanIdentifier(c); + } + return ScanGenericToken(c); } } } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 301d9c174..8aba3a781 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -30,29 +30,29 @@ namespace System.Management.Automation.Internal private List _commands = new List(); private List _redirectionPipes; - private PipelineReader externalInputPipe; - private PipelineWriter externalSuccessOutput; - private PipelineWriter externalErrorOutput; - private bool executionStarted = false; - private bool topLevel = false; - private bool stopping = false; - private SessionStateScope executionScope; + private PipelineReader _externalInputPipe; + private PipelineWriter _externalSuccessOutput; + private PipelineWriter _externalErrorOutput; + private bool _executionStarted = false; + private bool _topLevel = false; + private bool _stopping = false; + private SessionStateScope _executionScope; - private ExceptionDispatchInfo firstTerminatingError = null; + private ExceptionDispatchInfo _firstTerminatingError = null; private bool _linkedSuccessOutput = false; private bool _linkedErrorOutput = false; #if !CORECLR // Impersonation Not Supported On CSS // This is the security context when the pipeline was allocated - internal System.Security.SecurityContext SecurityContext = + internal System.Security.SecurityContext SecurityContext = System.Security.SecurityContext.Capture(); #endif #endregion private_members #region IDispose - private bool disposed = false; + private bool _disposed = false; /// /// When the command is complete, PipelineProcessor will be @@ -66,45 +66,45 @@ namespace System.Management.Automation.Internal /// public void Dispose() { - Dispose (true); - GC.SuppressFinalize (this); + Dispose(true); + GC.SuppressFinalize(this); } private void Dispose(bool disposing) { - if (disposed) + if (_disposed) return; if (disposing) { DisposeCommands(); - localPipeline = null; - externalSuccessOutput = null; - externalErrorOutput = null; - executionScope = null; - eventLogBuffer = null; + _localPipeline = null; + _externalSuccessOutput = null; + _externalErrorOutput = null; + _executionScope = null; + _eventLogBuffer = null; #if !CORECLR // Impersonation Not Supported On CSS SecurityContext.Dispose(); SecurityContext = null; #endif } - disposed = true; + _disposed = true; } /// /// Finalizer for class PipelineProcessor /// - ~PipelineProcessor () + ~PipelineProcessor() { - Dispose (false); + Dispose(false); } #endregion IDispose #region Execution Logging - private bool executionFailed = false; + private bool _executionFailed = false; internal List Commands { @@ -115,11 +115,11 @@ namespace System.Management.Automation.Internal { get { - return executionFailed; + return _executionFailed; } set { - executionFailed = value; + _executionFailed = value; } } @@ -155,16 +155,16 @@ namespace System.Management.Automation.Internal Log(message, invocationInfo, PipelineExecutionStatus.Error); } - private bool terminatingErrorLogged = false; + private bool _terminatingErrorLogged = false; internal void LogExecutionException(Exception exception) { - this.executionFailed = true; + _executionFailed = true; // Only log one terminating error for pipeline execution. - if (terminatingErrorLogged) + if (_terminatingErrorLogged) return; - terminatingErrorLogged = true; + _terminatingErrorLogged = true; if (exception == null) return; @@ -229,7 +229,7 @@ namespace System.Management.Automation.Internal if (!String.IsNullOrEmpty(logElement)) { - eventLogBuffer.Add(logElement); + _eventLogBuffer.Add(logElement); } } @@ -239,11 +239,11 @@ namespace System.Management.Automation.Internal { // We check to see if the command is needs writing (or if there is anything in the buffer) // before we flush it. Flushing the empty buffer causes a measurable performance degradation. - if (_commands == null || _commands.Count <= 0 || eventLogBuffer.Count == 0) + if (_commands == null || _commands.Count <= 0 || _eventLogBuffer.Count == 0) return; MshLog.LogPipelineExecutionDetailEvent(_commands[0].Command.Context, - eventLogBuffer, + _eventLogBuffer, _commands[0].Command.MyInvocation); } } @@ -264,7 +264,7 @@ namespace System.Management.Automation.Internal return false; } - List eventLogBuffer = new List(); + private List _eventLogBuffer = new List(); #endregion #region public_methods @@ -289,7 +289,6 @@ namespace System.Management.Automation.Internal if (_redirectionPipes == null) _redirectionPipes = new List(); _redirectionPipes.Add(pipelineProcessor); - } // 2004/02/28-JSnover (from spec review) ReadFromErrorQueue @@ -325,11 +324,11 @@ namespace System.Management.Automation.Internal // "_commands == null" throw PSTraceSource.NewInvalidOperationException(); } - if (disposed) + if (_disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } - if (executionStarted) + if (_executionStarted) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); @@ -367,7 +366,7 @@ namespace System.Management.Automation.Internal // "PipelineProcessor.AddCommand(): previous request object == null" throw PSTraceSource.NewInvalidOperationException(); } - Pipe UpstreamPipe = (readErrorQueue) ? + Pipe UpstreamPipe = (readErrorQueue) ? prevcommandProcessor.CommandRuntime.ErrorOutputPipe : prevcommandProcessor.CommandRuntime.OutputPipe; if (null == UpstreamPipe) { @@ -409,7 +408,6 @@ namespace System.Management.Automation.Internal prevcommandProcessor.CommandRuntime.ErrorOutputPipe = UpstreamPipe; } } // if MergeUnclaimedPreviousErrorResults - } _commands.Add(commandProcessor); @@ -505,8 +503,8 @@ namespace System.Management.Automation.Internal catch (PipelineStoppedException) { StopUpstreamCommandsException stopUpstreamCommandsException = - this.firstTerminatingError != null - ? firstTerminatingError.SourceException as StopUpstreamCommandsException + _firstTerminatingError != null + ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; if (stopUpstreamCommandsException == null) { @@ -514,7 +512,7 @@ namespace System.Management.Automation.Internal } else { - this.firstTerminatingError = null; + _firstTerminatingError = null; commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor; } } @@ -524,9 +522,9 @@ namespace System.Management.Automation.Internal // By this point, we are sure all commandProcessors hosted by the current pipelineProcess are done execution, // so if there are any redirection pipelineProcessors associated with any of those commandProcessors, we should // call DoComplete on them. - if (this._redirectionPipes != null) + if (_redirectionPipes != null) { - foreach (PipelineProcessor redirectPipelineProcessor in this._redirectionPipes) + foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes) { redirectPipelineProcessor.DoCompleteCore(null); } @@ -539,18 +537,18 @@ namespace System.Management.Automation.Internal // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - toRethrowInfo = firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); + toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); this.LogExecutionException(toRethrowInfo.SourceException); } - // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN + // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN catch (System.Runtime.InteropServices.InvalidComObjectException comException) { // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - toRethrowInfo = firstTerminatingError; + toRethrowInfo = _firstTerminatingError; } else { @@ -612,8 +610,8 @@ namespace System.Management.Automation.Internal catch (PipelineStoppedException) { StopUpstreamCommandsException stopUpstreamCommandsException = - this.firstTerminatingError != null - ? this.firstTerminatingError.SourceException as StopUpstreamCommandsException + _firstTerminatingError != null + ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; if (stopUpstreamCommandsException == null) { @@ -621,7 +619,7 @@ namespace System.Management.Automation.Internal } else { - this.firstTerminatingError = null; + _firstTerminatingError = null; commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor; } } @@ -650,17 +648,17 @@ namespace System.Management.Automation.Internal { // Only log the pipeline completion if this wasn't a nested pipeline, as // pipeline state in transcription is associated with the toplevel pipeline - if ((this.LocalPipeline == null) || (! this.LocalPipeline.IsNested)) + if ((this.LocalPipeline == null) || (!this.LocalPipeline.IsNested)) { lastCommandRuntime.PipelineProcessor.LogPipelineComplete(); } } // If a terminating error occurred, report it now. - if (firstTerminatingError != null) + if (_firstTerminatingError != null) { - this.LogExecutionException(firstTerminatingError.SourceException); - firstTerminatingError.Throw(); + this.LogExecutionException(_firstTerminatingError.SourceException); + _firstTerminatingError.Throw(); } } @@ -676,7 +674,7 @@ namespace System.Management.Automation.Internal throw new PipelineStoppedException(); } - if (!executionStarted) + if (!_executionStarted) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineNotStarted); @@ -694,7 +692,7 @@ namespace System.Management.Automation.Internal // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - toRethrowInfo = firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); + toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); this.LogExecutionException(toRethrowInfo.SourceException); } // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN @@ -703,9 +701,9 @@ namespace System.Management.Automation.Internal // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - toRethrowInfo = firstTerminatingError; + toRethrowInfo = _firstTerminatingError; } else { @@ -748,9 +746,9 @@ namespace System.Management.Automation.Internal Start(expectInput); // If a terminating error occurred, report it now. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - firstTerminatingError.Throw(); + _firstTerminatingError.Throw(); } } catch (PipelineStoppedException) @@ -760,9 +758,9 @@ namespace System.Management.Automation.Internal // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - firstTerminatingError.Throw(); + _firstTerminatingError.Throw(); } throw; } @@ -861,9 +859,9 @@ namespace System.Management.Automation.Internal Inject(input, enumerate: false); // If a terminating error occurred, report it now. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - firstTerminatingError.Throw(); + _firstTerminatingError.Throw(); } return RetrieveResults(); @@ -875,9 +873,9 @@ namespace System.Management.Automation.Internal // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (null != firstTerminatingError) + if (null != _firstTerminatingError) { - firstTerminatingError.Throw(); + _firstTerminatingError.Throw(); } throw; } @@ -922,7 +920,7 @@ namespace System.Management.Automation.Internal private void Start(bool incomingStream) { // Every call to Step or SynchronousExecute will call Start. - if (disposed) + if (_disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } @@ -931,7 +929,7 @@ namespace System.Management.Automation.Internal throw new PipelineStoppedException(); } - if (executionStarted) + if (_executionStarted) return; if (null == _commands || 0 == _commands.Count) @@ -949,9 +947,9 @@ namespace System.Management.Automation.Internal } // Set the execution scope using the current scope - if (executionScope == null) + if (_executionScope == null) { - executionScope = firstcommandProcessor.Context.EngineSessionState.CurrentScope; + _executionScope = firstcommandProcessor.Context.EngineSessionState.CurrentScope; } // add ExternalSuccessOutput to the last command @@ -983,7 +981,7 @@ namespace System.Management.Automation.Internal IDictionary psDefaultParameterValues = firstcommandProcessor.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary; - executionStarted = true; + _executionStarted = true; // // Allocate the pipeline iteration array; note that the pipeline position for @@ -1001,7 +999,7 @@ namespace System.Management.Automation.Internal // "null command " + i throw PSTraceSource.NewInvalidOperationException(); } - + // Generate new Activity Id for the thread Guid pipelineActivityId = EtwActivity.CreateActivityId(); @@ -1161,7 +1159,6 @@ namespace System.Management.Automation.Internal // Execute the first command - In the streamlet model, Execute of the first command will // automatically call the downstream command incase if there are any objects in the pipe. firstcommandProcessor.DoExecute(); - } // private void Inject /// @@ -1244,7 +1241,6 @@ namespace System.Management.Automation.Internal LastCommandProcessor.CommandRuntime.OutputPipe = pipeToUse; _linkedSuccessOutput = true; - } // private void SetResultPipe internal void LinkPipelineErrorOutput(Pipe pipeToUse) @@ -1282,7 +1278,7 @@ namespace System.Management.Automation.Internal // Note that this is not in a lock. // We do not make Dispose() wait until StopProcessing() // has completed. - stopping = true; + _stopping = true; LogToEventLog(); @@ -1370,7 +1366,7 @@ namespace System.Management.Automation.Internal _redirectionPipes = null; } - private object StopReasonLock = new object(); + private object _stopReasonLock = new object(); /// /// Makes an internal note of the exception, but only if this is /// the first error. @@ -1381,18 +1377,18 @@ namespace System.Management.Automation.Internal internal bool RecordFailure(Exception e, InternalCommand command) { bool wasStopping = false; - lock (StopReasonLock) + lock (_stopReasonLock) { - if (null == firstTerminatingError) + if (null == _firstTerminatingError) { - firstTerminatingError = ExceptionDispatchInfo.Capture(e); + _firstTerminatingError = ExceptionDispatchInfo.Capture(e); } // 905900-2005/05/12 // Drop5: Error Architecture: Log/trace second and subsequent RecordFailure // Note that the pipeline could have been stopped asynchronously // before hitting the error, therefore we check whether // firstTerminatingError is PipelineStoppedException. - else if ((!(firstTerminatingError.SourceException is PipelineStoppedException)) + else if ((!(_firstTerminatingError.SourceException is PipelineStoppedException)) && null != command && null != command.Context) { Exception ex = e; @@ -1404,8 +1400,8 @@ namespace System.Management.Automation.Internal if (!(ex is PipelineStoppedException)) { string message = StringUtil.Format(PipelineStrings.SecondFailure, - firstTerminatingError.GetType().Name, - firstTerminatingError.SourceException.StackTrace, + _firstTerminatingError.GetType().Name, + _firstTerminatingError.SourceException.StackTrace, ex.GetType().Name, ex.StackTrace ); @@ -1417,8 +1413,8 @@ namespace System.Management.Automation.Internal Severity.Warning); } } - wasStopping = stopping; - stopping = true; + wasStopping = _stopping; + _stopping = true; } return !wasStopping; } @@ -1429,7 +1425,7 @@ namespace System.Management.Automation.Internal /// internal void ForgetFailure() { - firstTerminatingError = null; + _firstTerminatingError = null; } // NOTICE-2004/06/08-JonN 959638 @@ -1458,16 +1454,15 @@ namespace System.Management.Automation.Internal /// internal PipelineReader ExternalInput { - get { return externalInputPipe; } + get { return _externalInputPipe; } set { - if (executionStarted) + if (_executionStarted) { - throw PSTraceSource.NewInvalidOperationException ( + throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); - } - externalInputPipe = value; + _externalInputPipe = value; } } @@ -1483,15 +1478,15 @@ namespace System.Management.Automation.Internal /// internal PipelineWriter ExternalSuccessOutput { - get { return externalSuccessOutput; } + get { return _externalSuccessOutput; } set { - if (executionStarted) + if (_executionStarted) { - throw PSTraceSource.NewInvalidOperationException ( + throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); } - externalSuccessOutput = value; + _externalSuccessOutput = value; } } @@ -1508,16 +1503,16 @@ namespace System.Management.Automation.Internal /// internal PipelineWriter ExternalErrorOutput { - get { return externalErrorOutput; } + get { return _externalErrorOutput; } set { - if (executionStarted) + if (_executionStarted) { - throw PSTraceSource.NewInvalidOperationException ( + throw PSTraceSource.NewInvalidOperationException( PipelineStrings.ExecutionAlreadyStarted); } - externalErrorOutput = value; + _externalErrorOutput = value; } } @@ -1527,7 +1522,7 @@ namespace System.Management.Automation.Internal /// internal bool ExecutionStarted { - get { return executionStarted; } + get { return _executionStarted; } } /// @@ -1535,20 +1530,20 @@ namespace System.Management.Automation.Internal /// internal bool Stopping { - get { return localPipeline != null && localPipeline.IsStopping; } + get { return _localPipeline != null && _localPipeline.IsStopping; } } - private LocalPipeline localPipeline; + private LocalPipeline _localPipeline; internal LocalPipeline LocalPipeline { - get { return localPipeline; } - set { localPipeline = value; } + get { return _localPipeline; } + set { _localPipeline = value; } } internal bool TopLevel { - get { return topLevel; } - set { topLevel = value; } + get { return _topLevel; } + set { _topLevel = value; } } /// @@ -1557,12 +1552,13 @@ namespace System.Management.Automation.Internal /// internal SessionStateScope ExecutionScope { - get { return executionScope; } - set { + get { return _executionScope; } + set + { // This needs to be settable so that a steppable pipeline // can be stepped in the context of the caller, not where // it was created... - executionScope = value; + _executionScope = value; } } #endregion public_properties @@ -1576,8 +1572,5 @@ namespace System.Management.Automation.Internal PipelineComplete } } - - - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 90f985e18..19f5608ba 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -38,7 +38,7 @@ namespace System.Management.Automation /// This yields faster execution but increases startup time. /// Compiled = 1, - + /// /// Specifies case-insensitive matching. /// @@ -58,7 +58,7 @@ namespace System.Management.Automation // // char that escapes special chars // - const char escapeChar = '`'; + private const char escapeChar = '`'; // // we convert a wildcard pattern to a predicate @@ -68,19 +68,19 @@ namespace System.Management.Automation // // wildcard pattern // - readonly string pattern; + private readonly string _pattern; internal string Pattern { - get { return pattern; } + get { return _pattern; } } // // options that control match behavior // - readonly WildcardOptions options = WildcardOptions.None; + private readonly WildcardOptions _options = WildcardOptions.None; internal WildcardOptions Options { - get { return options; } + get { return _options; } } /// @@ -109,7 +109,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("pattern"); } - this.pattern = pattern; + _pattern = pattern; } /// @@ -129,11 +129,11 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("pattern"); } - this.pattern = pattern; - this.options = options; + _pattern = pattern; + _options = options; } - static readonly WildcardPattern matchAllIgnoreCasePattern = new WildcardPattern("*", WildcardOptions.None); + private static readonly WildcardPattern s_matchAllIgnoreCasePattern = new WildcardPattern("*", WildcardOptions.None); /// /// Create a new WildcardPattern, or return an already created one. @@ -147,7 +147,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("pattern"); if (pattern.Length == 1 && pattern[0] == '*') - return matchAllIgnoreCasePattern; + return s_matchAllIgnoreCasePattern; return new WildcardPattern(pattern, options); } @@ -164,7 +164,7 @@ namespace System.Management.Automation { if (_isMatch == null) { - if (pattern.Length == 1 && pattern[0] == '*') + if (_pattern.Length == 1 && _pattern[0] == '*') { _isMatch = _ => true; } @@ -198,7 +198,7 @@ namespace System.Management.Automation /// internal static string Escape(string pattern, char[] charsNotToEscape) { - #pragma warning disable 56506 +#pragma warning disable 56506 if (pattern == null) { @@ -213,7 +213,7 @@ namespace System.Management.Automation char[] temp = new char[pattern.Length * 2 + 1]; int tempIndex = 0; - for (int i=0; i @@ -319,11 +319,11 @@ namespace System.Management.Automation int tempIndex = 0; bool prevCharWasEscapeChar = false; - for (int i=0; i /// constructed object - internal WildcardPatternException (ErrorRecord errorRecord) - : base( RetrieveMessage(errorRecord) ) + internal WildcardPatternException(ErrorRecord errorRecord) + : base(RetrieveMessage(errorRecord)) { if (null == errorRecord) { - throw new ArgumentNullException ("errorRecord"); + throw new ArgumentNullException("errorRecord"); } _errorRecord = errorRecord; } @@ -546,7 +546,7 @@ namespace System.Management.Automation /// and ending at /// protected abstract void AppendCharacterRangeToBracketExpression( - char startOfCharacterRange, + char startOfCharacterRange, char endOfCharacterRange); /// @@ -574,7 +574,7 @@ namespace System.Management.Automation int i = 0; while (i < brackedExpressionContents.Length) { - if (((i + 2) < brackedExpressionContents.Length) && + if (((i + 2) < brackedExpressionContents.Length) && (bracketExpressionOperators[i + 1] == '-')) { char lowerBound = brackedExpressionContents[i]; @@ -691,13 +691,13 @@ namespace System.Management.Automation new ParentContainsErrorRecordException(message); ErrorRecord er = - new ErrorRecord( pce, + new ErrorRecord(pce, "WildcardPattern_Invalid", ErrorCategory.InvalidArgument, - null ); + null); WildcardPatternException e = - new WildcardPatternException( er ); + new WildcardPatternException(er); return e; } @@ -720,13 +720,13 @@ namespace System.Management.Automation /// internal class WildcardPatternToRegexParser : WildcardPatternParser { - private StringBuilder regexPattern; - private RegexOptions regexOptions; + private StringBuilder _regexPattern; + private RegexOptions _regexOptions; private const string regexChars = "()[.?*{}^$+|\\"; // ']' is missing on purpose private static bool IsRegexChar(char ch) { - for (int i=0; iregex conversion from PS v1 (i.e. not to break unit tests // and not to break backcompatibility). - string regexPatternString = regexPattern.ToString(); + string regexPatternString = _regexPattern.ToString(); if (regexPatternString.Equals("^.*$", StringComparison.Ordinal)) { - regexPattern.Remove(0, 4); + _regexPattern.Remove(0, 4); } - else + else { if (regexPatternString.StartsWith("^.*", StringComparison.Ordinal)) { - regexPattern.Remove(0, 3); + _regexPattern.Remove(0, 3); } if (regexPatternString.EndsWith(".*$", StringComparison.Ordinal)) { - regexPattern.Remove(regexPattern.Length - 3, 3); + _regexPattern.Remove(_regexPattern.Length - 3, 3); } } } protected override void BeginBracketExpression() { - regexPattern.Append('['); + _regexPattern.Append('['); } internal static void AppendLiteralCharacterToBracketExpression(StringBuilder regexPattern, char c) @@ -842,12 +842,12 @@ namespace System.Management.Automation } protected override void AppendLiteralCharacterToBracketExpression(char c) { - AppendLiteralCharacterToBracketExpression(this.regexPattern, c); + AppendLiteralCharacterToBracketExpression(_regexPattern, c); } internal static void AppendCharacterRangeToBracketExpression( StringBuilder regexPattern, - char startOfCharacterRange, + char startOfCharacterRange, char endOfCharacterRange) { AppendLiteralCharacterToBracketExpression(regexPattern, startOfCharacterRange); @@ -859,12 +859,12 @@ namespace System.Management.Automation char startOfCharacterRange, char endOfCharacterRange) { - AppendCharacterRangeToBracketExpression(this.regexPattern, startOfCharacterRange, endOfCharacterRange); + AppendCharacterRangeToBracketExpression(_regexPattern, startOfCharacterRange, endOfCharacterRange); } protected override void EndBracketExpression() { - regexPattern.Append(']'); + _regexPattern.Append(']'); } /// @@ -878,9 +878,9 @@ namespace System.Management.Automation WildcardPatternParser.Parse(wildcardPattern, parser); try { - return new Regex(parser.regexPattern.ToString(), parser.regexOptions); + return new Regex(parser._regexPattern.ToString(), parser._regexOptions); } - catch(ArgumentException) + catch (ArgumentException) { throw WildcardPatternParser.NewWildcardPatternException(wildcardPattern.Pattern); } @@ -894,10 +894,10 @@ namespace System.Management.Automation internal WildcardPatternMatcher(WildcardPattern wildcardPattern) { - this._characterNormalizer = new CharacterNormalizer(wildcardPattern.Options); - this._patternElements = MyWildcardPatternParser.Parse( - wildcardPattern, - this._characterNormalizer); + _characterNormalizer = new CharacterNormalizer(wildcardPattern.Options); + _patternElements = MyWildcardPatternParser.Parse( + wildcardPattern, + _characterNormalizer); } internal bool IsMatch(string str) @@ -918,15 +918,15 @@ namespace System.Management.Automation // - Wikipedia calls this algorithm the "NFA" algorithm at // http://en.wikipedia.org/wiki/Regular_expression#Implementations_and_running_times - var patternPositionsForCurrentStringPosition = - new PatternPositionsVisitor(this._patternElements.Length); + var patternPositionsForCurrentStringPosition = + new PatternPositionsVisitor(_patternElements.Length); patternPositionsForCurrentStringPosition.Add(0); - var patternPositionsForNextStringPosition = - new PatternPositionsVisitor(this._patternElements.Length); + var patternPositionsForNextStringPosition = + new PatternPositionsVisitor(_patternElements.Length); - for (int currentStringPosition = 0; - currentStringPosition < str.Length; + for (int currentStringPosition = 0; + currentStringPosition < str.Length; currentStringPosition++) { char currentStringCharacter = _characterNormalizer.Normalize(str[currentStringPosition]); @@ -936,7 +936,7 @@ namespace System.Management.Automation int patternPosition; while (patternPositionsForCurrentStringPosition.MoveNext(out patternPosition)) { - this._patternElements[patternPosition].ProcessStringCharacter( + _patternElements[patternPosition].ProcessStringCharacter( currentStringCharacter, patternPosition, patternPositionsForCurrentStringPosition, @@ -953,7 +953,7 @@ namespace System.Management.Automation int patternPosition2; while (patternPositionsForCurrentStringPosition.MoveNext(out patternPosition2)) { - this._patternElements[patternPosition2].ProcessEndOfString( + _patternElements[patternPosition2].ProcessEndOfString( patternPosition2, patternPositionsForCurrentStringPosition); } @@ -974,16 +974,16 @@ namespace System.Management.Automation { Dbg.Assert(lengthOfPattern >= 0, "Caller should verify lengthOfPattern >= 0"); - this._lengthOfPattern = lengthOfPattern; + _lengthOfPattern = lengthOfPattern; - this._isPatternPositionVisitedMarker = new int[lengthOfPattern + 1]; - for (int i = 0; i < this._isPatternPositionVisitedMarker.Length; i++) + _isPatternPositionVisitedMarker = new int[lengthOfPattern + 1]; + for (int i = 0; i < _isPatternPositionVisitedMarker.Length; i++) { - this._isPatternPositionVisitedMarker[i] = -1; + _isPatternPositionVisitedMarker[i] = -1; } - this._patternPositionsForFurtherProcessing = new int[lengthOfPattern]; - this._patternPositionsForFurtherProcessingCount = 0; + _patternPositionsForFurtherProcessing = new int[lengthOfPattern]; + _patternPositionsForFurtherProcessingCount = 0; } public int StringPosition { private get; set; } @@ -992,25 +992,25 @@ namespace System.Management.Automation { Dbg.Assert(patternPosition >= 0, "Caller should verify patternPosition >= 0"); Dbg.Assert( - patternPosition <= this._lengthOfPattern, + patternPosition <= _lengthOfPattern, "Caller should verify patternPosition <= this._lengthOfPattern"); // is patternPosition already visited?); - if (this._isPatternPositionVisitedMarker[patternPosition] == this.StringPosition) + if (_isPatternPositionVisitedMarker[patternPosition] == this.StringPosition) { return; } // mark patternPosition as visited - this._isPatternPositionVisitedMarker[patternPosition] = this.StringPosition; + _isPatternPositionVisitedMarker[patternPosition] = this.StringPosition; // add patternPosition to the queue for further processing - if (patternPosition < this._lengthOfPattern) + if (patternPosition < _lengthOfPattern) { - this._patternPositionsForFurtherProcessing[this._patternPositionsForFurtherProcessingCount] = patternPosition; - this._patternPositionsForFurtherProcessingCount++; + _patternPositionsForFurtherProcessing[_patternPositionsForFurtherProcessingCount] = patternPosition; + _patternPositionsForFurtherProcessingCount++; Dbg.Assert( - this._patternPositionsForFurtherProcessingCount <= this._lengthOfPattern, + _patternPositionsForFurtherProcessingCount <= _lengthOfPattern, "There should never be more elements in the queue than the length of the pattern"); } } @@ -1019,7 +1019,7 @@ namespace System.Management.Automation { get { - return this._isPatternPositionVisitedMarker[this._lengthOfPattern] >= this.StringPosition; + return _isPatternPositionVisitedMarker[_lengthOfPattern] >= this.StringPosition; } } @@ -1028,17 +1028,17 @@ namespace System.Management.Automation public bool MoveNext(out int patternPosition) { Dbg.Assert( - this._patternPositionsForFurtherProcessingCount >= 0, + _patternPositionsForFurtherProcessingCount >= 0, "There should never be more elements in the queue than the length of the pattern"); - if (this._patternPositionsForFurtherProcessingCount == 0) + if (_patternPositionsForFurtherProcessingCount == 0) { patternPosition = -1; return false; } - this._patternPositionsForFurtherProcessingCount--; - patternPosition = this._patternPositionsForFurtherProcessing[this._patternPositionsForFurtherProcessingCount]; + _patternPositionsForFurtherProcessingCount--; + patternPosition = _patternPositionsForFurtherProcessing[_patternPositionsForFurtherProcessingCount]; return true; } } @@ -1046,22 +1046,22 @@ namespace System.Management.Automation private abstract class PatternElement { public abstract void ProcessStringCharacter( - char currentStringCharacter, - int currentPatternPosition, - PatternPositionsVisitor patternPositionsForCurrentStringPosition, + char currentStringCharacter, + int currentPatternPosition, + PatternPositionsVisitor patternPositionsForCurrentStringPosition, PatternPositionsVisitor patternPositionsForNextStringPosition); public abstract void ProcessEndOfString( - int currentPatternPosition, + int currentPatternPosition, PatternPositionsVisitor patternPositionsForEndOfStringPosition); } private class QuestionMarkElement : PatternElement { public override void ProcessStringCharacter( - char currentStringCharacter, - int currentPatternPosition, - PatternPositionsVisitor patternPositionsForCurrentStringPosition, + char currentStringCharacter, + int currentPatternPosition, + PatternPositionsVisitor patternPositionsForCurrentStringPosition, PatternPositionsVisitor patternPositionsForNextStringPosition) { // '?' : (patternPosition, stringPosition) => (patternPosition + 1, stringPosition + 1) @@ -1069,7 +1069,7 @@ namespace System.Management.Automation } public override void ProcessEndOfString( - int currentPatternPosition, + int currentPatternPosition, PatternPositionsVisitor patternPositionsForEndOfStringPosition) { // '?' : (patternPosition, endOfString) => @@ -1082,21 +1082,21 @@ namespace System.Management.Automation public LiteralCharacterElement(char literalCharacter) { - this._literalCharacter = literalCharacter; + _literalCharacter = literalCharacter; } public override void ProcessStringCharacter( - char currentStringCharacter, - int currentPatternPosition, - PatternPositionsVisitor patternPositionsForCurrentStringPosition, + char currentStringCharacter, + int currentPatternPosition, + PatternPositionsVisitor patternPositionsForCurrentStringPosition, PatternPositionsVisitor patternPositionsForNextStringPosition) { - if (this._literalCharacter == currentStringCharacter) + if (_literalCharacter == currentStringCharacter) { base.ProcessStringCharacter( - currentStringCharacter, - currentPatternPosition, - patternPositionsForCurrentStringPosition, + currentStringCharacter, + currentPatternPosition, + patternPositionsForCurrentStringPosition, patternPositionsForNextStringPosition); } } @@ -1109,16 +1109,16 @@ namespace System.Management.Automation public BracketExpressionElement(Regex regex) { Dbg.Assert(regex != null, "Caller should verify regex != null"); - this._regex = regex; + _regex = regex; } public override void ProcessStringCharacter( - char currentStringCharacter, - int currentPatternPosition, - PatternPositionsVisitor patternPositionsForCurrentStringPosition, + char currentStringCharacter, + int currentPatternPosition, + PatternPositionsVisitor patternPositionsForCurrentStringPosition, PatternPositionsVisitor patternPositionsForNextStringPosition) { - if (this._regex.IsMatch(new string(currentStringCharacter, 1))) + if (_regex.IsMatch(new string(currentStringCharacter, 1))) { base.ProcessStringCharacter(currentStringCharacter, currentPatternPosition, patternPositionsForCurrentStringPosition, @@ -1130,9 +1130,9 @@ namespace System.Management.Automation private class AsterixElement : PatternElement { public override void ProcessStringCharacter( - char currentStringCharacter, - int currentPatternPosition, - PatternPositionsVisitor patternPositionsForCurrentStringPosition, + char currentStringCharacter, + int currentPatternPosition, + PatternPositionsVisitor patternPositionsForCurrentStringPosition, PatternPositionsVisitor patternPositionsForNextStringPosition) { // '*' : (patternPosition, stringPosition) => (patternPosition + 1, stringPosition) @@ -1143,7 +1143,7 @@ namespace System.Management.Automation } public override void ProcessEndOfString( - int currentPatternPosition, + int currentPatternPosition, PatternPositionsVisitor patternPositionsForEndOfStringPosition) { // '*' : (patternPosition, endOfString) => (patternPosition + 1, endOfString) @@ -1159,62 +1159,62 @@ namespace System.Management.Automation private StringBuilder _bracketExpressionBuilder; static public PatternElement[] Parse( - WildcardPattern pattern, + WildcardPattern pattern, CharacterNormalizer characterNormalizer) { var parser = new MyWildcardPatternParser - { - _characterNormalizer = characterNormalizer, - _regexOptions = WildcardPatternToRegexParser.TranslateWildcardOptionsIntoRegexOptions(pattern.Options), - }; + { + _characterNormalizer = characterNormalizer, + _regexOptions = WildcardPatternToRegexParser.TranslateWildcardOptionsIntoRegexOptions(pattern.Options), + }; WildcardPatternParser.Parse(pattern, parser); return parser._patternElements.ToArray(); } protected override void AppendLiteralCharacter(char c) { - c = this._characterNormalizer.Normalize(c); - this._patternElements.Add(new LiteralCharacterElement(c)); + c = _characterNormalizer.Normalize(c); + _patternElements.Add(new LiteralCharacterElement(c)); } protected override void AppendAsterix() { - this._patternElements.Add(new AsterixElement()); + _patternElements.Add(new AsterixElement()); } protected override void AppendQuestionMark() { - this._patternElements.Add(new QuestionMarkElement()); + _patternElements.Add(new QuestionMarkElement()); } protected override void BeginBracketExpression() { - this._bracketExpressionBuilder = new StringBuilder(); - this._bracketExpressionBuilder.Append('['); + _bracketExpressionBuilder = new StringBuilder(); + _bracketExpressionBuilder.Append('['); } protected override void AppendLiteralCharacterToBracketExpression(char c) { WildcardPatternToRegexParser.AppendLiteralCharacterToBracketExpression( - this._bracketExpressionBuilder, + _bracketExpressionBuilder, c); } protected override void AppendCharacterRangeToBracketExpression( - char startOfCharacterRange, + char startOfCharacterRange, char endOfCharacterRange) { WildcardPatternToRegexParser.AppendCharacterRangeToBracketExpression( - this._bracketExpressionBuilder, - startOfCharacterRange, + _bracketExpressionBuilder, + startOfCharacterRange, endOfCharacterRange); } protected override void EndBracketExpression() { - this._bracketExpressionBuilder.Append(']'); - Regex regex = new Regex(this._bracketExpressionBuilder.ToString(), this._regexOptions); - this._patternElements.Add(new BracketExpressionElement(regex)); + _bracketExpressionBuilder.Append(']'); + Regex regex = new Regex(_bracketExpressionBuilder.ToString(), _regexOptions); + _patternElements.Add(new BracketExpressionElement(regex)); } } @@ -1242,9 +1242,9 @@ namespace System.Management.Automation [Pure] public char Normalize(char x) { - if (this._caseInsensitive) + if (_caseInsensitive) { - return this._cultureInfo.TextInfo.ToLower(x); + return _cultureInfo.TextInfo.ToLower(x); } return x; @@ -1257,21 +1257,21 @@ namespace System.Management.Automation /// internal class WildcardPatternToDosWildcardParser : WildcardPatternParser { - private readonly StringBuilder result = new StringBuilder(); + private readonly StringBuilder _result = new StringBuilder(); protected override void AppendLiteralCharacter(char c) { - this.result.Append(c); + _result.Append(c); } protected override void AppendAsterix() { - result.Append('*'); + _result.Append('*'); } protected override void AppendQuestionMark() { - result.Append('?'); + _result.Append('?'); } protected override void BeginBracketExpression() @@ -1288,7 +1288,7 @@ namespace System.Management.Automation protected override void EndBracketExpression() { - result.Append('?'); + _result.Append('?'); } /// @@ -1298,7 +1298,7 @@ namespace System.Management.Automation { var parser = new WildcardPatternToDosWildcardParser(); WildcardPatternParser.Parse(wildcardPattern, parser); - return parser.result.ToString(); + return parser._result.ToString(); } } } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 1c0a2fbbd..d60bfb117 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -168,13 +169,13 @@ namespace System.Management.Automation.Remoting // If error-stream is null or we are in pushed-runspace - then write error directly to console. if (errorStream == null || IsRunspacePushed(_clientHost)) { - writeErrorAction = delegate(ErrorRecord errorRecord) + writeErrorAction = delegate (ErrorRecord errorRecord) { try { - if (this._clientHost.UI != null) + if (_clientHost.UI != null) { - this._clientHost.UI.WriteErrorLine(errorRecord.ToString()); + _clientHost.UI.WriteErrorLine(errorRecord.ToString()); } } catch (Exception e) @@ -188,7 +189,7 @@ namespace System.Management.Automation.Remoting // Otherwise write it to error-stream. else { - writeErrorAction = delegate(ErrorRecord errorRecord) + writeErrorAction = delegate (ErrorRecord errorRecord) { errorStream.Write(errorRecord); }; diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 4abbcb961..28fc9693e 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -11,7 +11,7 @@ using System.Management.Automation.Remoting; using System.Collections.ObjectModel; namespace System.Management.Automation.Runspaces.Internal -{ +{ /// /// PowerShell client side proxy base which handles invocation /// of powershell on a remote machine @@ -21,7 +21,7 @@ namespace System.Management.Automation.Runspaces.Internal #region Tracer [TraceSourceAttribute("CRPS", "ClientRemotePowerShell")] - static private PSTraceSource tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); + static private PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); #endregion Tracer @@ -125,7 +125,7 @@ namespace System.Management.Automation.Runspaces.Internal { return outputstream; } - set + set { outputstream = value; } @@ -181,7 +181,7 @@ namespace System.Management.Automation.Runspaces.Internal { // If we are in robust connection retry mode then auto-disconnect this command // rather than try to stop it. - PSConnectionRetryStatus retryStatus = this.connectionRetryStatus; + PSConnectionRetryStatus retryStatus = _connectionRetryStatus; if ((retryStatus == PSConnectionRetryStatus.NetworkFailureDetected || retryStatus == PSConnectionRetryStatus.ConnectionRetryAttempt) && this.runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) @@ -265,7 +265,7 @@ namespace System.Management.Automation.Runspaces.Internal new EventHandler>(HandleBrokenNotificationFromRunspacePool); dataStructureHandler.ConnectCompleted += new EventHandler>(HandleConnectCompleted); dataStructureHandler.ReconnectCompleted += new EventHandler>(HandleConnectCompleted); - dataStructureHandler.RobustConnectionNotification += + dataStructureHandler.RobustConnectionNotification += new EventHandler(HandleRobustConnectionNotification); dataStructureHandler.CloseCompleted += new EventHandler(HandleCloseCompleted); @@ -276,7 +276,7 @@ namespace System.Management.Automation.Runspaces.Internal /// internal void Clear() { - initialized = false; + initialized = false; } /// @@ -351,7 +351,7 @@ namespace System.Management.Automation.Runspaces.Internal /// internal PSConnectionRetryStatus ConnectionRetryStatus { - get { return this.connectionRetryStatus; } + get { return _connectionRetryStatus; } } #endregion Internal Methods/Properties @@ -367,9 +367,8 @@ namespace System.Management.Automation.Runspaces.Internal /// arguments describing this event private void HandleErrorReceived(object sender, RemoteDataEventArgs eventArgs) { - using (tracer.TraceEventHandlers()) + using (s_tracer.TraceEventHandlers()) { - shell.SetHadErrors(true); errorstream.Write(eventArgs.Data); } @@ -384,7 +383,7 @@ namespace System.Management.Automation.Runspaces.Internal /// arguments describing this event private void HandleOutputReceived(object sender, RemoteDataEventArgs eventArgs) { - using (tracer.TraceEventHandlers()) + using (s_tracer.TraceEventHandlers()) { object data = eventArgs.Data; @@ -408,7 +407,7 @@ namespace System.Management.Automation.Runspaces.Internal private void HandleInvocationStateInfoReceived(object sender, RemoteDataEventArgs eventArgs) { - using (tracer.TraceEventHandlers()) + using (s_tracer.TraceEventHandlers()) { PSInvocationStateInfo stateInfo = eventArgs.Data; @@ -433,7 +432,7 @@ namespace System.Management.Automation.Runspaces.Internal if (stateInfo.State == PSInvocationState.Failed) { PSRemotingTransportException remotingTransportException = stateInfo.Reason as PSRemotingTransportException; - terminateSession = (remotingTransportException != null) && + terminateSession = (remotingTransportException != null) && (remotingTransportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST); } @@ -441,7 +440,7 @@ namespace System.Management.Automation.Runspaces.Internal // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); - + if (stopCalled || terminateSession) { // Reset stop called flag. @@ -450,7 +449,7 @@ namespace System.Management.Automation.Runspaces.Internal // if a Stop method has been called, then powershell // would have already raised a Stopping event, after // which only a Stopped should be raised - stateInfoQueue.Enqueue(new PSInvocationStateInfo(PSInvocationState.Stopped, + _stateInfoQueue.Enqueue(new PSInvocationStateInfo(PSInvocationState.Stopped, stateInfo.Reason)); // If the stop call failed due to network problems then close the runspace @@ -459,7 +458,7 @@ namespace System.Management.Automation.Runspaces.Internal } else { - stateInfoQueue.Enqueue(stateInfo); + _stateInfoQueue.Enqueue(stateInfo); } // calling close async only after making sure all the internal members are prepared // to handle close complete. @@ -521,7 +520,7 @@ namespace System.Management.Automation.Runspaces.Internal private void HandleInformationalMessageReceived(object sender, RemoteDataEventArgs eventArgs) { - using (tracer.TraceEventHandlers()) + using (s_tracer.TraceEventHandlers()) { InformationalMessage infoMessage = eventArgs.Data; @@ -547,7 +546,7 @@ namespace System.Management.Automation.Runspaces.Internal case RemotingDataType.PowerShellProgress: { - ProgressRecord progress = (ProgressRecord)LanguagePrimitives.ConvertTo(infoMessage.Message, + ProgressRecord progress = (ProgressRecord)LanguagePrimitives.ConvertTo(infoMessage.Message, typeof(ProgressRecord), System.Globalization.CultureInfo.InvariantCulture); informationalBuffers.AddProgress(progress); } @@ -555,10 +554,9 @@ namespace System.Management.Automation.Runspaces.Internal case RemotingDataType.PowerShellInformationStream: { - informationalBuffers.AddInformation((InformationRecord) infoMessage.Message); + informationalBuffers.AddInformation((InformationRecord)infoMessage.Message); } break; - } } } @@ -570,9 +568,9 @@ namespace System.Management.Automation.Runspaces.Internal /// private void HandleHostCallReceived(object sender, RemoteDataEventArgs eventArgs) { - using (tracer.TraceEventHandlers()) + using (s_tracer.TraceEventHandlers()) { - Collection prerequisiteCalls = + Collection prerequisiteCalls = eventArgs.Data.PerformSecurityChecksOnHostMessage(computerName); if (HostCallReceived != null) @@ -582,7 +580,7 @@ namespace System.Management.Automation.Runspaces.Internal { foreach (RemoteHostCall hostcall in prerequisiteCalls) { - RemoteDataEventArgs args = + RemoteDataEventArgs args = new RemoteDataEventArgs(hostcall); HostCallReceived.SafeInvoke(this, args); @@ -614,7 +612,7 @@ namespace System.Management.Automation.Runspaces.Internal /// /// Sender of this event, unused. /// Event arugments. - void HandleConnectCompleted(object sender, RemoteDataEventArgs e) + private void HandleConnectCompleted(object sender, RemoteDataEventArgs e) { // After initial connect/reconnect set state to "Running". Later events // will update state to appropriate command execution state. @@ -641,7 +639,7 @@ namespace System.Management.Automation.Runspaces.Internal // otherwise may have race conditions in Server.OutOfProcessMediator dataStructureHandler.RaiseRemoveAssociationEvent(); - if (stateInfoQueue.Count == 0) + if (_stateInfoQueue.Count == 0) { // If shell state is not finished on client side and queue is empty // then set state to stopped unless the current state is Disconnected @@ -661,9 +659,9 @@ namespace System.Management.Automation.Runspaces.Internal else { // Apply queued state changes. - while (stateInfoQueue.Count > 0) + while (_stateInfoQueue.Count > 0) { - PSInvocationStateInfo stateInfo = stateInfoQueue.Dequeue(); + PSInvocationStateInfo stateInfo = _stateInfoQueue.Dequeue(); SetStateInfo(stateInfo); } } @@ -713,7 +711,7 @@ namespace System.Management.Automation.Runspaces.Internal // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); - + // Since this is a terminal state..close the transport manager. dataStructureHandler.RaiseRemoveAssociationEvent(); @@ -762,13 +760,12 @@ namespace System.Management.Automation.Runspaces.Internal } else { - SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Failed, + SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Failed, eventArgs.Data)); } // Not calling dataStructureHandler.CloseConnection() as this must // have already been called by RunspacePool.Close() - } /// @@ -778,7 +775,7 @@ namespace System.Management.Automation.Runspaces.Internal /// /// private void HandleRobustConnectionNotification( - object sender, + object sender, ConnectionStatusEventArgs e) { // Create event arguments and warnings/errors for this robust connection notification. @@ -795,7 +792,7 @@ namespace System.Management.Automation.Runspaces.Internal StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected, this.computerName, maxRetryConnectionTimeMinutes)); - connectionRetryStatusArgs = + connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; @@ -805,7 +802,7 @@ namespace System.Management.Automation.Runspaces.Internal PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt, StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName)); - connectionRetryStatusArgs = + connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; @@ -815,7 +812,7 @@ namespace System.Management.Automation.Runspaces.Internal PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded, StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName)); - connectionRetryStatusArgs = + connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; @@ -837,7 +834,7 @@ namespace System.Management.Automation.Runspaces.Internal PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded, StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName)); - connectionRetryStatusArgs = + connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; @@ -847,7 +844,7 @@ namespace System.Management.Automation.Runspaces.Internal string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName); RuntimeException reason = new RuntimeException(msg); errorRecord = new ErrorRecord(reason, - PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed, + PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed, ErrorCategory.InvalidOperation, this); connectionRetryStatusArgs = @@ -863,7 +860,7 @@ namespace System.Management.Automation.Runspaces.Internal } // Update connection status. - this.connectionRetryStatus = connectionRetryStatusArgs.Notification; + _connectionRetryStatus = connectionRetryStatusArgs.Notification; if (warningRecord != null) { @@ -933,9 +930,9 @@ namespace System.Management.Automation.Runspaces.Internal /// datastructure handler. We cannot send the state back to the upper layers until /// close is completed from the datastructure/transport layer. /// - private Queue stateInfoQueue = new Queue(); + private Queue _stateInfoQueue = new Queue(); - private PSConnectionRetryStatus connectionRetryStatus = PSConnectionRetryStatus.None; + private PSConnectionRetryStatus _connectionRetryStatus = PSConnectionRetryStatus.None; #endregion Protected Members diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 166a5560f..117a83d7e 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -158,7 +158,7 @@ namespace System.Management.Automation ) ) { - currState = currentState; + _currState = currentState; } /// @@ -175,7 +175,7 @@ namespace System.Management.Automation ) ) { - currState = currentState; + _currState = currentState; } #region ISerializable Members @@ -210,7 +210,7 @@ namespace System.Management.Automation { get { - return currState; + return _currState; } } @@ -218,7 +218,7 @@ namespace System.Management.Automation /// State of job when exception was thrown. /// [NonSerialized] - private JobState currState = 0; + private JobState _currState = 0; } /// @@ -457,9 +457,9 @@ namespace System.Management.Automation /// /// Default constructor /// - protected Job() + protected Job() { - sessionId = System.Threading.Interlocked.Increment(ref _jobIdSeed); + _sessionId = System.Threading.Interlocked.Increment(ref s_jobIdSeed); } /// @@ -467,10 +467,10 @@ namespace System.Management.Automation /// /// Command invoked by this job object protected Job(string command) - :this() + : this() { - this.command = command; - name = AutoGenerateJobName(); + _command = command; + _name = AutoGenerateJobName(); } /// @@ -479,11 +479,11 @@ namespace System.Management.Automation /// Command invoked by this job object /// Friendly name for the job object protected Job(string command, string name) - :this(command) + : this(command) { if (!String.IsNullOrEmpty(name)) { - this.name = name; + _name = name; } } @@ -494,9 +494,9 @@ namespace System.Management.Automation /// Friendly name for the job object /// Child jobs of this job object protected Job(string command, string name, IList childJobs) - :this(command, name) + : this(command, name) { - this.childJobs = childJobs; + _childJobs = childJobs; } /// @@ -511,23 +511,23 @@ namespace System.Management.Automation { if (token == null) throw PSTraceSource.NewArgumentNullException("token", RemotingErrorIdStrings.JobIdentifierNull); - if (token.Id > _jobIdSeed) + if (token.Id > s_jobIdSeed) { throw PSTraceSource.NewArgumentException("token", RemotingErrorIdStrings.JobIdNotYetAssigned, token.Id); } - this.command = command; + _command = command; - sessionId = token.Id; - guid = token.InstanceId; + _sessionId = token.Id; + _guid = token.InstanceId; if (!String.IsNullOrEmpty(name)) { - this.name = name; + _name = name; } else { - this.name = AutoGenerateJobName(); + _name = AutoGenerateJobName(); } } @@ -540,9 +540,9 @@ namespace System.Management.Automation /// The InstanceId may need to be set to maintain job identity across /// instances of the process. protected Job(string command, string name, Guid instanceId) - :this(command, name) + : this(command, name) { - guid = instanceId; + _guid = instanceId; } static internal string GetCommandTextFromInvocationInfo(InvocationInfo invocationInfo) @@ -555,8 +555,8 @@ namespace System.Management.Automation IScriptExtent scriptExtent = invocationInfo.ScriptPosition; if ((scriptExtent != null) && (scriptExtent.StartScriptPosition != null) && !string.IsNullOrWhiteSpace(scriptExtent.StartScriptPosition.Line)) { - Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1"); - Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line"); + Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1"); + Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line"); return scriptExtent.StartScriptPosition.Line.Substring(scriptExtent.StartScriptPosition.ColumnNumber - 1).Trim(); } @@ -567,37 +567,37 @@ namespace System.Management.Automation #region Private Members - private readonly string command; - private JobStateInfo stateInfo = new JobStateInfo(JobState.NotStarted); - private ManualResetEvent finished = new ManualResetEvent(false); - - private Guid guid = Guid.NewGuid(); - private readonly int sessionId; - private string name; - private IList childJobs; + private readonly string _command; + private JobStateInfo _stateInfo = new JobStateInfo(JobState.NotStarted); + private ManualResetEvent _finished = new ManualResetEvent(false); + + private Guid _guid = Guid.NewGuid(); + private readonly int _sessionId; + private string _name; + private IList _childJobs; internal readonly object syncObject = new object(); // object used for synchronization //ISSUE: Should Result be public property - private PSDataCollection results = new PSDataCollection(); - bool resultsOwner = true; - private PSDataCollection error = new PSDataCollection(); - bool errorOwner = true; - private PSDataCollection progress = new PSDataCollection(); - bool progressOwner = true; - private PSDataCollection verbose = new PSDataCollection(); - bool verboseOwner = true; - private PSDataCollection warning = new PSDataCollection(); - bool warningOwner = true; - private PSDataCollection debug = new PSDataCollection(); - bool debugOwner = true; - private PSDataCollection information = new PSDataCollection(); - bool informationOwner = true; - private PSDataCollection output = new PSDataCollection(); - bool outputOwner = true; + private PSDataCollection _results = new PSDataCollection(); + private bool _resultsOwner = true; + private PSDataCollection _error = new PSDataCollection(); + private bool _errorOwner = true; + private PSDataCollection _progress = new PSDataCollection(); + private bool _progressOwner = true; + private PSDataCollection _verbose = new PSDataCollection(); + private bool _verboseOwner = true; + private PSDataCollection _warning = new PSDataCollection(); + private bool _warningOwner = true; + private PSDataCollection _debug = new PSDataCollection(); + private bool _debugOwner = true; + private PSDataCollection _information = new PSDataCollection(); + private bool _informationOwner = true; + private PSDataCollection _output = new PSDataCollection(); + private bool _outputOwner = true; /// /// Static variable which is incremented to generate id /// - static int _jobIdSeed = 0; + private static int s_jobIdSeed = 0; private DateTime? _beginTime = null; private DateTime? _endTime = null; @@ -610,11 +610,11 @@ namespace System.Management.Automation /// /// Command Invoked by this Job /// - public string Command + public string Command { get { - return command; + return _command; } } @@ -625,7 +625,7 @@ namespace System.Management.Automation { get { - return stateInfo; + return _stateInfo; } } @@ -640,9 +640,9 @@ namespace System.Management.Automation { lock (this.syncObject) { - if (finished != null) + if (_finished != null) { - return finished; + return _finished; } else { @@ -664,7 +664,7 @@ namespace System.Management.Automation { get { - return guid; + return _guid; } } @@ -676,7 +676,7 @@ namespace System.Management.Automation { get { - return sessionId; + return _sessionId; } } @@ -687,12 +687,12 @@ namespace System.Management.Automation { get { - return name; + return _name; } set { AssertNotDisposed(); - name = value; + _name = value; } } @@ -703,17 +703,17 @@ namespace System.Management.Automation { get { - if (childJobs == null) + if (_childJobs == null) { lock (syncObject) { - if (childJobs == null) + if (_childJobs == null) { - childJobs = new List(); + _childJobs = new List(); } } } - return childJobs; + return _childJobs; } } @@ -726,7 +726,7 @@ namespace System.Management.Automation /// Indicates that more data is available in this /// result object for reading. /// - public abstract bool HasMoreData { get;} + public abstract bool HasMoreData { get; } /// /// Time job was started. @@ -769,7 +769,7 @@ namespace System.Management.Automation { get { - return results; + return _results; } set { @@ -780,8 +780,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - resultsOwner = false; - results = value; + _resultsOwner = false; + _results = value; } } } @@ -800,23 +800,23 @@ namespace System.Management.Automation { get { - return this.suppressOutputForwarding; + return _suppressOutputForwarding; } set { - this.suppressOutputForwarding = value; + _suppressOutputForwarding = value; } } - private bool suppressOutputForwarding; + private bool _suppressOutputForwarding; internal virtual void WriteObject(object outputObject) { PSObject pso = (outputObject == null) ? null : PSObject.AsPSObject(outputObject); this.Output.Add(pso); - if (!this.suppressOutputForwarding) + if (!_suppressOutputForwarding) { - this.Results.Add(new PSStreamObject(PSStreamObjectType.Output,pso)); + this.Results.Add(new PSStreamObject(PSStreamObjectType.Output, pso)); } } @@ -828,14 +828,14 @@ namespace System.Management.Automation { get { - return this.propagateThrows; + return _propagateThrows; } set { - this.propagateThrows = value; + _propagateThrows = value; } } - private bool propagateThrows; + private bool _propagateThrows; private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord) { @@ -854,7 +854,7 @@ namespace System.Management.Automation { RuntimeException runtimeException = errorRecord.Exception as RuntimeException; if (runtimeException == null) - return null; + return null; RemoteException remoteException = runtimeException as RemoteException; if (remoteException == null) @@ -862,9 +862,9 @@ namespace System.Management.Automation PSPropertyInfo wasThrownFromThrow = remoteException.SerializedRemoteException.Properties["WasThrownFromThrowStatement"]; - if (wasThrownFromThrow == null || !((bool) wasThrownFromThrow.Value)) + if (wasThrownFromThrow == null || !((bool)wasThrownFromThrow.Value)) return null; - + runtimeException.WasThrownFromThrowStatement = true; return runtimeException; } @@ -905,7 +905,7 @@ namespace System.Management.Automation internal virtual void WriteVerbose(string message) { this.Verbose.Add(new VerboseRecord(message)); - this.Results.Add(new PSStreamObject(PSStreamObjectType.Verbose, message) ); + this.Results.Add(new PSStreamObject(PSStreamObjectType.Verbose, message)); } internal virtual void WriteDebug(string message) @@ -916,9 +916,9 @@ namespace System.Management.Automation internal virtual void WriteProgress(ProgressRecord progressRecord) { - if ((progressRecord.ParentActivityId == (-1)) && (this.parentActivityId != null)) + if ((progressRecord.ParentActivityId == (-1)) && (_parentActivityId != null)) { - progressRecord = new ProgressRecord(progressRecord) {ParentActivityId = this.parentActivityId.Value}; + progressRecord = new ProgressRecord(progressRecord) { ParentActivityId = _parentActivityId.Value }; } Progress.Add(progressRecord); @@ -931,11 +931,11 @@ namespace System.Management.Automation Results.Add(new PSStreamObject(PSStreamObjectType.Information, informationRecord)); } - private Lazy parentActivityId; + private Lazy _parentActivityId; internal void SetParentActivityIdGetter(Func parentActivityIdGetter) { Dbg.Assert(parentActivityIdGetter != null, "Caller should verify parentActivityIdGetter != null"); - this.parentActivityId = new Lazy(parentActivityIdGetter); + _parentActivityId = new Lazy(parentActivityIdGetter); } internal bool ShouldContinue(string query, string caption) @@ -958,7 +958,7 @@ namespace System.Management.Automation string caption) { InvokeCmdletMethodAndIgnoreResults( - delegate(Cmdlet cmdlet) + delegate (Cmdlet cmdlet) { ShouldProcessReason throwAwayProcessReason; cmdlet.ShouldProcess( @@ -985,7 +985,7 @@ namespace System.Management.Automation caption, out closureSafeShouldProcessReason), out exceptionThrownOnCmdletThread); - + shouldProcessReason = closureSafeShouldProcessReason; return methodResult; } @@ -994,11 +994,11 @@ namespace System.Management.Automation { object resultsLock = new object(); CmdletMethodInvoker methodInvoker = new CmdletMethodInvoker - { - Action = delegate(Cmdlet cmdlet) { invokeCmdletMethod(cmdlet); return null; }, - Finished = null, - SyncObject = resultsLock - }; + { + Action = delegate (Cmdlet cmdlet) { invokeCmdletMethod(cmdlet); return null; }, + Finished = null, + SyncObject = resultsLock + }; Results.Add(new PSStreamObject(PSStreamObjectType.BlockingError, methodInvoker)); } @@ -1012,7 +1012,7 @@ namespace System.Management.Automation using (var gotResultEvent = new ManualResetEventSlim(false)) { EventHandler stateChangedEventHandler = - delegate(object sender, JobStateEventArgs eventArgs) + delegate (object sender, JobStateEventArgs eventArgs) { if (IsFinishedState(eventArgs.JobStateInfo.State) || eventArgs.JobStateInfo.State == JobState.Stopping) { @@ -1035,11 +1035,11 @@ namespace System.Management.Automation // addition to results column happens here CmdletMethodInvoker methodInvoker = new CmdletMethodInvoker - { - Action = invokeCmdletMethodAndReturnResult, - Finished = gotResultEvent, - SyncObject = resultsLock - }; + { + Action = invokeCmdletMethodAndReturnResult, + Finished = gotResultEvent, + SyncObject = resultsLock + }; PSStreamObjectType objectType = PSStreamObjectType.ShouldMethod; if (typeof(T) == typeof(object)) @@ -1075,7 +1075,7 @@ namespace System.Management.Automation internal virtual void ForwardAvailableResultsToCmdlet(Cmdlet cmdlet) { - foreach(PSStreamObject obj in Results.ReadAll()) + foreach (PSStreamObject obj in Results.ReadAll()) { obj.WriteStreamObject(cmdlet); } @@ -1103,7 +1103,6 @@ namespace System.Management.Automation /// protected virtual void DoUnloadJobStreams() { - } /// @@ -1123,8 +1122,8 @@ namespace System.Management.Automation { DoLoadJobStreams(); } - catch(Exception e) - { + catch (Exception e) + { // third party call-out for platform API // Therefore it is fine to eat the exception // here @@ -1143,7 +1142,7 @@ namespace System.Management.Automation { if (!_jobStreamsLoaded) return; - lock(syncObject) + lock (syncObject) { if (!_jobStreamsLoaded) return; _jobStreamsLoaded = false; @@ -1153,7 +1152,7 @@ namespace System.Management.Automation { DoUnloadJobStreams(); } - catch(Exception e) + catch (Exception e) { // third party call-out for platform API // Therefore it is fine to eat the exception @@ -1181,7 +1180,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return output; + return _output; } set { @@ -1192,8 +1191,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - outputOwner = false; - output = value; + _outputOwner = false; + _output = value; _jobStreamsLoaded = true; } } @@ -1215,7 +1214,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return error; + return _error; } set { @@ -1226,8 +1225,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - errorOwner = false; - error = value; + _errorOwner = false; + _error = value; _jobStreamsLoaded = true; } } @@ -1249,7 +1248,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return progress; + return _progress; } set { @@ -1260,8 +1259,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - progressOwner = false; - progress = value; + _progressOwner = false; + _progress = value; _jobStreamsLoaded = true; } } @@ -1280,7 +1279,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return verbose; + return _verbose; } set { @@ -1291,8 +1290,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - verboseOwner = false; - verbose = value; + _verboseOwner = false; + _verbose = value; _jobStreamsLoaded = true; } } @@ -1314,7 +1313,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return debug; + return _debug; } set { @@ -1325,8 +1324,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - debugOwner = false; - debug = value; + _debugOwner = false; + _debug = value; } } } @@ -1347,7 +1346,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return warning; + return _warning; } set { @@ -1358,8 +1357,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - warningOwner = false; - warning = value; + _warningOwner = false; + _warning = value; _jobStreamsLoaded = true; } } @@ -1381,7 +1380,7 @@ namespace System.Management.Automation get { LoadJobStreams(); // for delayed loading - return information; + return _information; } set { @@ -1392,8 +1391,8 @@ namespace System.Management.Automation lock (syncObject) { AssertChangesAreAccepted(); - informationOwner = false; - information = value; + _informationOwner = false; + _information = value; _jobStreamsLoaded = true; } } @@ -1402,7 +1401,7 @@ namespace System.Management.Automation /// /// Indicates a location where this job is running /// - public abstract String Location { get;} + public abstract String Location { get; } #endregion results @@ -1468,11 +1467,11 @@ namespace System.Management.Automation AssertNotDisposed(); bool alldone = false; - JobStateInfo previousState = this.stateInfo; + JobStateInfo previousState = _stateInfo; lock (syncObject) { - stateInfo = new JobStateInfo(state, reason); + _stateInfo = new JobStateInfo(state, reason); if (state == JobState.Running) { @@ -1512,13 +1511,13 @@ namespace System.Management.Automation } } - #pragma warning disable 56500 +#pragma warning disable 56500 //Exception rasied in the eventhandler are not error in job. //silently ignore them. try { tracer.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Invoking StateChanged event", null); - StateChanged.SafeInvoke(this, new JobStateEventArgs(stateInfo.Clone(), previousState)); + StateChanged.SafeInvoke(this, new JobStateEventArgs(_stateInfo.Clone(), previousState)); } catch (Exception exception) // ignore non-severe exceptions { @@ -1534,9 +1533,9 @@ namespace System.Management.Automation { lock (syncObject) { - if (finished != null) + if (_finished != null) { - finished.Set(); + _finished.Set(); } } } @@ -1596,7 +1595,7 @@ namespace System.Management.Automation return (IsFinishedState(state) || state == JobState.Disconnected || state == JobState.Suspended); } } - + /// /// Checks if the current instance can accept changes like /// changing one of the properties like Output, Error etc. @@ -1631,7 +1630,7 @@ namespace System.Management.Automation /// localizable protected String AutoGenerateJobName() { - return "Job" + sessionId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + return "Job" + _sessionId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); } /// @@ -1643,25 +1642,25 @@ namespace System.Management.Automation /// internal void AssertNotDisposed() { - if (isDisposed) + if (_isDisposed) { throw PSTraceSource.NewObjectDisposedException("PSJob"); } } - + /// /// A helper method to close all the streams. /// internal void CloseAllStreams() { - if (resultsOwner) results.Complete(); - if (outputOwner) output.Complete(); - if (errorOwner) error.Complete(); - if (progressOwner) progress.Complete(); - if (verboseOwner) verbose.Complete(); - if (warningOwner) warning.Complete(); - if (debugOwner) debug.Complete(); - if (informationOwner) information.Complete(); + if (_resultsOwner) _results.Complete(); + if (_outputOwner) _output.Complete(); + if (_errorOwner) _error.Complete(); + if (_progressOwner) _progress.Complete(); + if (_verboseOwner) _verbose.Complete(); + if (_warningOwner) _warning.Complete(); + if (_debugOwner) _debug.Complete(); + if (_informationOwner) _information.Complete(); } /// @@ -1710,35 +1709,35 @@ namespace System.Management.Automation { if (disposing) { - if (!isDisposed) + if (!_isDisposed) { CloseAllStreams(); // release the WaitHandle lock (syncObject) { - if (null != finished) + if (null != _finished) { - finished.Dispose(); - finished = null; + _finished.Dispose(); + _finished = null; } } // Only dispose the collections if we've created them... - if (resultsOwner) results.Dispose(); - if (outputOwner) output.Dispose(); - if (errorOwner) error.Dispose(); - if (debugOwner) debug.Dispose(); - if (informationOwner) information.Dispose(); - if (verboseOwner) verbose.Dispose(); - if (warningOwner) warning.Dispose(); - if (progressOwner) progress.Dispose(); + if (_resultsOwner) _results.Dispose(); + if (_outputOwner) _output.Dispose(); + if (_errorOwner) _error.Dispose(); + if (_debugOwner) _debug.Dispose(); + if (_informationOwner) _information.Dispose(); + if (_verboseOwner) _verbose.Dispose(); + if (_warningOwner) _warning.Dispose(); + if (_progressOwner) _progress.Dispose(); - isDisposed = true; + _isDisposed = true; } } } - private bool isDisposed; + private bool _isDisposed; #endregion IDisposable Members @@ -1780,7 +1779,6 @@ namespace System.Management.Automation } #endregion - } //Job /// @@ -1811,7 +1809,8 @@ namespace System.Management.Automation internal PSRemotingJob(String[] computerNames, List computerNameHelpers, String remoteCommand, string name) : - this(computerNames, computerNameHelpers, remoteCommand, 0, name) { } + this(computerNames, computerNameHelpers, remoteCommand, 0, name) + { } /// /// Internal constructor for initializing job using @@ -1828,7 +1827,8 @@ namespace System.Management.Automation internal PSRemotingJob(PSSession[] remoteRunspaceInfos, List runspaceHelpers, String remoteCommand, string name) : - this(remoteRunspaceInfos, runspaceHelpers, remoteCommand, 0, name) { } + this(remoteRunspaceInfos, runspaceHelpers, remoteCommand, 0, name) + { } /// @@ -1847,14 +1847,14 @@ namespace System.Management.Automation internal PSRemotingJob(String[] computerNames, List computerNameHelpers, String remoteCommand, int throttleLimit, string name) - :base(remoteCommand,name) + : base(remoteCommand, name) { // Create child jobs for each object in the list foreach (ExecutionCmdletHelperComputerName helper in computerNameHelpers) { //Create Child Job and Register for its StateChanged Event - PSRemotingChildJob childJob = new PSRemotingChildJob(remoteCommand, - helper, throttleManager); + PSRemotingChildJob childJob = new PSRemotingChildJob(remoteCommand, + helper, _throttleManager); childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); childJob.JobUnblocked += new EventHandler(HandleJobUnblocked); @@ -1880,7 +1880,7 @@ namespace System.Management.Automation internal PSRemotingJob(PSSession[] remoteRunspaceInfos, List runspaceHelpers, String remoteCommand, int throttleLimit, string name) - :base(remoteCommand, name) + : base(remoteCommand, name) { // Create chiild jobs for each object in the list for (int i = 0; i < remoteRunspaceInfos.Length; i++) @@ -1888,8 +1888,8 @@ namespace System.Management.Automation ExecutionCmdletHelperRunspace helper = (ExecutionCmdletHelperRunspace)runspaceHelpers[i]; //Create Child Job object and Register for its state changed event - PSRemotingChildJob job = new PSRemotingChildJob(remoteCommand, - helper, throttleManager); + PSRemotingChildJob job = new PSRemotingChildJob(remoteCommand, + helper, _throttleManager); job.StateChanged += new EventHandler(HandleChildJobStateChanged); job.JobUnblocked += new EventHandler(HandleJobUnblocked); @@ -1909,7 +1909,7 @@ namespace System.Management.Automation /// Throttle limit value. /// Job name. /// Aggregate results. - internal PSRemotingJob(List helpers, + internal PSRemotingJob(List helpers, int throttleLimit, string name, bool aggregateResults) : base(string.Empty, name) { @@ -1918,7 +1918,7 @@ namespace System.Management.Automation // ExecutionCmdletHelperRunspace object and ThrottleManager. foreach (ExecutionCmdletHelper helper in helpers) { - PSRemotingChildJob job = new PSRemotingChildJob(helper, this.throttleManager, aggregateResults); + PSRemotingChildJob job = new PSRemotingChildJob(helper, _throttleManager, aggregateResults); job.StateChanged += new EventHandler(HandleChildJobStateChanged); job.JobUnblocked += new EventHandler(HandleJobUnblocked); @@ -1933,9 +1933,9 @@ namespace System.Management.Automation SetJobState(JobState.Disconnected); // Submit the disconnected operation helpers to the throttle manager - this.throttleManager.ThrottleLimit = throttleLimit; - this.throttleManager.SubmitOperations(helpers); - this.throttleManager.EndSubmitOperations(); + _throttleManager.ThrottleLimit = throttleLimit; + _throttleManager.SubmitOperations(helpers); + _throttleManager.EndSubmitOperations(); } /// @@ -1946,7 +1946,7 @@ namespace System.Management.Automation /// /// Initialization common to both constructors /// - void CommonInit(int throttleLimit, List helpers) + private void CommonInit(int throttleLimit, List helpers) { //Since no results are produced by any streams. We should //close all the streams @@ -1956,14 +1956,14 @@ namespace System.Management.Automation SetJobState(JobState.Running); // submit operations to the throttle manager - throttleManager.ThrottleLimit = throttleLimit; - throttleManager.SubmitOperations(helpers); - throttleManager.EndSubmitOperations(); + _throttleManager.ThrottleLimit = throttleLimit; + _throttleManager.SubmitOperations(helpers); + _throttleManager.EndSubmitOperations(); } #endregion Internal Constructors #region internal methods - + /// /// Get entity result for the specified computer /// @@ -1978,7 +1978,7 @@ namespace System.Management.Automation { PSRemotingChildJob child = j as PSRemotingChildJob; if (j == null) continue; - if (String.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName, + if (String.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName, StringComparison.OrdinalIgnoreCase)) { returnJobList.Add(child); @@ -2093,7 +2093,7 @@ namespace System.Management.Automation using (ManualResetEvent connectResult = new ManualResetEvent(false)) { EventHandler throttleCompleteEventHandler = - delegate(object sender, EventArgs eventArgs) + delegate (object sender, EventArgs eventArgs) { connectResult.Set(); }; @@ -2120,12 +2120,12 @@ namespace System.Management.Automation /// private class ConnectJobOperation : IThrottleOperation { - private PSRemotingChildJob psRemoteChildJob; + private PSRemotingChildJob _psRemoteChildJob; internal ConnectJobOperation(PSRemotingChildJob job) { - this.psRemoteChildJob = job; - this.psRemoteChildJob.StateChanged += ChildJobStateChangedHandler; + _psRemoteChildJob = job; + _psRemoteChildJob.StateChanged += ChildJobStateChangedHandler; } internal override void StartOperation() @@ -2134,16 +2134,16 @@ namespace System.Management.Automation try { - this.psRemoteChildJob.ConnectAsync(); + _psRemoteChildJob.ConnectAsync(); } catch (InvalidJobStateException e) { startedSuccessfully = false; - string msg = StringUtil.Format(RemotingErrorIdStrings.JobConnectFailed, this.psRemoteChildJob.Name); + string msg = StringUtil.Format(RemotingErrorIdStrings.JobConnectFailed, _psRemoteChildJob.Name); Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "PSJobConnectFailed", ErrorCategory.InvalidOperation, this.psRemoteChildJob); - this.psRemoteChildJob.WriteError(errorRecord); + ErrorRecord errorRecord = new ErrorRecord(reason, "PSJobConnectFailed", ErrorCategory.InvalidOperation, _psRemoteChildJob); + _psRemoteChildJob.WriteError(errorRecord); } if (!startedSuccessfully) @@ -2185,7 +2185,7 @@ namespace System.Management.Automation private void RemoveEventCallback() { - this.psRemoteChildJob.StateChanged -= ChildJobStateChangedHandler; + _psRemoteChildJob.StateChanged -= ChildJobStateChangedHandler; } } @@ -2237,28 +2237,28 @@ namespace System.Management.Automation /// internal void InternalStopJob() { - if (isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) + if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) { return; } lock (_syncObject) { - if (isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) + if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) { return; } _stopIsCalled = true; } - throttleManager.StopAllOperations(); + _throttleManager.StopAllOperations(); - Finished.WaitOne(); + Finished.WaitOne(); } #endregion - private bool moreData = true; + private bool _moreData = true; /// /// indicates if more data is available /// @@ -2273,7 +2273,7 @@ namespace System.Management.Automation // will remain so until the async result // object has completed execution. - if (moreData && IsFinishedState(JobStateInfo.State)) + if (_moreData && IsFinishedState(JobStateInfo.State)) { bool atleastOneChildHasMoreData = false; @@ -2286,14 +2286,14 @@ namespace System.Management.Automation } } - moreData = atleastOneChildHasMoreData; + _moreData = atleastOneChildHasMoreData; } - return moreData; + return _moreData; } - } - - + } + + private bool _stopIsCalled = false; /// /// Stop Job @@ -2338,8 +2338,8 @@ namespace System.Management.Automation InternalStopJob(); } - - string statusMessage; + + private string _statusMessage; /// /// Message indicating status of the job /// @@ -2347,7 +2347,7 @@ namespace System.Management.Automation { get { - return statusMessage; + return _statusMessage; } } @@ -2359,10 +2359,10 @@ namespace System.Management.Automation /// internal bool HideComputerName { - get { return hideComputerName; } + get { return _hideComputerName; } set { - hideComputerName = value; + _hideComputerName = value; foreach (Job job in this.ChildJobs) { PSRemotingChildJob rJob = job as PSRemotingChildJob; @@ -2373,7 +2373,7 @@ namespace System.Management.Automation } } } - private bool hideComputerName = true; + private bool _hideComputerName = true; //ISSUE: Implement StatusMessage /// @@ -2383,7 +2383,7 @@ namespace System.Management.Automation [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void SetStatusMessage() { - statusMessage = "test"; + _statusMessage = "test"; // bool localErrors = false; // if local errors are present // bool setFinished = false; // if finished needs to be set @@ -2427,20 +2427,20 @@ namespace System.Management.Automation #region finish logic //This variable is set to true if atleast one child job failed. - bool atleastOneChildJobFailed = false; + private bool _atleastOneChildJobFailed = false; // count of number of child jobs which have finished - private int finishedChildJobsCount = 0; + private int _finishedChildJobsCount = 0; // count of number of child jobs which are blocked - private int blockedChildJobsCount = 0; + private int _blockedChildJobsCount = 0; // count of child jobs that are in disconnected state. - private int disconnectedChildJobsCount = 0; + private int _disconnectedChildJobsCount = 0; // count of child jobs that are in Debug halted state. - private int debugChildJobsCount = 0; - + private int _debugChildJobsCount = 0; + /// /// Handles the StateChanged event from each of the child job objects /// @@ -2456,7 +2456,7 @@ namespace System.Management.Automation // increment count of blocked child jobs lock (_syncObject) { - blockedChildJobsCount++; + _blockedChildJobsCount++; } // if any of the child job is blocked, we set state to blocked @@ -2467,7 +2467,7 @@ namespace System.Management.Automation // Handle transition of child job to Debug halt state. if (e.JobStateInfo.State == JobState.AtBreakpoint) { - lock (_syncObject) { debugChildJobsCount++; } + lock (_syncObject) { _debugChildJobsCount++; } // If any child jobs are Debug halted, we set state to Debug. SetJobState(JobState.AtBreakpoint); @@ -2479,8 +2479,8 @@ namespace System.Management.Automation (e.PreviousJobStateInfo.State == JobState.AtBreakpoint)) { int totalDebugCount; - lock (_syncObject) { totalDebugCount = --debugChildJobsCount; } - + lock (_syncObject) { totalDebugCount = --_debugChildJobsCount; } + if (totalDebugCount == 0) { SetJobState(JobState.Running); @@ -2496,16 +2496,16 @@ namespace System.Management.Automation if (e.JobStateInfo.State == JobState.Failed) { //If any of the child job failed, we set status to failed - atleastOneChildJobFailed = true; + _atleastOneChildJobFailed = true; } bool allChildJobsFinished = false; lock (_syncObject) { - finishedChildJobsCount++; + _finishedChildJobsCount++; //We are done - if (finishedChildJobsCount + disconnectedChildJobsCount + if (_finishedChildJobsCount + _disconnectedChildJobsCount == ChildJobs.Count) { allChildJobsFinished = true; @@ -2516,11 +2516,11 @@ namespace System.Management.Automation //if any child job failed, set status to failed //If stop was called set, status to stopped //else completed - if (disconnectedChildJobsCount > 0) + if (_disconnectedChildJobsCount > 0) { SetJobState(JobState.Disconnected); } - else if (atleastOneChildJobFailed) + else if (_atleastOneChildJobFailed) { SetJobState(JobState.Failed); } @@ -2546,27 +2546,27 @@ namespace System.Management.Automation { return; } - + // Do all logic inside a lock to ensure it is atomic against // multiple job thread state changes. lock (_syncObject) { if (newState == JobState.Disconnected) { - ++(this.disconnectedChildJobsCount); + ++(_disconnectedChildJobsCount); // If previous state was Blocked then we need to decrement the count // since it is now Disconnected. if (prevState == JobState.Blocked) { - --this.blockedChildJobsCount; + --_blockedChildJobsCount; } // If all unfinished and unblocked child jobs are disconnected then this // parent job becomes disconnected. - if ((this.disconnectedChildJobsCount + - this.finishedChildJobsCount + - this.blockedChildJobsCount) == ChildJobs.Count) + if ((_disconnectedChildJobsCount + + _finishedChildJobsCount + + _blockedChildJobsCount) == ChildJobs.Count) { SetJobState(JobState.Disconnected, null); } @@ -2575,7 +2575,7 @@ namespace System.Management.Automation { if (prevState == JobState.Disconnected) { - --(this.disconnectedChildJobsCount); + --(_disconnectedChildJobsCount); } if ((newState == JobState.Running) && (JobStateInfo.State == JobState.Disconnected)) @@ -2600,19 +2600,19 @@ namespace System.Management.Automation { if (disposing) { - if (isDisposed) + if (_isDisposed) { return; } lock (_syncObject) { - if (isDisposed) + if (_isDisposed) { return; } - isDisposed = true; + _isDisposed = true; } try @@ -2625,7 +2625,7 @@ namespace System.Management.Automation { job.Dispose(); } - throttleManager.Dispose(); + _throttleManager.Dispose(); } finally { @@ -2633,8 +2633,8 @@ namespace System.Management.Automation } } } - - private bool isDisposed = false; + + private bool _isDisposed = false; private String ConstructLocation() { @@ -2658,7 +2658,7 @@ namespace System.Management.Automation /// public override string Location { - get + get { return ConstructLocation(); } @@ -2708,9 +2708,9 @@ namespace System.Management.Automation lock (_syncObject) { - blockedChildJobsCount--; + _blockedChildJobsCount--; - if (blockedChildJobsCount == 0) + if (_blockedChildJobsCount == 0) { unblockjob = true; } @@ -2724,10 +2724,10 @@ namespace System.Management.Automation #region Private Members - private ThrottleManager throttleManager = new ThrottleManager(); - + private ThrottleManager _throttleManager = new ThrottleManager(); + private readonly object _syncObject = new object(); // sync object - + #endregion Private Members } @@ -2827,12 +2827,12 @@ namespace System.Management.Automation UsesResultsCollection = true; Dbg.Assert(helper.Pipeline is RemotePipeline, "Pipeline passed should be a remote pipeline"); - this.helper = helper; - this.remoteRunspace = helper.Pipeline.Runspace; - this.remotePipeline = helper.Pipeline as RemotePipeline; - this.throttleManager = throttleManager; + _helper = helper; + _remoteRunspace = helper.Pipeline.Runspace; + _remotePipeline = helper.Pipeline as RemotePipeline; + _throttleManager = throttleManager; - RemoteRunspace remoteRS = remoteRunspace as RemoteRunspace; + RemoteRunspace remoteRS = _remoteRunspace as RemoteRunspace; if ((null != remoteRS) && (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen)) { remoteRS.URIRedirectionReported += HandleURIDirectionReported; @@ -2840,7 +2840,7 @@ namespace System.Management.Automation AggregateResultsFromHelper(helper); - remoteRunspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; + _remoteRunspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; RegisterThrottleComplete(throttleManager); } @@ -2861,10 +2861,10 @@ namespace System.Management.Automation Dbg.Assert((helper.Pipeline is RemotePipeline), "Helper pipeline object should be a remote pipeline"); Dbg.Assert((helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected), "Remote pipeline object must be in Disconnected state."); - this.helper = helper; - this.remotePipeline = helper.Pipeline as RemotePipeline; - this.remoteRunspace = helper.Pipeline.Runspace; - this.throttleManager = throttleManager; + _helper = helper; + _remotePipeline = helper.Pipeline as RemotePipeline; + _remoteRunspace = helper.Pipeline.Runspace; + _throttleManager = throttleManager; if (aggregateResults) { @@ -2872,12 +2872,12 @@ namespace System.Management.Automation } else { - this.remotePipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); - this.remotePipeline.Output.DataReady += new EventHandler(HandleOutputReady); - this.remotePipeline.Error.DataReady += new EventHandler(HandleErrorReady); + _remotePipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); + _remotePipeline.Output.DataReady += new EventHandler(HandleOutputReady); + _remotePipeline.Error.DataReady += new EventHandler(HandleErrorReady); } - remoteRunspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; + _remoteRunspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; IThrottleOperation operation = helper as IThrottleOperation; operation.OperationComplete += new EventHandler(HandleOperationComplete); @@ -2890,7 +2890,6 @@ namespace System.Management.Automation /// protected PSRemotingChildJob() { - } #endregion Internal Constructor @@ -2907,7 +2906,7 @@ namespace System.Management.Automation throw new InvalidJobStateException(JobStateInfo.State); } - this.remotePipeline.ConnectAsync(); + _remotePipeline.ConnectAsync(); } /// @@ -2916,7 +2915,7 @@ namespace System.Management.Automation /// internal void RemoveJobAggregation() { - RemoveAggreateCallbacksFromHelper(helper); + RemoveAggreateCallbacksFromHelper(_helper); } #endregion @@ -2929,22 +2928,22 @@ namespace System.Management.Automation /// public override void StopJob() { - if (isDisposed || stopIsCalled || IsFinishedState(JobStateInfo.State)) + if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) { return; } lock (SyncObject) { - if (isDisposed || stopIsCalled || IsFinishedState(JobStateInfo.State)) + if (_isDisposed || _stopIsCalled || IsFinishedState(JobStateInfo.State)) { return; } - stopIsCalled = true; + _stopIsCalled = true; } - throttleManager.StopOperation(helper); + _throttleManager.StopOperation(_helper); // if IgnoreStop is set, then StopOperation will // return immediately, but StopJob should only @@ -2990,7 +2989,7 @@ namespace System.Management.Automation { get { - return (remoteRunspace != null) ? remoteRunspace.ConnectionInfo.ComputerName : string.Empty; + return (_remoteRunspace != null) ? _remoteRunspace.ConnectionInfo.ComputerName : string.Empty; } } @@ -3001,11 +3000,11 @@ namespace System.Management.Automation { get { - return remoteRunspace; + return _remoteRunspace; } } - private Runspace remoteRunspace; + private Runspace _remoteRunspace; /// /// helper associated with this entity @@ -3014,7 +3013,7 @@ namespace System.Management.Automation { get { - return helper; + return _helper; } } @@ -3026,10 +3025,10 @@ namespace System.Management.Automation /// internal bool HideComputerName { - get { return hideComputerName; } + get { return _hideComputerName; } set { - hideComputerName = value; + _hideComputerName = value; foreach (Job job in this.ChildJobs) { PSRemotingChildJob rJob = job as PSRemotingChildJob; @@ -3040,7 +3039,7 @@ namespace System.Management.Automation } } } - private bool hideComputerName = true; + private bool _hideComputerName = true; /// /// Property that indicates this disconnected child job was @@ -3048,7 +3047,7 @@ namespace System.Management.Automation /// internal bool DisconnectedAndBlocked { - get { return this.disconnectedBlocked; } + get { return _disconnectedBlocked; } } /// @@ -3060,7 +3059,7 @@ namespace System.Management.Automation { get { - RemoteRunspace remoteRS = this.remoteRunspace as RemoteRunspace; + RemoteRunspace remoteRS = _remoteRunspace as RemoteRunspace; return (remoteRS != null) ? remoteRS.CanDisconnect : false; } } @@ -3081,9 +3080,9 @@ namespace System.Management.Automation lock (this.SyncObject) { if ((_jobDebugger == null) && - (this.remoteRunspace.Debugger != null)) + (_remoteRunspace.Debugger != null)) { - _jobDebugger = new RemotingJobDebugger(this.remoteRunspace.Debugger, this.remoteRunspace, this.Name); + _jobDebugger = new RemotingJobDebugger(_remoteRunspace.Debugger, _remoteRunspace, this.Name); } } } @@ -3147,7 +3146,7 @@ namespace System.Management.Automation // Ex: Invoke-Command localhost,blah { gps } | select PSComputerName should work. if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { - PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !hideComputerName); + PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !_hideComputerName); dataObject.Properties.Add(showComputerNameNP); } } @@ -3265,24 +3264,24 @@ namespace System.Management.Automation /// protected virtual void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e) { - if ((null != remoteRunspace) && (e.PipelineStateInfo.State != PipelineState.Running)) + if ((null != _remoteRunspace) && (e.PipelineStateInfo.State != PipelineState.Running)) { // since we got state changed event..we dont need to listen on // URI redirections anymore - ((RemoteRunspace)remoteRunspace).URIRedirectionReported -= HandleURIDirectionReported; + ((RemoteRunspace)_remoteRunspace).URIRedirectionReported -= HandleURIDirectionReported; // We monitor runspace RemoteDebug availability only while // this pipeline is running. - ((RemoteRunspace)remoteRunspace).AvailabilityChanged -= HandleRunspaceAvailabilityChangedForInvoke; + ((RemoteRunspace)_remoteRunspace).AvailabilityChanged -= HandleRunspaceAvailabilityChangedForInvoke; } PipelineState state = e.PipelineStateInfo.State; switch (state) { case PipelineState.Running: - if (this.disconnectedBlocked) + if (_disconnectedBlocked) { - this.disconnectedBlocked = false; + _disconnectedBlocked = false; SetJobState(JobState.Blocked); } else @@ -3292,7 +3291,7 @@ namespace System.Management.Automation break; case PipelineState.Disconnected: - this.disconnectedBlocked = (JobStateInfo.State == JobState.Blocked); + _disconnectedBlocked = (JobStateInfo.State == JobState.Blocked); SetJobState(JobState.Disconnected); break; } @@ -3344,7 +3343,7 @@ namespace System.Management.Automation DeterminedAndSetJobState(helper); } - bool doFinishCalled = false; + private bool _doFinishCalled = false; /// /// This method marks the completion state for Job. Also if job failed, it processes the @@ -3352,18 +3351,18 @@ namespace System.Management.Automation /// protected virtual void DoFinish() { - if (doFinishCalled == true) + if (_doFinishCalled == true) return; lock (SyncObject) { - if (doFinishCalled == true) + if (_doFinishCalled == true) return; - doFinishCalled = true; + _doFinishCalled = true; } - DeterminedAndSetJobState(helper); + DeterminedAndSetJobState(_helper); DoCleanupOnFinished(); } @@ -3371,7 +3370,7 @@ namespace System.Management.Automation /// /// This is the pretty formated error record associated with the reason of failure. /// - ErrorRecord failureErrorRecord; + private ErrorRecord _failureErrorRecord; /// /// This is the pretty formated error record associated with the reason of failure. @@ -3381,7 +3380,7 @@ namespace System.Management.Automation { get { - return failureErrorRecord; + return _failureErrorRecord; } } @@ -3446,7 +3445,7 @@ namespace System.Management.Automation PSRemotingTransportException transException = failureException as PSRemotingTransportException; - string fullyQualifiedErrorId = + string fullyQualifiedErrorId = System.Management.Automation.Remoting.Client.WSManTransportManagerUtils.GetFQEIDFromTransportError( (transException != null) ? transException.ErrorCode : 0, "PSSessionStateBroken"); @@ -3483,13 +3482,12 @@ namespace System.Management.Automation { failureException = new RuntimeException( PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, + RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, runspace.RunspaceStateInfo.State)); } failureErrorRecord = new ErrorRecord(failureException, targetObject, fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); - } // if (runspace... else if (pipeline.PipelineStateInfo.State == PipelineState.Failed) { @@ -3523,7 +3521,6 @@ namespace System.Management.Automation OriginInfo originInfo = new OriginInfo(computerName, runspaceId); failureErrorRecord = new RemotingErrorRecord(errorRecord, originInfo); - } // if (exception != null... } // if (pipeline... } @@ -3538,17 +3535,17 @@ namespace System.Management.Automation { if (disposing) { - if (isDisposed) + if (_isDisposed) { return; } lock (SyncObject) { - if (isDisposed) + if (_isDisposed) { return; } - isDisposed = true; + _isDisposed = true; } try @@ -3562,9 +3559,9 @@ namespace System.Management.Automation } } - private bool isDisposed = false; + private bool _isDisposed = false; - private bool cleanupDone = false; + private bool _cleanupDone = false; /// /// Cleanup after state changes to finished @@ -3572,25 +3569,25 @@ namespace System.Management.Automation protected virtual void DoCleanupOnFinished() { bool doCleanup = false; - if (cleanupDone == false) + if (_cleanupDone == false) { lock (SyncObject) { - if (cleanupDone == false) + if (_cleanupDone == false) { - cleanupDone = true; + _cleanupDone = true; doCleanup = true; } } } if (!doCleanup) return; - StopAggregateResultsFromHelper(helper); - remoteRunspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; - IThrottleOperation operation = helper as IThrottleOperation; + StopAggregateResultsFromHelper(_helper); + _remoteRunspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; + IThrottleOperation operation = _helper as IThrottleOperation; operation.OperationComplete -= new EventHandler(HandleOperationComplete); - UnregisterThrottleComplete(throttleManager); - throttleManager = null; + UnregisterThrottleComplete(_throttleManager); + _throttleManager = null; } /// @@ -3609,15 +3606,15 @@ namespace System.Management.Automation // Register handler for method executor object stream. Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); - RemotePipeline remotePipeline = pipeline as RemotePipeline; + RemotePipeline remotePipeline = pipeline as RemotePipeline; remotePipeline.MethodExecutorStream.DataReady += new EventHandler(HandleHostCalls); - remotePipeline.PowerShell.Streams.Progress.DataAdded += + remotePipeline.PowerShell.Streams.Progress.DataAdded += new EventHandler(HandleProgressAdded); - remotePipeline.PowerShell.Streams.Warning.DataAdded += + remotePipeline.PowerShell.Streams.Warning.DataAdded += new EventHandler(HandleWarningAdded); - remotePipeline.PowerShell.Streams.Verbose.DataAdded += + remotePipeline.PowerShell.Streams.Verbose.DataAdded += new EventHandler(HandleVerboseAdded); - remotePipeline.PowerShell.Streams.Debug.DataAdded += + remotePipeline.PowerShell.Streams.Debug.DataAdded += new EventHandler(HandleDebugAdded); remotePipeline.PowerShell.Streams.Information.DataAdded += new EventHandler(HandleInformationAdded); @@ -3657,7 +3654,7 @@ namespace System.Management.Automation private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs) { int index = eventArgs.Index; - PowerShell powershell = GetPipelinePowerShell(remotePipeline, eventArgs.PowerShellInstanceId); + PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); if (powershell != null) { @@ -3674,7 +3671,7 @@ namespace System.Management.Automation private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs) { int index = eventArgs.Index; - PowerShell powershell = GetPipelinePowerShell(remotePipeline, eventArgs.PowerShellInstanceId); + PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); if (powershell != null) { @@ -3691,7 +3688,7 @@ namespace System.Management.Automation private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs) { int index = eventArgs.Index; - PowerShell powershell = GetPipelinePowerShell(remotePipeline, eventArgs.PowerShellInstanceId); + PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); if (powershell != null) { @@ -3710,7 +3707,7 @@ namespace System.Management.Automation private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs) { int index = eventArgs.Index; - PowerShell powershell = GetPipelinePowerShell(remotePipeline, eventArgs.PowerShellInstanceId); + PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); if (powershell != null) { @@ -3727,7 +3724,7 @@ namespace System.Management.Automation private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs) { int index = eventArgs.Index; - PowerShell powershell = GetPipelinePowerShell(remotePipeline, eventArgs.PowerShellInstanceId); + PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); if (powershell != null) { @@ -3832,7 +3829,7 @@ namespace System.Management.Automation { Exception failureException; //Process the reason in case of failure. - ProcessJobFailure(helper, out failureException, out failureErrorRecord); + ProcessJobFailure(helper, out failureException, out _failureErrorRecord); if (failureException != null) { @@ -3893,9 +3890,9 @@ namespace System.Management.Automation internal PowerShell GetPowerShell() { PowerShell ps = null; - if (this.remotePipeline != null) + if (_remotePipeline != null) { - ps = this.remotePipeline.PowerShell; + ps = _remotePipeline.PowerShell; } return ps; @@ -3935,16 +3932,16 @@ namespace System.Management.Automation #region Private Members //helper associated with this job object - private ExecutionCmdletHelper helper = null; - private RemotePipeline remotePipeline = null; + private ExecutionCmdletHelper _helper = null; + private RemotePipeline _remotePipeline = null; //object used for synchronization protected object SyncObject = new object(); - private ThrottleManager throttleManager; - private bool stopIsCalled = false; + private ThrottleManager _throttleManager; + private bool _stopIsCalled = false; - private bool disconnectedBlocked = false; + private bool _disconnectedBlocked = false; private volatile Debugger _jobDebugger; @@ -4083,10 +4080,10 @@ namespace System.Management.Automation /// host /// Current path public override void SetParent( - Debugger parent, - IEnumerable breakPoints, - DebuggerResumeAction? startAction, - PSHost host, + Debugger parent, + IEnumerable breakPoints, + DebuggerResumeAction? startAction, + PSHost host, PathInfo path) { // For now always enable step mode debugging. @@ -4145,7 +4142,7 @@ namespace System.Management.Automation #region Private methods - void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) + private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { Pipeline remoteRunningCmd = null; try @@ -4220,12 +4217,12 @@ namespace System.Management.Automation { #region Private Members - private List helpers = new List(); - private ThrottleManager throttleManager; - private Dictionary powershells = new Dictionary(); + private List _helpers = new List(); + private ThrottleManager _throttleManager; + private Dictionary _powershells = new Dictionary(); - private int pipelineFinishedCount; - private int pipelineDisconnectedCount; + private int _pipelineFinishedCount; + private int _pipelineDisconnectedCount; #endregion Private Members @@ -4242,8 +4239,8 @@ namespace System.Management.Automation UsesResultsCollection = true; Results.AddRef(); - this.throttleManager = throttleManager; - RegisterThrottleComplete(this.throttleManager); + _throttleManager = throttleManager; + RegisterThrottleComplete(_throttleManager); foreach (IThrottleOperation operation in operations) { @@ -4260,12 +4257,12 @@ namespace System.Management.Automation remoteRS.URIRedirectionReported += HandleURIDirectionReported; } } - helpers.Add(helper); + _helpers.Add(helper); AggregateResultsFromHelper(helper); Dbg.Assert(helper.Pipeline is RemotePipeline, "Only remote pipeline can be used in InvokeExpressionSyncJob"); RemotePipeline pipeline = helper.Pipeline as RemotePipeline; - powershells.Add(pipeline.PowerShell.InstanceId, pipeline.PowerShell); + _powershells.Add(pipeline.PowerShell.InstanceId, pipeline.PowerShell); } } @@ -4273,7 +4270,7 @@ namespace System.Management.Automation #region Protected Methods - private bool cleanupDone = false; + private bool _cleanupDone = false; /// /// Clean up once job is finished @@ -4281,13 +4278,13 @@ namespace System.Management.Automation protected override void DoCleanupOnFinished() { bool doCleanup = false; - if (cleanupDone == false) + if (_cleanupDone == false) { lock (SyncObject) { - if (cleanupDone == false) + if (_cleanupDone == false) { - cleanupDone = true; + _cleanupDone = true; doCleanup = true; } } @@ -4295,7 +4292,7 @@ namespace System.Management.Automation if (!doCleanup) return; - foreach (ExecutionCmdletHelper helper in helpers) + foreach (ExecutionCmdletHelper helper in _helpers) { // cleanup remote runspace related handlers RemoteRunspace remoteRS = helper.PipelineRunspace as RemoteRunspace; @@ -4308,7 +4305,7 @@ namespace System.Management.Automation StopAggregateResultsFromHelper(helper); } - UnregisterThrottleComplete(throttleManager); + UnregisterThrottleComplete(_throttleManager); //throttleManager = null; Results.DecrementRef(); @@ -4389,16 +4386,16 @@ namespace System.Management.Automation case PipelineState.Completed: case PipelineState.Failed: case PipelineState.Stopped: - pipelineFinishedCount += 1; + _pipelineFinishedCount += 1; break; case PipelineState.Disconnected: - pipelineDisconnectedCount += 1; + _pipelineDisconnectedCount += 1; break; } - setJobStateToDisconnected = ((pipelineFinishedCount + pipelineDisconnectedCount) == this.helpers.Count && - pipelineDisconnectedCount > 0); + setJobStateToDisconnected = ((_pipelineFinishedCount + _pipelineDisconnectedCount) == _helpers.Count && + _pipelineDisconnectedCount > 0); } if (setJobStateToDisconnected) @@ -4414,10 +4411,10 @@ namespace System.Management.Automation /// public override void StopJob() { - throttleManager.StopAllOperations(); + _throttleManager.StopAllOperations(); } - private bool doFinishCalled = false; + private bool _doFinishCalled = false; /// /// This method marks the completion state for Job. Also if job failed, it processes the @@ -4425,23 +4422,23 @@ namespace System.Management.Automation /// protected override void DoFinish() { - if (doFinishCalled == true) + if (_doFinishCalled == true) return; lock (SyncObject) { - if (doFinishCalled == true) + if (_doFinishCalled == true) return; - doFinishCalled = true; + _doFinishCalled = true; } - foreach (ExecutionCmdletHelper helper in helpers) + foreach (ExecutionCmdletHelper helper in _helpers) { DeterminedAndSetJobState(helper); } - if (helpers.Count == 0 && this.JobStateInfo.State == JobState.NotStarted) + if (_helpers.Count == 0 && this.JobStateInfo.State == JobState.NotStarted) { SetJobState(JobState.Completed); } @@ -4458,7 +4455,7 @@ namespace System.Management.Automation { PowerShell powershell = null; - powershells.TryGetValue(instanceId, out powershell); + _powershells.TryGetValue(instanceId, out powershell); return powershell; } @@ -4502,8 +4499,8 @@ namespace System.Management.Automation internal void StartOperations(List operations) { // submit operations to the throttle manager - throttleManager.SubmitOperations(operations); - throttleManager.EndSubmitOperations(); + _throttleManager.SubmitOperations(operations); + _throttleManager.EndSubmitOperations(); } /// @@ -4524,7 +4521,7 @@ namespace System.Management.Automation internal Collection GetPowerShells() { Collection powershellsToReturn = new Collection(); - foreach (PowerShell ps in this.powershells.Values) + foreach (PowerShell ps in _powershells.Values) { powershellsToReturn.Add(ps); } @@ -4539,7 +4536,7 @@ namespace System.Management.Automation internal PSRemotingJob CreateDisconnectedRemotingJob() { List disconnectedJobHelpers = new List(); - foreach (var helper in this.helpers) + foreach (var helper in _helpers) { if (helper.Pipeline.PipelineStateInfo.State == PipelineState.Disconnected) { @@ -4560,7 +4557,6 @@ namespace System.Management.Automation } #endregion Internal Methods - } #region OutputProcessingState class diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index 7db406912..60f094129 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Linq; using System.Collections.Generic; using System.Threading; @@ -23,7 +24,6 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace System.Management.Automation { - #region PowerShell v3 Job Extensions /// @@ -113,7 +113,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("value"); } - lock(_syncobject) + lock (_syncobject) { _parameters = value; } @@ -151,7 +151,7 @@ namespace System.Management.Automation /// Command invoked by this job object /// Friendly name for the job object protected Job2(string command, string name) - :base(command, name) + : base(command, name) { } @@ -449,7 +449,6 @@ namespace System.Management.Automation public event EventHandler UnblockJobCompleted; #endregion State Management - } /// @@ -536,8 +535,8 @@ namespace System.Management.Automation internal PSEventManager EventManager { get { return _eventManager; } - set - { + set + { _tracer.WriteMessage("Setting event manager for Job ", InstanceId); _eventManager = value; } @@ -706,7 +705,7 @@ namespace System.Management.Automation { throw new ArgumentNullException("childJob"); } - _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : " , InstanceId.ToString()); + _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); JobStateInfo childJobStateInfo; lock (childJob.syncObject) @@ -772,7 +771,7 @@ namespace System.Management.Automation { AssertNotDisposed(); _tracer.WriteMessage(TraceClassName, "StartJob", Guid.Empty, this, "Entering method", null); - StructuredTracer.BeginContainerParentJobExecution(InstanceId); + s_structuredTracer.BeginContainerParentJobExecution(InstanceId); // If parent contains no child jobs then this method will hang. Throw error in this case. if (ChildJobs.Count == 0) @@ -861,7 +860,7 @@ namespace System.Management.Automation job.StartJobAsync(); } completed.WaitOne(); - foreach(Job2 job in ChildJobs) + foreach (Job2 job in ChildJobs) { Dbg.Assert(job != null, "Job is null after initial null check"); @@ -881,7 +880,7 @@ namespace System.Management.Automation _tracer.WriteMessage(TraceClassName, "StartJob", Guid.Empty, this, "Exiting method", null); } - private static Tracer StructuredTracer = new Tracer(); + private static Tracer s_structuredTracer = new Tracer(); /// /// Starts all child jobs asynchronously. @@ -895,7 +894,7 @@ namespace System.Management.Automation return; } _tracer.WriteMessage(TraceClassName, "StartJobAsync", Guid.Empty, this, "Entering method", null); - StructuredTracer.BeginContainerParentJobExecution(InstanceId); + s_structuredTracer.BeginContainerParentJobExecution(InstanceId); foreach (Job2 job in this.ChildJobs) { if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); @@ -1778,9 +1777,9 @@ namespace System.Management.Automation if (_finishedChildJobsCount == ChildJobs.Count) { - StructuredTracer.EndContainerParentJobExecution(InstanceId); + s_structuredTracer.EndContainerParentJobExecution(InstanceId); } - } + } } /// @@ -1798,8 +1797,8 @@ namespace System.Management.Automation /// /// true if the job state needs to be modified, false otherwise internal static bool ComputeJobStateFromChildJobStates(string traceClassName, JobStateEventArgs e, - ref int blockedChildJobsCount, ref int suspendedChildJobsCount, ref int suspendingChildJobsCount, ref int finishedChildJobsCount, - ref int failedChildJobsCount, ref int stoppedChildJobsCount, int childJobsCount, + ref int blockedChildJobsCount, ref int suspendedChildJobsCount, ref int suspendingChildJobsCount, ref int finishedChildJobsCount, + ref int failedChildJobsCount, ref int stoppedChildJobsCount, int childJobsCount, out JobState computedJobState) { computedJobState = JobState.NotStarted; @@ -1857,7 +1856,7 @@ namespace System.Management.Automation if (suspendedChildJobsCount + finishedChildJobsCount == childJobsCount) { tracer.WriteMessage(traceClassName, ": JobState is suspended, all child jobs are suspended."); - computedJobState = JobState.Suspended; + computedJobState = JobState.Suspended; return true; } @@ -2023,7 +2022,7 @@ namespace System.Management.Automation StringBuilder sb = new StringBuilder(); - for(int i = 0; i < ChildJobs.Count; i++) + for (int i = 0; i < ChildJobs.Count; i++) { if (!String.IsNullOrEmpty(ChildJobs[i].StatusMessage)) { @@ -2071,7 +2070,7 @@ namespace System.Management.Automation return; } - foreach(var job in ChildJobs) + foreach (var job in ChildJobs) { UnregisterJobEvent(job); } @@ -2122,8 +2121,8 @@ namespace System.Management.Automation /// A ScriptExtent that describes where this error originated from. public JobFailedException(Exception innerException, ScriptExtent displayScriptPosition) { - this.reason = innerException; - this.displayScriptPosition = displayScriptPosition; + _reason = innerException; + _displayScriptPosition = displayScriptPosition; } /// @@ -2134,21 +2133,21 @@ namespace System.Management.Automation protected JobFailedException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { - reason = (Exception) serializationInfo.GetValue("Reason", typeof(Exception)); - displayScriptPosition = (ScriptExtent) serializationInfo.GetValue("DisplayScriptPosition", typeof(ScriptExtent)); + _reason = (Exception)serializationInfo.GetValue("Reason", typeof(Exception)); + _displayScriptPosition = (ScriptExtent)serializationInfo.GetValue("DisplayScriptPosition", typeof(ScriptExtent)); } /// /// The actual exception that caused this error. /// - public Exception Reason { get { return this.reason; } } - private Exception reason; + public Exception Reason { get { return _reason; } } + private Exception _reason; /// /// The user-focused location from where this error originated. /// - public ScriptExtent DisplayScriptPosition { get { return this.displayScriptPosition; } } - private ScriptExtent displayScriptPosition; + public ScriptExtent DisplayScriptPosition { get { return _displayScriptPosition; } } + private ScriptExtent _displayScriptPosition; /// /// Gets the information for serialization @@ -2156,14 +2155,14 @@ namespace System.Management.Automation /// The standard SerializationInfo /// The standard StreaminContext public override void GetObjectData(SerializationInfo info, StreamingContext context) - { + { if (info == null) throw new ArgumentNullException("info"); base.GetObjectData(info, context); - info.AddValue("Reason", reason); - info.AddValue("DisplayScriptPosition", displayScriptPosition); + info.AddValue("Reason", _reason); + info.AddValue("DisplayScriptPosition", _displayScriptPosition); } /// diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 66b0c1688..c8e452451 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Globalization; @@ -27,7 +28,7 @@ namespace System.Management.Automation /// public sealed class JobManager { - private readonly PowerShellTraceSource Tracer = PowerShellTraceSourceFactory.GetTraceSource(); + private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); /// /// Collection of registered JobSourceAdapters. @@ -40,15 +41,15 @@ namespace System.Management.Automation /// /// Collection of job IDs that are valid for reuse. /// - private static readonly Dictionary> JobIdsForReuse = new Dictionary>(); + private static readonly Dictionary> s_jobIdsForReuse = new Dictionary>(); - private static readonly object SyncObject = new object(); + private static readonly object s_syncObject = new object(); /// /// Creates a JobManager instance. /// internal JobManager() - { + { } /// @@ -107,27 +108,27 @@ namespace System.Management.Automation } catch (MemberAccessException exception) { - Tracer.TraceException(exception); + _tracer.TraceException(exception); throw; } catch (TargetInvocationException exception) { - Tracer.TraceException(exception); + _tracer.TraceException(exception); throw; } catch (TargetParameterCountException exception) { - Tracer.TraceException(exception); + _tracer.TraceException(exception); throw; } catch (NotSupportedException exception) { - Tracer.TraceException(exception); + _tracer.TraceException(exception); throw; } catch (SecurityException exception) { - Tracer.TraceException(exception); + _tracer.TraceException(exception); throw; } } @@ -150,10 +151,10 @@ namespace System.Management.Automation /// Token for job creation. internal static JobIdentifier GetJobIdentifier(Guid instanceId, string typeName) { - lock (SyncObject) + lock (s_syncObject) { KeyValuePair keyValuePair; - if (JobIdsForReuse.TryGetValue(instanceId, out keyValuePair) && keyValuePair.Value.Equals(typeName)) + if (s_jobIdsForReuse.TryGetValue(instanceId, out keyValuePair) && keyValuePair.Value.Equals(typeName)) return new JobIdentifier(keyValuePair.Key, instanceId); return null; } @@ -168,10 +169,10 @@ namespace System.Management.Automation /// The type name for the JobSourceAdapter implementation doing the save. internal static void SaveJobId(Guid instanceId, int id, string typeName) { - lock (SyncObject) + lock (s_syncObject) { - if (JobIdsForReuse.ContainsKey(instanceId)) return; - JobIdsForReuse.Add(instanceId, new KeyValuePair(id, typeName)); + if (s_jobIdsForReuse.ContainsKey(instanceId)) return; + s_jobIdsForReuse.Add(instanceId, new KeyValuePair(id, typeName)); } } @@ -209,7 +210,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.NewJob returned unknown error. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } @@ -232,7 +233,7 @@ namespace System.Management.Automation if (specification == null) { throw new ArgumentNullException("specification"); - } + } if (specification.Definition == null) { @@ -255,14 +256,14 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.NewJob returned unknown error. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } #pragma warning restore 56500 return newJob; - } + } #endregion NewJob @@ -298,7 +299,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.NewJob returned unknown error. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } @@ -431,8 +432,8 @@ namespace System.Management.Automation /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobs( - Cmdlet cmdlet, - bool writeErrorOnException, + Cmdlet cmdlet, + bool writeErrorOnException, bool writeObject, string[] jobSourceAdapterTypes) { @@ -454,10 +455,10 @@ namespace System.Management.Automation /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByName( - string name, - Cmdlet cmdlet, - bool writeErrorOnException, - bool writeObject, + string name, + Cmdlet cmdlet, + bool writeErrorOnException, + bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { @@ -478,10 +479,10 @@ namespace System.Management.Automation /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByCommand( - string command, - Cmdlet cmdlet, - bool writeErrorOnException, - bool writeObject, + string command, + Cmdlet cmdlet, + bool writeErrorOnException, + bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { @@ -502,10 +503,10 @@ namespace System.Management.Automation /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. internal List GetJobsByState( - JobState state, - Cmdlet cmdlet, - bool writeErrorOnException, - bool writeObject, + JobState state, + Cmdlet cmdlet, + bool writeErrorOnException, + bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { @@ -541,7 +542,7 @@ namespace System.Management.Automation { lock (_syncObject) { - foreach (JobSourceAdapter sourceAdapter in this._sourceAdapters.Values) + foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { if (sourceAdapter.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { @@ -568,11 +569,11 @@ namespace System.Management.Automation /// If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation. private List GetFilteredJobs( - object filter, - FilterType filterType, - Cmdlet cmdlet, - bool writeErrorOnException, - bool writeObject, + object filter, + FilterType filterType, + Cmdlet cmdlet, + bool writeErrorOnException, + bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { @@ -582,7 +583,7 @@ namespace System.Management.Automation lock (_syncObject) { - foreach (JobSourceAdapter sourceAdapter in this._sourceAdapters.Values) + foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { List jobs = null; @@ -605,7 +606,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.GetJobsByFilter() threw unknown exception. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobsError", sourceAdapter); } @@ -685,7 +686,7 @@ namespace System.Management.Automation switch (filterType) { case FilterType.Command: - + matches = sourceAdapter.GetJobsByCommand((string)filter, recurse); break; case FilterType.Filter: @@ -772,7 +773,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.GetJobByInstanceId threw unknown exception. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); @@ -810,7 +811,7 @@ namespace System.Management.Automation bool writeErrorOnException) { List jobs = new List(); - WildcardPattern typeNamePattern = (definitionType != null) ? + WildcardPattern typeNamePattern = (definitionType != null) ? WildcardPattern.Get(definitionType, WildcardOptions.IgnoreCase) : null; lock (_syncObject) @@ -847,7 +848,7 @@ namespace System.Management.Automation // other cases the appropriate exception // needs to be caught. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); @@ -862,7 +863,6 @@ namespace System.Management.Automation { try { - if (writeErrorOnException) { cmdlet.WriteError(new ErrorRecord(exception, identifier, ErrorCategory.OpenError, sourceAdapter)); @@ -877,7 +877,7 @@ namespace System.Management.Automation cmdlet.WriteWarning(message); } } - catch(Exception) + catch (Exception) { // if this call is not made from a cmdlet thread or if // the cmdlet is closed this will thrown an exception @@ -895,7 +895,7 @@ namespace System.Management.Automation List adapterNames = new List(); lock (_syncObject) { - foreach (JobSourceAdapter sourceAdapter in this._sourceAdapters.Values) + foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { if (CheckTypeNames(sourceAdapter, adapterTypeNames)) { @@ -954,7 +954,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.GetJobByInstanceId() threw unknown exception. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); if (throwExceptions) throw; WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter); @@ -978,7 +978,7 @@ namespace System.Management.Automation // needs to be caught. // sourceAdapter.RemoveJob() threw unknown exception. - Tracer.TraceException(exception); + _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); if (throwExceptions) throw; WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter); @@ -1007,9 +1007,9 @@ namespace System.Management.Automation private void RemoveJobIdForReuseHelper(Hashtable duplicateDetector, Job job) { - lock (SyncObject) + lock (s_syncObject) { - JobIdsForReuse.Remove(job.InstanceId); + s_jobIdsForReuse.Remove(job.InstanceId); } foreach (Job child in job.ChildJobs) diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index 7927de6be..be23436c5 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -166,7 +167,7 @@ namespace System.Management.Automation protected JobDefinition(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); - } + } /// /// @@ -209,7 +210,7 @@ namespace System.Management.Automation _name = value; } } - string _name = string.Empty; + private string _name = string.Empty; private string _command; @@ -289,7 +290,7 @@ namespace System.Management.Automation /// Constructor. /// protected JobInvocationInfo() - { } + { } /// /// Create a new job definition with a single set of parameters. @@ -456,7 +457,7 @@ namespace System.Management.Automation duplicateDetector.Add(job.InstanceId, job.InstanceId); JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name); - + if (!recurse || job.ChildJobs == null) return; foreach (Job child in job.ChildJobs) { @@ -473,7 +474,7 @@ namespace System.Management.Automation /// job object public Job2 NewJob(JobDefinition definition) { - return NewJob(new JobInvocationInfo(definition, new Dictionary())); + return NewJob(new JobInvocationInfo(definition, new Dictionary())); } /// diff --git a/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs b/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs index 4915b94fb..15b689f99 100644 --- a/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/PSProxyJob.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -185,7 +186,7 @@ namespace System.Management.Automation /// /// /// - public override void StopJob(bool force, string reason) + public override void StopJob(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyJobControlNotSupported); } @@ -195,7 +196,7 @@ namespace System.Management.Automation /// /// /// - public override void StopJobAsync(bool force, string reason) + public override void StopJobAsync(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyJobControlNotSupported); } @@ -260,7 +261,7 @@ namespace System.Management.Automation /// /// /// - public override void SuspendJob(bool force, string reason) + public override void SuspendJob(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyJobControlNotSupported); } @@ -270,7 +271,7 @@ namespace System.Management.Automation /// /// /// - public override void SuspendJobAsync(bool force, string reason) + public override void SuspendJobAsync(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyJobControlNotSupported); } @@ -348,7 +349,7 @@ namespace System.Management.Automation } #endregion - + #region Additional State Management Methods /// @@ -471,7 +472,7 @@ namespace System.Management.Automation // this is true. if (!_removeCalled) { - Diagnostics.Assert(false, "remove called is false after calling remove. No exception was thrown."); + Diagnostics.Assert(false, "remove called is false after calling remove. No exception was thrown."); return; } } @@ -799,7 +800,7 @@ namespace System.Management.Automation Collection jobs = new Collection(); foreach (var deserializedJob in jobResults) - { + { if (!Deserializer.IsDeserializedInstanceOfType(deserializedJob, typeof(Job))) { // Do not create proxies if jobs are live. @@ -1194,7 +1195,7 @@ namespace System.Management.Automation _tracer.WriteMessage(ClassNameTrace, "DoStartAsync", _remoteJobInstanceId, this, "Starting command invocation.", null); - StructuredTracer.BeginProxyJobExecution(InstanceId); + s_structuredTracer.BeginProxyJobExecution(InstanceId); DoStartPrepare(); @@ -1412,7 +1413,6 @@ namespace System.Management.Automation { DoSetJobState(JobState.Stopped); } - } catch (Exception) { @@ -1632,7 +1632,7 @@ namespace System.Management.Automation TryGetJobPropertyValue(o, "StatusMessage", out _remoteJobStatusMessage); TryGetJobPropertyValue(o, "Location", out _remoteJobLocation); - StructuredTracer.ProxyJobRemoteJobAssociation(InstanceId, _remoteJobInstanceId); + s_structuredTracer.ProxyJobRemoteJobAssociation(InstanceId, _remoteJobInstanceId); string name; TryGetJobPropertyValue(o, "Name", out name); @@ -1785,13 +1785,14 @@ namespace System.Management.Automation { JobState computedJobState; if (!ContainerParentJob.ComputeJobStateFromChildJobStates(ClassNameTrace, e, ref _blockedChildJobsCount, - ref _suspendedChildJobsCount, + ref _suspendedChildJobsCount, ref _suspendingChildJobsCount, - ref _finishedChildJobsCount, - ref _failedChildJobsCount, - ref _stoppedChildJobsCount, + ref _finishedChildJobsCount, + ref _failedChildJobsCount, + ref _stoppedChildJobsCount, ChildJobs.Count, - out computedJobState)) return; + out computedJobState)) + return; if (computedJobState == JobState.Suspending) return; // Ignor for proxy job _tracer.WriteMessage(ClassNameTrace, "HandleChildProxyJobStateChanged", Guid.Empty, this, @@ -1999,10 +2000,10 @@ namespace System.Management.Automation { _tracer.WriteMessage(ClassNameTrace, "DoSetJobState", _remoteJobInstanceId, this, "BEGIN Set job state to {0} and call event handlers", state.ToString()); - StructuredTracer.EndProxyJobExecution(InstanceId); - StructuredTracer.BeginProxyJobEventHandler(InstanceId); + s_structuredTracer.EndProxyJobExecution(InstanceId); + s_structuredTracer.BeginProxyJobEventHandler(InstanceId); SetJobState(state, reason); - StructuredTracer.EndProxyJobEventHandler(InstanceId); + s_structuredTracer.EndProxyJobEventHandler(InstanceId); _tracer.WriteMessage(ClassNameTrace, "DoSetJobState", _remoteJobInstanceId, this, "END Set job state to {0} and call event handlers", state.ToString()); } @@ -2050,7 +2051,6 @@ namespace System.Management.Automation // as an indication of a failed command execution. if (!Deserializer.IsDeserializedInstanceOfType(newObject, typeof(Job))) { - _tracer.WriteMessage(ClassNameTrace, "DataAddedToOutput", _remoteJobInstanceId, this, "Setting job state to failed. Command did not return a job object.", null); @@ -2122,12 +2122,11 @@ namespace System.Management.Automation _tracer.WriteMessage(ClassNameTrace, "DataAddedToOutput", Guid.Empty, this, "Updating child job {0} state to {1} ", sourceJobId.ToString(), jobStateEventArgs.JobStateInfo.State.ToString()); - ((PSChildJobProxy) _childJobsMapping[sourceJobId]).DoSetJobState( + ((PSChildJobProxy)_childJobsMapping[sourceJobId]).DoSetJobState( jobStateEventArgs.JobStateInfo.State, jobStateEventArgs.JobStateInfo.Reason); _tracer.WriteMessage(ClassNameTrace, "DataAddedToOutput", Guid.Empty, this, "Finished updating child job {0} state to {1} ", sourceJobId.ToString(), jobStateEventArgs.JobStateInfo.State.ToString()); - } return; } @@ -2491,7 +2490,7 @@ namespace System.Management.Automation private JobState _previousState = JobState.NotStarted; private JobState _computedJobState; private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - private static Tracer StructuredTracer = new Tracer(); + private static Tracer s_structuredTracer = new Tracer(); private bool _jobInitialized; private bool _removeCalled; private bool _startCalled; @@ -2607,7 +2606,7 @@ namespace System.Management.Automation OnJobDataAdded(new JobDataAddedEventArgs(this, PowerShellStreamType.Information, e.Index)); } - private static Tracer StructuredTracer = new Tracer(); + private static Tracer s_structuredTracer = new Tracer(); internal void DoSetJobState(JobState state, Exception reason = null) { if (_disposed) return; @@ -2661,9 +2660,9 @@ namespace System.Management.Automation Dbg.Assert(state != JobStateInfo.State, "Setting job state should always change the state."); _tracer.WriteMessage("PSChildJobProxy", "DoSetJobState", Guid.Empty, this, "BEGIN Set job state to {0} and call event handlers", state.ToString()); - StructuredTracer.BeginProxyChildJobEventHandler(InstanceId); + s_structuredTracer.BeginProxyChildJobEventHandler(InstanceId); SetJobState(state, reason); - StructuredTracer.EndProxyJobEventHandler(InstanceId); + s_structuredTracer.EndProxyJobEventHandler(InstanceId); _tracer.WriteMessage("PSChildJobProxy", "DoSetJobState", Guid.Empty, this, "END Set job state to {0} and call event handlers", state.ToString()); } @@ -2719,7 +2718,7 @@ namespace System.Management.Automation /// /// /// - public override void StopJob(bool force, string reason) + public override void StopJob(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyChildJobControlNotSupported); } @@ -2763,7 +2762,7 @@ namespace System.Management.Automation /// /// /// - public override void SuspendJob(bool force, string reason) + public override void SuspendJob(bool force, string reason) { throw PSTraceSource.NewNotSupportedException(PowerShellStrings.ProxyChildJobControlNotSupported); } diff --git a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs index 73e30ac7a..11c304f5b 100644 --- a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs +++ b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs @@ -12,68 +12,68 @@ namespace System.Management.Automation /// /// Input stream for incoming objects. /// - private PSDataCollection inputStream; - + private PSDataCollection _inputStream; + /// /// Output stream for returned objects. /// - private PSDataCollection outputStream; + private PSDataCollection _outputStream; /// /// Error stream for error messages. /// - private PSDataCollection errorStream; + private PSDataCollection _errorStream; /// /// Warning stream for warning messages. /// - private PSDataCollection warningStream; + private PSDataCollection _warningStream; /// /// Progress stream for progress messages. /// - private PSDataCollection progressStream; + private PSDataCollection _progressStream; /// /// Verbose stream for verbose messages. /// - private PSDataCollection verboseStream; + private PSDataCollection _verboseStream; /// /// Debug stream for debug messages. /// - private PSDataCollection debugStream; + private PSDataCollection _debugStream; /// /// Information stream for Information messages. /// - private PSDataCollection informationStream; + private PSDataCollection _informationStream; /// /// If the object is already disposed or not. /// - private bool disposed; + private bool _disposed; /// /// Private object for thread-safe exection. /// - private readonly object syncLock = new object(); + private readonly object _syncLock = new object(); /// /// Default constructor. /// public PowerShellStreams() { - this.inputStream = null; - this.outputStream = null; - this.errorStream = null; - this.warningStream = null; - this.progressStream = null; - this.verboseStream = null; - this.debugStream = null; - this.informationStream = null; + _inputStream = null; + _outputStream = null; + _errorStream = null; + _warningStream = null; + _progressStream = null; + _verboseStream = null; + _debugStream = null; + _informationStream = null; - this.disposed = false; + _disposed = false; } /// @@ -84,24 +84,24 @@ namespace System.Management.Automation // Populate the input collection if there is any... if (pipelineInput == null) { - inputStream = new PSDataCollection(); + _inputStream = new PSDataCollection(); } else { - inputStream = pipelineInput; + _inputStream = pipelineInput; } - inputStream.Complete(); + _inputStream.Complete(); - this.outputStream = new PSDataCollection(); - this.errorStream = new PSDataCollection(); - this.warningStream = new PSDataCollection(); - this.progressStream = new PSDataCollection(); - this.verboseStream = new PSDataCollection(); - this.debugStream = new PSDataCollection(); - this.informationStream = new PSDataCollection(); + _outputStream = new PSDataCollection(); + _errorStream = new PSDataCollection(); + _warningStream = new PSDataCollection(); + _progressStream = new PSDataCollection(); + _verboseStream = new PSDataCollection(); + _debugStream = new PSDataCollection(); + _informationStream = new PSDataCollection(); - this.disposed = false; + _disposed = false; } /// @@ -119,35 +119,35 @@ namespace System.Management.Automation /// private void Dispose(bool disposing) { - if (this.disposed) + if (_disposed) return; - lock (syncLock) + lock (_syncLock) { - if (!this.disposed) + if (!_disposed) { if (disposing) { - this.inputStream.Dispose(); - this.outputStream.Dispose(); - this.errorStream.Dispose(); - this.warningStream.Dispose(); - this.progressStream.Dispose(); - this.verboseStream.Dispose(); - this.debugStream.Dispose(); - this.informationStream.Dispose(); + _inputStream.Dispose(); + _outputStream.Dispose(); + _errorStream.Dispose(); + _warningStream.Dispose(); + _progressStream.Dispose(); + _verboseStream.Dispose(); + _debugStream.Dispose(); + _informationStream.Dispose(); - this.inputStream = null; - this.outputStream = null; - this.errorStream = null; - this.warningStream = null; - this.progressStream = null; - this.verboseStream = null; - this.debugStream = null; - this.informationStream = null; + _inputStream = null; + _outputStream = null; + _errorStream = null; + _warningStream = null; + _progressStream = null; + _verboseStream = null; + _debugStream = null; + _informationStream = null; } - this.disposed = true; + _disposed = true; } } } @@ -158,8 +158,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection InputStream { - get { return this.inputStream; } - set { this.inputStream = value; } + get { return _inputStream; } + set { _inputStream = value; } } /// @@ -168,8 +168,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection OutputStream { - get { return this.outputStream; } - set { this.outputStream = value; } + get { return _outputStream; } + set { _outputStream = value; } } /// @@ -178,8 +178,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection ErrorStream { - get { return this.errorStream; } - set { this.errorStream = value; } + get { return _errorStream; } + set { _errorStream = value; } } /// @@ -188,8 +188,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection WarningStream { - get { return this.warningStream; } - set { this.warningStream = value; } + get { return _warningStream; } + set { _warningStream = value; } } /// @@ -198,8 +198,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection ProgressStream { - get { return this.progressStream; } - set { this.progressStream = value; } + get { return _progressStream; } + set { _progressStream = value; } } /// @@ -208,8 +208,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection VerboseStream { - get { return this.verboseStream; } - set { this.verboseStream = value; } + get { return _verboseStream; } + set { _verboseStream = value; } } /// @@ -218,8 +218,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection DebugStream { - get { return this.debugStream; } - set { this.debugStream = value; } + get { return _debugStream; } + set { _debugStream = value; } } /// @@ -228,8 +228,8 @@ namespace System.Management.Automation [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSDataCollection InformationStream { - get { return this.informationStream; } - set { this.informationStream = value; } + get { return _informationStream; } + set { _informationStream = value; } } /// @@ -238,19 +238,19 @@ namespace System.Management.Automation /// public void CloseAll() { - if (this.disposed == false) + if (_disposed == false) { - lock (syncLock) + lock (_syncLock) { - if (this.disposed == false) + if (_disposed == false) { - this.outputStream.Complete(); - this.errorStream.Complete(); - this.warningStream.Complete(); - this.progressStream.Complete(); - this.verboseStream.Complete(); - this.debugStream.Complete(); - this.informationStream.Complete(); + _outputStream.Complete(); + _errorStream.Complete(); + _warningStream.Complete(); + _progressStream.Complete(); + _verboseStream.Complete(); + _debugStream.Complete(); + _informationStream.Complete(); } } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 3b2d70a60..4d9d6a98e 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -25,7 +25,7 @@ namespace System.Management.Automation.Runspaces.Internal internal class RemoteRunspacePoolInternal : RunspacePoolInternal, IDisposable { #region Constructor - + /// /// Constructor which creates a RunspacePool using the /// supplied , @@ -74,18 +74,18 @@ namespace System.Management.Automation.Runspaces.Internal } PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, - PSOpcode.Constructor, PSTask.CreateRunspace, + PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, - instanceId.ToString(), - minPoolSz.ToString(CultureInfo.InvariantCulture), + instanceId.ToString(), + minPoolSz.ToString(CultureInfo.InvariantCulture), maxPoolSz.ToString(CultureInfo.InvariantCulture)); - this.connectionInfo = connectionInfo.InternalCopy(); + _connectionInfo = connectionInfo.InternalCopy(); this.host = host; - this.applicationArguments = applicationArguments; - this.availableForConnection = false; - dispatchTable = new DispatchTable(); + _applicationArguments = applicationArguments; + _availableForConnection = false; + _dispatchTable = new DispatchTable(); _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack(); if (!string.IsNullOrEmpty(name)) @@ -125,7 +125,7 @@ namespace System.Management.Automation.Runspaces.Internal if (connectionInfo is WSManConnectionInfo) { - this.connectionInfo = connectionInfo.InternalCopy(); + _connectionInfo = connectionInfo.InternalCopy(); } else { @@ -147,10 +147,10 @@ namespace System.Management.Automation.Runspaces.Internal minPoolSz.ToString(CultureInfo.InvariantCulture), maxPoolSz.ToString(CultureInfo.InvariantCulture)); - this.connectCommands = connectCommands; + _connectCommands = connectCommands; this.Name = name; this.host = host; - this.dispatchTable = new DispatchTable(); + _dispatchTable = new DispatchTable(); _runningPowerShells = new System.Collections.Concurrent.ConcurrentStack(); // Create this object in the disconnected state. @@ -158,7 +158,7 @@ namespace System.Management.Automation.Runspaces.Internal CreateDSHandler(typeTable); - this.availableForConnection = isDisconnected; + _availableForConnection = isDisconnected; } /// @@ -166,34 +166,34 @@ namespace System.Management.Automation.Runspaces.Internal /// private void CreateDSHandler(TypeTable typeTable) { - dataStructureHandler = new ClientRunspacePoolDataStructureHandler(this, typeTable); + _dataStructureHandler = new ClientRunspacePoolDataStructureHandler(this, typeTable); // register for events from the data structure handler - dataStructureHandler.RemoteHostCallReceived += + _dataStructureHandler.RemoteHostCallReceived += new EventHandler>(HandleRemoteHostCalls); - dataStructureHandler.StateInfoReceived += + _dataStructureHandler.StateInfoReceived += new EventHandler>(HandleStateInfoReceived); - dataStructureHandler.RSPoolInitInfoReceived += + _dataStructureHandler.RSPoolInitInfoReceived += new EventHandler>(HandleInitInfoReceived); - dataStructureHandler.ApplicationPrivateDataReceived += + _dataStructureHandler.ApplicationPrivateDataReceived += new EventHandler>(HandleApplicationPrivateDataReceived); - dataStructureHandler.SessionClosing += + _dataStructureHandler.SessionClosing += new EventHandler>(HandleSessionClosing); - dataStructureHandler.SessionClosed += + _dataStructureHandler.SessionClosed += new EventHandler>(HandleSessionClosed); - dataStructureHandler.SetMaxMinRunspacesResponseRecieved += + _dataStructureHandler.SetMaxMinRunspacesResponseRecieved += new EventHandler>(HandleResponseReceived); - dataStructureHandler.URIRedirectionReported += + _dataStructureHandler.URIRedirectionReported += new EventHandler>(HandleURIDirectionReported); - dataStructureHandler.PSEventArgsReceived += + _dataStructureHandler.PSEventArgsReceived += new EventHandler>(HandlePSEventArgsReceived); - dataStructureHandler.SessionDisconnected += + _dataStructureHandler.SessionDisconnected += new EventHandler>(HandleSessionDisconnected); - dataStructureHandler.SessionReconnected += + _dataStructureHandler.SessionReconnected += new EventHandler>(HandleSessionReconnected); - dataStructureHandler.SessionRCDisconnecting += + _dataStructureHandler.SessionRCDisconnecting += new EventHandler>(HandleSessionRCDisconnecting); - dataStructureHandler.SessionCreateCompleted += + _dataStructureHandler.SessionCreateCompleted += new EventHandler(HandleSessionCreateCompleted); } @@ -208,7 +208,7 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return connectionInfo; + return _connectionInfo; } } @@ -220,7 +220,7 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return dataStructureHandler; + return _dataStructureHandler; } } @@ -230,8 +230,8 @@ namespace System.Management.Automation.Runspaces.Internal /// internal ConnectCommandInfo[] ConnectCommands { - get { return this.connectCommands; } - set { this.connectCommands = value; } + get { return _connectCommands; } + set { _connectCommands = value; } } /// @@ -239,17 +239,17 @@ namespace System.Management.Automation.Runspaces.Internal /// internal string Name { - get { return this.friendlyName; } + get { return _friendlyName; } set { if (value == null) { - this.friendlyName = string.Empty; + _friendlyName = string.Empty; } else { - this.friendlyName = value; + _friendlyName = value; } } } @@ -259,7 +259,7 @@ namespace System.Management.Automation.Runspaces.Internal /// internal bool AvailableForConnection { - get { return this.availableForConnection; } + get { return _availableForConnection; } } /// @@ -269,7 +269,7 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return (dataStructureHandler != null) ? dataStructureHandler.MaxRetryConnectionTime : 0; + return (_dataStructureHandler != null) ? _dataStructureHandler.MaxRetryConnectionTime : 0; } } @@ -334,7 +334,7 @@ namespace System.Management.Automation.Runspaces.Internal lock (syncObject) { callId = DispatchTable.CreateNewCallId(); - dataStructureHandler.SendResetRunspaceStateToServer(callId); + _dataStructureHandler.SendResetRunspaceStateToServer(callId); } // This call blocks until the response is received. @@ -386,7 +386,7 @@ namespace System.Management.Automation.Runspaces.Internal // they were called in the client callId = DispatchTable.CreateNewCallId(); - dataStructureHandler.SendSetMaxRunspacesToServer(maxRunspaces, callId); + _dataStructureHandler.SendSetMaxRunspacesToServer(maxRunspaces, callId); } // lock ... // this call blocks until the response is received @@ -426,8 +426,8 @@ namespace System.Management.Automation.Runspaces.Internal lock (syncObject) { - if ((minRunspaces < 1) || (minRunspaces > maxPoolSz) || (minRunspaces == minPoolSz) - || stateInfo.State == RunspacePoolState.Closed || stateInfo.State == RunspacePoolState.Closing || + if ((minRunspaces < 1) || (minRunspaces > maxPoolSz) || (minRunspaces == minPoolSz) + || stateInfo.State == RunspacePoolState.Closed || stateInfo.State == RunspacePoolState.Closing || stateInfo.State == RunspacePoolState.Broken) { return false; @@ -436,7 +436,7 @@ namespace System.Management.Automation.Runspaces.Internal // if the runspace pool is not opened as yet, or is in Disconnected state. // just change the value locally. No need to // send a message - if (stateInfo.State == RunspacePoolState.BeforeOpen || + if (stateInfo.State == RunspacePoolState.BeforeOpen || stateInfo.State == RunspacePoolState.Disconnected) { minPoolSz = minRunspaces; @@ -449,8 +449,7 @@ namespace System.Management.Automation.Runspaces.Internal // they were called in the client callId = DispatchTable.CreateNewCallId(); - dataStructureHandler.SendSetMinRunspacesToServer(minRunspaces, callId); - + _dataStructureHandler.SendSetMinRunspacesToServer(minRunspaces, callId); } // lock ... // this call blocks until the response is received @@ -501,14 +500,14 @@ namespace System.Management.Automation.Runspaces.Internal return maxPoolSz; } - dataStructureHandler.SendGetAvailableRunspacesToServer(callId); + _dataStructureHandler.SendGetAvailableRunspacesToServer(callId); } // lock ... // this call blocks until the response is received - object response = dispatchTable.GetResponse(callId, 0); + object response = _dispatchTable.GetResponse(callId, 0); availableRunspaces = (int)response; - return availableRunspaces; + return availableRunspaces; } /// @@ -530,7 +529,7 @@ namespace System.Management.Automation.Runspaces.Internal bool raiseEvents = false; - lock(syncObject) + lock (syncObject) { minPoolSz = eventArgs.Data.MinRunspaces; maxPoolSz = eventArgs.Data.MaxRunspaces; @@ -558,7 +557,7 @@ namespace System.Management.Automation.Runspaces.Internal /// /// argument describing this event /// sender of this event - internal void HandleStateInfoReceived(object sender, + internal void HandleStateInfoReceived(object sender, RemoteDataEventArgs eventArgs) { RunspacePoolStateInfo newStateInfo = eventArgs.Data; @@ -598,7 +597,7 @@ namespace System.Management.Automation.Runspaces.Internal } if (stateInfo.State == RunspacePoolState.Opening - || stateInfo.State == RunspacePoolState.Opened + || stateInfo.State == RunspacePoolState.Opened || stateInfo.State == RunspacePoolState.Closing) { doClose = true; @@ -611,10 +610,10 @@ namespace System.Management.Automation.Runspaces.Internal // if closeAsyncResult is null, BeginClose is not called. That means // we are getting close event from server, in this case release the // local resources - if (null == closeAsyncResult) + if (null == _closeAsyncResult) { // Close the local resources. - dataStructureHandler.CloseRunspacePoolAsync(); + _dataStructureHandler.CloseRunspacePoolAsync(); } // Delay notifying upper layers of finished state change event @@ -647,10 +646,10 @@ namespace System.Management.Automation.Runspaces.Internal else { RemoteHostResponse remoteHostResponse = hostCall.ExecuteNonVoidMethod(host); - dataStructureHandler.SendHostResponseToServer(remoteHostResponse); + _dataStructureHandler.SendHostResponseToServer(remoteHostResponse); } } - } + } internal PSHost Host { @@ -667,11 +666,11 @@ namespace System.Management.Automation.Runspaces.Internal { get { - return applicationArguments; + return _applicationArguments; } } - private PSPrimitiveDictionary applicationArguments; + private PSPrimitiveDictionary _applicationArguments; /// /// Private data to be used by applications built on top of PowerShell. @@ -681,29 +680,29 @@ namespace System.Management.Automation.Runspaces.Internal /// - unless the runspace is disconnected and data hasn't been received in which case it returns null immediately. /// internal override PSPrimitiveDictionary GetApplicationPrivateData() - { + { if (this.RunspacePoolStateInfo.State == RunspacePoolState.Disconnected && - !this.applicationPrivateDataReceived.WaitOne(0)) + !_applicationPrivateDataReceived.WaitOne(0)) { // Runspace pool was disconnected before application data was returned. Application // data cannot be returned with the runspace pool disconnected so return null. return null; } - return this.applicationPrivateData; + return _applicationPrivateData; } internal void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { lock (this.syncObject) { - if (this.applicationPrivateDataReceived.WaitOne(0)) + if (_applicationPrivateDataReceived.WaitOne(0)) { return; // ignore server's attempt to set application private data if it has already been set } - this.applicationPrivateData = applicationPrivateData; - this.applicationPrivateDataReceived.Set(); + _applicationPrivateData = applicationPrivateData; + _applicationPrivateDataReceived.Set(); foreach (Runspace runspace in this.runspaceList) { @@ -714,14 +713,14 @@ namespace System.Management.Automation.Runspaces.Internal internal override void PropagateApplicationPrivateData(Runspace runspace) { - if (this.applicationPrivateDataReceived.WaitOne(0)) + if (_applicationPrivateDataReceived.WaitOne(0)) { runspace.SetApplicationPrivateData(this.GetApplicationPrivateData()); } } - private PSPrimitiveDictionary applicationPrivateData; - private ManualResetEvent applicationPrivateDataReceived = new ManualResetEvent(false); + private PSPrimitiveDictionary _applicationPrivateData; + private ManualResetEvent _applicationPrivateDataReceived = new ManualResetEvent(false); /// /// This event is raised, when a host call is for a remote runspace @@ -745,7 +744,7 @@ namespace System.Management.Automation.Runspaces.Internal /// internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) { - dataStructureHandler.CreatePowerShellOnServerAndInvoke(shell); + _dataStructureHandler.CreatePowerShellOnServerAndInvoke(shell); // send any input that may be available if (!shell.NoInput) @@ -761,7 +760,7 @@ namespace System.Management.Automation.Runspaces.Internal /// ClientPowerShellDataStructureHandler for PowerShell. internal void AddRemotePowerShellDSHandler(Guid psShellInstanceId, ClientPowerShellDataStructureHandler psDSHandler) { - this.dataStructureHandler.AddRemotePowerShellDSHandler(psShellInstanceId, psDSHandler); + _dataStructureHandler.AddRemotePowerShellDSHandler(psShellInstanceId, psDSHandler); } /// @@ -772,12 +771,12 @@ namespace System.Management.Automation.Runspaces.Internal get { Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion; - if (remoteProtocolVersionDeclaredByServer != null && dataStructureHandler != null) + if (remoteProtocolVersionDeclaredByServer != null && _dataStructureHandler != null) { // Disconnect/Connect support is currently only provided by the WSMan transport // that is running PSRP protocol version 2.2 and greater. return (remoteProtocolVersionDeclaredByServer >= RemotingConstants.ProtocolVersionWin8RTM && - dataStructureHandler.EndpointSupportsDisconnect); + _dataStructureHandler.EndpointSupportsDisconnect); } return false; @@ -885,7 +884,7 @@ namespace System.Management.Automation.Runspaces.Internal PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational); - TelemetryAPI.ReportRemoteSessionCreated(connectionInfo); + TelemetryAPI.ReportRemoteSessionCreated(_connectionInfo); lock (syncObject) { @@ -902,12 +901,12 @@ namespace System.Management.Automation.Runspaces.Internal RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult( instanceId, callback, asyncState, true); - openAsyncResult = asyncResult; - + _openAsyncResult = asyncResult; + // send a message using the data structure handler to open the RunspacePool // on the remote server - dataStructureHandler.CreateRunspacePoolAndOpenAsync(); + _dataStructureHandler.CreateRunspacePoolAndOpenAsync(); return asyncResult; } @@ -979,15 +978,15 @@ namespace System.Management.Automation.Runspaces.Internal copyState = stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closed, null); raiseEvents = true; skipClosing = true; - closeAsyncResult = null; + _closeAsyncResult = null; asyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); } else if (stateInfo.State == RunspacePoolState.Opened || stateInfo.State == RunspacePoolState.Opening) { copyState = stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Closing, null); - closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); - asyncResult = closeAsyncResult; + _closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); + asyncResult = _closeAsyncResult; raiseEvents = true; } else if (stateInfo.State == RunspacePoolState.Disconnected || @@ -996,12 +995,12 @@ namespace System.Management.Automation.Runspaces.Internal { // Continue with closing so the PSRP layer is aware that the client side session is // being closed. This will result in a broken session on the client. - closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); - asyncResult = closeAsyncResult; + _closeAsyncResult = new RunspacePoolAsyncResult(instanceId, callback, asyncState, false); + asyncResult = _closeAsyncResult; } else if (stateInfo.State == RunspacePoolState.Closing) { - return closeAsyncResult; + return _closeAsyncResult; } } @@ -1017,7 +1016,7 @@ namespace System.Management.Automation.Runspaces.Internal // send a message using the data structure handler to close the RunspacePool // on the remote server - dataStructureHandler.CloseRunspacePoolAsync(); + _dataStructureHandler.CloseRunspacePoolAsync(); } else { @@ -1076,8 +1075,8 @@ namespace System.Management.Automation.Runspaces.Internal RunspacePoolAsyncResult asyncResult = new RunspacePoolAsyncResult( instanceId, callback, state, false); - disconnectAsyncResult = asyncResult; - dataStructureHandler.DisconnectPoolAsync(); + _disconnectAsyncResult = asyncResult; + _dataStructureHandler.DisconnectPoolAsync(); // Return local reference to async object since the class member can // be asynchronously nulled if the session closes suddenly. @@ -1111,7 +1110,7 @@ namespace System.Management.Automation.Runspaces.Internal (rsAsyncResult.IsAssociatedWithAsyncOpen)) { throw PSTraceSource.NewArgumentException("asyncResult", - RunspacePoolStrings.AsyncResultNotOwned, + RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); } @@ -1171,19 +1170,19 @@ namespace System.Management.Automation.Runspaces.Internal RunspacePoolAsyncResult ret = new RunspacePoolAsyncResult( instanceId, callback, state, false); - if (this.canReconnect) + if (_canReconnect) { // This indicates a reconnect scenario where this object instance was previously // disconnected. - reconnectAsyncResult = ret; - dataStructureHandler.ReconnectPoolAsync(); + _reconnectAsyncResult = ret; + _dataStructureHandler.ReconnectPoolAsync(); } else { // This indicates a reconstruction scenario where this object was created // in the disconnect state and is being connected for the first time. - openAsyncResult = ret; - dataStructureHandler.ConnectPoolAsync(); + _openAsyncResult = ret; + _dataStructureHandler.ConnectPoolAsync(); } if (raiseEvents) @@ -1369,7 +1368,7 @@ namespace System.Management.Automation.Runspaces.Internal // At this point we don't know if the runspace pool we want to connect to has just one runspace // (a RemoteRunspace/PSSession) or multiple runspaces in its pool. We do have an array of // running command information which will indicate a runspace pool if the count is gt one. - RunspacePool runspacePool = new RunspacePool(isDisconnected, shellId, strName, + RunspacePool runspacePool = new RunspacePool(isDisconnected, shellId, strName, connectCmdInfos.ToArray(), wsmanConnectionInfo, host, typeTable); discRunspacePools.Add(runspacePool); } @@ -1389,7 +1388,7 @@ namespace System.Management.Automation.Runspaces.Internal } private static void UpdateWSManConnectionInfo( - WSManConnectionInfo wsmanConnectionInfo, + WSManConnectionInfo wsmanConnectionInfo, PSObject rsInfoObject) { PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"]; @@ -1495,8 +1494,8 @@ namespace System.Management.Automation.Runspaces.Internal } private static void ComputeDisconnectedOnExpiresOn( - PSObject rsInfoObject, - out DateTime? disconnectedOn, + PSObject rsInfoObject, + out DateTime? disconnectedOn, out DateTime? expiresOn) { PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"]; @@ -1588,7 +1587,7 @@ namespace System.Management.Automation.Runspaces.Internal stateInfo = newStateInfo; // Update the availableForConnection variable based on state change. - this.availableForConnection = (stateInfo.State == RunspacePoolState.Disconnected || + _availableForConnection = (stateInfo.State == RunspacePoolState.Disconnected || stateInfo.State == RunspacePoolState.Opened); if (raiseEvents) @@ -1613,7 +1612,7 @@ namespace System.Management.Automation.Runspaces.Internal // Set boolean indicating this object has previous connection state and so // can be reconnected as opposed to the alternative where the connection // state has to be reconstructed then connected. - this.canReconnect = true; + _canReconnect = true; } // Do state change work outside of lock. @@ -1626,10 +1625,10 @@ namespace System.Management.Automation.Runspaces.Internal private void SetDisconnectAsCompleted() { - if (disconnectAsyncResult != null && !disconnectAsyncResult.IsCompleted) + if (_disconnectAsyncResult != null && !_disconnectAsyncResult.IsCompleted) { - disconnectAsyncResult.SetAsCompleted(stateInfo.Reason); - disconnectAsyncResult = null; + _disconnectAsyncResult.SetAsCompleted(stateInfo.Reason); + _disconnectAsyncResult = null; } } @@ -1657,10 +1656,10 @@ namespace System.Management.Automation.Runspaces.Internal private void SetReconnectAsCompleted() { - if (reconnectAsyncResult != null && !reconnectAsyncResult.IsCompleted) + if (_reconnectAsyncResult != null && !_reconnectAsyncResult.IsCompleted) { - reconnectAsyncResult.SetAsCompleted(stateInfo.Reason); - reconnectAsyncResult = null; + _reconnectAsyncResult.SetAsCompleted(stateInfo.Reason); + _reconnectAsyncResult = null; } } @@ -1673,7 +1672,7 @@ namespace System.Management.Automation.Runspaces.Internal { // just capture the reason for closing here..handle the session closed event // to change state appropriately. - closingReason = eventArgs.Data; + _closingReason = eventArgs.Data; } /// @@ -1685,7 +1684,7 @@ namespace System.Management.Automation.Runspaces.Internal { if (eventArgs.Data != null) { - closingReason = eventArgs.Data; + _closingReason = eventArgs.Data; } // Set state under lock. @@ -1704,11 +1703,11 @@ namespace System.Management.Automation.Runspaces.Internal case RunspacePoolState.Connecting: // Since RunspacePool is not in closing state, this close is // happening because of data structure handler error. Set the state to broken. - SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Broken, closingReason)); + SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Broken, _closingReason)); break; case RunspacePoolState.Closing: - SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Closed, closingReason)); + SetRunspacePoolState(new RunspacePoolStateInfo(RunspacePoolState.Closed, _closingReason)); break; } @@ -1741,8 +1740,8 @@ namespace System.Management.Automation.Runspaces.Internal /// private void SetOpenAsCompleted() { - RunspacePoolAsyncResult tempOpenAsyncResult = openAsyncResult; - openAsyncResult = null; + RunspacePoolAsyncResult tempOpenAsyncResult = _openAsyncResult; + _openAsyncResult = null; if (tempOpenAsyncResult != null && !tempOpenAsyncResult.IsCompleted) { tempOpenAsyncResult.SetAsCompleted(stateInfo.Reason); @@ -1757,10 +1756,10 @@ namespace System.Management.Automation.Runspaces.Internal // abort all pending calls. DispatchTable.AbortAllCalls(); - if (closeAsyncResult != null) + if (_closeAsyncResult != null) { - closeAsyncResult.SetAsCompleted(stateInfo.Reason); - closeAsyncResult = null; + _closeAsyncResult.SetAsCompleted(stateInfo.Reason); + _closeAsyncResult = null; } // Ensure that openAsyncResult is completed and that @@ -1772,7 +1771,7 @@ namespace System.Management.Automation.Runspaces.Internal // Ensure private application data wait is released. try { - this.applicationPrivateDataReceived.Set(); + _applicationPrivateDataReceived.Set(); } catch (ObjectDisposedException) { } } @@ -1789,7 +1788,7 @@ namespace System.Management.Automation.Runspaces.Internal PSObject data = eventArgs.Data; object response = RemotingDecoder.GetPropertyValue(data, RemoteDataNameStrings.RunspacePoolOperationResponse); long callId = RemotingDecoder.GetPropertyValue(data, RemoteDataNameStrings.CallId); - dispatchTable.SetResponse(callId, response); + _dispatchTable.SetResponse(callId, response); } /// @@ -1800,7 +1799,7 @@ namespace System.Management.Automation.Runspaces.Internal /// private void HandleURIDirectionReported(object sender, RemoteDataEventArgs eventArgs) { - WSManConnectionInfo wsmanConnectionInfo = connectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; if (null != wsmanConnectionInfo) { wsmanConnectionInfo.ConnectionUri = eventArgs.Data; @@ -1845,9 +1844,9 @@ namespace System.Management.Automation.Runspaces.Internal // Update connectionInfo with updated information from the transport. if (eventArgs != null) { - this.connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout; - this.connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout; - WSManConnectionInfo wsmanConnectionInfo = this.connectionInfo as WSManConnectionInfo; + _connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout; + _connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout; + WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { wsmanConnectionInfo.OutputBufferingMode = @@ -1862,7 +1861,7 @@ namespace System.Management.Automation.Runspaces.Internal private void ResetDisconnectedOnExpiresOn() { // Reset DisconnectedOn/ExpiresOn - WSManConnectionInfo wsManConnectionInfo = this.connectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo; if (wsManConnectionInfo != null) { wsManConnectionInfo.NullDisconnectedExpiresOn(); @@ -1872,7 +1871,7 @@ namespace System.Management.Automation.Runspaces.Internal private void UpdateDisconnectedExpiresOn() { // Set DisconnectedOn/ExpiresOn for disconnected session. - WSManConnectionInfo wsManConnectionInfo = this.connectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo; if (wsManConnectionInfo != null) { wsManConnectionInfo.SetDisconnectedExpiresOnToNow(); @@ -1892,7 +1891,7 @@ namespace System.Management.Automation.Runspaces.Internal // Wait for private application data to arrive from server. try { - this.applicationPrivateDataReceived.WaitOne(); + _applicationPrivateDataReceived.WaitOne(); } catch (ObjectDisposedException) { } @@ -1914,32 +1913,32 @@ namespace System.Management.Automation.Runspaces.Internal #region Private Members - private RunspaceConnectionInfo connectionInfo; // connection info with which this + private RunspaceConnectionInfo _connectionInfo; // connection info with which this // runspace is created - private ClientRunspacePoolDataStructureHandler dataStructureHandler; // runspace pool data structure handler for all + private ClientRunspacePoolDataStructureHandler _dataStructureHandler; // runspace pool data structure handler for all // data structure handler handling - private RunspacePoolAsyncResult openAsyncResult;// async result object generated on + private RunspacePoolAsyncResult _openAsyncResult;// async result object generated on // CoreOpen - private RunspacePoolAsyncResult closeAsyncResult; // async result object generated by + private RunspacePoolAsyncResult _closeAsyncResult; // async result object generated by // BeginClose - private Exception closingReason; // reason for a Closing state transition - private RunspacePoolAsyncResult disconnectAsyncResult; // async result object generated on CoreDisconnect - private RunspacePoolAsyncResult reconnectAsyncResult; // async result object generated on CoreReconnect - private bool isDisposed; - private DispatchTable dispatchTable; + private Exception _closingReason; // reason for a Closing state transition + private RunspacePoolAsyncResult _disconnectAsyncResult; // async result object generated on CoreDisconnect + private RunspacePoolAsyncResult _reconnectAsyncResult; // async result object generated on CoreReconnect + private bool _isDisposed; + private DispatchTable _dispatchTable; private DispatchTable DispatchTable { get { - return dispatchTable; + return _dispatchTable; } } - private ConnectCommandInfo[] connectCommands = null; - private bool canReconnect; - private string friendlyName = string.Empty; - private bool availableForConnection; + private ConnectCommandInfo[] _connectCommands = null; + private bool _canReconnect; + private string _friendlyName = string.Empty; + private bool _availableForConnection; private System.Collections.Concurrent.ConcurrentStack _runningPowerShells; @@ -1965,11 +1964,11 @@ namespace System.Management.Automation.Runspaces.Internal { // dispose the base class before disposing dataStructure handler. base.Dispose(disposing); - if (!isDisposed) + if (!_isDisposed) { - isDisposed = true; - dataStructureHandler.Dispose(disposing); - applicationPrivateDataReceived.Dispose(); + _isDisposed = true; + _dataStructureHandler.Dispose(disposing); + _applicationPrivateDataReceived.Dispose(); } } @@ -1983,15 +1982,15 @@ namespace System.Management.Automation.Runspaces.Internal /// internal class ConnectCommandInfo { - private Guid cmdId = Guid.Empty; - private string cmdStr = String.Empty; + private Guid _cmdId = Guid.Empty; + private string _cmdStr = String.Empty; /// /// Remote command instance Id. /// public Guid CommandId { - get { return this.cmdId; } + get { return _cmdId; } } /// @@ -1999,7 +1998,7 @@ namespace System.Management.Automation.Runspaces.Internal /// public string Command { - get { return this.cmdStr; } + get { return _cmdStr; } } /// @@ -2009,8 +2008,8 @@ namespace System.Management.Automation.Runspaces.Internal /// Command string. public ConnectCommandInfo(Guid cmdId, string cmdStr) { - this.cmdId = cmdId; - this.cmdStr = cmdStr; + _cmdId = cmdId; + _cmdStr = cmdStr; } } @@ -2222,5 +2221,5 @@ namespace System.Management.Automation.Runspaces.Internal } } -#endregion + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 9d7968ea7..249be65d1 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -167,7 +167,7 @@ namespace System.Management.Automation.Runspaces get { return _originInfo; } } [DataMemberAttribute()] - private readonly OriginInfo _originInfo; + private readonly OriginInfo _originInfo; /// /// Constructor diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index ad3988571..a43e276f0 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -26,7 +26,6 @@ namespace System.Management.Automation.Internal /// internal class ClientRunspacePoolDataStructureHandler : IDisposable { - private bool _reconnecting = false; #region Constructors @@ -40,24 +39,24 @@ namespace System.Management.Automation.Internal internal ClientRunspacePoolDataStructureHandler(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable) { - clientRunspacePoolId = clientRunspacePool.InstanceId; - minRunspaces = clientRunspacePool.GetMinRunspaces(); - maxRunspaces = clientRunspacePool.GetMaxRunspaces(); - host = clientRunspacePool.Host; - applicationArguments = clientRunspacePool.ApplicationArguments; - remoteSession = CreateClientRemoteSession(clientRunspacePool); + _clientRunspacePoolId = clientRunspacePool.InstanceId; + _minRunspaces = clientRunspacePool.GetMinRunspaces(); + _maxRunspaces = clientRunspacePool.GetMaxRunspaces(); + _host = clientRunspacePool.Host; + _applicationArguments = clientRunspacePool.ApplicationArguments; + _remoteSession = CreateClientRemoteSession(clientRunspacePool); //TODO: Assign remote session name.. should be passed from clientRunspacePool - transportManager = remoteSession.SessionDataStructureHandler.TransportManager; - transportManager.TypeTable = typeTable; - remoteSession.StateChanged += + _transportManager = _remoteSession.SessionDataStructureHandler.TransportManager; + _transportManager.TypeTable = typeTable; + _remoteSession.StateChanged += new EventHandler( HandleClientRemoteSessionStateChanged); _reconnecting = false; - transportManager.RobustConnectionNotification += + _transportManager.RobustConnectionNotification += new EventHandler(HandleRobustConnectionNotification); - transportManager.CreateCompleted += + _transportManager.CreateCompleted += new EventHandler(HandleSessionCreateCompleted); } @@ -72,9 +71,9 @@ namespace System.Management.Automation.Internal internal void CreateRunspacePoolAndOpenAsync() { // #1: Connect to remote session - Dbg.Assert(remoteSession.SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Idle, + Dbg.Assert(_remoteSession.SessionDataStructureHandler.StateMachine.State == RemoteSessionState.Idle, "State of ClientRemoteSession is expected to be idle before connection is established"); - remoteSession.CreateAsync(); + _remoteSession.CreateAsync(); // #2: send the message for runspace pool creation // this is done in HandleClientRemoteSessionStateChanged @@ -85,7 +84,7 @@ namespace System.Management.Automation.Internal /// internal void CloseRunspacePoolAsync() { - remoteSession.CloseAsync(); + _remoteSession.CloseAsync(); } /// @@ -106,7 +105,7 @@ namespace System.Management.Automation.Internal //TODO: Integrate this into state machine _reconnecting = true; PrepareForConnect(); - remoteSession.ReconnectAsync(); + _remoteSession.ReconnectAsync(); } /// @@ -115,7 +114,7 @@ namespace System.Management.Automation.Internal internal void ConnectPoolAsync() { PrepareForConnect(); - remoteSession.ConnectAsync(); + _remoteSession.ConnectAsync(); } /// @@ -126,10 +125,10 @@ namespace System.Management.Automation.Internal internal void ProcessReceivedData(RemoteDataObject receivedData) { // verify if this data structure handler is the intended recipient - if (receivedData.RunspacePoolId != clientRunspacePoolId) + if (receivedData.RunspacePoolId != _clientRunspacePoolId) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceIdsDoNotMatch, - receivedData.RunspacePoolId, clientRunspacePoolId); + receivedData.RunspacePoolId, _clientRunspacePoolId); } // take appropriate action based on the action type @@ -156,7 +155,6 @@ namespace System.Management.Automation.Internal "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); RSPoolInitInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(initInfo)); - } break; @@ -203,7 +201,6 @@ namespace System.Management.Automation.Internal PSEventArgsReceived.SafeInvoke(this, new RemoteDataEventArgs(psEventArgs)); } break; - } // switch ... } // ProcessReceivedData @@ -217,11 +214,11 @@ namespace System.Management.Automation.Internal ClientRemotePowerShell shell) { BaseClientCommandTransportManager clientTrsptMgr = - remoteSession.SessionDataStructureHandler. + _remoteSession.SessionDataStructureHandler. CreateClientCommandTransportManager(shell, shell.NoInput); return new ClientPowerShellDataStructureHandler( - clientTrsptMgr, clientRunspacePoolId, shell.InstanceId); + clientTrsptMgr, _clientRunspacePoolId, shell.InstanceId); } /// @@ -232,9 +229,9 @@ namespace System.Management.Automation.Internal internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) { // add to associated powershell list and send request to server - lock (associationSyncObject) + lock (_associationSyncObject) { - associatedPowerShellDSHandlers.Add(shell.InstanceId, shell.DataStructureHandler); + _associatedPowerShellDSHandlers.Add(shell.InstanceId, shell.DataStructureHandler); } shell.DataStructureHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); @@ -247,12 +244,12 @@ namespace System.Management.Automation.Internal throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect); } - if(remoteSession == null) + if (_remoteSession == null) { throw new ObjectDisposedException("ClientRunspacePoolDataStructureHandler"); } - shell.DataStructureHandler.Start(remoteSession.SessionDataStructureHandler.StateMachine, invokeAndDisconnect); + shell.DataStructureHandler.Start(_remoteSession.SessionDataStructureHandler.StateMachine, invokeAndDisconnect); } /// @@ -262,10 +259,10 @@ namespace System.Management.Automation.Internal /// ClientPowerShellDataStructureHandler for PowerShell. internal void AddRemotePowerShellDSHandler(Guid psShellInstanceId, ClientPowerShellDataStructureHandler psDSHandler) { - lock (associationSyncObject) + lock (_associationSyncObject) { // Remove old DSHandler and replace with new. - associatedPowerShellDSHandlers[psShellInstanceId] = psDSHandler; + _associatedPowerShellDSHandlers[psShellInstanceId] = psDSHandler; } psDSHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); @@ -305,7 +302,7 @@ namespace System.Management.Automation.Internal internal void SendResetRunspaceStateToServer(long callId) { RemoteDataObject message = - RemotingEncoder.GenerateResetRunspaceState(clientRunspacePoolId, callId); + RemotingEncoder.GenerateResetRunspaceState(_clientRunspacePoolId, callId); SendDataAsync(message); } @@ -319,7 +316,7 @@ namespace System.Management.Automation.Internal internal void SendSetMaxRunspacesToServer(int maxRunspaces, long callId) { RemoteDataObject message = - RemotingEncoder.GenerateSetMaxRunspaces(clientRunspacePoolId, maxRunspaces, callId); + RemotingEncoder.GenerateSetMaxRunspaces(_clientRunspacePoolId, maxRunspaces, callId); SendDataAsync(message); } @@ -333,7 +330,7 @@ namespace System.Management.Automation.Internal internal void SendSetMinRunspacesToServer(int minRunspaces, long callId) { RemoteDataObject message = - RemotingEncoder.GenerateSetMinRunspaces(clientRunspacePoolId, minRunspaces, callId); + RemotingEncoder.GenerateSetMinRunspaces(_clientRunspacePoolId, minRunspaces, callId); SendDataAsync(message); } @@ -345,9 +342,9 @@ namespace System.Management.Automation.Internal /// be blocked on internal void SendGetAvailableRunspacesToServer(long callId) { - SendDataAsync(RemotingEncoder.GenerateGetAvailableRunspaces(clientRunspacePoolId, callId)); + SendDataAsync(RemotingEncoder.GenerateGetAvailableRunspaces(_clientRunspacePoolId, callId)); } - + #endregion Data Structure Handler Methods #region Data Structure Handler events @@ -434,7 +431,7 @@ namespace System.Management.Automation.Internal /// the one used within the code private void SendDataAsync(RemoteDataObject data) { - transportManager.DataToBeSentCollection.Add(data); + _transportManager.DataToBeSentCollection.Add(data); } /// @@ -446,7 +443,7 @@ namespace System.Management.Automation.Internal /// priority with which to send data internal void SendDataAsync(RemoteDataObject data, DataPriorityType priority) { - transportManager.DataToBeSentCollection.Add(data, priority); + _transportManager.DataToBeSentCollection.Add(data, priority); } /// @@ -458,9 +455,9 @@ namespace System.Management.Automation.Internal internal void SendDataAsync(PSObject data, DataPriorityType priority) { RemoteDataObject dataToBeSent = RemoteDataObject.CreateFrom(RemotingDestination.Server, - RemotingDataType.InvalidDataType, clientRunspacePoolId, Guid.Empty, data); + RemotingDataType.InvalidDataType, _clientRunspacePoolId, Guid.Empty, data); - transportManager.DataToBeSentCollection.Add(dataToBeSent); + _transportManager.DataToBeSentCollection.Add(dataToBeSent); } /// @@ -490,57 +487,57 @@ namespace System.Management.Automation.Internal // save 1 network call to create a runspace on the server. if (e.SessionStateInfo.State == RemoteSessionState.NegotiationSending) { - if (createRunspaceCalled) + if (_createRunspaceCalled) { return; } - lock (syncObject) + lock (_syncObject) { //We are doing this check because Establised event //is raised more than once - if (createRunspaceCalled) + if (_createRunspaceCalled) { // TODO: Put an assert here. NegotiationSending cannot // occur multiple time in v2 remoting. return; } - createRunspaceCalled = true; + _createRunspaceCalled = true; } // make client's PSVersionTable available to the server using applicationArguments PSPrimitiveDictionary argumentsWithVersionTable = - PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationArguments); + PSPrimitiveDictionary.CloneAndAddPSVersionTable(_applicationArguments); // send a message to the server.. SendDataAsync(RemotingEncoder.GenerateCreateRunspacePool( - clientRunspacePoolId, minRunspaces, maxRunspaces, this.remoteSession.RemoteRunspacePoolInternal, host, + _clientRunspacePoolId, _minRunspaces, _maxRunspaces, _remoteSession.RemoteRunspacePoolInternal, _host, argumentsWithVersionTable)); } if (e.SessionStateInfo.State == RemoteSessionState.NegotiationSendingOnConnect) { // send connect message to the server. SendDataAsync(RemotingEncoder.GenerateConnectRunspacePool( - clientRunspacePoolId, minRunspaces, maxRunspaces)); + _clientRunspacePoolId, _minRunspaces, _maxRunspaces)); } else if (e.SessionStateInfo.State == RemoteSessionState.ClosingConnection) { // use the first reason which caused the error - Exception reason = closingReason; + Exception reason = _closingReason; if (reason == null) { reason = e.SessionStateInfo.Reason; - closingReason = reason; + _closingReason = reason; } // close transport managers of the associated commands List dsHandlers; - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(associatedPowerShellDSHandlers.Values); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { - dsHandler.CloseConnectionAsync(closingReason); + dsHandler.CloseConnectionAsync(_closingReason); } SessionClosing.SafeInvoke(this, new RemoteDataEventArgs(reason)); @@ -548,11 +545,11 @@ namespace System.Management.Automation.Internal else if (e.SessionStateInfo.State == RemoteSessionState.Closed) { // use the first reason which caused the error - Exception reason = closingReason; + Exception reason = _closingReason; if (reason == null) { reason = e.SessionStateInfo.Reason; - closingReason = reason; + _closingReason = reason; } // if there is a reason associated, then most likely the @@ -573,7 +570,7 @@ namespace System.Management.Automation.Internal else if (e.SessionStateInfo.State == RemoteSessionState.Connected) { // write a transfer event here - PSEtwLog.ReplaceActivityIdForCurrentThread(clientRunspacePoolId, PSEventId.OperationalTransferEventRunspacePool, + PSEtwLog.ReplaceActivityIdForCurrentThread(_clientRunspacePoolId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Runspace, PSTask.CreateRunspace); } else if (e.SessionStateInfo.State == RemoteSessionState.Disconnected) @@ -596,7 +593,7 @@ namespace System.Management.Automation.Internal { if (e.SessionStateInfo.Reason != null) { - closingReason = e.SessionStateInfo.Reason; + _closingReason = e.SessionStateInfo.Reason; } } } // HandleClientRemoteSessionStateChanged @@ -622,10 +619,9 @@ namespace System.Management.Automation.Internal if (stateInfo.State == RunspacePoolState.Disconnected) { - - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(associatedPowerShellDSHandlers.Values); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { @@ -639,10 +635,10 @@ namespace System.Management.Automation.Internal // associated powershells to stopped if (stateInfo.State == RunspacePoolState.Broken || stateInfo.State == RunspacePoolState.Closed) { - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(associatedPowerShellDSHandlers.Values); - associatedPowerShellDSHandlers.Clear(); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); + _associatedPowerShellDSHandlers.Clear(); } if (stateInfo.State == RunspacePoolState.Broken) @@ -652,7 +648,6 @@ namespace System.Management.Automation.Internal { dsHandler.SetStateToFailed(stateInfo.Reason); } - } // if ... else if (stateInfo.State == RunspacePoolState.Closed) { @@ -676,9 +671,9 @@ namespace System.Management.Automation.Internal { ClientPowerShellDataStructureHandler dsHandler = null; - lock (associationSyncObject) + lock (_associationSyncObject) { - bool success = associatedPowerShellDSHandlers.TryGetValue(clientPowerShellId, out dsHandler); + bool success = _associatedPowerShellDSHandlers.TryGetValue(clientPowerShellId, out dsHandler); if (!success) { @@ -702,12 +697,12 @@ namespace System.Management.Automation.Internal ClientPowerShellDataStructureHandler dsHandler = sender as ClientPowerShellDataStructureHandler; - lock (associationSyncObject) + lock (_associationSyncObject) { - associatedPowerShellDSHandlers.Remove(dsHandler.PowerShellId); + _associatedPowerShellDSHandlers.Remove(dsHandler.PowerShellId); } - transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); + _transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); } /// @@ -719,13 +714,13 @@ namespace System.Management.Automation.Internal { bool startDisconnectNow; - lock (associationSyncObject) + lock (_associationSyncObject) { - if (this.associatedPowerShellDSHandlers.Count == 0) + if (_associatedPowerShellDSHandlers.Count == 0) { // There are no running commands associated with this runspace pool. startDisconnectNow = true; - this.preparingForDisconnectList = null; + _preparingForDisconnectList = null; } else { @@ -734,11 +729,11 @@ namespace System.Management.Automation.Internal // Create and fill list of active transportmanager objects to be disconnected. // Add ready-for-disconnect callback handler to DSHandler transportmanager objects. - Dbg.Assert(this.preparingForDisconnectList == null, "Cannot prepare for disconnect while disconnect is pending."); - this.preparingForDisconnectList = new List(); - foreach (ClientPowerShellDataStructureHandler dsHandler in this.associatedPowerShellDSHandlers.Values) + Dbg.Assert(_preparingForDisconnectList == null, "Cannot prepare for disconnect while disconnect is pending."); + _preparingForDisconnectList = new List(); + foreach (ClientPowerShellDataStructureHandler dsHandler in _associatedPowerShellDSHandlers.Values) { - this.preparingForDisconnectList.Add(dsHandler.TransportManager); + _preparingForDisconnectList.Add(dsHandler.TransportManager); dsHandler.TransportManager.ReadyForDisconnect += HandleReadyForDisconnect; } } @@ -747,16 +742,16 @@ namespace System.Management.Automation.Internal if (startDisconnectNow) { // Ok to start on this thread. - StartDisconnectAsync(remoteSession); + StartDisconnectAsync(_remoteSession); } else { // Start preparation for disconnect. The HandleReadyForDisconnect callback will be // called when a transportManager is ready for disconnect. List dsHandlers; - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(this.associatedPowerShellDSHandlers.Values); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { @@ -772,9 +767,9 @@ namespace System.Management.Automation.Internal private void PrepareForConnect() { List dsHandlers; - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(this.associatedPowerShellDSHandlers.Values); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { @@ -798,28 +793,28 @@ namespace System.Management.Automation.Internal BaseClientCommandTransportManager bcmdTM = (BaseClientCommandTransportManager)sender; - lock (associationSyncObject) + lock (_associationSyncObject) { // Ignore extra event calls after disconnect is started. - if (this.preparingForDisconnectList == null) + if (_preparingForDisconnectList == null) { return; } - if (this.preparingForDisconnectList.Contains(bcmdTM)) + if (_preparingForDisconnectList.Contains(bcmdTM)) { - this.preparingForDisconnectList.Remove(bcmdTM); + _preparingForDisconnectList.Remove(bcmdTM); } - if (this.preparingForDisconnectList.Count == 0) + if (_preparingForDisconnectList.Count == 0) { - this.preparingForDisconnectList = null; + _preparingForDisconnectList = null; // Start the asynchronous disconnect on a worker thread because we don't know // what thread this callback is made from. If it was made from a transport // callback event then a deadlock may occur when DisconnectAsync is called on // that same thread. - ThreadPool.QueueUserWorkItem(new WaitCallback(StartDisconnectAsync), remoteSession); + ThreadPool.QueueUserWorkItem(new WaitCallback(StartDisconnectAsync), _remoteSession); } } } @@ -839,13 +834,13 @@ namespace System.Management.Automation.Internal /// /// private void HandleRobustConnectionNotification( - object sender, + object sender, ConnectionStatusEventArgs e) { List dsHandlers; - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(this.associatedPowerShellDSHandlers.Values); + dsHandlers = new List(_associatedPowerShellDSHandlers.Values); } foreach (ClientPowerShellDataStructureHandler dsHandler in dsHandlers) { @@ -867,25 +862,25 @@ namespace System.Management.Automation.Internal #region Private Members - private Guid clientRunspacePoolId; - private ClientRemoteSession remoteSession; - private object syncObject = new object(); - private bool createRunspaceCalled = false; - private Exception closingReason; - private int minRunspaces; - private int maxRunspaces; - private PSHost host; - private PSPrimitiveDictionary applicationArguments; - private Dictionary associatedPowerShellDSHandlers + private Guid _clientRunspacePoolId; + private ClientRemoteSession _remoteSession; + private object _syncObject = new object(); + private bool _createRunspaceCalled = false; + private Exception _closingReason; + private int _minRunspaces; + private int _maxRunspaces; + private PSHost _host; + private PSPrimitiveDictionary _applicationArguments; + private Dictionary _associatedPowerShellDSHandlers = new Dictionary(); // data structure handlers of all ClientRemotePowerShell which are // associated with this runspace pool - private object associationSyncObject = new object(); + private object _associationSyncObject = new object(); // object to synchronize operations to above - private BaseClientSessionTransportManager transportManager; + private BaseClientSessionTransportManager _transportManager; // session transport manager associated with this runspace - private List preparingForDisconnectList; + private List _preparingForDisconnectList; #endregion Private Members @@ -899,7 +894,7 @@ namespace System.Management.Automation.Internal { get { - return remoteSession; + return _remoteSession; } } @@ -910,9 +905,9 @@ namespace System.Management.Automation.Internal { get { - if (remoteSession != null) + if (_remoteSession != null) { - return this.remoteSession.SessionDataStructureHandler.TransportManager; + return _remoteSession.SessionDataStructureHandler.TransportManager; } else { @@ -929,10 +924,10 @@ namespace System.Management.Automation.Internal { get { - if (this.transportManager != null && - this.transportManager is WSManClientSessionTransportManager) + if (_transportManager != null && + _transportManager is WSManClientSessionTransportManager) { - return ((WSManClientSessionTransportManager)(this.transportManager)).MaxRetryConnectionTime; + return ((WSManClientSessionTransportManager)(_transportManager)).MaxRetryConnectionTime; } return 0; @@ -947,11 +942,11 @@ namespace System.Management.Automation.Internal { get { - WSManClientSessionTransportManager wsmanTransportManager = this.transportManager as WSManClientSessionTransportManager; + WSManClientSessionTransportManager wsmanTransportManager = _transportManager as WSManClientSessionTransportManager; return (wsmanTransportManager != null) ? wsmanTransportManager.SupportsDisconnect : false; } } - + #endregion Internal Properties #region IDisposable @@ -974,16 +969,15 @@ namespace System.Management.Automation.Internal { if (disposing) { - if (remoteSession != null) + if (_remoteSession != null) { - ((ClientRemoteSessionImpl)remoteSession).Dispose(); - remoteSession = null; + ((ClientRemoteSessionImpl)_remoteSession).Dispose(); + _remoteSession = null; } } } #endregion IDisposable - } /// @@ -1085,10 +1079,10 @@ namespace System.Management.Automation.Internal { // Add all callbacks to transport manager. SetupTransportManager(inDisconnectMode); - transportManager.CreateAsync(); + _transportManager.CreateAsync(); } - void HandleDelayStreamRequestProcessed(object sender, EventArgs e) + private void HandleDelayStreamRequestProcessed(object sender, EventArgs e) { //client's request to start pipeline in disconnected mode has been successfully processed ProcessDisconnect(null); @@ -1096,7 +1090,7 @@ namespace System.Management.Automation.Internal internal void HandleReconnectCompleted(object sender, EventArgs args) { - Int32 currentState = Interlocked.CompareExchange(ref connectionState, (Int32)connectionStates.Connected, (Int32)connectionStates.Reconnecting); + Int32 currentState = Interlocked.CompareExchange(ref _connectionState, (Int32)connectionStates.Connected, (Int32)connectionStates.Reconnecting); ReconnectCompleted.SafeInvoke(this, new RemoteDataEventArgs(null)); return; @@ -1104,7 +1098,7 @@ namespace System.Management.Automation.Internal internal void HandleConnectCompleted(object sender, EventArgs args) { - Int32 currentState = Interlocked.CompareExchange(ref connectionState, (Int32)connectionStates.Connected, (Int32)connectionStates.Connecting); + Int32 currentState = Interlocked.CompareExchange(ref _connectionState, (Int32)connectionStates.Connected, (Int32)connectionStates.Connecting); ConnectCompleted.SafeInvoke(this, new RemoteDataEventArgs(null)); return; @@ -1130,8 +1124,8 @@ namespace System.Management.Automation.Internal /// internal void SendStopPowerShellMessage() { - transportManager.CryptoHelper.CompleteKeyExchange(); - transportManager.SendStopSignal(); + _transportManager.CryptoHelper.CompleteKeyExchange(); + _transportManager.SendStopSignal(); } /// @@ -1139,7 +1133,7 @@ namespace System.Management.Automation.Internal /// /// /// - void OnSignalCompleted(object sender, EventArgs e) + private void OnSignalCompleted(object sender, EventArgs e) { // Raise stopped event locally...By the time this event // is raised, the remote server would have sent state changed info. @@ -1165,7 +1159,7 @@ namespace System.Management.Automation.Internal clientPowerShellId, hostResponse.Encode()); - transportManager.DataToBeSentCollection.Add(dataToBeSent, + _transportManager.DataToBeSentCollection.Add(dataToBeSent, DataPriorityType.PromptResponse); } @@ -1180,7 +1174,7 @@ namespace System.Management.Automation.Internal { // there is no input, send an end of input // message - lock (inputSyncObject) + lock (_inputSyncObject) { // send input closed information to server SendDataAsync(RemotingEncoder.GeneratePowerShellInputEnd( @@ -1197,7 +1191,7 @@ namespace System.Management.Automation.Internal // for enumeration are written out before any newly added data // is written. Hence the lock is made even before the handler is // registered - lock (inputSyncObject) + lock (_inputSyncObject) { inputstream.DataReady += new EventHandler(HandleInputDataReady); WriteInput(inputstream); @@ -1375,23 +1369,23 @@ namespace System.Management.Automation.Internal _sessionClosedReason = sessionCloseReason; // wait for the close to complete and then dispose the transport manager - transportManager.CloseCompleted += delegate(object source, EventArgs args) + _transportManager.CloseCompleted += delegate (object source, EventArgs args) { if (null != CloseCompleted) { // If the provided event args are empty then call CloseCompleted with // RemoteSessionStateEventArgs containing session closed reason exception. - EventArgs closeCompletedEventArgs = (args == EventArgs.Empty) ? + EventArgs closeCompletedEventArgs = (args == EventArgs.Empty) ? new RemoteSessionStateEventArgs(new RemoteSessionStateInfo(RemoteSessionState.Closed, _sessionClosedReason)) : args; CloseCompleted(this, closeCompletedEventArgs); } - transportManager.Dispose(); + _transportManager.Dispose(); }; - transportManager.CloseAsync(); + _transportManager.CloseAsync(); } /// @@ -1413,7 +1407,7 @@ namespace System.Management.Automation.Internal { //disconnect may be called on a pipeline that is already disconnected. PSInvocationStateInfo stateInfo = - new PSInvocationStateInfo(PSInvocationState.Disconnected, + new PSInvocationStateInfo(PSInvocationState.Disconnected, (rsStateInfo != null) ? rsStateInfo.Reason : null); Dbg.Assert(InvocationStateInfoReceived != null, @@ -1421,7 +1415,7 @@ namespace System.Management.Automation.Internal InvocationStateInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(stateInfo)); - Interlocked.CompareExchange(ref connectionState, (Int32)connectionStates.Disconnected, (Int32)connectionStates.Connected); + Interlocked.CompareExchange(ref _connectionState, (Int32)connectionStates.Disconnected, (Int32)connectionStates.Connected); } /// @@ -1432,28 +1426,27 @@ namespace System.Management.Automation.Internal /// internal void ReconnectAsync() { - Int32 currentState = Interlocked.CompareExchange(ref connectionState, (Int32)connectionStates.Reconnecting, (Int32)connectionStates.Disconnected); + Int32 currentState = Interlocked.CompareExchange(ref _connectionState, (Int32)connectionStates.Reconnecting, (Int32)connectionStates.Disconnected); if ((currentState != (Int32)connectionStates.Disconnected)) { - Dbg.Assert(false, "Pipeline DS Handler is in unexpected connection state"); - + // TODO: Raise appropriate exception return; } - transportManager.ReconnectAsync(); + _transportManager.ReconnectAsync(); } //Called from session DSHandler. Connects to a remote powershell instance. internal void ConnectAsync() { - Int32 currentState = Interlocked.CompareExchange(ref connectionState, (Int32)connectionStates.Connecting, (Int32)connectionStates.Disconnected); + Int32 currentState = Interlocked.CompareExchange(ref _connectionState, (Int32)connectionStates.Connecting, (Int32)connectionStates.Disconnected); // Connect is called for *reconstruct* connection case and so // we need to set up all transport manager callbacks. SetupTransportManager(false); - transportManager.ConnectAsync(); + _transportManager.ConnectAsync(); } /// @@ -1492,7 +1485,7 @@ namespace System.Management.Automation.Internal internal ClientPowerShellDataStructureHandler(BaseClientCommandTransportManager transportManager, Guid clientRunspacePoolId, Guid clientPowerShellId) { - this.transportManager = transportManager; + _transportManager = transportManager; this.clientRunspacePoolId = clientRunspacePoolId; this.clientPowerShellId = clientPowerShellId; transportManager.SignalCompleted += new EventHandler(OnSignalCompleted); @@ -1521,7 +1514,7 @@ namespace System.Management.Automation.Internal { get { - return this.transportManager; + return _transportManager; } } @@ -1539,7 +1532,7 @@ namespace System.Management.Automation.Internal private void SendDataAsync(RemoteDataObject data) { RemoteDataObject dataToBeSent = (RemoteDataObject)data; - transportManager.DataToBeSentCollection.Add(dataToBeSent); + _transportManager.DataToBeSentCollection.Add(dataToBeSent); } /// @@ -1550,7 +1543,7 @@ namespace System.Management.Automation.Internal private void HandleInputDataReady(object sender, EventArgs e) { // make sure only one thread calls the WriteInput. - lock (inputSyncObject) + lock (_inputSyncObject) { ObjectStreamBase inputstream = sender as ObjectStreamBase; WriteInput(inputstream); @@ -1601,47 +1594,46 @@ namespace System.Management.Automation.Internal /// Boolean private void SetupTransportManager(bool inDisconnectMode) { - transportManager.WSManTransportErrorOccured += HandleTransportError; - transportManager.ReconnectCompleted += HandleReconnectCompleted; - transportManager.ConnectCompleted += HandleConnectCompleted; - transportManager.DelayStreamRequestProcessed += HandleDelayStreamRequestProcessed; - transportManager.startInDisconnectedMode = inDisconnectMode; + _transportManager.WSManTransportErrorOccured += HandleTransportError; + _transportManager.ReconnectCompleted += HandleReconnectCompleted; + _transportManager.ConnectCompleted += HandleConnectCompleted; + _transportManager.DelayStreamRequestProcessed += HandleDelayStreamRequestProcessed; + _transportManager.startInDisconnectedMode = inDisconnectMode; } #endregion Private Methods #region Private Members - private BaseClientCommandTransportManager transportManager; + private BaseClientCommandTransportManager _transportManager; // object for synchronizing input to be sent // to server powershell - private object inputSyncObject = new object(); + private object _inputSyncObject = new object(); private enum connectionStates { Connected = 1, Disconnected = 3, Reconnecting = 4, Connecting = 5 } - private Int32 connectionState = (Int32)connectionStates.Connected; + private Int32 _connectionState = (Int32)connectionStates.Connected; // Contains the associated session closed reason exception if any, // otherwise is null. private Exception _sessionClosedReason; #endregion Private Members - } internal class InformationalMessage { - private object message; - private RemotingDataType dataType; + private object _message; + private RemotingDataType _dataType; internal object Message { get { - return message; + return _message; } } @@ -1649,14 +1641,14 @@ namespace System.Management.Automation.Internal { get { - return dataType; + return _dataType; } } internal InformationalMessage(object message, RemotingDataType dataType) { - this.dataType = dataType; - this.message = message; + _dataType = dataType; + _message = message; } } } diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index 3a40fd10d..a0af06a63 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -34,7 +35,7 @@ namespace System.Management.Automation.Remoting private ObjectRef _runspaceRef; private bool _stopInvoke; private object _localSyncObject; - private static RobustConnectionProgress RCProgress = new RobustConnectionProgress(); + private static RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); /// /// Constructor for RunspaceRef. @@ -202,7 +203,7 @@ namespace System.Management.Automation.Remoting if (psCommand != null) { pipeline = useNestedPipelines ? - _runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory): + _runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory) : _runspaceRef.Value.CreatePipeline(psCommand.Commands[0].CommandText, addToHistory); pipeline.Commands.Clear(); @@ -309,13 +310,13 @@ namespace System.Management.Automation.Remoting isRunspacePushed = true; } - if ( (remoteRunspace.GetCurrentlyRunningPipeline() != null) ) + if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } - using(PowerShell powerShell = PowerShell.Create()) + using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); @@ -327,7 +328,7 @@ namespace System.Management.Automation.Remoting int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += new EventHandler>(HandleHostCall); - + IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection results = new PSDataCollection(); @@ -396,7 +397,7 @@ namespace System.Management.Automation.Remoting remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null) { remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine( - StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError, + StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError, remoteRunspace.ConnectionInfo.ComputerName)); } } @@ -409,7 +410,7 @@ namespace System.Management.Automation.Remoting RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; if (remoteRunspace != null) { - RCProgress.StartProgress( + s_RCProgress.StartProgress( sourceId, computerName, totalSeconds, @@ -420,7 +421,7 @@ namespace System.Management.Automation.Remoting private void StopProgressBar( long sourceId) { - RCProgress.StopProgress(sourceId); + s_RCProgress.StopProgress(sourceId); } #endregion diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 7081e23e5..df83127b8 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -41,7 +41,7 @@ namespace System.Management.Automation this.StopJob(); List childJobsToDispose; - lock (this._lockObject) + lock (_lockObject) { Dbg.Assert(this.IsFinishedState(this.JobStateInfo.State), "ThrottlingJob should be completed before removing and disposing child jobs"); childJobsToDispose = new List(this.ChildJobs); @@ -51,11 +51,11 @@ namespace System.Management.Automation { childJob.Dispose(); } - if (this._jobResultsThrottlingSemaphore != null) + if (_jobResultsThrottlingSemaphore != null) { - this._jobResultsThrottlingSemaphore.Dispose(); + _jobResultsThrottlingSemaphore.Dispose(); } - this._cancellationTokenSource.Dispose(); + _cancellationTokenSource.Dispose(); } } finally @@ -75,14 +75,14 @@ namespace System.Management.Automation internal int GetProgressActivityId() { - lock (this._progressLock) + lock (_progressLock) { - if (this._progressReportLastTime.Equals(DateTime.MinValue)) + if (_progressReportLastTime.Equals(DateTime.MinValue)) { try { this.ReportProgress(minimizeFrequentUpdates: false); - Dbg.Assert(this._progressReportLastTime > DateTime.MinValue, "Progress was reported (lastTimeProgressWasReported)"); + Dbg.Assert(_progressReportLastTime > DateTime.MinValue, "Progress was reported (lastTimeProgressWasReported)"); } catch (PSInvalidOperationException) { @@ -91,37 +91,37 @@ namespace System.Management.Automation } } - return this._progressActivityId; + return _progressActivityId; } } private void ReportProgress(bool minimizeFrequentUpdates) { - lock (this._progressLock) + lock (_progressLock) { DateTime now = DateTime.UtcNow; if (minimizeFrequentUpdates) { - if ((now - this._progressStartTime) < TimeSpan.FromSeconds(1)) + if ((now - _progressStartTime) < TimeSpan.FromSeconds(1)) { return; } - if ((!this._progressReportLastTime.Equals(DateTime.MinValue)) && - (now - this._progressReportLastTime < TimeSpan.FromMilliseconds(200))) + if ((!_progressReportLastTime.Equals(DateTime.MinValue)) && + (now - _progressReportLastTime < TimeSpan.FromMilliseconds(200))) { return; } } - this._progressReportLastTime = now; + _progressReportLastTime = now; double workCompleted; double totalWork; int percentComplete; - lock (this._lockObject) + lock (_lockObject) { - totalWork = this._countOfAllChildJobs; + totalWork = _countOfAllChildJobs; workCompleted = this.CountOfFinishedChildJobs; } if (totalWork >= 1.0) @@ -135,13 +135,13 @@ namespace System.Management.Automation percentComplete = Math.Max(-1, Math.Min(100, percentComplete)); var progressRecord = new ProgressRecord( - activityId: this._progressActivityId, - activity: this.Command, + activityId: _progressActivityId, + activity: this.Command, statusDescription: this.StatusMessage); if (this.IsThrottlingJobCompleted) { - if (this._progressReportLastTime.Equals(DateTime.MinValue)) + if (_progressReportLastTime.Equals(DateTime.MinValue)) { return; } @@ -156,7 +156,7 @@ namespace System.Management.Automation int? secondsRemaining = null; if (percentComplete >= 0) { - secondsRemaining = ProgressRecord.GetSecondsRemaining(this._progressStartTime, (double)percentComplete / 100.0); + secondsRemaining = ProgressRecord.GetSecondsRemaining(_progressStartTime, (double)percentComplete / 100.0); } if (secondsRemaining.HasValue) { @@ -197,9 +197,9 @@ namespace System.Management.Automation { get { - lock (this._lockObject) + lock (_lockObject) { - return this._isStopping || (this._ownerWontSubmitNewChildJobs && this._setOfChildJobsThatCanAddMoreChildJobs.Count == 0); + return _isStopping || (_ownerWontSubmitNewChildJobs && _setOfChildJobsThatCanAddMoreChildJobs.Count == 0); } } } @@ -207,9 +207,9 @@ namespace System.Management.Automation { get { - lock (this._lockObject) + lock (_lockObject) { - return this.IsEndOfChildJobs && (this._countOfAllChildJobs <= this.CountOfFinishedChildJobs); + return this.IsEndOfChildJobs && (_countOfAllChildJobs <= this.CountOfFinishedChildJobs); } } } @@ -227,9 +227,9 @@ namespace System.Management.Automation { get { - lock (this._lockObject) + lock (_lockObject) { - return this._countOfFailedChildJobs + this._countOfStoppedChildJobs + this._countOfSuccessfullyCompletedChildJobs; + return _countOfFailedChildJobs + _countOfStoppedChildJobs + _countOfSuccessfullyCompletedChildJobs; } } } @@ -238,9 +238,9 @@ namespace System.Management.Automation { get { - lock (this._lockObject) + lock (_lockObject) { - return this._countOfAllChildJobs - this.CountOfFinishedChildJobs; + return _countOfAllChildJobs - this.CountOfFinishedChildJobs; } } } @@ -269,13 +269,13 @@ namespace System.Management.Automation : base(command, jobName) { this.Results.BlockingEnumerator = true; - this._cmdletMode = cmdletMode; + _cmdletMode = cmdletMode; this.PSJobTypeName = jobTypeName; - if (this._cmdletMode) + if (_cmdletMode) { - this._jobResultsThrottlingSemaphore = new SemaphoreSlim(ForwardingHelper.AggregationQueueMaxCapacity); + _jobResultsThrottlingSemaphore = new SemaphoreSlim(ForwardingHelper.AggregationQueueMaxCapacity); } - this._progressActivityId = new Random(this.GetHashCode()).Next(); + _progressActivityId = new Random(this.GetHashCode()).Next(); this.SetupThrottlingQueue(maximumConcurrentChildJobs); } @@ -310,19 +310,19 @@ namespace System.Management.Automation private bool _alreadyDisabledFlowControlForPendingJobsQueue = false; internal void DisableFlowControlForPendingJobsQueue() { - if (!this._cmdletMode || this._alreadyDisabledFlowControlForPendingJobsQueue) + if (!_cmdletMode || _alreadyDisabledFlowControlForPendingJobsQueue) { return; } - this._alreadyDisabledFlowControlForPendingJobsQueue = true; + _alreadyDisabledFlowControlForPendingJobsQueue = true; - lock (this._lockObject) + lock (_lockObject) { - this._maxReadyToRunJobs = int.MaxValue; + _maxReadyToRunJobs = int.MaxValue; - while (this._actionsForUnblockingChildAdditions.Count > 0) + while (_actionsForUnblockingChildAdditions.Count > 0) { - Action a = this._actionsForUnblockingChildAdditions.Dequeue(); + Action a = _actionsForUnblockingChildAdditions.Dequeue(); if (a != null) { a(); @@ -334,16 +334,16 @@ namespace System.Management.Automation private bool _alreadyDisabledFlowControlForPendingCmdletActionsQueue = false; internal void DisableFlowControlForPendingCmdletActionsQueue() { - if (!this._cmdletMode || this._alreadyDisabledFlowControlForPendingCmdletActionsQueue) + if (!_cmdletMode || _alreadyDisabledFlowControlForPendingCmdletActionsQueue) { return; } - this._alreadyDisabledFlowControlForPendingCmdletActionsQueue = true; + _alreadyDisabledFlowControlForPendingCmdletActionsQueue = true; - long slotsToRelease = (long)(int.MaxValue/2) - (long)(this._jobResultsThrottlingSemaphore.CurrentCount); + long slotsToRelease = (long)(int.MaxValue / 2) - (long)(_jobResultsThrottlingSemaphore.CurrentCount); if ((slotsToRelease > 0) && (slotsToRelease < int.MaxValue)) { - this._jobResultsThrottlingSemaphore.Release((int)slotsToRelease); + _jobResultsThrottlingSemaphore.Release((int)slotsToRelease); } } @@ -364,27 +364,27 @@ namespace System.Management.Automation this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; - lock (this._lockObject) + lock (_lockObject) { if (this.IsEndOfChildJobs) throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs); - if (this._isStopping) { return; } + if (_isStopping) { return; } - if (this._countOfAllChildJobs == 0) + if (_countOfAllChildJobs == 0) { newJobStateInfo = new JobStateInfo(JobState.Running); } if (ChildJobFlags.CreatesChildJobs == (ChildJobFlags.CreatesChildJobs & flags)) { - this._setOfChildJobsThatCanAddMoreChildJobs.Add(childJob.InstanceId); + _setOfChildJobsThatCanAddMoreChildJobs.Add(childJob.InstanceId); } this.ChildJobs.Add(childJob); - this._childJobLocations.Add(childJob.Location); - this._countOfAllChildJobs++; - + _childJobLocations.Add(childJob.Location); + _countOfAllChildJobs++; + this.WriteWarningAboutHighUsageOfFlowControlBuffers(this.CountOfRunningOrReadyToRunChildJobs); - if (this.CountOfRunningOrReadyToRunChildJobs > this._maxReadyToRunJobs) + if (this.CountOfRunningOrReadyToRunChildJobs > _maxReadyToRunJobs) { - this._actionsForUnblockingChildAdditions.Enqueue(jobEnqueuedAction); + _actionsForUnblockingChildAdditions.Enqueue(jobEnqueuedAction); } else { @@ -403,7 +403,7 @@ namespace System.Management.Automation childJob.SetParentActivityIdGetter(this.GetProgressActivityId); childJob.StateChanged += this.childJob_StateChanged; - if (this._cmdletMode) + if (_cmdletMode) { childJob.Results.DataAdded += new EventHandler(childJob_ResultsAdded); } @@ -414,13 +414,13 @@ namespace System.Management.Automation private void childJob_ResultsAdded(object sender, DataAddedEventArgs e) { - Dbg.Assert(this._jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be non-null if childJob_ResultsAdded handled is registered"); + Dbg.Assert(_jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be non-null if childJob_ResultsAdded handled is registered"); try { - long jobResultsUpdatedCount = Interlocked.Increment(ref this._jobResultsCurrentCount); + long jobResultsUpdatedCount = Interlocked.Increment(ref _jobResultsCurrentCount); this.WriteWarningAboutHighUsageOfFlowControlBuffers(jobResultsUpdatedCount); - this._jobResultsThrottlingSemaphore.Wait(this._cancellationTokenSource.Token); + _jobResultsThrottlingSemaphore.Wait(_cancellationTokenSource.Token); } catch (ObjectDisposedException) { @@ -436,7 +436,7 @@ namespace System.Management.Automation private void WriteWarningAboutHighUsageOfFlowControlBuffers(long currentCount) { - if (!this._cmdletMode) + if (!_cmdletMode) { return; } @@ -446,13 +446,13 @@ namespace System.Management.Automation return; } - lock (this._alreadyWroteFlowControlBuffersHighMemoryUsageWarningLock) + lock (_alreadyWroteFlowControlBuffersHighMemoryUsageWarningLock) { - if (this._alreadyWroteFlowControlBuffersHighMemoryUsageWarning) + if (_alreadyWroteFlowControlBuffersHighMemoryUsageWarning) { return; } - this._alreadyWroteFlowControlBuffersHighMemoryUsageWarning = true; + _alreadyWroteFlowControlBuffersHighMemoryUsageWarning = true; } string warningMessage = string.Format( @@ -475,51 +475,51 @@ namespace System.Management.Automation private readonly SemaphoreSlim _jobResultsThrottlingSemaphore; private long _jobResultsCurrentCount; - private static readonly int MaximumReadyToRunJobs = 10000; + private static readonly int s_maximumReadyToRunJobs = 10000; private void SetupThrottlingQueue(int maximumConcurrentChildJobs) { - this._maximumConcurrentChildJobs = maximumConcurrentChildJobs > 0 ? maximumConcurrentChildJobs : int.MaxValue; + _maximumConcurrentChildJobs = maximumConcurrentChildJobs > 0 ? maximumConcurrentChildJobs : int.MaxValue; if (_cmdletMode) { - this._maxReadyToRunJobs = MaximumReadyToRunJobs; + _maxReadyToRunJobs = s_maximumReadyToRunJobs; } else { - this._maxReadyToRunJobs = int.MaxValue; + _maxReadyToRunJobs = int.MaxValue; } - this._extraCapacityForRunningAllJobs = this._maximumConcurrentChildJobs; - this._extraCapacityForRunningQueryJobs = Math.Max(1, this._extraCapacityForRunningAllJobs / 2); + _extraCapacityForRunningAllJobs = _maximumConcurrentChildJobs; + _extraCapacityForRunningQueryJobs = Math.Max(1, _extraCapacityForRunningAllJobs / 2); - this._inBoostModeToPreventQueryJobDeadlock = false; - this._readyToRunQueryJobs = new Queue(); - this._readyToRunRegularJobs = new Queue(); - this._actionsForUnblockingChildAdditions = new Queue(); + _inBoostModeToPreventQueryJobDeadlock = false; + _readyToRunQueryJobs = new Queue(); + _readyToRunRegularJobs = new Queue(); + _actionsForUnblockingChildAdditions = new Queue(); } private void StartChildJobIfPossible() { StartableJob readyToRunChildJob = null; - lock (this._lockObject) + lock (_lockObject) { do { - if ((this._readyToRunQueryJobs.Count > 0) && - (this._extraCapacityForRunningQueryJobs > 0) && - (this._extraCapacityForRunningAllJobs > 0)) + if ((_readyToRunQueryJobs.Count > 0) && + (_extraCapacityForRunningQueryJobs > 0) && + (_extraCapacityForRunningAllJobs > 0)) { - this._extraCapacityForRunningQueryJobs--; - this._extraCapacityForRunningAllJobs--; - readyToRunChildJob = this._readyToRunQueryJobs.Dequeue(); + _extraCapacityForRunningQueryJobs--; + _extraCapacityForRunningAllJobs--; + readyToRunChildJob = _readyToRunQueryJobs.Dequeue(); break; } - if ((this._readyToRunRegularJobs.Count > 0) && - (this._extraCapacityForRunningAllJobs > 0)) + if ((_readyToRunRegularJobs.Count > 0) && + (_extraCapacityForRunningAllJobs > 0)) { - this._extraCapacityForRunningAllJobs--; - readyToRunChildJob = this._readyToRunRegularJobs.Dequeue(); + _extraCapacityForRunningAllJobs--; + readyToRunChildJob = _readyToRunRegularJobs.Dequeue(); break; } } while (false); @@ -533,24 +533,24 @@ namespace System.Management.Automation private void EnqueueReadyToRunChildJob(StartableJob childJob) { - lock (this._lockObject) + lock (_lockObject) { - bool isQueryJob = this._setOfChildJobsThatCanAddMoreChildJobs.Contains(childJob.InstanceId); + bool isQueryJob = _setOfChildJobsThatCanAddMoreChildJobs.Contains(childJob.InstanceId); if (isQueryJob && - !this._inBoostModeToPreventQueryJobDeadlock && - (this._maximumConcurrentChildJobs == 1)) + !_inBoostModeToPreventQueryJobDeadlock && + (_maximumConcurrentChildJobs == 1)) { - this._inBoostModeToPreventQueryJobDeadlock = true; - this._extraCapacityForRunningAllJobs++; + _inBoostModeToPreventQueryJobDeadlock = true; + _extraCapacityForRunningAllJobs++; } if (isQueryJob) { - this._readyToRunQueryJobs.Enqueue(childJob); + _readyToRunQueryJobs.Enqueue(childJob); } else { - this._readyToRunRegularJobs.Enqueue(childJob); + _readyToRunRegularJobs.Enqueue(childJob); } } @@ -559,20 +559,20 @@ namespace System.Management.Automation private void MakeRoomForRunningOtherJobs(Job completedChildJob) { - lock (this._lockObject) + lock (_lockObject) { - this._extraCapacityForRunningAllJobs++; + _extraCapacityForRunningAllJobs++; - bool isQueryJob = this._setOfChildJobsThatCanAddMoreChildJobs.Contains(completedChildJob.InstanceId); + bool isQueryJob = _setOfChildJobsThatCanAddMoreChildJobs.Contains(completedChildJob.InstanceId); if (isQueryJob) { - this._setOfChildJobsThatCanAddMoreChildJobs.Remove(completedChildJob.InstanceId); + _setOfChildJobsThatCanAddMoreChildJobs.Remove(completedChildJob.InstanceId); - this._extraCapacityForRunningQueryJobs++; - if (this._inBoostModeToPreventQueryJobDeadlock && (this._setOfChildJobsThatCanAddMoreChildJobs.Count == 0)) + _extraCapacityForRunningQueryJobs++; + if (_inBoostModeToPreventQueryJobDeadlock && (_setOfChildJobsThatCanAddMoreChildJobs.Count == 0)) { - this._inBoostModeToPreventQueryJobDeadlock = false; - this._extraCapacityForRunningAllJobs--; + _inBoostModeToPreventQueryJobDeadlock = false; + _extraCapacityForRunningAllJobs--; } } } @@ -583,19 +583,19 @@ namespace System.Management.Automation private void FigureOutIfThrottlingJobIsCompleted() { JobStateInfo finalJobStateInfo = null; - lock (this._lockObject) + lock (_lockObject) { if (this.IsThrottlingJobCompleted && !IsFinishedState(this.JobStateInfo.State)) { - if (this._isStopping) + if (_isStopping) { finalJobStateInfo = new JobStateInfo(JobState.Stopped, null); } - else if (this._countOfFailedChildJobs > 0) + else if (_countOfFailedChildJobs > 0) { finalJobStateInfo = new JobStateInfo(JobState.Failed, null); } - else if (this._countOfStoppedChildJobs > 0) + else if (_countOfStoppedChildJobs > 0) { finalJobStateInfo = new JobStateInfo(JobState.Stopped, null); } @@ -618,9 +618,9 @@ namespace System.Management.Automation internal void EndOfChildJobs() { this.AssertNotDisposed(); - lock (this._lockObject) + lock (_lockObject) { - this._ownerWontSubmitNewChildJobs = true; + _ownerWontSubmitNewChildJobs = true; } this.FigureOutIfThrottlingJobIsCompleted(); } @@ -631,11 +631,11 @@ namespace System.Management.Automation public override void StopJob() { List childJobsToStop = null; - lock (this._lockObject) + lock (_lockObject) { - if (!(this._isStopping || this.IsThrottlingJobCompleted)) + if (!(_isStopping || this.IsThrottlingJobCompleted)) { - this._isStopping = true; + _isStopping = true; childJobsToStop = this.GetChildJobsSnapshot(); } } @@ -644,7 +644,7 @@ namespace System.Management.Automation { this.SetJobState(JobState.Stopping); - this._cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); foreach (Job childJob in childJobsToStop) { if (!childJob.IsFinishedState(childJob.JobStateInfo.State)) @@ -671,10 +671,10 @@ namespace System.Management.Automation if ((e.PreviousJobStateInfo.State == JobState.Blocked) && (e.JobStateInfo.State != JobState.Blocked)) { bool parentJobGotUnblocked = false; - lock (this._lockObject) + lock (_lockObject) { - this._countOfBlockedChildJobs--; - if (this._countOfBlockedChildJobs == 0) + _countOfBlockedChildJobs--; + if (_countOfBlockedChildJobs == 0) { parentJobGotUnblocked = true; } @@ -689,9 +689,9 @@ namespace System.Management.Automation { // intermediate states case JobState.Blocked: - lock (this._lockObject) + lock (_lockObject) { - this._countOfBlockedChildJobs++; + _countOfBlockedChildJobs++; } this.SetJobState(JobState.Blocked); break; @@ -702,38 +702,38 @@ namespace System.Management.Automation case JobState.Completed: childJob.StateChanged -= childJob_StateChanged; this.MakeRoomForRunningOtherJobs(childJob); - lock (this._lockObject) + lock (_lockObject) { if (e.JobStateInfo.State == JobState.Failed) { - this._countOfFailedChildJobs++; + _countOfFailedChildJobs++; } else if (e.JobStateInfo.State == JobState.Stopped) { - this._countOfStoppedChildJobs++; + _countOfStoppedChildJobs++; } else if (e.JobStateInfo.State == JobState.Completed) { - this._countOfSuccessfullyCompletedChildJobs++; + _countOfSuccessfullyCompletedChildJobs++; } - if (this._actionsForUnblockingChildAdditions.Count > 0) + if (_actionsForUnblockingChildAdditions.Count > 0) { - Action a = this._actionsForUnblockingChildAdditions.Dequeue(); + Action a = _actionsForUnblockingChildAdditions.Dequeue(); if (a != null) { a(); } } - if (this._cmdletMode) + if (_cmdletMode) { foreach (PSStreamObject streamObject in childJob.Results.ReadAll()) { this.Results.Add(streamObject); } - this.ChildJobs.Remove(childJob); - this._setOfChildJobsThatCanAddMoreChildJobs.Remove(childJob.InstanceId); + this.ChildJobs.Remove(childJob); + _setOfChildJobsThatCanAddMoreChildJobs.Remove(childJob.InstanceId); childJob.Dispose(); } } @@ -750,7 +750,7 @@ namespace System.Management.Automation private List GetChildJobsSnapshot() { - lock (this._lockObject) + lock (_lockObject) { return new List(this.ChildJobs); } @@ -776,9 +776,9 @@ namespace System.Management.Automation { get { - lock (this._lockObject) + lock (_lockObject) { - return string.Join(", ", this._childJobLocations); + return string.Join(", ", _childJobLocations); } } } @@ -788,17 +788,17 @@ namespace System.Management.Automation /// Status message associated with the Job /// public override string StatusMessage - { - get + { + get { int completedChildJobs; int totalChildJobs; - lock (this._lockObject) + lock (_lockObject) { completedChildJobs = this.CountOfFinishedChildJobs; - totalChildJobs = this._countOfAllChildJobs; + totalChildJobs = _countOfAllChildJobs; } - + string totalChildJobsString = totalChildJobs.ToString(CultureInfo.CurrentCulture); if (!this.IsEndOfChildJobs) { @@ -834,7 +834,7 @@ namespace System.Management.Automation // RemoteDiscoveryHelper.BlockingCollectionCapacity // It needs to be higher, because the high value is used as an attempt to workaround the fact that // WSMan will timeout if an OnNext call blocks for more than X minutes. - + // This is a static field (instead of a constant) to make it possible to set through tests (and/or by customers if needed for a workaround) internal static readonly int AggregationQueueMaxCapacity = 10000; @@ -849,27 +849,27 @@ namespace System.Management.Automation private ForwardingHelper(ThrottlingJob throttlingJob) { - this._throttlingJob = throttlingJob; + _throttlingJob = throttlingJob; - this._myLock = new object(); - this._monitoredJobs = new HashSet(); + _myLock = new object(); + _monitoredJobs = new HashSet(); - this._aggregatedResults = new BlockingCollection(); + _aggregatedResults = new BlockingCollection(); } private void StartMonitoringJob(Job job) { - lock (this._myLock) + lock (_myLock) { if (_disposed || _stoppedMonitoringAllJobs) { return; } - if (this._monitoredJobs.Contains(job)) + if (_monitoredJobs.Contains(job)) { return; } - this._monitoredJobs.Add(job); + _monitoredJobs.Add(job); job.Results.DataAdded += this.MonitoredJobResults_DataAdded; job.StateChanged += MonitoredJob_StateChanged; @@ -880,23 +880,23 @@ namespace System.Management.Automation private void StopMonitoringJob(Job job) { - lock (this._myLock) + lock (_myLock) { - if (this._monitoredJobs.Contains(job)) + if (_monitoredJobs.Contains(job)) { job.Results.DataAdded -= this.MonitoredJobResults_DataAdded; job.StateChanged -= this.MonitoredJob_StateChanged; - this._monitoredJobs.Remove(job); + _monitoredJobs.Remove(job); } } } private void AggregateJobResults(PSDataCollection resultsCollection) { - lock (this._myLock) + lock (_myLock) { // try not to remove results from a job, unless it seems safe ... - if (_disposed || _stoppedMonitoringAllJobs || this._aggregatedResults.IsAddingCompleted || this._cancellationTokenSource.IsCancellationRequested) + if (_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested) { return; } @@ -908,12 +908,12 @@ namespace System.Management.Automation bool successfullyAggregatedResult = false; try { - lock (this._myLock) + lock (_myLock) { // try not to remove results from a job, unless it seems safe ... - if (!(_disposed || _stoppedMonitoringAllJobs || this._aggregatedResults.IsAddingCompleted || this._cancellationTokenSource.IsCancellationRequested)) + if (!(_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested)) { - this._aggregatedResults.Add(result, this._cancellationTokenSource.Token); + _aggregatedResults.Add(result, _cancellationTokenSource.Token); successfullyAggregatedResult = true; } } @@ -925,10 +925,10 @@ namespace System.Management.Automation // ... so if _aggregatedResults is not accepting new results, we will store them in the throttling job if (!successfullyAggregatedResult) { - this.StopMonitoringJob(this._throttlingJob); + this.StopMonitoringJob(_throttlingJob); try { - this._throttlingJob.Results.Add(result); + _throttlingJob.Results.Add(result); } catch (InvalidOperationException) { @@ -940,11 +940,11 @@ namespace System.Management.Automation private void CancelForwarding() { - this._cancellationTokenSource.Cancel(); - lock (this._myLock) + _cancellationTokenSource.Cancel(); + lock (_myLock) { - Dbg.Assert(!this._disposed, "CancelForwarding should be unregistered before ForwardingHelper gets disposed"); - this._aggregatedResults.CompleteAdding(); + Dbg.Assert(!_disposed, "CancelForwarding should be unregistered before ForwardingHelper gets disposed"); + _aggregatedResults.CompleteAdding(); } } @@ -957,7 +957,7 @@ namespace System.Management.Automation { if (job.IsFinishedState(jobState)) { - lock (this._myLock) + lock (_myLock) { this.StopMonitoringJob(job); } @@ -966,20 +966,20 @@ namespace System.Management.Automation private void CheckIfThrottlingJobIsComplete() { - if (this._throttlingJob.IsThrottlingJobCompleted) + if (_throttlingJob.IsThrottlingJobCompleted) { List> resultsToAggregate = new List>(); - lock (this._myLock) + lock (_myLock) { - foreach (Job registeredJob in this._monitoredJobs) + foreach (Job registeredJob in _monitoredJobs) { resultsToAggregate.Add(registeredJob.Results); } - foreach (Job throttledJob in this._throttlingJob.GetChildJobsSnapshot()) + foreach (Job throttledJob in _throttlingJob.GetChildJobsSnapshot()) { resultsToAggregate.Add(throttledJob.Results); } - resultsToAggregate.Add(this._throttlingJob.Results); + resultsToAggregate.Add(_throttlingJob.Results); } foreach (PSDataCollection resultToAggregate in resultsToAggregate) @@ -987,11 +987,11 @@ namespace System.Management.Automation this.AggregateJobResults(resultToAggregate); } - lock (this._myLock) + lock (_myLock) { - if (!this._disposed && !this._aggregatedResults.IsAddingCompleted) + if (!_disposed && !_aggregatedResults.IsAddingCompleted) { - this._aggregatedResults.CompleteAdding(); + _aggregatedResults.CompleteAdding(); } } } @@ -1022,26 +1022,26 @@ namespace System.Management.Automation private void AttemptToPreserveAggregatedResults() { #if DEBUG - lock (this._myLock) + lock (_myLock) { - Dbg.Assert(!this._disposed, "AttemptToPreserveAggregatedResults should be called before disposing ForwardingHelper"); - Dbg.Assert(this._stoppedMonitoringAllJobs, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (1)"); - Dbg.Assert(this._aggregatedResults.IsAddingCompleted, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (2)"); + Dbg.Assert(!_disposed, "AttemptToPreserveAggregatedResults should be called before disposing ForwardingHelper"); + Dbg.Assert(_stoppedMonitoringAllJobs, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (1)"); + Dbg.Assert(_aggregatedResults.IsAddingCompleted, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (2)"); } #endif bool isThrottlingJobFinished = false; - foreach (var aggregatedButNotYetProcessedResult in this._aggregatedResults) + foreach (var aggregatedButNotYetProcessedResult in _aggregatedResults) { if (!isThrottlingJobFinished) { try { - this._throttlingJob.Results.Add(aggregatedButNotYetProcessedResult); + _throttlingJob.Results.Add(aggregatedButNotYetProcessedResult); } catch (PSInvalidOperationException) { - isThrottlingJobFinished = this._throttlingJob.IsFinishedState(this._throttlingJob.JobStateInfo.State); + isThrottlingJobFinished = _throttlingJob.IsFinishedState(_throttlingJob.JobStateInfo.State); Dbg.Assert(isThrottlingJobFinished, "Buffers should not be closed before throttling job is stopped"); } } @@ -1051,7 +1051,7 @@ namespace System.Management.Automation #if DEBUG // CDXML_CLIXML_TEST testability hook - private static readonly bool IsCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); + private static readonly bool s_isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); private static bool GetIsCliXmlTestabilityHookActive() { @@ -1060,7 +1060,7 @@ namespace System.Management.Automation internal static void ProcessCliXmlTestabilityHook(PSStreamObject streamObject) { - if (!IsCliXmlTestabilityHookActive) + if (!s_isCliXmlTestabilityHookActive) { return; } @@ -1090,7 +1090,7 @@ namespace System.Management.Automation { try { - foreach (var result in this._aggregatedResults.GetConsumingEnumerable(this._throttlingJob._cancellationTokenSource.Token)) + foreach (var result in _aggregatedResults.GetConsumingEnumerable(_throttlingJob._cancellationTokenSource.Token)) { if (result != null) { @@ -1104,11 +1104,11 @@ namespace System.Management.Automation } finally { - if (this._throttlingJob._cmdletMode) + if (_throttlingJob._cmdletMode) { - Dbg.Assert(this._throttlingJob._jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be present in cmdlet mode"); - Interlocked.Decrement(ref this._throttlingJob._jobResultsCurrentCount); - this._throttlingJob._jobResultsThrottlingSemaphore.Release(); + Dbg.Assert(_throttlingJob._jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be present in cmdlet mode"); + Interlocked.Decrement(ref _throttlingJob._jobResultsCurrentCount); + _throttlingJob._jobResultsThrottlingSemaphore.Release(); } } } @@ -1126,21 +1126,21 @@ namespace System.Management.Automation private bool _stoppedMonitoringAllJobs; private void StopMonitoringAllJobs() { - this._cancellationTokenSource.Cancel(); - lock (this._myLock) + _cancellationTokenSource.Cancel(); + lock (_myLock) { _stoppedMonitoringAllJobs = true; - List snapshotOfCurrentlyMonitoredJobs = this._monitoredJobs.ToList(); + List snapshotOfCurrentlyMonitoredJobs = _monitoredJobs.ToList(); foreach (Job monitoredJob in snapshotOfCurrentlyMonitoredJobs) { this.StopMonitoringJob(monitoredJob); } - Dbg.Assert(this._monitoredJobs.Count == 0, "No monitored jobs should be left after ForwardingHelper is disposed"); + Dbg.Assert(_monitoredJobs.Count == 0, "No monitored jobs should be left after ForwardingHelper is disposed"); - if (!this._disposed && !this._aggregatedResults.IsAddingCompleted) + if (!_disposed && !_aggregatedResults.IsAddingCompleted) { - this._aggregatedResults.CompleteAdding(); + _aggregatedResults.CompleteAdding(); } } } @@ -1148,18 +1148,18 @@ namespace System.Management.Automation public void Dispose() { GC.SuppressFinalize(this); - this._cancellationTokenSource.Cancel(); - lock (this._myLock) + _cancellationTokenSource.Cancel(); + lock (_myLock) { - if (this._disposed) + if (_disposed) { return; } this.StopMonitoringAllJobs(); - this._aggregatedResults.Dispose(); - this._cancellationTokenSource.Dispose(); - this._disposed = true; + _aggregatedResults.Dispose(); + _cancellationTokenSource.Dispose(); + _disposed = true; } } @@ -1239,14 +1239,14 @@ namespace System.Management.Automation { get { - return this._addedChildJob; + return _addedChildJob; } } internal ThrottlingJobChildAddedEventArgs(Job addedChildJob) { Dbg.Assert(addedChildJob != null, "Caller should verify addedChildJob != null"); - this._addedChildJob = addedChildJob; + _addedChildJob = addedChildJob; } } } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index c061a58dd..b6a8de542 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -14,6 +14,7 @@ using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces.Internal; using Dbg = System.Management.Automation.Diagnostics; + namespace System.Management.Automation.Remoting { /// @@ -116,9 +117,8 @@ namespace System.Management.Automation.Remoting /// internal abstract class ClientRemoteSession : RemoteSession { - [TraceSourceAttribute("CRSession", "ClientRemoteSession")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); #region Public_Method_API @@ -216,7 +216,7 @@ namespace System.Management.Automation.Remoting - private RemoteRunspacePoolInternal remoteRunspacePool; + private RemoteRunspacePoolInternal _remoteRunspacePool; /// /// remote runspace pool if used, for this session @@ -225,13 +225,13 @@ namespace System.Management.Automation.Remoting { get { - return remoteRunspacePool; + return _remoteRunspacePool; } set { - Dbg.Assert(remoteRunspacePool == null, @"RunspacePool should be + Dbg.Assert(_remoteRunspacePool == null, @"RunspacePool should be attached only once to the session"); - remoteRunspacePool = value; + _remoteRunspacePool = value; } } @@ -244,15 +244,14 @@ namespace System.Management.Automation.Remoting /// internal RemoteRunspacePoolInternal GetRunspacePool(Guid clientRunspacePoolId) { - if (remoteRunspacePool != null) + if (_remoteRunspacePool != null) { - if (remoteRunspacePool.InstanceId.Equals(clientRunspacePoolId)) - return remoteRunspacePool; + if (_remoteRunspacePool.InstanceId.Equals(clientRunspacePoolId)) + return _remoteRunspacePool; } return null; } - } /// @@ -260,9 +259,8 @@ namespace System.Management.Automation.Remoting /// internal class ClientRemoteSessionImpl : ClientRemoteSession, IDisposable { - [TraceSourceAttribute("CRSessionImpl", "ClientRemoteSessionImpl")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); private PSRemotingCryptoHelperClient _cryptoHelper = null; @@ -355,7 +353,6 @@ namespace System.Management.Automation.Remoting { RemoteSessionStateMachineEventArgs startDisconnectArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.DisconnectStart); SessionDataStructureHandler.StateMachine.RaiseEvent(startDisconnectArg); - } /// @@ -381,7 +378,7 @@ namespace System.Management.Automation.Remoting /// private void HandleConnectionStateChanged(object sender, RemoteSessionStateEventArgs arg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (arg == null) { @@ -534,7 +531,7 @@ namespace System.Management.Automation.Remoting /// private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEventArgs arg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (arg == null) { @@ -695,7 +692,6 @@ namespace System.Management.Automation.Remoting } #endregion IDisposable - } } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index 86d9e01d0..1b7e6b397 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -12,7 +12,6 @@ using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { - /// /// This class implements a Finite State Machine (FSM) to control the remote connection on the client side. /// There is a similar but not identical FSM on the server side for this connection. @@ -37,7 +36,7 @@ namespace System.Management.Automation.Remoting internal class ClientRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); /// /// Event handling matrix. It defines what action to take when an event occur. @@ -51,15 +50,15 @@ namespace System.Management.Automation.Remoting /// private RemoteSessionState _state; - private Queue processPendingEventsQueue + private Queue _processPendingEventsQueue = new Queue(); // all events raised through the state machine // will be queued in this - private object syncObject = new object(); + private object _syncObject = new object(); // object for synchronizing access to the above // queue - private bool eventsInProcess = false; + private bool _eventsInProcess = false; // whether some thread is actively processing events // in a loop. If this is set then other threads // should simply add to the queue and not attempt @@ -75,14 +74,14 @@ namespace System.Management.Automation.Remoting /// /// indicates that the client has previously completed the session key exchange /// - private bool keyExchanged = false; + private bool _keyExchanged = false; /// /// this is to queue up a disconnect request when a key exchange is in process /// the session will be disconnect once the exchange is complete /// intermediate disconnect requests are tracked by this flag /// - private bool pendingDisconnect = false; + private bool _pendingDisconnect = false; /// /// processes events in the queue. If there are no @@ -97,14 +96,14 @@ namespace System.Management.Automation.Remoting do { - lock (syncObject) + lock (_syncObject) { - if (processPendingEventsQueue.Count == 0) + if (_processPendingEventsQueue.Count == 0) { - eventsInProcess = false; + _eventsInProcess = false; break; } - eventArgs = processPendingEventsQueue.Dequeue(); + eventArgs = _processPendingEventsQueue.Dequeue(); } try @@ -124,8 +123,7 @@ namespace System.Management.Automation.Remoting { HandleFatalError(ex); } - - } while (eventsInProcess); + } while (_eventsInProcess); } private void HandleFatalError(Exception ex) @@ -166,7 +164,7 @@ namespace System.Management.Automation.Remoting /// Unique identifier for this state machine. Used /// in tracing /// - private Guid id; + private Guid _id; /// /// Handler to be used in cases, where setting the state is the @@ -245,10 +243,10 @@ namespace System.Management.Automation.Remoting case RemoteSessionEvent.KeyReceived: { - Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, + Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "Key Receving can only be raised after reaching the Established state"); - if (_state == RemoteSessionState.EstablishedAndKeySent) + if (_state == RemoteSessionState.EstablishedAndKeySent) { Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) @@ -256,13 +254,13 @@ namespace System.Management.Automation.Remoting tmp.Dispose(); } - keyExchanged = true; + _keyExchanged = true; SetState(RemoteSessionState.Established, eventArgs.Reason); - if (pendingDisconnect) + if (_pendingDisconnect) { //session key exchange is complete, if there is a disconnect pending, process it now - pendingDisconnect = false; + _pendingDisconnect = false; DoDisconnect(sender, eventArgs); } } @@ -274,7 +272,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(_state >= RemoteSessionState.Established, "Client can send a public key only after reaching the Established state"); - Dbg.Assert(keyExchanged == false, "Client should do key exchange only once"); + Dbg.Assert(_keyExchanged == false, "Client should do key exchange only once"); if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyRequested) @@ -306,7 +304,6 @@ namespace System.Management.Automation.Remoting { SetState(RemoteSessionState.Disconnected, eventArgs.Reason); //set state to disconnected even TODO. Put some ETW event describing the disconnect process failure } - } break; case RemoteSessionEvent.ReconnectCompleted: @@ -341,7 +338,6 @@ namespace System.Management.Automation.Remoting new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientKeyExchangeFailed); RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception)); - } // SetStateHandler /// @@ -387,7 +383,7 @@ namespace System.Management.Automation.Remoting internal ClientRemoteSessionDSHandlerStateMachine() { _clientRemoteSessionStateChangeQueue = new Queue(); - + //Initialize the state machine event handling matrix _stateMachineHandle = new EventHandler[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) @@ -397,12 +393,12 @@ namespace System.Management.Automation.Remoting _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += SetStateHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler; - + _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += SetStateToClosedHandler; - _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += SetStateToClosedHandler; + _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnectSession; } @@ -414,11 +410,11 @@ namespace System.Management.Automation.Remoting _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationSendingOnConnect, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; - + _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationReceived] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationCompleted] += SetStateHandler; - + _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += SetStateToClosedHandler; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += SetStateHandler; @@ -440,7 +436,7 @@ namespace System.Management.Automation.Remoting //Disconnect during key exchange process _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; - + _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySent] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // @@ -463,7 +459,7 @@ namespace System.Management.Automation.Remoting } } - id = Guid.NewGuid(); + _id = Guid.NewGuid(); // initialize the state to be Idle: this means it is ready to start connecting. SetState(RemoteSessionState.Idle, null); @@ -512,25 +508,25 @@ namespace System.Management.Automation.Remoting /// internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueuedEvents = false) { - lock (syncObject) + lock (_syncObject) { - _trace.WriteLine("Event recieved : {0} for {1}", arg.StateEvent, id); + s_trace.WriteLine("Event recieved : {0} for {1}", arg.StateEvent, _id); if (clearQueuedEvents) { - processPendingEventsQueue.Clear(); + _processPendingEventsQueue.Clear(); } - processPendingEventsQueue.Enqueue(arg); + _processPendingEventsQueue.Enqueue(arg); - if (!eventsInProcess) + if (!_eventsInProcess) { - eventsInProcess = true; + _eventsInProcess = true; } else { return; } } - + ProcessEvents(); } @@ -554,14 +550,14 @@ namespace System.Management.Automation.Remoting throw PSTraceSource.NewArgumentNullException("arg"); } - EventHandler handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; + EventHandler handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; if (handler != null) { - _trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, id); + s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); handler(this, arg); - _trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, id); + s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); } } @@ -599,7 +595,7 @@ namespace System.Management.Automation.Remoting /// private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs arg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); @@ -634,11 +630,11 @@ namespace System.Management.Automation.Remoting /// private void DoConnectSession(object sender, RemoteSessionStateMachineEventArgs arg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); - + if (State == RemoteSessionState.Idle) { //We need to send negotiotion and connect algorithm related info @@ -681,7 +677,7 @@ namespace System.Management.Automation.Remoting private void DoDisconnectDuringKeyExchange(object sender, RemoteSessionStateMachineEventArgs arg) { //set flag to indicate Disconnect request queue up - pendingDisconnect = true; + _pendingDisconnect = true; } private void DoDisconnect(object sender, RemoteSessionStateMachineEventArgs arg) @@ -719,7 +715,7 @@ namespace System.Management.Automation.Remoting /// private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { RemoteSessionState oldState = _state; @@ -769,7 +765,7 @@ namespace System.Management.Automation.Remoting PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(eventArgs.Reason, RemotingErrorIdStrings.FatalErrorCausingClose); - RemoteSessionStateMachineEventArgs closeEvent = + RemoteSessionStateMachineEventArgs closeEvent = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError); RaiseEvent(closeEvent); @@ -792,11 +788,11 @@ namespace System.Management.Automation.Remoting private void SetState(RemoteSessionState newState, Exception reason) { RemoteSessionState oldState = _state; - + if (newState != oldState) { _state = newState; - _trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); + s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); RemoteSessionStateInfo stateInfo = new RemoteSessionStateInfo(_state, reason); RemoteSessionStateEventArgs sessionStateEventArg = new RemoteSessionStateEventArgs(stateInfo); diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index b4a9afe5e..97184e7a0 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -20,7 +20,7 @@ using System.Management.Automation.Runspaces.Internal; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings -namespace System.Management.Automation +namespace System.Management.Automation { internal class RemotePipeline : Pipeline { @@ -180,10 +180,10 @@ namespace System.Management.Automation /// pipeline to clone from /// This constructor is private because this will /// only be called from the copy method - private RemotePipeline(RemotePipeline pipeline): + private RemotePipeline(RemotePipeline pipeline) : this((RemoteRunspace)pipeline.Runspace, null, false, pipeline.IsNested) { - this._isSteppable = pipeline._isSteppable; + _isSteppable = pipeline._isSteppable; // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 // the above comment copied from RemotePipelineBase which @@ -194,7 +194,7 @@ namespace System.Management.Automation } if (pipeline._disposed) { - throw PSTraceSource.NewObjectDisposedException("pipeline"); + throw PSTraceSource.NewObjectDisposedException("pipeline"); } _addToHistory = pipeline._addToHistory; @@ -235,7 +235,6 @@ namespace System.Management.Automation { get { - #pragma warning disable 56503 // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) @@ -397,7 +396,7 @@ namespace System.Management.Automation return _inputStream; } } - + #endregion streams #region Invoke @@ -458,7 +457,7 @@ namespace System.Management.Automation InvalidRunspaceStateException e = new InvalidRunspaceStateException ( - StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline,_runspace.RunspaceStateInfo.State.ToString()), + StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline, _runspace.RunspaceStateInfo.State.ToString()), _runspace.RunspaceStateInfo.State, RunspaceState.Opened ); @@ -504,9 +503,9 @@ namespace System.Management.Automation // collect output in. Check to see if the output was collected in a member variable. if (results.Count == 0) { - if (this._outputCollection != null && this._outputCollection.Count > 0) + if (_outputCollection != null && _outputCollection.Count > 0) { - results = new Collection(this._outputCollection); + results = new Collection(_outputCollection); } } @@ -561,7 +560,7 @@ namespace System.Management.Automation { throw PSTraceSource.NewObjectDisposedException("Pipeline"); }; - + asyncresult.AsyncWaitHandle.WaitOne(); } } @@ -747,7 +746,7 @@ namespace System.Management.Automation private void SetPipelineState(PipelineState state, Exception reason) { PipelineState copyState = state; - PipelineStateInfo copyStateInfo = null; + PipelineStateInfo copyStateInfo = null; lock (_syncRoot) { @@ -798,7 +797,6 @@ namespace System.Management.Automation _pipelineStateInfo.Clone(), previousAvailability, _runspace.RunspaceAvailability)); - } // lock... // using the copyStateInfo here as this piece of code is @@ -813,7 +811,7 @@ namespace System.Management.Automation Cleanup(); } } - + /// /// Raises events for changes in execution state. /// @@ -909,7 +907,6 @@ namespace System.Management.Automation _powershell.RemotePowerShell.HostCallReceived += new EventHandler>(HandleHostCallReceived); - } /// @@ -963,9 +960,9 @@ namespace System.Management.Automation ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal.Host, _errorStream, _methodExecutorStream, - IsMethodExecutorStreamEnabled, + IsMethodExecutorStreamEnabled, ((RemoteRunspace)_runspace).RunspacePool.RemoteRunspacePoolInternal, - _powershell.InstanceId, + _powershell.InstanceId, eventArgs.Data); } @@ -1103,15 +1100,15 @@ namespace System.Management.Automation if (currentPipeline == null && ((RemoteRunspace)_runspace).RemoteCommand != null && - this._connectCmdInfo != null && - Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, this._connectCmdInfo.CommandId)) + _connectCmdInfo != null && + Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId)) { // Connect case. We can add a pipeline to a busy runspace when // that pipeline represents the same command as is currently // running. return; } - + if (currentPipeline != null && ReferenceEquals(currentPipeline, this)) { diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 52e7f349b..0401eda32 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -29,7 +29,7 @@ namespace System.Management.Automation internal class RemoteRunspace : Runspace, IDisposable { #region Private Members - + private RunspacePool _runspacePool; private ArrayList _runningPipelines = new ArrayList(); private object _syncRoot = new object(); @@ -46,8 +46,8 @@ namespace System.Management.Automation // the following two variables have been added for supporting // the Invoke-Command | Invoke-Command scenario - private InvokeCommandCommand currentInvokeCommand = null; - private long currentLocalPipelineId = 0; + private InvokeCommandCommand _currentInvokeCommand = null; + private long _currentLocalPipelineId = 0; /// /// This is queue of all the state change event which have occured for @@ -99,7 +99,7 @@ namespace System.Management.Automation } } - bool _shouldCloseOnPop = false; + private bool _shouldCloseOnPop = false; /// /// Temporary place to remember whether to close this runspace on pop or not. @@ -163,8 +163,8 @@ namespace System.Management.Automation { // The RemoteRunspace object can only be constructed this way with a RunspacePool that // is in the disconnected state. - if ( (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || - !(runspacePool.ConnectionInfo is WSManConnectionInfo) ) + if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || + !(runspacePool.ConnectionInfo is WSManConnectionInfo)) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.InvalidRunspacePool); } @@ -188,14 +188,14 @@ namespace System.Management.Automation // Normal Availability for a disconnected runspace is "None", which means it can be connected. // However, we can also have disconnected runspace objects that are *not* avaialable for // connection and in this case the Availability is set to "Busy". - this._runspaceAvailability = _runspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? + _runspaceAvailability = _runspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? Runspaces.RunspaceAvailability.None : Runspaces.RunspaceAvailability.Busy; SetEventHandlers(); PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, - PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, + PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, this.InstanceId.ToString()); } @@ -219,10 +219,10 @@ namespace System.Management.Automation _runspacePool.ForwardEvent += new EventHandler(HandleRunspacePoolForwardEvent); - _runspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted += + _runspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted += new EventHandler(HandleSessionCreateCompleted); } - + #endregion Constructors #region Properties @@ -239,14 +239,11 @@ namespace System.Management.Automation { get { - #pragma warning disable 56503 throw PSTraceSource.NewNotImplementedException(); #pragma warning restore 56503 - - } } @@ -258,14 +255,11 @@ namespace System.Management.Automation { get { - #pragma warning disable 56503 throw PSTraceSource.NewNotImplementedException(); #pragma warning restore 56503 - - } } @@ -334,26 +328,26 @@ namespace System.Management.Automation { get { - return this.createThreadOptions; + return _createThreadOptions; } set { lock (_syncRoot) { - if (value != this.createThreadOptions) + if (value != _createThreadOptions) { if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen) { throw new InvalidRunspaceStateException(StringUtil.Format(RunspaceStrings.ChangePropertyAfterOpen)); } - this.createThreadOptions = value; + _createThreadOptions = value; } } } } - private PSThreadOptions createThreadOptions = PSThreadOptions.Default; + private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// /// Gets the current availability of the Runspace @@ -515,8 +509,8 @@ namespace System.Management.Automation /// internal string PSSessionName { - get { return this._runspacePool.RemoteRunspacePoolInternal.Name; } - set { this._runspacePool.RemoteRunspacePoolInternal.Name = value; } + get { return _runspacePool.RemoteRunspacePoolInternal.Name; } + set { _runspacePool.RemoteRunspacePoolInternal.Name = value; } } /// @@ -524,10 +518,10 @@ namespace System.Management.Automation /// internal int PSSessionId { - get { return this.id; } - set { this.id = value; } + get { return _id; } + set { _id = value; } } - private int id = -1; + private int _id = -1; /// /// Returns true if Runspace supports disconnect. @@ -555,7 +549,7 @@ namespace System.Management.Automation return _remoteDebugger; } } - + #endregion Properties #region Open @@ -613,10 +607,9 @@ namespace System.Management.Automation /// public override void CloseAsync() { - try { - _runspacePool.BeginClose(null,null); + _runspacePool.BeginClose(null, null); } catch (InvalidRunspacePoolStateException e) { @@ -632,10 +625,9 @@ namespace System.Management.Automation /// public override void Close() { - try { - IAsyncResult result = _runspacePool.BeginClose(null,null); + IAsyncResult result = _runspacePool.BeginClose(null, null); WaitForFinishofPipelines(); @@ -1013,7 +1005,7 @@ namespace System.Management.Automation { ContainerConnectionInfo containerConnectionInfo = _connectionInfo as ContainerConnectionInfo; - if ((containerConnectionInfo != null) && + if ((containerConnectionInfo != null) && (containerConnectionInfo.ContainerProc.RuntimeId == Guid.Empty)) { returnCaps |= RunspaceCapability.NamedPipeTransport; @@ -1167,7 +1159,7 @@ namespace System.Management.Automation lock (_syncRoot) { - if (_bypassRunspaceStateCheck == false && + if (_bypassRunspaceStateCheck == false && _runspaceStateInfo.State != RunspaceState.Opened && _runspaceStateInfo.State != RunspaceState.Disconnected) // Disconnected runspaces can have running pipelines. { @@ -1255,12 +1247,12 @@ namespace System.Management.Automation /// internal override SessionStateProxy GetSessionStateProxy() { - if(sessionStateProxy == null) - sessionStateProxy = new RemoteSessionStateProxy(this); + if (_sessionStateProxy == null) + _sessionStateProxy = new RemoteSessionStateProxy(this); - return sessionStateProxy; + return _sessionStateProxy; } - private RemoteSessionStateProxy sessionStateProxy = null; + private RemoteSessionStateProxy _sessionStateProxy = null; #endregion SessionState Proxy @@ -1615,11 +1607,11 @@ namespace System.Management.Automation { ClientMethodExecutor.Dispatch( _runspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager, - _runspacePool.RemoteRunspacePoolInternal.Host, + _runspacePool.RemoteRunspacePoolInternal.Host, null, /* error stream */ null, /* method executor stream */ false, /* is method stream enabled */ - _runspacePool.RemoteRunspacePoolInternal, + _runspacePool.RemoteRunspacePoolInternal, Guid.Empty, /* powershell id */ eventArgs.Data); } @@ -1672,9 +1664,9 @@ namespace System.Management.Automation // Update connectionInfo with updated information from the transport. if (eventArgs != null) { - this._connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout; - this._connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout; - WSManConnectionInfo wsmanConnectionInfo = this._connectionInfo as WSManConnectionInfo; + _connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout; + _connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout; + WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { wsmanConnectionInfo.OutputBufferingMode = @@ -1688,7 +1680,7 @@ namespace System.Management.Automation /// private void UpdateDisconnectExpiresOn() { - WSManConnectionInfo wsmanConnectionInfo = this._runspacePool.RemoteRunspacePoolInternal.ConnectionInfo as WSManConnectionInfo; + WSManConnectionInfo wsmanConnectionInfo = _runspacePool.RemoteRunspacePoolInternal.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) { this.DisconnectedOn = wsmanConnectionInfo.DisconnectedOn; @@ -1718,7 +1710,7 @@ namespace System.Management.Automation // return true, when one invoke-command is running as a // job and another invoke-command is entered at the // console prompt - if (currentLocalPipelineId != localPipelineId && currentLocalPipelineId != 0) + if (_currentLocalPipelineId != localPipelineId && _currentLocalPipelineId != 0) { return false; } @@ -1728,14 +1720,14 @@ namespace System.Management.Automation // this invoke command is running may be // running in the same pipeline as another // invoke command - if (currentInvokeCommand == null) + if (_currentInvokeCommand == null) { // this is the first invoke-command, just // set the reference SetCurrentInvokeCommand(invokeCommand, localPipelineId); return false; } - else if (currentInvokeCommand.Equals(invokeCommand)) + else if (_currentInvokeCommand.Equals(invokeCommand)) { // the currently active invoke command is the one // specified @@ -1763,8 +1755,8 @@ namespace System.Management.Automation Dbg.Assert(invokeCommand != null, "InvokeCommand instance cannot be null, use ClearInvokeCommand() method to reset current command"); Dbg.Assert(localPipelineId != 0, "Local pipeline id needs to be supplied - cannot be 0"); - currentInvokeCommand = invokeCommand; - currentLocalPipelineId = localPipelineId; + _currentInvokeCommand = invokeCommand; + _currentLocalPipelineId = localPipelineId; } /// @@ -1773,8 +1765,8 @@ namespace System.Management.Automation /// internal void ClearInvokeCommand() { - currentLocalPipelineId = 0; - currentInvokeCommand = null; + _currentLocalPipelineId = 0; + _currentInvokeCommand = null; } /// @@ -1786,7 +1778,7 @@ namespace System.Management.Automation { System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager transportManager = _runspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager as System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager; - + if (transportManager != null) { transportManager.AbortConnect(); @@ -1866,8 +1858,8 @@ namespace System.Management.Automation private bool _detachCommand; // Impersonation flow - WindowsIdentity _identityToPersonate; - bool _identityPersonationChecked; + private WindowsIdentity _identityToPersonate; + private bool _identityPersonationChecked; /// /// RemoteDebuggerStopEvent @@ -2178,7 +2170,7 @@ namespace System.Management.Automation /// public override bool IsActive { - get { return _isActive; } + get { return _isActive; } } /// @@ -2259,7 +2251,7 @@ namespace System.Management.Automation { _runspace.RemoteDebuggerStop -= HandleForwardedDebuggerStopEvent; _runspace.RemoteDebuggerBreakpointUpdated -= HandleForwardedDebuggerBreakpointUpdatedEvent; - + if (_identityToPersonate != null) { _identityToPersonate.Dispose(); @@ -2306,8 +2298,8 @@ namespace System.Management.Automation /// UnhandledBreakpointMode /// Server PowerShell version internal void SetClientDebugInfo( - DebugModes? debugMode, - bool inBreakpoint, + DebugModes? debugMode, + bool inBreakpoint, int breakpointCount, bool breakAll, UnhandledBreakpointProcessingMode unhandledBreakpointMode, @@ -2421,7 +2413,6 @@ namespace System.Management.Automation private void ProcessDebuggerStopEvent(DebuggerStopEventArgs args) { - // It is possible to get a stop event raise request while // debugger is already in stop mode (after remote runspace debugger // reconnect). In this case ignore the request. @@ -2439,7 +2430,7 @@ namespace System.Management.Automation ProcessDebuggerStopEventProc, args); } - + if (!invokedOnBlockedThread) { #if CORECLR @@ -2488,7 +2479,7 @@ namespace System.Management.Automation } } } - else + else { // If no debugger is subscribed to the DebuggerStop event then we // allow the server side script execution to remain blocked in debug @@ -2568,7 +2559,7 @@ namespace System.Management.Automation { throw new InvalidRunspaceStateException(); } - + if (!_identityPersonationChecked) { _identityPersonationChecked = true; @@ -2587,8 +2578,8 @@ namespace System.Management.Automation private void SetRemoteDebug(bool remoteDebug, RunspaceAvailability? availability) { if (_runspace.RunspaceStateInfo.State != RunspaceState.Opened) - { - return; + { + return; } if (IsRemoteDebug != remoteDebug) @@ -2650,16 +2641,16 @@ namespace System.Management.Automation internal class RemoteSessionStateProxy : SessionStateProxy { - RemoteRunspace _runspace; + private RemoteRunspace _runspace; internal RemoteSessionStateProxy(RemoteRunspace runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); _runspace = runspace; } - private Exception isInNoLangugeModeException = null; - private Exception getVariableCommandNotFoundException = null; - private Exception setVariableCommandNotFoundException = null; + private Exception _isInNoLangugeModeException = null; + private Exception _getVariableCommandNotFoundException = null; + private Exception _setVariableCommandNotFoundException = null; /// /// Set a variable in session state. @@ -2693,8 +2684,8 @@ namespace System.Management.Automation // Verify the runspace has the Set-Variable command. For performance, throw if we got an error // before. - if (setVariableCommandNotFoundException != null) - throw setVariableCommandNotFoundException; + if (_setVariableCommandNotFoundException != null) + throw _setVariableCommandNotFoundException; // Since these are implemented as pipelines, we don't need to do our own // locking of sessionStateCallInProgress like we do with local runspaces. @@ -2712,15 +2703,15 @@ namespace System.Management.Automation { if (String.Equals("CommandNotFoundException", e.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase)) { - setVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); - throw setVariableCommandNotFoundException; + _setVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); + throw _setVariableCommandNotFoundException; } else throw; } if (remotePipeline.Error.Count > 0) { // Don't cache these errors, as they are related to the actual variable being set. - ErrorRecord error = (ErrorRecord) remotePipeline.Error.Read(); + ErrorRecord error = (ErrorRecord)remotePipeline.Error.Read(); throw new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, error.Exception); } } @@ -2757,8 +2748,8 @@ namespace System.Management.Automation // Verify the runspace has the Get-Variable command. For performance, throw if we got an error // before. - if (getVariableCommandNotFoundException != null) - throw getVariableCommandNotFoundException; + if (_getVariableCommandNotFoundException != null) + throw _getVariableCommandNotFoundException; // Since these are implemented as pipelines, we don't need to do our own // locking of sessionStateCallInProgress like we do with local runspaces. @@ -2776,8 +2767,8 @@ namespace System.Management.Automation { if (String.Equals("CommandNotFoundException", e.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase)) { - getVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); - throw getVariableCommandNotFoundException; + _getVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); + throw _getVariableCommandNotFoundException; } else throw; } @@ -2818,8 +2809,8 @@ namespace System.Management.Automation { // Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error // before. - if (isInNoLangugeModeException != null) - throw isInNoLangugeModeException; + if (_isInNoLangugeModeException != null) + throw _isInNoLangugeModeException; // Since these are implemented as pipelines, we don't need to do our own // locking of sessionStateCallInProgress like we do with local runspaces. @@ -2838,8 +2829,8 @@ namespace System.Management.Automation { if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError) { - isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); - throw isInNoLangugeModeException; + _isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); + throw _isInNoLangugeModeException; } else throw; } @@ -2865,8 +2856,8 @@ namespace System.Management.Automation { // Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error // before. - if (isInNoLangugeModeException != null) - throw isInNoLangugeModeException; + if (_isInNoLangugeModeException != null) + throw _isInNoLangugeModeException; // Since these are implemented as pipelines, we don't need to do our own // locking of sessionStateCallInProgress like we do with local runspaces. @@ -2885,8 +2876,8 @@ namespace System.Management.Automation { if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError) { - isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); - throw isInNoLangugeModeException; + _isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); + throw _isInNoLangugeModeException; } else throw; } @@ -2931,7 +2922,7 @@ namespace System.Management.Automation { // Verify the runspace has is not in NoLanguage mode. For performance, return our // cached value if we got an error before. - if (isInNoLangugeModeException != null) + if (_isInNoLangugeModeException != null) return PSLanguageMode.NoLanguage; // Since these are implemented as pipelines, we don't need to do our own @@ -2949,13 +2940,13 @@ namespace System.Management.Automation { if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError) { - isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); + _isInNoLangugeModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e); return PSLanguageMode.NoLanguage; } else throw; } - return (PSLanguageMode) LanguagePrimitives.ConvertTo(result[0], typeof(PSLanguageMode), CultureInfo.InvariantCulture); + return (PSLanguageMode)LanguagePrimitives.ConvertTo(result[0], typeof(PSLanguageMode), CultureInfo.InvariantCulture); } set { diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index 5fe2bd85f..e4ba3bff1 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -10,18 +10,18 @@ namespace System.Management.Automation.Runspaces /// /// Computer target type /// - public enum TargetMachineType - { + public enum TargetMachineType + { /// /// Target is a machine with which the session is based on networking /// - RemoteMachine, - + RemoteMachine, + /// /// Target is a virtual machine with which the session is based on Hyper-V socket /// - VirtualMachine, - + VirtualMachine, + /// /// Target is a container with which the session is based on Hyper-V socket (Hyper-V /// container) or named pipe (windows container) @@ -43,17 +43,17 @@ namespace System.Management.Automation.Runspaces { #region Private Members - private RemoteRunspace remoteRunspace; - private String shell; - private TargetMachineType computerType; + private RemoteRunspace _remoteRunspace; + private String _shell; + private TargetMachineType _computerType; /// /// Static variable which is incremented to generate id /// - private static int seed = 0; + private static int s_seed = 0; - private int sessionid; - private String name; + private int _sessionid; + private String _name; #endregion Private Members @@ -66,11 +66,11 @@ namespace System.Management.Automation.Runspaces { get { - return computerType; + return _computerType; } set { - computerType = value; + _computerType = value; } } @@ -81,7 +81,7 @@ namespace System.Management.Automation.Runspaces { get { - return remoteRunspace.ConnectionInfo.ComputerName; + return _remoteRunspace.ConnectionInfo.ComputerName; } } @@ -94,7 +94,7 @@ namespace System.Management.Automation.Runspaces { if (ComputerType == TargetMachineType.Container) { - ContainerConnectionInfo connectionInfo = remoteRunspace.ConnectionInfo as ContainerConnectionInfo; + ContainerConnectionInfo connectionInfo = _remoteRunspace.ConnectionInfo as ContainerConnectionInfo; return connectionInfo.ContainerProc.ContainerId; } else @@ -113,7 +113,7 @@ namespace System.Management.Automation.Runspaces { if (ComputerType == TargetMachineType.VirtualMachine) { - return remoteRunspace.ConnectionInfo.ComputerName; + return _remoteRunspace.ConnectionInfo.ComputerName; } else { @@ -131,7 +131,7 @@ namespace System.Management.Automation.Runspaces { if (ComputerType == TargetMachineType.VirtualMachine) { - VMConnectionInfo connectionInfo = remoteRunspace.ConnectionInfo as VMConnectionInfo; + VMConnectionInfo connectionInfo = _remoteRunspace.ConnectionInfo as VMConnectionInfo; return connectionInfo.VMGuid; } else @@ -148,7 +148,7 @@ namespace System.Management.Automation.Runspaces { get { - return shell; + return _shell; } } @@ -159,7 +159,7 @@ namespace System.Management.Automation.Runspaces { get { - return remoteRunspace.InstanceId; + return _remoteRunspace.InstanceId; } } @@ -171,7 +171,7 @@ namespace System.Management.Automation.Runspaces { get { - return sessionid; + return _sessionid; } } @@ -182,15 +182,15 @@ namespace System.Management.Automation.Runspaces { get { - return name; + return _name; } set { - name = value; + _name = value; } } - + /// /// Indicates whether the specified runspace is available /// for executing commands @@ -210,8 +210,8 @@ namespace System.Management.Automation.Runspaces public PSPrimitiveDictionary ApplicationPrivateData { get - { - return this.Runspace.GetApplicationPrivateData(); + { + return this.Runspace.GetApplicationPrivateData(); } } @@ -226,7 +226,7 @@ namespace System.Management.Automation.Runspaces { get { - return remoteRunspace; + return _remoteRunspace; } } @@ -260,12 +260,12 @@ namespace System.Management.Automation.Runspaces internal bool InsertRunspace(RemoteRunspace remoteRunspace) { if (remoteRunspace == null || - remoteRunspace.InstanceId != this.remoteRunspace.InstanceId) + remoteRunspace.InstanceId != _remoteRunspace.InstanceId) { return false; } - this.remoteRunspace = remoteRunspace; + _remoteRunspace = remoteRunspace; return true; } @@ -281,40 +281,40 @@ namespace System.Management.Automation.Runspaces /// the info object need to be created internal PSSession(RemoteRunspace remoteRunspace) { - this.remoteRunspace = remoteRunspace; + _remoteRunspace = remoteRunspace; // Use passed in session Id, if available. if (remoteRunspace.PSSessionId != -1) { - sessionid = remoteRunspace.PSSessionId; + _sessionid = remoteRunspace.PSSessionId; } else { - sessionid = System.Threading.Interlocked.Increment(ref seed); - remoteRunspace.PSSessionId = sessionid; + _sessionid = System.Threading.Interlocked.Increment(ref s_seed); + remoteRunspace.PSSessionId = _sessionid; } // Use passed in friendly name, if available. if (!string.IsNullOrEmpty(remoteRunspace.PSSessionName)) { - name = remoteRunspace.PSSessionName; + _name = remoteRunspace.PSSessionName; } else { - name = AutoGenerateRunspaceName(); - remoteRunspace.PSSessionName = name; + _name = AutoGenerateRunspaceName(); + remoteRunspace.PSSessionName = _name; } // WSMan session if (remoteRunspace.ConnectionInfo is WSManConnectionInfo) { - computerType = TargetMachineType.RemoteMachine; + _computerType = TargetMachineType.RemoteMachine; string fullShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo( remoteRunspace.ConnectionInfo, "ShellUri", string.Empty); - - shell = GetDisplayShellName(fullShellName); + + _shell = GetDisplayShellName(fullShellName); return; } @@ -322,8 +322,8 @@ namespace System.Management.Automation.Runspaces VMConnectionInfo vmConnectionInfo = remoteRunspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) { - computerType = TargetMachineType.VirtualMachine; - shell = vmConnectionInfo.ConfigurationName; + _computerType = TargetMachineType.VirtualMachine; + _shell = vmConnectionInfo.ConfigurationName; return; } @@ -331,8 +331,8 @@ namespace System.Management.Automation.Runspaces ContainerConnectionInfo containerConnectionInfo = remoteRunspace.ConnectionInfo as ContainerConnectionInfo; if (containerConnectionInfo != null) { - computerType = TargetMachineType.Container; - shell = containerConnectionInfo.ContainerProc.ConfigurationName; + _computerType = TargetMachineType.Container; + _shell = containerConnectionInfo.ContainerProc.ConfigurationName; return; } @@ -350,7 +350,7 @@ namespace System.Management.Automation.Runspaces /// auto generated name private String AutoGenerateRunspaceName() { - return "Session" + sessionid.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + return "Session" + _sessionid.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); } /// @@ -377,7 +377,7 @@ namespace System.Management.Automation.Runspaces /// Returned name internal static String GenerateRunspaceName(out int rtnId) { - int id = System.Threading.Interlocked.Increment(ref seed); + int id = System.Threading.Interlocked.Increment(ref s_seed); rtnId = id; return ComposeRunspaceName(id); } @@ -388,7 +388,7 @@ namespace System.Management.Automation.Runspaces /// Id internal static int GenerateRunspaceId() { - return System.Threading.Interlocked.Increment(ref seed); + return System.Threading.Interlocked.Increment(ref s_seed); } /// diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs index 379e9a698..f61f85884 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs @@ -23,9 +23,9 @@ namespace System.Management.Automation.Remoting #region Abstract_API internal abstract void CreateAsync(); - + internal abstract event EventHandler ConnectionStateChanged; - + internal abstract void SendNegotiationAsync(RemoteSessionState sessionState); internal abstract event EventHandler NegotiationReceived; @@ -41,10 +41,10 @@ namespace System.Management.Automation.Remoting get; } - internal abstract BaseClientSessionTransportManager TransportManager { get;} + internal abstract BaseClientSessionTransportManager TransportManager { get; } internal abstract BaseClientCommandTransportManager CreateClientCommandTransportManager( - System.Management.Automation.Runspaces.Internal.ClientRemotePowerShell cmd, + System.Management.Automation.Runspaces.Internal.ClientRemotePowerShell cmd, bool noInput); // TODO: If this is not used, remove this. diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index 46398aedd..0f004ca91 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation.Remoting internal class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructureHandler, IDisposable { [TraceSourceAttribute("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); private const string resBaseName = "remotingerroridstrings"; private BaseClientSessionTransportManager _transportManager; @@ -25,12 +25,12 @@ namespace System.Management.Automation.Remoting private RunspaceConnectionInfo _connectionInfo; // used for connection redirection. private Uri _redirectUri; - private int maxUriRedirectionCount; - private bool isCloseCalled; - private object syncObject = new object(); + private int _maxUriRedirectionCount; + private bool _isCloseCalled; + private object _syncObject = new object(); private PSRemotingCryptoHelper _cryptoHelper; - private ClientRemoteSession.URIDirectionReported uriRedirectionHandler; + private ClientRemoteSession.URIDirectionReported _uriRedirectionHandler; internal override BaseClientSessionTransportManager TransportManager { @@ -57,12 +57,12 @@ namespace System.Management.Automation.Remoting /// /// Creates an instance of ClientRemoteSessionDSHandlerImpl /// - internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, + internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, ClientRemoteSession.URIDirectionReported uriRedirectionHandler) { - Dbg.Assert(maxUriRedirectionCount >= 0, "maxUriRedirectionCount cannot be less than 0."); + Dbg.Assert(_maxUriRedirectionCount >= 0, "maxUriRedirectionCount cannot be less than 0."); if (session == null) { @@ -99,8 +99,8 @@ namespace System.Management.Automation.Remoting // store the uri redirection handler and authmechanism // for uri redirection. - this.uriRedirectionHandler = uriRedirectionHandler; - this.maxUriRedirectionCount = wsmanConnectionInfo.MaximumConnectionRedirectionCount; + _uriRedirectionHandler = uriRedirectionHandler; + _maxUriRedirectionCount = wsmanConnectionInfo.MaximumConnectionRedirectionCount; } } @@ -160,7 +160,7 @@ namespace System.Management.Automation.Remoting #region RobustConnection events - void HandleRobustConnectionNotification(object sender, ConnectionStatusEventArgs e) + private void HandleRobustConnectionNotification(object sender, ConnectionStatusEventArgs e) { RemoteSessionStateMachineEventArgs eventArgument = null; switch (e.Notification) @@ -210,24 +210,24 @@ namespace System.Management.Automation.Remoting /// internal override void CloseConnectionAsync() { - lock (syncObject) + lock (_syncObject) { - if (isCloseCalled) + if (_isCloseCalled) { return; } _transportManager.CloseAsync(); - isCloseCalled = true; + _isCloseCalled = true; } } private void HandleCloseComplete(object sender, EventArgs args) { // This event gets raised only when the connection is closed successfully. - + RemoteSessionStateMachineEventArgs closeCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CloseCompleted); - _stateMachine.RaiseEvent(closeCompletedArg); + _stateMachine.RaiseEvent(closeCompletedArg); } @@ -256,7 +256,7 @@ namespace System.Management.Automation.Remoting else if (sessionState == RemoteSessionState.NegotiationSendingOnConnect) { _transportManager.ConnectCompleted += HandleConnectComplete; - _transportManager.ConnectAsync(); + _transportManager.ConnectAsync(); } else { @@ -304,7 +304,7 @@ namespace System.Management.Automation.Remoting if (tm != null) { tm.AdjustForProtocolVariations(_session.ServerProtocolVersion); - tm.StartReceivingData(); + tm.StartReceivingData(); } } @@ -381,10 +381,10 @@ namespace System.Management.Automation.Remoting _redirectUri = new Uri(newURIString); // make sure connection is not closed while we are handling the redirection. - lock (syncObject) + lock (_syncObject) { // if connection is closed by the user..no need to redirect - if (isCloseCalled) + if (_isCloseCalled) { return; } @@ -407,7 +407,7 @@ namespace System.Management.Automation.Remoting { _transportManager.CloseCompleted -= HandleTransportCloseCompleteForRedirection; _transportManager.WSManTransportErrorOccured -= HandleTransportErrorForRedirection; - + // reattach the close complete and error handlers _transportManager.CloseCompleted += HandleCloseComplete; _transportManager.WSManTransportErrorOccured += HandleTransportError; @@ -419,7 +419,7 @@ namespace System.Management.Automation.Remoting { _transportManager.CloseCompleted -= HandleTransportCloseCompleteForRedirection; _transportManager.WSManTransportErrorOccured -= HandleTransportErrorForRedirection; - + // reattach the close complete and error handlers _transportManager.CloseCompleted += HandleCloseComplete; _transportManager.WSManTransportErrorOccured += HandleTransportError; @@ -435,18 +435,18 @@ namespace System.Management.Automation.Remoting private void PerformURIRedirectionStep2(System.Uri newURI) { Dbg.Assert(null != newURI, "Uri cannot be null"); - lock (syncObject) + lock (_syncObject) { // if connection is closed by the user..no need to redirect - if (isCloseCalled) + if (_isCloseCalled) { return; } // raise warning to report the redirection - if (null != uriRedirectionHandler) + if (null != _uriRedirectionHandler) { - uriRedirectionHandler(newURI); + _uriRedirectionHandler(newURI); } // start a new connection @@ -468,14 +468,14 @@ namespace System.Management.Automation.Remoting Dbg.Assert(e != null, "HandleTransportError expects non-null eventargs"); // handle uri redirections PSRemotingTransportRedirectException redirectException = e.Exception as PSRemotingTransportRedirectException; - if ((redirectException != null) && (maxUriRedirectionCount > 0)) + if ((redirectException != null) && (_maxUriRedirectionCount > 0)) { Exception exception = null; try { // honor max redirection count given by the user. - maxUriRedirectionCount--; + _maxUriRedirectionCount--; PerformURIRedirection(redirectException.RedirectLocation); return; } @@ -492,7 +492,7 @@ namespace System.Management.Automation.Remoting { PSRemotingTransportException newException = new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted, - _session.Context.RemoteAddress.OriginalString, + _session.Context.RemoteAddress.OriginalString, redirectException.RedirectLocation); newException.TransportMessage = e.Exception.TransportMessage; e.Exception = newException; @@ -666,7 +666,7 @@ namespace System.Management.Automation.Remoting { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType); } - } + } } /// @@ -693,7 +693,7 @@ namespace System.Management.Automation.Remoting { case RemotingTargetInterface.Session: - Dbg.Assert(false, + Dbg.Assert(false, "The session remote data is handled my session data structure handler, not here"); break; @@ -710,7 +710,7 @@ namespace System.Management.Automation.Remoting { // The runspace pool may have been removed on the client side, // so, we should just ignore the message. - _trace.WriteLine(@"Client received data for Runspace (id: {0}), + s_trace.WriteLine(@"Client received data for Runspace (id: {0}), but the Runspace cannot be found", clientRunspacePoolId); } @@ -752,8 +752,8 @@ namespace System.Management.Automation.Remoting { if (disposing) { - _transportManager.Dispose(); - } + _transportManager.Dispose(); + } } #endregion IDisposable @@ -767,7 +767,7 @@ namespace System.Management.Automation.Remoting /// Send the specified local public key to the remote end /// /// local public key as a string - internal override void SendPublicKeyAsync(string localPublicKey) + internal override void SendPublicKeyAsync(string localPublicKey) { _transportManager.DataToBeSentCollection.Add( RemotingEncoder.GenerateMyPublicKey(_session.RemoteRunspacePoolInternal.InstanceId, @@ -786,5 +786,5 @@ namespace System.Management.Automation.Remoting } #endregion Key Exchange - } + } } diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index 8243626a3..aff5acc7c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -70,10 +70,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSSession[] Session { - get { return this.remotePSSessionInfo; } - set { this.remotePSSessionInfo = value; } + get { return _remotePSSessionInfo; } + set { _remotePSSessionInfo = value; } } - private PSSession[] remotePSSessionInfo; + private PSSession[] _remotePSSessionInfo; /// /// Computer names to connect to. @@ -87,10 +87,10 @@ namespace Microsoft.PowerShell.Commands [Alias("Cn")] public override String[] ComputerName { - get { return this.computerNames; } - set { this.computerNames = value; } + get { return _computerNames; } + set { _computerNames = value; } } - private String[] computerNames; + private String[] _computerNames; /// /// This parameters specifies the appname which identifies the connection @@ -104,13 +104,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = ConnectPSSessionCommand.ComputerNameGuidParameterSet)] public String ApplicationName { - get { return appName; } + get { return _appName; } set { - appName = ResolveAppName(value); + _appName = ResolveAppName(value); } } - private String appName; + private String _appName; /// /// If this parameter is not specified then the value specified in @@ -127,13 +127,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public String ConfigurationName { - get { return shell; } + get { return _shell; } set { - shell = ResolveShell(value); + _shell = ResolveShell(value); } } - private String shell; + private String _shell; /// /// A complete URI(s) specified for the remote computer and shell to @@ -150,10 +150,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Uri[] ConnectionUri { - get { return uris; } - set { uris = value; } + get { return _uris; } + set { _uris = value; } } - private Uri[] uris; + private Uri[] _uris; /// /// The AllowRedirection parameter enables the implicit redirection functionality. @@ -162,10 +162,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public SwitchParameter AllowRedirection { - get { return this.allowRedirection; } - set { this.allowRedirection = value; } + get { return _allowRedirection; } + set { _allowRedirection = value; } } - private bool allowRedirection = false; + private bool _allowRedirection = false; /// /// RemoteRunspaceId to retrieve corresponding PSSession @@ -211,15 +211,15 @@ namespace Microsoft.PowerShell.Commands [Credential()] public PSCredential Credential { - get { return this.psCredential; } - set - { - this.psCredential = value; + get { return _psCredential; } + set + { + _psCredential = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private PSCredential psCredential; + private PSCredential _psCredential; /// /// Use basic authentication to authenticate the user. @@ -230,15 +230,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public AuthenticationMechanism Authentication { - get { return this.authentication; } + get { return _authentication; } set { - this.authentication = value; + _authentication = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private AuthenticationMechanism authentication; + private AuthenticationMechanism _authentication; /// @@ -251,15 +251,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public string CertificateThumbprint { - get { return this.thumbprint; } + get { return _thumbprint; } set { - this.thumbprint = value; + _thumbprint = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private string thumbprint; + private string _thumbprint; /// @@ -280,14 +280,14 @@ namespace Microsoft.PowerShell.Commands { get { - return port; + return _port; } set { - port = value; + _port = value; } } - private Int32 port; + private Int32 _port; /// @@ -304,14 +304,14 @@ namespace Microsoft.PowerShell.Commands { get { - return useSSL; + return _useSSL; } set { - useSSL = value; + _useSSL = value; } } - private SwitchParameter useSSL; + private SwitchParameter _useSSL; /// @@ -323,10 +323,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public PSSessionOption SessionOption { - get { return this.sessionOption; } - set { this.sessionOption = value; } + get { return _sessionOption; } + set { _sessionOption = value; } } - private PSSessionOption sessionOption; + private PSSessionOption _sessionOption; /// @@ -344,10 +344,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ConnectPSSessionCommand.InstanceIdParameterSet)] public Int32 ThrottleLimit { - get { return this.throttleLimit; } - set { this.throttleLimit = value; } + get { return _throttleLimit; } + set { _throttleLimit = value; } } - private Int32 throttleLimit = 0; + private Int32 _throttleLimit = 0; /// /// Overriding to suppress this parameter @@ -393,8 +393,8 @@ namespace Microsoft.PowerShell.Commands { base.BeginProcessing(); - this.throttleManager.ThrottleLimit = ThrottleLimit; - this.throttleManager.ThrottleComplete += new EventHandler(HandleThrottleConnectComplete); + _throttleManager.ThrottleLimit = ThrottleLimit; + _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleConnectComplete); } /// @@ -423,25 +423,25 @@ namespace Microsoft.PowerShell.Commands catch (PSRemotingDataStructureException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (PSRemotingTransportException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (RemoteException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (InvalidRunspaceStateException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } @@ -453,29 +453,29 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - this.throttleManager.EndSubmitOperations(); + _throttleManager.EndSubmitOperations(); // Wait for all connect operations to complete. - this.operationsComplete.WaitOne(); + _operationsComplete.WaitOne(); // If there are failed connect operations due to stale // session state then perform the query retry here. - if (failedSessions.Count > 0) + if (_failedSessions.Count > 0) { RetryFailedSessions(); } // Read all objects in the stream pipeline. - while (this.stream.ObjectReader.Count > 0) + while (_stream.ObjectReader.Count > 0) { - Object streamObject = stream.ObjectReader.Read(); + Object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action)streamObject); } - this.stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); // Add all successfully connected sessions to local repository. - foreach (PSSession psSession in this.allSessions) + foreach (PSSession psSession in _allSessions) { if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { @@ -492,17 +492,17 @@ namespace Microsoft.PowerShell.Commands protected override void StopProcessing() { // Close the output stream for any further writes. - this.stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); // Stop any remote server queries that may be running. - this.queryRunspaces.StopAllOperations(); + _queryRunspaces.StopAllOperations(); // Signal the ThrottleManager to stop any further // PSSession connect processing. - this.throttleManager.StopAllOperations(); + _throttleManager.StopAllOperations(); // Signal the Retry throttle manager in case it is running. - this.retryThrottleManager.StopAllOperations(); + _retryThrottleManager.StopAllOperations(); } #endregion @@ -523,7 +523,7 @@ namespace Microsoft.PowerShell.Commands private static object s_LockObject = new object(); internal ConnectRunspaceOperation( - PSSession session, + PSSession session, ObjectStream stream, PSHost host, QueryRunspaces queryRunspaces, @@ -675,7 +675,7 @@ namespace Microsoft.PowerShell.Commands writeError = false; } } - + if (writeError) { // Connect operation failed, write error. @@ -730,7 +730,7 @@ namespace Microsoft.PowerShell.Commands // and this particular method may be called on a thread that // is different from Pipeline Execution Thread. Hence using // a delegate to perform the WriteObject. - Action outputWriter = delegate(Cmdlet cmdlet) + Action outputWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteObject(outSession); }; @@ -766,7 +766,7 @@ namespace Microsoft.PowerShell.Commands session.Runspace.RunspaceStateInfo.State.ToString()), null); } ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; @@ -809,12 +809,12 @@ namespace Microsoft.PowerShell.Commands private Collection QueryForDisconnectedSessions() { Collection connectionInfos = GetConnectionObjects(); - Collection psSessions = this.queryRunspaces.GetDisconnectedSessions(connectionInfos, this.Host, this.stream, - this.RunspaceRepository, this.throttleLimit, + Collection psSessions = _queryRunspaces.GetDisconnectedSessions(connectionInfos, this.Host, _stream, + this.RunspaceRepository, _throttleLimit, SessionFilterState.Disconnected, this.InstanceId, this.Name, ConfigurationName); - + // Write any error output from stream object. - Collection streamObjects = this.stream.ObjectReader.NonBlockingRead(); + Collection streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action)streamObject); @@ -835,9 +835,9 @@ namespace Microsoft.PowerShell.Commands // Get all remote runspaces to disconnect. if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet) { - if (this.remotePSSessionInfo != null) + if (_remotePSSessionInfo != null) { - foreach (PSSession psSession in this.remotePSSessionInfo) + foreach (PSSession psSession in _remotePSSessionInfo) { psSessions.Add(psSession); } @@ -904,10 +904,10 @@ namespace Microsoft.PowerShell.Commands ConnectRunspaceOperation connectOperation = new ConnectRunspaceOperation( psSession, - this.stream, + _stream, this.Host, null, - this.failedSessions); + _failedSessions); connectOperations.Add(connectOperation); } else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) @@ -925,19 +925,19 @@ namespace Microsoft.PowerShell.Commands } } - this.allSessions.Add(psSession); + _allSessions.Add(psSession); } if (connectOperations.Count > 0) { // Make sure operations are not set as complete while processing input. - this.operationsComplete.Reset(); + _operationsComplete.Reset(); // Submit list of connect operations. - this.throttleManager.SubmitOperations(connectOperations); + _throttleManager.SubmitOperations(connectOperations); // Write any output now. - Collection streamObjects = this.stream.ObjectReader.NonBlockingRead(); + Collection streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action)streamObject); @@ -952,7 +952,7 @@ namespace Microsoft.PowerShell.Commands /// EventArgs private void HandleThrottleConnectComplete(object sender, EventArgs eventArgs) { - this.operationsComplete.Set(); + _operationsComplete.Set(); } private Collection GetConnectionObjects() @@ -1025,7 +1025,7 @@ namespace Microsoft.PowerShell.Commands connectionInfo.MaximumConnectionRedirectionCount = 0; } - if (!this.allowRedirection) + if (!_allowRedirection) { // uri redirection required explicit user consent connectionInfo.MaximumConnectionRedirectionCount = 0; @@ -1044,8 +1044,8 @@ namespace Microsoft.PowerShell.Commands { Collection connectedSessions = new Collection(); List retryConnectionOperations = new List(); - retryThrottleManager.ThrottleLimit = ThrottleLimit; - retryThrottleManager.ThrottleComplete += (sender, eventArgs) => + _retryThrottleManager.ThrottleLimit = ThrottleLimit; + _retryThrottleManager.ThrottleComplete += (sender, eventArgs) => { try { @@ -1054,18 +1054,18 @@ namespace Microsoft.PowerShell.Commands catch (ObjectDisposedException) { } }; - foreach (var session in failedSessions) + foreach (var session in _failedSessions) { retryConnectionOperations.Add(new ConnectRunspaceOperation( session, - this.stream, + _stream, this.Host, new QueryRunspaces(), connectedSessions)); } - retryThrottleManager.SubmitOperations(retryConnectionOperations); - retryThrottleManager.EndSubmitOperations(); + _retryThrottleManager.SubmitOperations(retryConnectionOperations); + _retryThrottleManager.EndSubmitOperations(); retrysComplete.WaitOne(); @@ -1103,15 +1103,15 @@ namespace Microsoft.PowerShell.Commands { if (disposing) { - this.throttleManager.Dispose(); + _throttleManager.Dispose(); - this.operationsComplete.WaitOne(); - this.operationsComplete.Dispose(); + _operationsComplete.WaitOne(); + _operationsComplete.Dispose(); - this.throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleConnectComplete); - this.retryThrottleManager.Dispose(); + _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleConnectComplete); + _retryThrottleManager.Dispose(); - this.stream.Dispose(); + _stream.Dispose(); } } @@ -1120,24 +1120,24 @@ namespace Microsoft.PowerShell.Commands #region Private Members // Collection of PSSessions to be connected. - private Collection allSessions = new Collection(); + private Collection _allSessions = new Collection(); // Object used to perform network disconnect operations in a limited manner. - private ThrottleManager throttleManager = new ThrottleManager(); + private ThrottleManager _throttleManager = new ThrottleManager(); // Event indicating that all disconnect operations through the ThrottleManager // are complete. - private ManualResetEvent operationsComplete = new ManualResetEvent(true); + private ManualResetEvent _operationsComplete = new ManualResetEvent(true); // Object used for querying remote runspaces. - QueryRunspaces queryRunspaces = new QueryRunspaces(); + private QueryRunspaces _queryRunspaces = new QueryRunspaces(); // Object to collect output data from multiple threads. - private ObjectStream stream = new ObjectStream(); + private ObjectStream _stream = new ObjectStream(); // Support for connection retry on failure. - private ThrottleManager retryThrottleManager = new ThrottleManager(); - private Collection failedSessions = new Collection(); + private ThrottleManager _retryThrottleManager = new ThrottleManager(); + private Collection _failedSessions = new Collection(); #endregion } @@ -1150,7 +1150,7 @@ namespace Microsoft.PowerShell.Commands internal QueryRunspaces() { - this.stopProcessing = false; + _stopProcessing = false; } #endregion @@ -1172,9 +1172,9 @@ namespace Microsoft.PowerShell.Commands /// Array of session Names to match to. /// Configuration name to match to. /// Collection of disconnected PSSession objects. - internal Collection GetDisconnectedSessions(Collection connectionInfos, PSHost host, - ObjectStream stream, RunspaceRepository runspaceRepository, - int throttleLimit, SessionFilterState filterState, + internal Collection GetDisconnectedSessions(Collection connectionInfos, PSHost host, + ObjectStream stream, RunspaceRepository runspaceRepository, + int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection filteredPSSesions = new Collection(); @@ -1204,7 +1204,7 @@ namespace Microsoft.PowerShell.Commands Exception reason = new RuntimeException(msg, e.InnerException); ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo); stream.ObjectWriter.Write((Action)(cmdlet => cmdlet.WriteError(errorRecord))); - } + } } else { @@ -1212,7 +1212,7 @@ namespace Microsoft.PowerShell.Commands } } - if (this.stopProcessing) + if (_stopProcessing) { break; } @@ -1270,7 +1270,7 @@ namespace Microsoft.PowerShell.Commands } // Return only PSSessions that match provided Ids or Names. - if ((matchIds != null) && (filteredPSSesions.Count > 0)) + if ((matchIds != null) && (filteredPSSesions.Count > 0)) { Collection matchIdsSessions = new Collection(); foreach (Guid id in matchIds) @@ -1278,7 +1278,7 @@ namespace Microsoft.PowerShell.Commands bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { - if (this.stopProcessing) + if (_stopProcessing) { break; } @@ -1312,7 +1312,7 @@ namespace Microsoft.PowerShell.Commands bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { - if (this.stopProcessing) + if (_stopProcessing) { break; } @@ -1390,7 +1390,7 @@ namespace Microsoft.PowerShell.Commands if (e == null || e.Message == null) - { + { return string.Empty; } @@ -1448,7 +1448,7 @@ namespace Microsoft.PowerShell.Commands /// internal void StopAllOperations() { - this.stopProcessing = true; + _stopProcessing = true; } /// @@ -1518,13 +1518,12 @@ namespace Microsoft.PowerShell.Commands #region Private Members - private bool stopProcessing; + private bool _stopProcessing; private static readonly object s_SyncObject = new object(); private static TypeTable s_TypeTable; #endregion - } #endregion diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 623eb116c..6843fb2f5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -31,7 +31,7 @@ using System.Security.Principal; // Some APIs are missing from System.Environment. We use System.Management.Automation.Environment as a proxy type: // - for missing APIs, System.Management.Automation.Environment has extension implementation. // - for existing APIs, System.Management.Automation.Environment redirect the call to System.Environment. -using Environment = System.Management.Automation.Environment; +using Environment = System.Management.Automation.Environment; #endif namespace Microsoft.PowerShell.Commands @@ -272,7 +272,7 @@ else Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -erroraction $args[14] }} "; - private static readonly ScriptBlock newPluginSb; + private static readonly ScriptBlock s_newPluginSb; private const string pluginXmlFormat = @" {0}"; - private string gmsaAccount; - private string configTableSDDL; + private string _gmsaAccount; + private string _configTableSDDL; // true if there are errors running the wsman's configuration // command - private bool isErrorReported; + private bool _isErrorReported; #endregion @@ -337,20 +337,20 @@ else { get { - return architecture; + return _architecture; } set { - architecture = value; + _architecture = value; } } - private string architecture; + private string _architecture; /// /// SessionType /// /// Only want this on non assemblyName parameter set, since assembly decides the sessiontype. - [Parameter (ParameterSetName = PSSessionConfigurationCommandBase.NameParameterSetName)] + [Parameter(ParameterSetName = PSSessionConfigurationCommandBase.NameParameterSetName)] public PSSessionType SessionType { get @@ -378,8 +378,8 @@ else newPluginSbFormat, WSManNativeApi.ResourceURIPrefix, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID); - newPluginSb = ScriptBlock.Create(newPluginSbString); - newPluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_newPluginSb = ScriptBlock.Create(newPluginSbString); + s_newPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -443,7 +443,7 @@ else // BA SecurityIdentifier baSidIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, baSidIdentifier, 268435456, InheritanceFlags.None, PropagationFlags.None); - + // Only for Win8+ if (Environment.OSVersion.Version >= new Version(6, 2)) { @@ -546,9 +546,9 @@ else } // Use the Group Managed Service Account if provided. - if (!isRunAsCredentialSpecified && !string.IsNullOrEmpty(this.gmsaAccount)) + if (!isRunAsCredentialSpecified && !string.IsNullOrEmpty(_gmsaAccount)) { - runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(this.gmsaAccount); + runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(_gmsaAccount); } try @@ -577,7 +577,7 @@ else ArrayList errorList = (ArrayList)Context.DollarErrorVariable; int errorCountBefore = errorList.Count; - if (force && + if (force && this.Context != null && this.Context.EngineHostInterface != null && this.Context.EngineHostInterface.ExternalHost != null && @@ -586,7 +586,7 @@ else WriteWarning(RemotingErrorIdStrings.WinRMForceRestartWarning); } - newPluginSb.InvokeUsingCmdlet( + s_newPluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -607,13 +607,12 @@ else runAsCredential != null ? runAsCredential.Password : null, AccessMode, isSddlSpecified, - this.configTableSDDL, + _configTableSDDL, errorAction }); errorList = (ArrayList)Context.DollarErrorVariable; - isErrorReported = errorList.Count > errorCountBefore; - + _isErrorReported = errorList.Count > errorCountBefore; } finally { @@ -940,12 +939,12 @@ else if (configTable.ContainsKey(ConfigFileConstants.GMSAAccount)) { - this.gmsaAccount = configTable[ConfigFileConstants.GMSAAccount] as string; + _gmsaAccount = configTable[ConfigFileConstants.GMSAAccount] as string; } // Get role account and group restriction SDDL from configuration table, if any. ErrorRecord error; - this.configTableSDDL = PSSessionConfigurationCommandUtilities.ComputeSDDLFromConfiguration( + _configTableSDDL = PSSessionConfigurationCommandUtilities.ComputeSDDLFromConfiguration( configTable, AccessMode, out error); @@ -955,7 +954,7 @@ else } // Update default Sddl with any group membership requirements. - if (string.IsNullOrEmpty(configTableSDDL) && !this.isSddlSpecified && !string.IsNullOrEmpty(sddl)) + if (string.IsNullOrEmpty(_configTableSDDL) && !this.isSddlSpecified && !string.IsNullOrEmpty(sddl)) { string configGroupMemberShipACE = PSSessionConfigurationCommandUtilities.CreateConditionalACEFromConfig(configTable); if (!string.IsNullOrEmpty(configGroupMemberShipACE)) @@ -985,7 +984,7 @@ else string destPath = System.IO.Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "SessionConfig", shellName + "_" + sessionGuid.ToString() + StringLiterals.PowerShellDISCFileExtension); - if (string.Equals(ProcessorArchitecture,"x86", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(ProcessorArchitecture, "x86", StringComparison.OrdinalIgnoreCase)) { string procArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); @@ -1125,10 +1124,10 @@ else } string architectureParameter = string.Empty; - if (!string.IsNullOrEmpty(architecture)) + if (!string.IsNullOrEmpty(_architecture)) { string tempValue = "32"; - switch (architecture.ToLowerInvariant()) + switch (_architecture.ToLowerInvariant()) { case "x86": tempValue = "32"; @@ -1266,7 +1265,6 @@ else } #endregion - } #endregion Register-PSSessionConfiguration cmdlet @@ -1509,7 +1507,6 @@ else PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NetFrameWorkV2NotInstalled)); } - } catch (PSArgumentException) { @@ -1862,7 +1859,7 @@ else if (values != null) { int count = values.Length; - for (int i = 0; i < count; ) + for (int i = 0; i < count;) { ParseValues(sb, values[i++]); if (i < count) @@ -1975,7 +1972,6 @@ else internal static string GetRemoteSddl() { return (Environment.OSVersion.Version >= new Version(6, 2)) ? remoteSDDL_Win8 : remoteSDDL; - } internal static void CheckPSVersion(Version version) @@ -2137,14 +2133,14 @@ else [Parameter] public PSSessionConfigurationAccessMode AccessMode { - get { return accessMode; } + get { return _accessMode; } set { - accessMode = value; + _accessMode = value; accessModeSpecified = true; } } - private PSSessionConfigurationAccessMode accessMode = PSSessionConfigurationAccessMode.Remote; + private PSSessionConfigurationAccessMode _accessMode = PSSessionConfigurationAccessMode.Remote; internal bool accessModeSpecified = false; /// @@ -2155,15 +2151,15 @@ else { get { - return useSharedProcess; + return _useSharedProcess; } set { - useSharedProcess = value; + _useSharedProcess = value; isUseSharedProcessSpecified = true; } } - private bool useSharedProcess; + private bool _useSharedProcess; internal bool isUseSharedProcessSpecified; /// @@ -2267,14 +2263,14 @@ else [Parameter()] public SwitchParameter ShowSecurityDescriptorUI { - get { return showUI; } + get { return _showUI; } set { - showUI = value; + _showUI = value; showUISpecified = true; } } - private bool showUI; + private bool _showUI; internal bool showUISpecified; /// @@ -2430,33 +2426,33 @@ else { get { - return configPath; + return _configPath; } set { - configPath = value; + _configPath = value; } } - private string configPath; + private string _configPath; // Other helper variables that come along with the path /// /// protected bool RunAsVirtualAccount { - get { return runAsVirtualAccount; } - set { runAsVirtualAccount = value; } + get { return _runAsVirtualAccount; } + set { _runAsVirtualAccount = value; } } - private bool runAsVirtualAccount = false; + private bool _runAsVirtualAccount = false; /// /// protected bool RunAsVirtualAccountSpecified { - get { return runAsVirtualAccountSpecified; } - set { runAsVirtualAccountSpecified = value; } + get { return _runAsVirtualAccountSpecified; } + set { _runAsVirtualAccountSpecified = value; } } - private bool runAsVirtualAccountSpecified = false; + private bool _runAsVirtualAccountSpecified = false; /// /// Comma delimited string specifying groups a virtual account is associated with @@ -2563,8 +2559,8 @@ else Unregister-PSSessionConfiguration -filter $args[0] -whatif:$args[1] -confirm:$args[2] -action $args[3] -targetTemplate $args[4] -shellNotErrMsgFormat $args[5] -force $args[6] -erroraction $args[7] }} "; - private static readonly ScriptBlock removePluginSb; - private bool isErrorReported; + private static readonly ScriptBlock s_removePluginSb; + private bool _isErrorReported; #endregion @@ -2580,14 +2576,14 @@ else { get { - return shellName; + return _shellName; } set { - shellName = value; + _shellName = value; } } - private string shellName; + private string _shellName; /// /// Property that sets force parameter. This will allow @@ -2599,14 +2595,14 @@ else { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// If true, then the cmdlet will not attempt to restart @@ -2618,14 +2614,14 @@ else { get { - return noRestart; + return _noRestart; } set { - noRestart = value; + _noRestart = value; } } - private bool noRestart; + private bool _noRestart; #endregion @@ -2638,8 +2634,8 @@ else RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - removePluginSb = ScriptBlock.Create(removePluginScript); - removePluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_removePluginSb = ScriptBlock.Create(removePluginScript); + s_removePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -2681,7 +2677,7 @@ else ArrayList errorList = (ArrayList)Context.DollarErrorVariable; int errorCountBefore = errorList.Count; - removePluginSb.InvokeUsingCmdlet( + s_removePluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -2689,18 +2685,18 @@ else input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - shellName, + _shellName, whatIf, confirm, action, targetTemplate, csNotFoundMessageFormat, - force, + _force, errorAction }); errorList = (ArrayList)Context.DollarErrorVariable; - isErrorReported = errorList.Count > errorCountBefore; + _isErrorReported = errorList.Count > errorCountBefore; } /// @@ -2849,7 +2845,7 @@ $args[0] | foreach {{ "; private const string MODULEPATH = "ModulesToImport"; - private static readonly ScriptBlock getPluginSb; + private static readonly ScriptBlock s_getPluginSb; #endregion @@ -2863,8 +2859,8 @@ $args[0] | foreach {{ RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - getPluginSb = ScriptBlock.Create(scriptToRun); - getPluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_getPluginSb = ScriptBlock.Create(scriptToRun); + s_getPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -2879,14 +2875,14 @@ $args[0] | foreach {{ { get { - return shellName; + return _shellName; } set { - shellName = value; + _shellName = value; } } - private string[] shellName; + private string[] _shellName; /// /// Force parameter @@ -2896,14 +2892,14 @@ $args[0] | foreach {{ { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; #endregion @@ -2926,9 +2922,9 @@ $args[0] | foreach {{ string csNotFoundMessageFormat = RemotingErrorIdStrings.CustomShellNotFound; object arguments = "*"; - if (null != shellName) + if (null != _shellName) { - arguments = shellName; + arguments = _shellName; } ActionPreference backupPreference = Context.ErrorActionPreferenceVariable; @@ -2939,7 +2935,7 @@ $args[0] | foreach {{ Context.ErrorActionPreferenceVariable = Context.CurrentCommandProcessor.CommandRuntime.ErrorAction; } - getPluginSb.InvokeUsingCmdlet( + s_getPluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -2949,7 +2945,7 @@ $args[0] | foreach {{ args: new object[] { arguments, csNotFoundMessageFormat, - force} + _force} ); } finally @@ -3244,9 +3240,9 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] private const string UseSharedProcessToken = "UseSharedProcess"; private const string AllowRemoteAccessToken = "Enabled"; - private static readonly ScriptBlock setPluginSb; + private static readonly ScriptBlock s_setPluginSb; // property names used by the script to update InitParameters. - private static readonly string[] initParametersMap = new string[] { + private static readonly string[] s_initParametersMap = new string[] { ConfigurationDataFromXML.APPBASETOKEN, ConfigurationDataFromXML.ASSEMBLYTOKEN, ConfigurationDataFromXML.SHELLCONFIGTYPETOKEN, @@ -3262,13 +3258,13 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] ConfigurationDataFromXML.SESSIONCONFIGTOKEN, }; - private bool isErrorReported; - - private Hashtable configTable; - private string configFilePath; + private bool _isErrorReported; - private string gmsaAccount; - private string configSddl; + private Hashtable _configTable; + private string _configFilePath; + + private string _gmsaAccount; + private string _configSddl; #endregion @@ -3283,8 +3279,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - setPluginSb = ScriptBlock.Create(setPluginScript); - setPluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_setPluginSb = ScriptBlock.Create(setPluginScript); + s_setPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -3314,21 +3310,21 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] } // Populate the configTable hash, and get its SDDL if needed - if(Path != null) + if (Path != null) { ProviderInfo provider = null; PSDriveInfo drive; - configFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(Path, out provider, out drive); + _configFilePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(Path, out provider, out drive); string scriptName; - ExternalScriptInfo scriptInfo = DISCUtils.GetScriptInfoForFile(this.Context, configFilePath, out scriptName); - configTable = DISCUtils.LoadConfigFile(this.Context, scriptInfo); + ExternalScriptInfo scriptInfo = DISCUtils.GetScriptInfoForFile(this.Context, _configFilePath, out scriptName); + _configTable = DISCUtils.LoadConfigFile(this.Context, scriptInfo); if (!isSddlSpecified) { ErrorRecord error; - configSddl = PSSessionConfigurationCommandUtilities.ComputeSDDLFromConfiguration( - configTable, + _configSddl = PSSessionConfigurationCommandUtilities.ComputeSDDLFromConfiguration( + _configTable, AccessMode, out error); if (error != null) @@ -3336,24 +3332,24 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] WriteError(error); } - if (!string.IsNullOrEmpty(configSddl)) + if (!string.IsNullOrEmpty(_configSddl)) { // Use Sddl from configuration. isSddlSpecified = true; - SecurityDescriptorSddl = configSddl; + SecurityDescriptorSddl = _configSddl; } } - if (configTable.ContainsKey(ConfigFileConstants.RunAsVirtualAccount)) + if (_configTable.ContainsKey(ConfigFileConstants.RunAsVirtualAccount)) { - this.RunAsVirtualAccount = LanguagePrimitives.ConvertTo(configTable[ConfigFileConstants.RunAsVirtualAccount]); + this.RunAsVirtualAccount = LanguagePrimitives.ConvertTo(_configTable[ConfigFileConstants.RunAsVirtualAccount]); this.RunAsVirtualAccountSpecified = true; } - if (configTable.ContainsKey(ConfigFileConstants.RunAsVirtualAccountGroups)) + if (_configTable.ContainsKey(ConfigFileConstants.RunAsVirtualAccountGroups)) { this.RunAsVirtualAccountGroups = PSSessionConfigurationCommandUtilities.GetRunAsVirtualAccountGroupsString( - DISCPowerShellConfiguration.TryGetStringArray(configTable[ConfigFileConstants.RunAsVirtualAccountGroups])); + DISCPowerShellConfiguration.TryGetStringArray(_configTable[ConfigFileConstants.RunAsVirtualAccountGroups])); } } @@ -3466,27 +3462,27 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] } // Update the PSSC file if there was one - if (configTable != null) + if (_configTable != null) { Guid sessionGuid = Guid.Empty; // Extract the GUID for the configuration - if (configTable.ContainsKey(ConfigFileConstants.Guid)) + if (_configTable.ContainsKey(ConfigFileConstants.Guid)) { - sessionGuid = Guid.Parse(configTable[ConfigFileConstants.Guid].ToString()); + sessionGuid = Guid.Parse(_configTable[ConfigFileConstants.Guid].ToString()); } // Extract the GMSA account name if available - if (configTable.ContainsKey(ConfigFileConstants.GMSAAccount)) + if (_configTable.ContainsKey(ConfigFileConstants.GMSAAccount)) { - this.gmsaAccount = configTable[ConfigFileConstants.GMSAAccount] as string; + _gmsaAccount = _configTable[ConfigFileConstants.GMSAAccount] as string; } string destPath = System.IO.Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "SessionConfig", shellName + "_" + sessionGuid.ToString() + StringLiterals.PowerShellDISCFileExtension); // If the config file with the same guid name already exists then it would be overwritten. - File.Copy(configFilePath, destPath, true); + File.Copy(_configFilePath, destPath, true); } @@ -3499,7 +3495,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] // hack to see if there is any error reported running the script. ArrayList errorList = (ArrayList)Context.DollarErrorVariable; int errorCountBefore = errorList.Count; - setPluginSb.InvokeUsingCmdlet( + s_setPluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -3508,7 +3504,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] scriptThis: AutomationNull.Value, args: new object[] { propertiesToUpdate, - initParametersMap, + s_initParametersMap, force, sddl, isSddlSpecified, @@ -3520,11 +3516,11 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] }); - errorList = (ArrayList) Context.DollarErrorVariable; + errorList = (ArrayList)Context.DollarErrorVariable; if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3532,7 +3528,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3540,7 +3536,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3548,7 +3544,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3556,7 +3552,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3568,7 +3564,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } @@ -3576,7 +3572,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (errorList.Count > errorCountBefore) { - isErrorReported = true; + _isErrorReported = true; return; } } @@ -3585,8 +3581,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] { if (this.runAsCredential == null) { - if (string.IsNullOrEmpty(this.gmsaAccount)) { return; } - runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(this.gmsaAccount); + if (string.IsNullOrEmpty(_gmsaAccount)) { return; } + runAsCredential = PSSessionConfigurationCommandUtilities.CreateGMSAAccountCredentials(_gmsaAccount); } ScriptBlock setRunAsSbFormatSb = ScriptBlock.Create( @@ -3601,14 +3597,14 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - runAsCredential.UserName, + runAsCredential.UserName, runAsCredential.Password, - }); + }); } private void SetVirtualAccount() { - if (! this.RunAsVirtualAccountSpecified) + if (!this.RunAsVirtualAccountSpecified) return; using (System.Management.Automation.PowerShell invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) @@ -3630,7 +3626,7 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] Hashtable quotas = transportOption.ConstructQuotasAsHashtable(); int idleTimeOut = 0; - + if (idleTimeOut != 0 && quotas.ContainsKey(WSManConfigurationOption.AttribMaxIdleTimeout)) { bool setMaxIdleTimoutFirst = true; @@ -3728,9 +3724,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - optionsTable, - }); - + optionsTable, + }); } private void SetSessionConfigurationTypeOptions() @@ -3757,8 +3752,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] if (modulePathSpecified) { bool isWorkflowConfiguration = IsWorkflowConfigurationType(ps); - if (modulesToImport == null || - modulesToImport.Length == 0 || + if (modulesToImport == null || + modulesToImport.Length == 0 || (modulesToImport.Length == 1 && modulesToImport[0] is string && ((string)modulesToImport[0]).Equals(string.Empty, StringComparison.OrdinalIgnoreCase))) { unsetModulePath = true; @@ -3833,8 +3828,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - encodedSessionConfigData, - }); + encodedSessionConfigData, + }); } } } @@ -3844,8 +3839,8 @@ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] /// protected override void EndProcessing() { - PSSessionConfigurationCommandUtilities.RestartWinRMService(this, isErrorReported, Force, noRestart); - if (!isErrorReported && noRestart) + PSSessionConfigurationCommandUtilities.RestartWinRMService(this, _isErrorReported, Force, noRestart); + if (!_isErrorReported && noRestart) { string action = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction, this.CommandInfo.Name); WriteWarning(StringUtil.Format(RemotingErrorIdStrings.WinRMRequiresRestart, action)); @@ -4312,7 +4307,7 @@ param( $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecified $args[2] -queryForSet $args[3] -captionForSet $args[4] -queryForQC $args[5] -captionForQC $args[6] -whatif:$args[7] -confirm:$args[8] -shouldProcessDescForQC $args[9] -setEnabledTarget $args[10] -setEnabledAction $args[11] -skipNetworkProfileCheck $args[12] -noServiceRestart $args[13] "; - private static ScriptBlock enablePluginSb; + private static ScriptBlock s_enablePluginSb; #endregion @@ -4325,8 +4320,8 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - enablePluginSb = ScriptBlock.Create(enablePluginScript); - enablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_enablePluginSb = ScriptBlock.Create(enablePluginScript); + s_enablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -4343,15 +4338,15 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi { get { - return shellName; + return _shellName; } set { - shellName = value; + _shellName = value; } } - private string[] shellName; - private Collection shellsToEnable = new Collection(); + private string[] _shellName; + private Collection _shellsToEnable = new Collection(); /// /// Property that sets force parameter. This will allow @@ -4363,14 +4358,14 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// This enables the user to specify an SDDL for whom the session @@ -4412,10 +4407,10 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi [Parameter()] public SwitchParameter SkipNetworkProfileCheck { - get { return skipNetworkProfileCheck; } - set { skipNetworkProfileCheck = value; } + get { return _skipNetworkProfileCheck; } + set { _skipNetworkProfileCheck = value; } } - private bool skipNetworkProfileCheck; + private bool _skipNetworkProfileCheck; /// /// If true, then the cmdlet will not attempt to restart @@ -4425,10 +4420,10 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi [Parameter()] public SwitchParameter NoServiceRestart { - get { return noRestart; } - set { noRestart = value; } + get { return _noRestart; } + set { _noRestart = value; } } - private bool noRestart; + private bool _noRestart; #endregion @@ -4453,11 +4448,11 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi /// protected override void ProcessRecord() { - if (shellName != null) + if (_shellName != null) { - foreach (string shell in shellName) + foreach (string shell in _shellName) { - shellsToEnable.Add(shell); + _shellsToEnable.Add(shell); } } } @@ -4468,9 +4463,9 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi protected override void EndProcessing() { // if user did not specify any shell, act on the default shell. - if (shellsToEnable.Count == 0) + if (_shellsToEnable.Count == 0) { - shellsToEnable.Add(RemotingConstants.DefaultShellName); + _shellsToEnable.Add(RemotingConstants.DefaultShellName); } WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.EcsScriptMessageV, enablePluginSbFormat)); @@ -4490,15 +4485,15 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi string setEnabledAction = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction, "Set-Item"); string setEnabledTarget = RemotingErrorIdStrings.SetEnabledTrueTarget; - enablePluginSb.InvokeUsingCmdlet( + s_enablePluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: shellsToEnable, + dollarUnder: _shellsToEnable, input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - force, + _force, sddl, isSddlSpecified, setQueryMessage, @@ -4510,8 +4505,8 @@ $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecifi qcShoudProcessDesc, setEnabledTarget, setEnabledAction, - skipNetworkProfileCheck, - noRestart}); + _skipNetworkProfileCheck, + _noRestart}); System.Management.Automation.Tracing.Tracer tracer = new System.Management.Automation.Tracing.Tracer(); @@ -4606,7 +4601,7 @@ param( $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$args[2] -restartWinRMMessage $args[3] -setEnabledTarget $args[4] -setEnabledAction $args[5] -noServiceRestart $args[6] "; - private static ScriptBlock disablePluginSb; + private static ScriptBlock s_disablePluginSb; #endregion @@ -4619,8 +4614,8 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - disablePluginSb = ScriptBlock.Create(disablePluginScript); - disablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; + s_disablePluginSb = ScriptBlock.Create(disablePluginScript); + s_disablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -4637,15 +4632,15 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a { get { - return shellName; + return _shellName; } set { - shellName = value; + _shellName = value; } } - private string[] shellName; - private Collection shellsToDisable = new Collection(); + private string[] _shellName; + private Collection _shellsToDisable = new Collection(); /// /// Property that sets force parameter. This will allow @@ -4657,14 +4652,14 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// If true, then the cmdlet will not attempt to restart @@ -4674,10 +4669,10 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a [Parameter()] public SwitchParameter NoServiceRestart { - get { return noRestart; } - set { noRestart = value; } + get { return _noRestart; } + set { _noRestart = value; } } - private bool noRestart; + private bool _noRestart; #endregion @@ -4702,11 +4697,11 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a /// protected override void ProcessRecord() { - if (shellName != null) + if (_shellName != null) { - foreach (string shell in shellName) + foreach (string shell in _shellName) { - shellsToDisable.Add(shell); + _shellsToDisable.Add(shell); } } } @@ -4717,9 +4712,9 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a protected override void EndProcessing() { // if user did not specify any shell, act on the default shell. - if (shellsToDisable.Count == 0) + if (_shellsToDisable.Count == 0) { - shellsToDisable.Add(RemotingConstants.DefaultShellName); + _shellsToDisable.Add(RemotingConstants.DefaultShellName); } //WriteWarning(StringUtil.Format(RemotingErrorIdStrings.DcsWarningMessage)); @@ -4735,21 +4730,21 @@ $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$a string setEnabledTarget = RemotingErrorIdStrings.SetEnabledFalseTarget; string setEnabledAction = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction, "Set-Item"); - disablePluginSb.InvokeUsingCmdlet( + s_disablePluginSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: shellsToDisable, + dollarUnder: _shellsToDisable, input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - force, + _force, whatIf, confirm, restartWinRMMessage, setEnabledTarget, setEnabledAction, - noRestart}); + _noRestart}); System.Management.Automation.Tracing.Tracer tracer = new System.Management.Automation.Tracing.Tracer(); @@ -5003,7 +4998,7 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR "; - private static ScriptBlock enableRemotingSb; + private static ScriptBlock s_enableRemotingSb; #endregion @@ -5024,8 +5019,8 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - enableRemotingSb = ScriptBlock.Create(enableRemotingScript); - enableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; + s_enableRemotingSb = ScriptBlock.Create(enableRemotingScript); + s_enableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion @@ -5042,14 +5037,14 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Property that will allow configuring WinRM with Public @@ -5058,10 +5053,10 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR [Parameter()] public SwitchParameter SkipNetworkProfileCheck { - get { return skipNetworkProfileCheck; } - set { skipNetworkProfileCheck = value; } + get { return _skipNetworkProfileCheck; } + set { _skipNetworkProfileCheck = value; } } - private bool skipNetworkProfileCheck; + private bool _skipNetworkProfileCheck; #endregion @@ -5098,7 +5093,7 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR string setCaptionMessage = StringUtil.Format(RemotingErrorIdStrings.CSShouldProcessAction, "Set-PSSessionConfiguration"); string setQueryMessage = RemotingErrorIdStrings.EcsShouldProcessTarget; - enableRemotingSb.InvokeUsingCmdlet( + s_enableRemotingSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -5106,14 +5101,14 @@ Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForR input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - force, + _force, queryMessage, captionMessage, setQueryMessage, setCaptionMessage, whatIf, confirm, - skipNetworkProfileCheck}); + _skipNetworkProfileCheck}); } #endregion @@ -5231,7 +5226,7 @@ param( Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] -restartWinRMMessage $args[3] -whatif:$args[4] -confirm:$args[5] "; - private static ScriptBlock disableRemotingSb; + private static ScriptBlock s_disableRemotingSb; #endregion Private Data @@ -5244,8 +5239,8 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] // compile the script block statically and reuse the same instance // everytime the command is run..This will save on parsing time. - disableRemotingSb = ScriptBlock.Create(disableRemotingScript); - disableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; + s_disableRemotingSb = ScriptBlock.Create(disableRemotingScript); + s_disableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } #endregion Constructors @@ -5260,14 +5255,14 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; #endregion Parameters @@ -5301,7 +5296,7 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] string queryMessage = RemotingErrorIdStrings.DisableRemotingShouldProcessTarget; string restartWinRMMessage = RemotingErrorIdStrings.RestartWinRMMessage; - disableRemotingSb.InvokeUsingCmdlet( + s_disableRemotingSb.InvokeUsingCmdlet( contextCmdlet: this, useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, @@ -5309,7 +5304,7 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] input: Utils.EmptyArray(), scriptThis: AutomationNull.Value, args: new object[] { - force, + _force, queryMessage, captionMessage, restartWinRMMessage, @@ -5392,14 +5387,14 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] this.Username = upnComponents[1] + "@" + upnComponents[0]; } } - + try { System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal( new System.Security.Principal.WindowsIdentity(this.Username)); validator = (role) => windowsPrincipal.IsInRole(role); } - catch(SecurityException e) + catch (SecurityException e) { // Identity could not be mapped string message = StringUtil.Format(RemotingErrorIdStrings.CouldNotResolveUsername, this.Username); @@ -5410,20 +5405,20 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] } } - foreach(PSObject foundConfiguration in configurations) + foreach (PSObject foundConfiguration in configurations) { string configFilePath = null; PSPropertyInfo configFilePathProperty = foundConfiguration.Properties["ConfigFilePath"]; - if(configFilePathProperty != null) + if (configFilePathProperty != null) { configFilePath = configFilePathProperty.Value as string; } - + // If we could not get the config file, throw an error that it's not a configuration created with // config file-based session configurations. - if(configFilePath == null) + if (configFilePath == null) { - string configurationName = (string) foundConfiguration.Properties["Name"].Value; + string configurationName = (string)foundConfiguration.Properties["Name"].Value; string message = StringUtil.Format(RemotingErrorIdStrings.SessionConfigurationMustBeFileBased, configurationName); ArgumentException ioe = new ArgumentException(message); ErrorRecord er = new ErrorRecord(ioe, "SessionConfigurationMustBeFileBased", ErrorCategory.InvalidArgument, foundConfiguration); @@ -5432,16 +5427,16 @@ Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] } InitialSessionState iss = InitialSessionState.CreateFromSessionConfigurationFile(configFilePath, validator); - if(this.Full) + if (this.Full) { WriteObject(iss); } else { - using(PowerShellApi analyzer = PowerShellApi.Create(iss)) + using (PowerShellApi analyzer = PowerShellApi.Create(iss)) { analyzer.AddCommand("Get-Command").AddParameter("CommandType", "All"); - foreach(PSObject output in analyzer.Invoke()) + foreach (PSObject output in analyzer.Invoke()) { WriteObject(output); } diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index ec80c2e7d..979c1149b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -424,7 +424,7 @@ namespace Microsoft.PowerShell.Commands return null; } - + if ((jobs1.Count > 1) || (jobs1.Count == 1) && (job2 != null)) { diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index a4ae14610..6759ecadd 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -59,10 +59,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSSession[] Session { - get { return this.remotePSSessionInfo; } - set { this.remotePSSessionInfo = value; } + get { return _remotePSSessionInfo; } + set { _remotePSSessionInfo = value; } } - private PSSession[] remotePSSessionInfo; + private PSSession[] _remotePSSessionInfo; /// /// Idle Timeout session option in seconds. Used in this cmdlet to set server disconnect idletimeout option. @@ -102,10 +102,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = PSRunspaceCmdlet.InstanceIdParameterSet)] public Int32 ThrottleLimit { - get { return this.throttleLimit; } - set { this.throttleLimit = value; } + get { return _throttleLimit; } + set { _throttleLimit = value; } } - private Int32 throttleLimit = 0; + private Int32 _throttleLimit = 0; /// /// Disconnect-PSSession does not support ComputerName parameter set. @@ -123,14 +123,14 @@ namespace Microsoft.PowerShell.Commands { // no need to lock as the cmdlet parameters will not be assigned // from multiple threads. - if (null == sessionOption) + if (null == _sessionOption) { - sessionOption = new PSSessionOption(); + _sessionOption = new PSSessionOption(); } - return sessionOption; + return _sessionOption; } } - private PSSessionOption sessionOption; + private PSSessionOption _sessionOption; /// /// Overriding to suppress this parameter @@ -176,8 +176,8 @@ namespace Microsoft.PowerShell.Commands { base.BeginProcessing(); - this.throttleManager.ThrottleLimit = ThrottleLimit; - this.throttleManager.ThrottleComplete += new EventHandler(HandleThrottleDisconnectComplete); + _throttleManager.ThrottleLimit = ThrottleLimit; + _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleDisconnectComplete); } /// @@ -193,13 +193,13 @@ namespace Microsoft.PowerShell.Commands // Get all remote runspaces to disconnect. if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet) { - if (this.remotePSSessionInfo == null || this.remotePSSessionInfo.Length == 0) + if (_remotePSSessionInfo == null || _remotePSSessionInfo.Length == 0) { return; } psSessions = new Dictionary(); - foreach (PSSession psSession in this.remotePSSessionInfo) + foreach (PSSession psSession in _remotePSSessionInfo) { psSessions.Add(psSession.InstanceId, psSession); } @@ -240,9 +240,9 @@ namespace Microsoft.PowerShell.Commands if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { // Update the connectionInfo object with passed in session options. - if (sessionOption != null) + if (_sessionOption != null) { - psSession.Runspace.ConnectionInfo.SetSessionOptions(sessionOption); + psSession.Runspace.ConnectionInfo.SetSessionOptions(_sessionOption); } // Validate the ConnectionInfo IdleTimeout value against the MaxIdleTimeout @@ -252,7 +252,7 @@ namespace Microsoft.PowerShell.Commands continue; } - DisconnectRunspaceOperation disconnectOperation = new DisconnectRunspaceOperation(psSession, this.stream); + DisconnectRunspaceOperation disconnectOperation = new DisconnectRunspaceOperation(psSession, _stream); disconnectOperations.Add(disconnectOperation); } else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected) @@ -274,38 +274,38 @@ namespace Microsoft.PowerShell.Commands catch (PSRemotingDataStructureException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (PSRemotingTransportException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (RemoteException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } catch (InvalidRunspaceStateException) { // Allow cmdlet to end and then re-throw exception. - this.operationsComplete.Set(); + _operationsComplete.Set(); throw; } if (disconnectOperations.Count > 0) { // Make sure operations are not set as complete while processing input. - this.operationsComplete.Reset(); + _operationsComplete.Reset(); // Submit list of disconnect operations. - this.throttleManager.SubmitOperations(disconnectOperations); + _throttleManager.SubmitOperations(disconnectOperations); // Write any output now. - Collection streamObjects = this.stream.ObjectReader.NonBlockingRead(); + Collection streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action)streamObject); @@ -318,15 +318,15 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - this.throttleManager.EndSubmitOperations(); + _throttleManager.EndSubmitOperations(); // Wait for all disconnect operations to complete. - this.operationsComplete.WaitOne(); + _operationsComplete.WaitOne(); // Read all objects in the stream pipeline. - while (!this.stream.ObjectReader.EndOfPipeline) + while (!_stream.ObjectReader.EndOfPipeline) { - Object streamObject = stream.ObjectReader.Read(); + Object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action)streamObject); } } @@ -337,11 +337,11 @@ namespace Microsoft.PowerShell.Commands protected override void StopProcessing() { // Close the output stream for any further writes. - this.stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); // Signal the ThrottleManager to stop any further processing // of PSSessions. - this.throttleManager.StopAllOperations(); + _throttleManager.StopAllOperations(); } #endregion @@ -355,8 +355,8 @@ namespace Microsoft.PowerShell.Commands /// EventArgs private void HandleThrottleDisconnectComplete(object sender, EventArgs eventArgs) { - this.stream.ObjectWriter.Close(); - this.operationsComplete.Set(); + _stream.ObjectWriter.Close(); + _operationsComplete.Set(); } private bool ValidateIdleTimeout(PSSession session) @@ -368,9 +368,9 @@ namespace Microsoft.PowerShell.Commands if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout && (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout)) { - string msg = StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout, - session.Name, idleTimeout/1000, maxIdleTimeout/1000, minIdleTimeout/1000); - ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(msg), + string msg = StringUtil.Format(RemotingErrorIdStrings.CannotDisconnectSessionWithInvalidIdleTimeout, + session.Name, idleTimeout / 1000, maxIdleTimeout / 1000, minIdleTimeout / 1000); + ErrorRecord errorRecord = new ErrorRecord(new RuntimeException(msg), "CannotDisconnectSessionWithInvalidIdleTimeout", ErrorCategory.InvalidArgument, session); WriteError(errorRecord); @@ -411,14 +411,14 @@ namespace Microsoft.PowerShell.Commands /// private class DisconnectRunspaceOperation : IThrottleOperation { - private PSSession remoteSession; - private ObjectStream writeStream; + private PSSession _remoteSession; + private ObjectStream _writeStream; internal DisconnectRunspaceOperation(PSSession session, ObjectStream stream) { - this.remoteSession = session; - this.writeStream = stream; - this.remoteSession.Runspace.StateChanged += StateCallBackHandler; + _remoteSession = session; + _writeStream = stream; + _remoteSession.Runspace.StateChanged += StateCallBackHandler; } internal override void StartOperation() @@ -427,7 +427,7 @@ namespace Microsoft.PowerShell.Commands try { - this.remoteSession.Runspace.DisconnectAsync(); + _remoteSession.Runspace.DisconnectAsync(); } catch (InvalidRunspacePoolStateException e) { @@ -443,7 +443,7 @@ namespace Microsoft.PowerShell.Commands if (!startedSuccessfully) { // We are done at this point. Notify throttle manager. - this.remoteSession.Runspace.StateChanged -= StateCallBackHandler; + _remoteSession.Runspace.StateChanged -= StateCallBackHandler; SendStartComplete(); } } @@ -451,14 +451,14 @@ namespace Microsoft.PowerShell.Commands internal override void StopOperation() { // Cannot stop a disconnect attempt. - this.remoteSession.Runspace.StateChanged -= StateCallBackHandler; + _remoteSession.Runspace.StateChanged -= StateCallBackHandler; SendStopComplete(); } internal override event EventHandler OperationComplete; private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) - { + { if (eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting) { return; @@ -476,10 +476,10 @@ namespace Microsoft.PowerShell.Commands } // Notify throttle manager that the start is complete. - this.remoteSession.Runspace.StateChanged -= StateCallBackHandler; + _remoteSession.Runspace.StateChanged -= StateCallBackHandler; SendStartComplete(); } - + private void SendStartComplete() { OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); @@ -496,37 +496,37 @@ namespace Microsoft.PowerShell.Commands private void WriteDisconnectedPSSession() { - if (this.writeStream.ObjectWriter.IsOpen) + if (_writeStream.ObjectWriter.IsOpen) { - Action outputWriter = delegate(Cmdlet cmdlet) + Action outputWriter = delegate (Cmdlet cmdlet) { - cmdlet.WriteObject(this.remoteSession); + cmdlet.WriteObject(_remoteSession); }; - this.writeStream.ObjectWriter.Write(outputWriter); + _writeStream.ObjectWriter.Write(outputWriter); } } private void WriteDisconnectFailed(Exception e = null) { - if (this.writeStream.ObjectWriter.IsOpen) + if (_writeStream.ObjectWriter.IsOpen) { string msg; if (e != null && !string.IsNullOrWhiteSpace(e.Message)) { - msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, this.remoteSession.InstanceId, e.Message); + msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, _remoteSession.InstanceId, e.Message); } else { - msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, this.remoteSession.InstanceId); + msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, _remoteSession.InstanceId); } Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, this.remoteSession); - Action errorWriter = delegate(Cmdlet cmdlet) + ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, _remoteSession); + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; - this.writeStream.ObjectWriter.Write(errorWriter); + _writeStream.ObjectWriter.Write(errorWriter); } } } @@ -557,13 +557,13 @@ namespace Microsoft.PowerShell.Commands { if (disposing) { - this.throttleManager.Dispose(); + _throttleManager.Dispose(); - this.operationsComplete.WaitOne(); - this.operationsComplete.Dispose(); + _operationsComplete.WaitOne(); + _operationsComplete.Dispose(); - this.throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleDisconnectComplete); - this.stream.Dispose(); + _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleDisconnectComplete); + _stream.Dispose(); } } @@ -572,16 +572,15 @@ namespace Microsoft.PowerShell.Commands #region Private Members // Object used to perform network disconnect operations in a limited manner. - private ThrottleManager throttleManager = new ThrottleManager(); + private ThrottleManager _throttleManager = new ThrottleManager(); // Event indicating that all disconnect operations through the ThrottleManager // are complete. - private ManualResetEvent operationsComplete = new ManualResetEvent(true); + private ManualResetEvent _operationsComplete = new ManualResetEvent(true); // Output data stream. - private ObjectStream stream = new ObjectStream(); + private ObjectStream _stream = new ObjectStream(); #endregion - } // DisconnectPSSessionCommand } diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 6b8577fb9..f2971676d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -1,7 +1,8 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ -using System; + +using System; using System.Diagnostics; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -210,7 +211,7 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError( new ErrorRecord( new RuntimeException( - StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess, + StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessCannotConnectToProcess, msgAppDomainName, procId, errorMessage), e.InnerException), "EnterPSHostProcessCannotConnectToProcess", @@ -643,7 +644,7 @@ namespace Microsoft.PowerShell.Commands } #endif -#endregion + #endregion #region Constructors diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index 359ba916f..8ecc65ce7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -32,7 +32,7 @@ namespace Microsoft.PowerShell.Commands set { _includeChildJob = value; } } private SwitchParameter _includeChildJob; - + /// /// ChildJobState parameter. /// @@ -267,11 +267,11 @@ namespace Microsoft.PowerShell.Commands // add all child jobs if ChildJobState is not specified // - if(!childJobStateParameter && includeChildJobParameter) + if (!childJobStateParameter && includeChildJobParameter) { foreach (Job job in jobList) { - if ( job.ChildJobs != null && job.ChildJobs.Count>0 ) + if (job.ChildJobs != null && job.ChildJobs.Count > 0) { matches.AddRange(job.ChildJobs); } @@ -354,7 +354,7 @@ namespace Microsoft.PowerShell.Commands // // Apply Newest count. // - + // Sort filtered jobs filteredJobs.Sort((firstJob, secondJob) => { diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index afe3e474a..ab769854f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -395,14 +395,14 @@ namespace Microsoft.PowerShell.Commands { get { - return asjob; + return _asjob; } set { - asjob = value; + _asjob = value; } } - private bool asjob = false; + private bool _asjob = false; /// /// Specifies that after the command is invoked on a remote computer the @@ -432,7 +432,7 @@ namespace Microsoft.PowerShell.Commands get { return DisconnectedSessionName; } set { DisconnectedSessionName = value; } } - + /// /// Hide/Show computername of the remote objects. /// @@ -451,10 +451,10 @@ namespace Microsoft.PowerShell.Commands [Alias("HCN")] public SwitchParameter HideComputerName { - get { return hideComputerName; } - set { hideComputerName = value; } + get { return _hideComputerName; } + set { _hideComputerName = value; } } - private bool hideComputerName; + private bool _hideComputerName; /// /// Friendly name for the job object if AsJob is used @@ -471,18 +471,18 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set { if (!String.IsNullOrEmpty(value)) { - name = value; - asjob = true; + _name = value; + _asjob = true; } } } - private String name = String.Empty; + private String _name = String.Empty; /// /// The script block that the user has specified in the @@ -567,23 +567,23 @@ namespace Microsoft.PowerShell.Commands } } - /// - /// The AllowRediraction parameter enables the implicit redirection functionality - /// - [Parameter(ParameterSetName = InvokeCommandCommand.UriParameterSet)] - [Parameter(ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)] - public override SwitchParameter AllowRedirection - { - get - { - return base.AllowRedirection; - } - set - { - base.AllowRedirection = value; - } - } - + /// + /// The AllowRediraction parameter enables the implicit redirection functionality + /// + [Parameter(ParameterSetName = InvokeCommandCommand.UriParameterSet)] + [Parameter(ParameterSetName = InvokeCommandCommand.FilePathUriParameterSet)] + public override SwitchParameter AllowRedirection + { + get + { + return base.AllowRedirection; + } + set + { + base.AllowRedirection = value; + } + } + /// /// Extended Session Options for controlling the session creation. Use @@ -664,13 +664,13 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - if (this.InvokeAndDisconnect && this.asjob) + if (this.InvokeAndDisconnect && _asjob) { // The -AsJob and -InDisconnectedSession parameter switches are mutually exclusive. throw new InvalidOperationException(RemotingErrorIdStrings.AsJobAndDisconnectedError); } - if (this.InvokeAndDisconnect && + if (this.InvokeAndDisconnect && (this.ComputerName == null || this.ComputerName.Length == 0) && (this.ConnectionUri == null || this.ConnectionUri.Length == 0)) { @@ -685,7 +685,7 @@ namespace Microsoft.PowerShell.Commands // Checking session's availability and reporting errors in early stage, unless '-AsJob' is specified. // When '-AsJob' is specified, Invoke-Command should return a job object without throwing error, even // if the session is not in available state -- this is the PSv3 behavior and we should not break it. - if (!this.asjob && (ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet) || + if (!_asjob && (ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet) || ParameterSetName.Equals(InvokeCommandCommand.FilePathSessionParameterSet))) { long localPipelineId = @@ -761,8 +761,8 @@ namespace Microsoft.PowerShell.Commands { try { - this.steppablePipeline = ScriptBlock.GetSteppablePipeline(CommandOrigin.Internal, ArgumentList); - this.steppablePipeline.Begin(this); + _steppablePipeline = ScriptBlock.GetSteppablePipeline(CommandOrigin.Internal, ArgumentList); + _steppablePipeline.Begin(this); } catch (InvalidOperationException) { @@ -796,7 +796,7 @@ namespace Microsoft.PowerShell.Commands // create collection of input writers here foreach (IThrottleOperation operation in Operations) { - inputWriters.Add(((ExecutionCmdletHelper)operation).Pipeline.Input); + _inputWriters.Add(((ExecutionCmdletHelper)operation).Pipeline.Input); } // we need to verify, if this Invoke-Command is the first @@ -835,8 +835,8 @@ namespace Microsoft.PowerShell.Commands if (version >= RemotingConstants.ProtocolVersionWin8RTM) { // Supress collection behavior - needToCollect = false; - needToStartSteppablePipelineOnServer = true; + _needToCollect = false; + _needToStartSteppablePipelineOnServer = true; break; } } @@ -844,14 +844,14 @@ namespace Microsoft.PowerShell.Commands } // Either version table is null or the server is not version 2.2 and beyond, we need to collect - needToCollect = true; - needToStartSteppablePipelineOnServer = false; + _needToCollect = true; + _needToStartSteppablePipelineOnServer = false; break; } } } - if (needToStartSteppablePipelineOnServer) + if (_needToStartSteppablePipelineOnServer) { // create collection of input writers here foreach (IThrottleOperation operation in Operations) @@ -870,7 +870,7 @@ namespace Microsoft.PowerShell.Commands { // RemoteRunspace must be holding this InvokeCommand..So release // this at dispose time - clearInvokeCommandOnRunspace = true; + _clearInvokeCommandOnRunspace = true; } // check if we need to propagate terminating errors @@ -890,14 +890,14 @@ namespace Microsoft.PowerShell.Commands // we should create the pipeline on first instance // and if there are no invoke-commands running // ahead in the pipeline - if (!pipelineinvoked &&!needToCollect) + if (!_pipelineinvoked && !_needToCollect) { - pipelineinvoked = true; + _pipelineinvoked = true; if (InputObject == AutomationNull.Value) { CloseAllInputStreams(); - inputStreamClosed = true; + _inputStreamClosed = true; } if (!ParameterSetName.Equals("InProcess")) @@ -905,7 +905,7 @@ namespace Microsoft.PowerShell.Commands // at this point there is nothing to do for // inproc case. The script block is executed // in EndProcessing - if (!asjob) + if (!_asjob) { CreateAndRunSyncJob(); } @@ -925,9 +925,9 @@ namespace Microsoft.PowerShell.Commands if (ResolvedComputerNames.Length != 0 && Operations.Count > 0) { PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations, - ScriptBlock.ToString(), ThrottleLimit, name); + ScriptBlock.ToString(), ThrottleLimit, _name); job.PSJobTypeName = RemoteJobType; - job.HideComputerName = hideComputerName; + job.HideComputerName = _hideComputerName; this.JobRepository.Add(job); WriteObject(job); } @@ -938,9 +938,9 @@ namespace Microsoft.PowerShell.Commands case InvokeCommandCommand.FilePathSessionParameterSet: { PSRemotingJob job = new PSRemotingJob(Session, Operations, - ScriptBlock.ToString(), ThrottleLimit, name); + ScriptBlock.ToString(), ThrottleLimit, _name); job.PSJobTypeName = RemoteJobType; - job.HideComputerName = hideComputerName; + job.HideComputerName = _hideComputerName; this.JobRepository.Add(job); WriteObject(job); } @@ -958,9 +958,9 @@ namespace Microsoft.PowerShell.Commands } PSRemotingJob job = new PSRemotingJob(locations, Operations, - ScriptBlock.ToString(), ThrottleLimit, name); + ScriptBlock.ToString(), ThrottleLimit, _name); job.PSJobTypeName = RemoteJobType; - job.HideComputerName = hideComputerName; + job.HideComputerName = _hideComputerName; this.JobRepository.Add(job); WriteObject(job); } @@ -971,23 +971,23 @@ namespace Microsoft.PowerShell.Commands } } // if (!pipelineinvoked... - if (InputObject != AutomationNull.Value && !inputStreamClosed) + if (InputObject != AutomationNull.Value && !_inputStreamClosed) { - if ((ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (this.steppablePipeline == null)) || - needToCollect) + if ((ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline == null)) || + _needToCollect) { - input.Add(InputObject); + _input.Add(InputObject); } - else if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (this.steppablePipeline != null)) + else if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline != null)) { - this.steppablePipeline.Process(InputObject); + _steppablePipeline.Process(InputObject); } else { WriteInput(InputObject); // if not a job write out the results available thus far - if (!asjob) + if (!_asjob) { WriteJobResults(true); } @@ -1002,35 +1002,35 @@ namespace Microsoft.PowerShell.Commands protected override void EndProcessing() { // close the input stream on all the pipelines - if (!needToCollect) + if (!_needToCollect) { CloseAllInputStreams(); } - if (!asjob) + if (!_asjob) { if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet)) { - if (this.steppablePipeline != null) + if (_steppablePipeline != null) { - this.steppablePipeline.End(); + _steppablePipeline.End(); } else { ScriptBlock.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: ! NoNewScope, + contextCmdlet: this, + useLocalScope: !NoNewScope, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: input, - scriptThis: AutomationNull.Value, - args: ArgumentList); + dollarUnder: AutomationNull.Value, + input: _input, + scriptThis: AutomationNull.Value, + args: ArgumentList); } } else { // runspace and computername parameter sets - if (job != null) + if (_job != null) { // The job/command is disconnected immediately after it is invoked. The command // will continue to run on the server but we don't wait and return immediately. @@ -1048,9 +1048,9 @@ namespace Microsoft.PowerShell.Commands WriteJobResults(false); // finally dispose the job. - if (!asjob) + if (!_asjob) { - job.Dispose(); + _job.Dispose(); } // We no longer need to call ClearInvokeCommandOnRunspaces() here because @@ -1060,7 +1060,7 @@ namespace Microsoft.PowerShell.Commands } else { - if (needToCollect && ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet)) + if (_needToCollect && ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet)) { // if job was null, then its because the invoke-command // was collecting or ProcessRecord() was not called. @@ -1069,13 +1069,13 @@ namespace Microsoft.PowerShell.Commands // so now start the execution with the collected // input - Dbg.Assert(needToCollect, "InvokeCommand should have collected input before this"); + Dbg.Assert(_needToCollect, "InvokeCommand should have collected input before this"); Dbg.Assert(ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet), "Collecting and invoking should happen only in case of Runspace parameter set"); CreateAndRunSyncJob(); // loop through and write all input - foreach (object inputValue in input) + foreach (object inputValue in _input) { WriteInput(inputValue); } @@ -1098,14 +1098,13 @@ namespace Microsoft.PowerShell.Commands WriteJobResults(false); // finally dispose the job. - if (!asjob) + if (!_asjob) { - job.Dispose(); + _job.Dispose(); } } // if (needToCollect... }// else - job == null } - }// if (!async ... } // EndProcessing @@ -1123,16 +1122,16 @@ namespace Microsoft.PowerShell.Commands { if (!ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet)) { - if (!asjob) + if (!_asjob) { // stop all operations in the job // we need to check is job is not null, since // StopProcessing() may be called even before the // job is created bool stopjob = false; - lock (jobSyncObject) + lock (_jobSyncObject) { - if (job != null) + if (_job != null) { stopjob = true; } @@ -1140,20 +1139,19 @@ namespace Microsoft.PowerShell.Commands { // StopProcessing() has already been called // the job should not be created anymore - nojob = true; + _nojob = true; } } if (stopjob) { - job.StopJob(); + _job.StopJob(); } // clear the need to collect flag - needToCollect = false; + _needToCollect = false; } } - }// StopProcessing() #endregion Overrides @@ -1168,9 +1166,8 @@ namespace Microsoft.PowerShell.Commands /// private void HandleThrottleComplete(object sender, EventArgs eventArgs) { - operationsComplete.Set(); - throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); - + _operationsComplete.Set(); + _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); } // HandleThrottleComplete /// @@ -1195,24 +1192,24 @@ namespace Microsoft.PowerShell.Commands /// private void CreateAndRunSyncJob() { - lock (jobSyncObject) + lock (_jobSyncObject) { - if (!nojob) + if (!_nojob) { - throttleManager.ThrottleLimit = ThrottleLimit; - throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleLimit = ThrottleLimit; + _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); - operationsComplete.Reset(); - Dbg.Assert(this.disconnectComplete == null, "disconnectComplete event should only be used once."); - this.disconnectComplete = new ManualResetEvent(false); - job = new PSInvokeExpressionSyncJob(Operations, throttleManager); - job.HideComputerName = hideComputerName; - job.StateChanged += new EventHandler(HandleJobStateChanged); + _operationsComplete.Reset(); + Dbg.Assert(_disconnectComplete == null, "disconnectComplete event should only be used once."); + _disconnectComplete = new ManualResetEvent(false); + _job = new PSInvokeExpressionSyncJob(Operations, _throttleManager); + _job.HideComputerName = _hideComputerName; + _job.StateChanged += new EventHandler(HandleJobStateChanged); // Add robust connection retry notification handler. - AddConnectionRetryHandler(job); + AddConnectionRetryHandler(_job); - job.StartOperations(Operations); + _job.StartOperations(Operations); } } } @@ -1225,15 +1222,15 @@ namespace Microsoft.PowerShell.Commands state == JobState.Stopped || state == JobState.Failed) { - job.StateChanged -= new EventHandler(HandleJobStateChanged); + _job.StateChanged -= new EventHandler(HandleJobStateChanged); RemoveConnectionRetryHandler(sender as PSInvokeExpressionSyncJob); // Signal that this job has been disconnected, or has ended. - lock (jobSyncObject) + lock (_jobSyncObject) { - if (this.disconnectComplete != null) + if (_disconnectComplete != null) { - this.disconnectComplete.Set(); + _disconnectComplete.Set(); } } } @@ -1250,7 +1247,7 @@ namespace Microsoft.PowerShell.Commands { if (ps.RemotePowerShell != null) { - ps.RemotePowerShell.RCConnectionNotification += + ps.RemotePowerShell.RCConnectionNotification += new EventHandler(RCConnectionNotificationHandler); } } @@ -1299,12 +1296,12 @@ namespace Microsoft.PowerShell.Commands /// private void WaitForDisconnectAndDisposeJob() { - if (this.disconnectComplete != null) + if (_disconnectComplete != null) { - this.disconnectComplete.WaitOne(); + _disconnectComplete.WaitOne(); // Create disconnected PSSession objects for each powershell and write to output. - List discSessions = GetDisconnectedSessions(job); + List discSessions = GetDisconnectedSessions(_job); foreach (PSSession session in discSessions) { this.RunspaceRepository.AddOrReplace(session); @@ -1312,12 +1309,12 @@ namespace Microsoft.PowerShell.Commands } // Check to see if the disconnect was successful. If not write any errors there may be. - if (job.Error.Count > 0) + if (_job.Error.Count > 0) { - WriteStreamObjectsFromCollection(job.ReadAll()); + WriteStreamObjectsFromCollection(_job.ReadAll()); } - job.Dispose(); + _job.Dispose(); } } @@ -1335,7 +1332,7 @@ namespace Microsoft.PowerShell.Commands foreach (System.Management.Automation.PowerShell ps in powershells) { // Get the command information from the PowerShell object. - string commandText = (ps.Commands != null && ps.Commands.Commands.Count > 0) ? + string commandText = (ps.Commands != null && ps.Commands.Commands.Count > 0) ? ps.Commands.Commands[0].CommandText : string.Empty; ConnectCommandInfo cmdInfo = new ConnectCommandInfo(ps.InstanceId, commandText); @@ -1418,9 +1415,9 @@ namespace Microsoft.PowerShell.Commands // when there are no input writers, there is no // point either accumulating or trying to write data // so throw an exception in that case - if (inputWriters.Count == 0) + if (_inputWriters.Count == 0) { - if (!asjob) + if (!_asjob) { WriteJobResults(false); } @@ -1431,7 +1428,7 @@ namespace Microsoft.PowerShell.Commands List removeCollection = new List(); - foreach(PipelineWriter writer in inputWriters) + foreach (PipelineWriter writer in _inputWriters) { try { @@ -1446,7 +1443,7 @@ namespace Microsoft.PowerShell.Commands foreach (PipelineWriter writer in removeCollection) { - inputWriters.Remove(writer); + _inputWriters.Remove(writer); } } @@ -1456,10 +1453,10 @@ namespace Microsoft.PowerShell.Commands /// Write in a non-blocking manner private void WriteJobResults(bool nonblocking) { - if (job != null) + if (_job != null) { PipelineStoppedException caughtPipelineStoppedException = null; - job.PropagateThrows = this.propagateErrors; + _job.PropagateThrows = _propagateErrors; do { @@ -1470,23 +1467,23 @@ namespace Microsoft.PowerShell.Commands // ensure that the thread blocks. Else // the thread will spin leading to a CPU // usage spike - if (this.disconnectComplete != null) + if (_disconnectComplete != null) { // An auto-disconnect can occur and we need to detect // this condition along with a job results signal. WaitHandle.WaitAny(new WaitHandle[] { - this.disconnectComplete, - job.Results.WaitHandle }); + _disconnectComplete, + _job.Results.WaitHandle }); } else { - job.Results.WaitHandle.WaitOne(); + _job.Results.WaitHandle.WaitOne(); } } try { - WriteStreamObjectsFromCollection(job.ReadAll()); + WriteStreamObjectsFromCollection(_job.ReadAll()); } catch (System.Management.Automation.PipelineStoppedException pse) { @@ -1497,11 +1494,11 @@ namespace Microsoft.PowerShell.Commands { break; } - } while (!job.IsTerminalState()); + } while (!_job.IsTerminalState()); try { - WriteStreamObjectsFromCollection(job.ReadAll()); + WriteStreamObjectsFromCollection(_job.ReadAll()); } catch (System.Management.Automation.PipelineStoppedException pse) { @@ -1514,14 +1511,14 @@ namespace Microsoft.PowerShell.Commands throw caughtPipelineStoppedException; } - if (job.JobStateInfo.State == JobState.Disconnected) + if (_job.JobStateInfo.State == JobState.Disconnected) { if (ParameterSetName == InvokeCommandCommand.SessionParameterSet || ParameterSetName == InvokeCommandCommand.FilePathSessionParameterSet) { // Create a PSRemoting job we can add to the job repository and that // a user can reconnect to (via Receive-PSSession). - PSRemotingJob rtnJob = job.CreateDisconnectedRemotingJob(); + PSRemotingJob rtnJob = _job.CreateDisconnectedRemotingJob(); if (rtnJob != null) { rtnJob.PSJobTypeName = RemoteJobType; @@ -1529,7 +1526,7 @@ namespace Microsoft.PowerShell.Commands // Don't let the job object be disposed or stopped since // we want to be able to reconnect to the disconnected // pipelines. - this.asjob = true; + _asjob = true; List removedDebugStopJobs = new List(); @@ -1594,7 +1591,7 @@ namespace Microsoft.PowerShell.Commands { // Create disconnected sessions for each PowerShell in job that was disconnected, // and add them to the local repository. - List discSessions = GetDisconnectedSessions(job); + List discSessions = GetDisconnectedSessions(_job); foreach (PSSession session in discSessions) { // Add to session repository. @@ -1661,7 +1658,7 @@ namespace Microsoft.PowerShell.Commands { // Emit warning for cases where commands were stopped during connection retry attempts. bool retryCanceled = false; - Collection powershells = job.GetPowerShells(); + Collection powershells = _job.GetPowerShells(); foreach (System.Management.Automation.PowerShell ps in powershells) { if (ps.RemotePowerShell != null && @@ -1686,7 +1683,7 @@ namespace Microsoft.PowerShell.Commands string computerName, int totalSeconds) { - RCProgress.StartProgress( + s_RCProgress.StartProgress( sourceId, computerName, totalSeconds, @@ -1696,7 +1693,7 @@ namespace Microsoft.PowerShell.Commands private void StopProgressBar( long sourceId) { - RCProgress.StopProgress(sourceId); + s_RCProgress.StopProgress(sourceId); } /// @@ -1738,14 +1735,14 @@ namespace Microsoft.PowerShell.Commands // in proc parameter set - just return return; } - if (!asjob) + if (!_asjob) { if (ParameterSetName.Equals(InvokeCommandCommand.ComputerNameParameterSet) || ParameterSetName.Equals(InvokeCommandCommand.FilePathComputerNameParameterSet)) { if (ComputerName.Length == 1) { - propagateErrors = true; + _propagateErrors = true; } } else if (ParameterSetName.Equals(InvokeCommandCommand.SessionParameterSet) || @@ -1753,7 +1750,7 @@ namespace Microsoft.PowerShell.Commands { if (Session.Length == 1) { - propagateErrors = true; + _propagateErrors = true; } } else if (ParameterSetName.Equals(InvokeCommandCommand.UriParameterSet) || @@ -1761,7 +1758,7 @@ namespace Microsoft.PowerShell.Commands { if (ConnectionUri.Length == 1) { - propagateErrors = true; + _propagateErrors = true; } } } @@ -1779,16 +1776,16 @@ namespace Microsoft.PowerShell.Commands // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((errorRecord != null) && - (errorRecord.Exception != null) && + if ((errorRecord != null) && + (errorRecord.Exception != null) && (errorRecord.Exception.InnerException != null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; if (ex != null) { - streamObject.Value = new ErrorRecord(errorRecord.Exception.InnerException, - errorRecord.FullyQualifiedErrorId, - errorRecord.CategoryInfo.Category, + streamObject.Value = new ErrorRecord(errorRecord.Exception.InnerException, + errorRecord.FullyQualifiedErrorId, + errorRecord.CategoryInfo.Category, errorRecord.TargetObject); } } @@ -1798,36 +1795,36 @@ namespace Microsoft.PowerShell.Commands #region Private Members - private ThrottleManager throttleManager = new ThrottleManager(); + private ThrottleManager _throttleManager = new ThrottleManager(); // throttle manager for handling all throttling operations - private ManualResetEvent operationsComplete = new ManualResetEvent(true); - private ManualResetEvent disconnectComplete; + private ManualResetEvent _operationsComplete = new ManualResetEvent(true); + private ManualResetEvent _disconnectComplete; // the initial state is true because when no // operations actually take place as in case of a // parameter binding exception, then Dispose is // called. Since Dispose waits on this handler // it is set to true initially and is Reset() in // BeginProcessing() - private PSInvokeExpressionSyncJob job; + private PSInvokeExpressionSyncJob _job; // used for streaming behavior for local invocations - private SteppablePipeline steppablePipeline; + private SteppablePipeline _steppablePipeline; - private bool pipelineinvoked = false; // if pipeline has been invoked - private bool inputStreamClosed = false; + private bool _pipelineinvoked = false; // if pipeline has been invoked + private bool _inputStreamClosed = false; private const string InProcParameterSet = "InProcess"; - private PSDataCollection input = new PSDataCollection(); - private bool needToCollect = false; - private bool needToStartSteppablePipelineOnServer = false; - private bool clearInvokeCommandOnRunspace = false; - private List inputWriters = new List(); - private object jobSyncObject = new object(); - private bool nojob = false; - private Guid instanceId = Guid.NewGuid(); - private bool propagateErrors = false; + private PSDataCollection _input = new PSDataCollection(); + private bool _needToCollect = false; + private bool _needToStartSteppablePipelineOnServer = false; + private bool _clearInvokeCommandOnRunspace = false; + private List _inputWriters = new List(); + private object _jobSyncObject = new object(); + private bool _nojob = false; + private Guid _instanceId = Guid.NewGuid(); + private bool _propagateErrors = false; - private static RobustConnectionProgress RCProgress = new RobustConnectionProgress(); + private static RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); internal static readonly string RemoteJobType = "RemoteJob"; @@ -1858,36 +1855,36 @@ namespace Microsoft.PowerShell.Commands this.StopProcessing(); // wait for all operations to complete - operationsComplete.WaitOne(); - operationsComplete.Dispose(); + _operationsComplete.WaitOne(); + _operationsComplete.Dispose(); - if (!asjob) + if (!_asjob) { - if (job != null) + if (_job != null) { // job will be null in the "InProcess" case - job.Dispose(); + _job.Dispose(); } - throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); - throttleManager.Dispose(); - throttleManager = null; + _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + _throttleManager.Dispose(); + _throttleManager = null; } // clear the invoke command references we have stored - if (this.clearInvokeCommandOnRunspace) + if (_clearInvokeCommandOnRunspace) { ClearInvokeCommandOnRunspaces(); } - input.Dispose(); + _input.Dispose(); - lock (jobSyncObject) + lock (_jobSyncObject) { - if (this.disconnectComplete != null) + if (_disconnectComplete != null) { - this.disconnectComplete.Dispose(); - this.disconnectComplete = null; + _disconnectComplete.Dispose(); + _disconnectComplete = null; } } } @@ -2000,7 +1997,7 @@ namespace System.Management.Automation.Internal if (_secondsRemaining > 0) { // Update progress bar. - _progressRecord.PercentComplete = + _progressRecord.PercentComplete = ((_secondsTotal - _secondsRemaining) * 100) / _secondsTotal; _progressRecord.SecondsRemaining = _secondsRemaining--; _progressRecord.RecordType = ProgressRecordType.Processing; diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index df93d1efd..fae2ca38d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation /// /// class which has list of job objects currently active in the system. /// - public abstract class Repository where T: class + public abstract class Repository where T : class { #region Public Methods @@ -22,19 +22,19 @@ namespace System.Management.Automation { if (item == null) { - throw new ArgumentNullException(identifier); + throw new ArgumentNullException(_identifier); } - lock (syncObject) + lock (_syncObject) { Guid instanceId = GetKey(item); - if (!repository.ContainsKey(instanceId)) + if (!_repository.ContainsKey(instanceId)) { - repository.Add(instanceId, item); + _repository.Add(instanceId, item); } else { - throw new ArgumentException(identifier); + throw new ArgumentException(_identifier); } } } @@ -47,13 +47,13 @@ namespace System.Management.Automation { if (item == null) { - throw new ArgumentNullException(identifier); + throw new ArgumentNullException(_identifier); } - lock (syncObject) + lock (_syncObject) { Guid instanceId = GetKey(item); - if (!repository.Remove(instanceId)) + if (!_repository.Remove(instanceId)) { String message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, @@ -63,7 +63,7 @@ namespace System.Management.Automation } } } - + /// /// /// @@ -88,7 +88,7 @@ namespace System.Management.Automation /// protected Repository(string identifier) { - this.identifier = identifier; + _identifier = identifier; } /// @@ -98,9 +98,9 @@ namespace System.Management.Automation { get { - lock (syncObject) + lock (_syncObject) { - return new List(repository.Values); + return new List(_repository.Values); } } } @@ -112,10 +112,10 @@ namespace System.Management.Automation /// public T GetItem(Guid instanceId) { - lock (syncObject) + lock (_syncObject) { T result; - repository.TryGetValue(instanceId, out result); + _repository.TryGetValue(instanceId, out result); return result; } } @@ -125,16 +125,16 @@ namespace System.Management.Automation /// internal Dictionary Dictionary { - get { return this.repository; } + get { return _repository; } } #endregion Private Methods #region Private Members - private Dictionary repository = new Dictionary(); - private object syncObject = new object(); // object for synchronization - private string identifier; + private Dictionary _repository = new Dictionary(); + private object _syncObject = new object(); // object for synchronization + private string _identifier; #endregion Private Members } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 70618687d..3b48203ec 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -38,14 +38,14 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; + _path = value; } } - private string path; + private string _path; /// /// Configuration file schema version @@ -56,14 +56,14 @@ namespace Microsoft.PowerShell.Commands { get { - return schemaVersion; + return _schemaVersion; } set { - schemaVersion = value; + _schemaVersion = value; } } - private Version schemaVersion = new Version("2.0.0.0"); + private Version _schemaVersion = new Version("2.0.0.0"); /// /// Configuration file GUID @@ -73,14 +73,14 @@ namespace Microsoft.PowerShell.Commands { get { - return guid; + return _guid; } set { - guid = value; + _guid = value; } } - private Guid guid = Guid.NewGuid(); + private Guid _guid = Guid.NewGuid(); /// /// Author of the configuration file @@ -90,14 +90,14 @@ namespace Microsoft.PowerShell.Commands { get { - return author; + return _author; } set { - author = value; + _author = value; } } - private string author; + private string _author; /// /// Description @@ -107,14 +107,14 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// /// Company name @@ -124,14 +124,14 @@ namespace Microsoft.PowerShell.Commands { get { - return companyName; + return _companyName; } set { - companyName = value; + _companyName = value; } } - private string companyName; + private string _companyName; /// /// Copyright information @@ -141,14 +141,14 @@ namespace Microsoft.PowerShell.Commands { get { - return copyright; + return _copyright; } set { - copyright = value; + _copyright = value; } } - private string copyright; + private string _copyright; /// /// Specifies type of initial session state to use. @@ -158,14 +158,14 @@ namespace Microsoft.PowerShell.Commands { get { - return sessionType; + return _sessionType; } set { - sessionType = value; + _sessionType = value; } } - private SessionType sessionType = SessionType.Default; + private SessionType _sessionType = SessionType.Default; /// /// Specifies the directory for transcripts to be placed. @@ -175,14 +175,14 @@ namespace Microsoft.PowerShell.Commands { get { - return transcriptDirectory; + return _transcriptDirectory; } set { - transcriptDirectory = value; + _transcriptDirectory = value; } } - private string transcriptDirectory = null; + private string _transcriptDirectory = null; /// /// Specifies whether to run this configuration under a virtual account. @@ -203,8 +203,8 @@ namespace Microsoft.PowerShell.Commands /// not visible in the session. /// [Parameter()] - public SwitchParameter MountUserDrive - { + public SwitchParameter MountUserDrive + { get; set; } @@ -245,14 +245,14 @@ namespace Microsoft.PowerShell.Commands { get { - return scriptsToProcess; + return _scriptsToProcess; } set { - scriptsToProcess = value; + _scriptsToProcess = value; } } - private string[] scriptsToProcess = Utils.EmptyArray(); + private string[] _scriptsToProcess = Utils.EmptyArray(); /// /// Role definitions for this session configuration (Role name -> Role capability) @@ -263,14 +263,14 @@ namespace Microsoft.PowerShell.Commands { get { - return roleDefinitions; + return _roleDefinitions; } set { - roleDefinitions = value; + _roleDefinitions = value; } } - private IDictionary roleDefinitions; + private IDictionary _roleDefinitions; /// /// Specifies account groups that are membership requirements for this session @@ -279,10 +279,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary RequiredGroups { - get { return requiredGroups; } - set { requiredGroups = value; } + get { return _requiredGroups; } + set { _requiredGroups = value; } } - private IDictionary requiredGroups; + private IDictionary _requiredGroups; /// /// Languange mode @@ -292,16 +292,16 @@ namespace Microsoft.PowerShell.Commands { get { - return languageMode; + return _languageMode; } set { - languageMode = value; - isLanguageModeSpecified = true; + _languageMode = value; + _isLanguageModeSpecified = true; } } - private PSLanguageMode languageMode = PSLanguageMode.NoLanguage; - private bool isLanguageModeSpecified; + private PSLanguageMode _languageMode = PSLanguageMode.NoLanguage; + private bool _isLanguageModeSpecified; /// /// Execution policy @@ -311,14 +311,14 @@ namespace Microsoft.PowerShell.Commands { get { - return executionPolicy; + return _executionPolicy; } set { - executionPolicy = value; + _executionPolicy = value; } } - private ExecutionPolicy executionPolicy = ExecutionPolicy.Restricted; + private ExecutionPolicy _executionPolicy = ExecutionPolicy.Restricted; /// /// PowerShell version @@ -328,14 +328,14 @@ namespace Microsoft.PowerShell.Commands { get { - return powerShellVersion; + return _powerShellVersion; } set { - powerShellVersion = value; + _powerShellVersion = value; } } - private Version powerShellVersion; + private Version _powerShellVersion; /// /// A list of modules to import @@ -346,14 +346,14 @@ namespace Microsoft.PowerShell.Commands { get { - return modulesToImport; + return _modulesToImport; } set { - modulesToImport = value; + _modulesToImport = value; } } - private object[] modulesToImport; + private object[] _modulesToImport; /// /// A list of visible aliases @@ -364,14 +364,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleAliases; + return _visibleAliases; } set { - visibleAliases = value; + _visibleAliases = value; } } - private string[] visibleAliases = Utils.EmptyArray(); + private string[] _visibleAliases = Utils.EmptyArray(); /// /// A list of visible cmdlets @@ -382,14 +382,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleCmdlets; + return _visibleCmdlets; } set { - visibleCmdlets = value; + _visibleCmdlets = value; } } - private Object[] visibleCmdlets = null; + private Object[] _visibleCmdlets = null; /// /// A list of visible functions @@ -400,14 +400,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleFunctions; + return _visibleFunctions; } set { - visibleFunctions = value; + _visibleFunctions = value; } } - private Object[] visibleFunctions = null; + private Object[] _visibleFunctions = null; /// /// A list of visible external commands (scripts and applications) @@ -418,14 +418,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleExternalCommands; + return _visibleExternalCommands; } set { - visibleExternalCommands = value; + _visibleExternalCommands = value; } } - private string[] visibleExternalCommands = Utils.EmptyArray(); + private string[] _visibleExternalCommands = Utils.EmptyArray(); /// /// A list of providers @@ -436,14 +436,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleProviders; + return _visibleProviders; } set { - visibleProviders = value; + _visibleProviders = value; } } - private string[] visibleProviders = Utils.EmptyArray(); + private string[] _visibleProviders = Utils.EmptyArray(); /// /// A list of alises @@ -454,14 +454,14 @@ namespace Microsoft.PowerShell.Commands { get { - return aliasDefinitions; + return _aliasDefinitions; } set { - aliasDefinitions = value; + _aliasDefinitions = value; } } - private IDictionary[] aliasDefinitions; + private IDictionary[] _aliasDefinitions; /// /// A list of functions @@ -472,14 +472,14 @@ namespace Microsoft.PowerShell.Commands { get { - return functionDefinitions; + return _functionDefinitions; } set { - functionDefinitions = value; + _functionDefinitions = value; } } - private IDictionary[] functionDefinitions; + private IDictionary[] _functionDefinitions; /// /// A list of variables @@ -490,14 +490,14 @@ namespace Microsoft.PowerShell.Commands { get { - return variableDefinitions; + return _variableDefinitions; } set { - variableDefinitions = value; + _variableDefinitions = value; } } - private object variableDefinitions; + private object _variableDefinitions; /// /// A list of environment variables @@ -509,14 +509,14 @@ namespace Microsoft.PowerShell.Commands { get { - return environmentVariables; + return _environmentVariables; } set { - environmentVariables = value; + _environmentVariables = value; } } - private IDictionary environmentVariables; + private IDictionary _environmentVariables; /// /// A list of types to process @@ -527,14 +527,14 @@ namespace Microsoft.PowerShell.Commands { get { - return typesToProcess; + return _typesToProcess; } set { - typesToProcess = value; + _typesToProcess = value; } } - private string[] typesToProcess = Utils.EmptyArray(); + private string[] _typesToProcess = Utils.EmptyArray(); /// /// A list of format data to process @@ -545,14 +545,14 @@ namespace Microsoft.PowerShell.Commands { get { - return formatsToProcess; + return _formatsToProcess; } set { - formatsToProcess = value; + _formatsToProcess = value; } } - private string[] formatsToProcess = Utils.EmptyArray(); + private string[] _formatsToProcess = Utils.EmptyArray(); /// /// A list of assemblies to load @@ -563,14 +563,14 @@ namespace Microsoft.PowerShell.Commands { get { - return assembliesToLoad; + return _assembliesToLoad; } set { - assembliesToLoad = value; + _assembliesToLoad = value; } } - private string[] assembliesToLoad; + private string[] _assembliesToLoad; /// /// Gets or sets whether to include a full expansion of all possible session configuration @@ -588,18 +588,18 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - Debug.Assert(!String.IsNullOrEmpty(path)); + Debug.Assert(!String.IsNullOrEmpty(_path)); ProviderInfo provider = null; PSDriveInfo drive; - string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out drive); + string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive); if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase)) { - string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, path); + string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, _path); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath", - ErrorCategory.InvalidArgument, path); + ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } @@ -632,55 +632,55 @@ namespace Microsoft.PowerShell.Commands // Schema version result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment, - SessionConfigurationUtils.QuoteName(schemaVersion), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_schemaVersion), streamWriter, false)); // Guid - result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(guid), streamWriter, false)); + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(_guid), streamWriter, false)); // Author - if (String.IsNullOrEmpty(author)) + if (String.IsNullOrEmpty(_author)) { - author = Environment.UserName; + _author = Environment.UserName; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment, - SessionConfigurationUtils.QuoteName(author), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_author), streamWriter, false)); // Description result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Description, RemotingErrorIdStrings.DISCDescriptionComment, - SessionConfigurationUtils.QuoteName(description), streamWriter, String.IsNullOrEmpty(description))); + SessionConfigurationUtils.QuoteName(_description), streamWriter, String.IsNullOrEmpty(_description))); // Company name if (ShouldGenerateConfigurationSnippet("CompanyName")) { - if (String.IsNullOrEmpty(companyName)) + if (String.IsNullOrEmpty(_companyName)) { - companyName = Modules.DefaultCompanyName; + _companyName = Modules.DefaultCompanyName; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, - SessionConfigurationUtils.QuoteName(companyName), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false)); } // Copyright if (ShouldGenerateConfigurationSnippet("Copyright")) { - if (String.IsNullOrEmpty(copyright)) + if (String.IsNullOrEmpty(_copyright)) { - copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, author); + _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, _author); } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, - SessionConfigurationUtils.QuoteName(copyright), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false)); } // Session type result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment, - SessionConfigurationUtils.QuoteName(sessionType), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_sessionType), streamWriter, false)); string resultData = null; // Transcript directory - resultData = String.IsNullOrEmpty(transcriptDirectory) ? "'C:\\Transcripts\\'" : SessionConfigurationUtils.QuoteName(transcriptDirectory); + resultData = String.IsNullOrEmpty(_transcriptDirectory) ? "'C:\\Transcripts\\'" : SessionConfigurationUtils.QuoteName(_transcriptDirectory); result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TranscriptDirectory, RemotingErrorIdStrings.DISCTranscriptDirectoryComment, - resultData, streamWriter, String.IsNullOrEmpty(transcriptDirectory))); + resultData, streamWriter, String.IsNullOrEmpty(_transcriptDirectory))); // Run as virtual account result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccount, RemotingErrorIdStrings.DISCRunAsVirtualAccountComment, @@ -727,28 +727,28 @@ namespace Microsoft.PowerShell.Commands } // Scripts to process - resultData = (scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'"; + resultData = (_scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, - resultData, streamWriter, (scriptsToProcess.Length == 0))); + resultData, streamWriter, (_scriptsToProcess.Length == 0))); // Role definitions - if (roleDefinitions == null) + if (_roleDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment, "@{ 'CONTOSO\\SqlAdmins' = @{ RoleCapabilities = 'SqlAdministration' }; 'CONTOSO\\ServerMonitors' = @{ VisibleCmdlets = 'Get-Process' } } ", streamWriter, true)); } else { - DISCUtils.ValidateRoleDefinitions(roleDefinitions); + DISCUtils.ValidateRoleDefinitions(_roleDefinitions); result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment, - SessionConfigurationUtils.CombineHashtable(roleDefinitions, streamWriter), streamWriter, false)); + SessionConfigurationUtils.CombineHashtable(_roleDefinitions, streamWriter), streamWriter, false)); } // Required groups if (ShouldGenerateConfigurationSnippet("RequiredGroups")) { - if (requiredGroups == null) + if (_requiredGroups == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment, "@{ And = @{ Or = 'CONTOSO\\SmartCard-Logon1', 'CONTOSO\\SmartCard-Logon2' }, 'Administrators' }", streamWriter, true)); @@ -756,29 +756,29 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment, - SessionConfigurationUtils.CombineRequiredGroupsHash(requiredGroups), streamWriter, false)); + SessionConfigurationUtils.CombineRequiredGroupsHash(_requiredGroups), streamWriter, false)); } } // PSLanguageMode languageMode if (ShouldGenerateConfigurationSnippet("LanguageMode")) { - if (!isLanguageModeSpecified) + if (!_isLanguageModeSpecified) { - if (sessionType == SessionType.Default) + if (_sessionType == SessionType.Default) { - languageMode = PSLanguageMode.FullLanguage; + _languageMode = PSLanguageMode.FullLanguage; } } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, - SessionConfigurationUtils.QuoteName(languageMode), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_languageMode), streamWriter, false)); } // ExecutionPolicy executionPolicy if (ShouldGenerateConfigurationSnippet("ExecutionPolicy")) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment, - SessionConfigurationUtils.QuoteName(executionPolicy), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_executionPolicy), streamWriter, false)); } // PowerShell version @@ -786,17 +786,17 @@ namespace Microsoft.PowerShell.Commands if (ShouldGenerateConfigurationSnippet("PowerShellVersion")) { - if (powerShellVersion == null) + if (_powerShellVersion == null) { isExample = true; - powerShellVersion = PSVersionInfo.PSVersion; + _powerShellVersion = PSVersionInfo.PSVersion; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, - SessionConfigurationUtils.QuoteName(powerShellVersion), streamWriter, isExample)); + SessionConfigurationUtils.QuoteName(_powerShellVersion), streamWriter, isExample)); } // Modules to import - if (modulesToImport == null) + if (_modulesToImport == null) { if (Full) { @@ -807,18 +807,18 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, - SessionConfigurationUtils.CombineHashTableOrStringArray(modulesToImport, streamWriter, this), streamWriter, false)); + SessionConfigurationUtils.CombineHashTableOrStringArray(_modulesToImport, streamWriter, this), streamWriter, false)); } // Visible aliases if (ShouldGenerateConfigurationSnippet("VisibleAliases")) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleAliases, streamWriter, this), streamWriter, visibleAliases.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0)); } // Visible cmdlets - if ((visibleCmdlets == null) || (visibleCmdlets.Length == 0)) + if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0)) { if (Full) { @@ -829,11 +829,11 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleCmdlets, streamWriter, this), streamWriter, false)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleCmdlets, streamWriter, this), streamWriter, false)); } // Visible functions - if ((visibleFunctions == null) || (visibleFunctions.Length == 0)) + if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0)) { if (Full) { @@ -844,25 +844,25 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleFunctions, streamWriter, this), streamWriter, visibleFunctions.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleFunctions, streamWriter, this), streamWriter, _visibleFunctions.Length == 0)); } // Visible external commands (scripts, executables) if (ShouldGenerateConfigurationSnippet("VisibleExternalCommands")) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleExternalCommands, RemotingErrorIdStrings.DISCVisibleExternalCommandsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleExternalCommands, streamWriter, this), streamWriter, visibleExternalCommands.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleExternalCommands, streamWriter, this), streamWriter, _visibleExternalCommands.Length == 0)); } // Visible providers if (ShouldGenerateConfigurationSnippet("VisibleProviders")) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleProviders, streamWriter, this), streamWriter, visibleProviders.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleProviders, streamWriter, this), streamWriter, _visibleProviders.Length == 0)); } // Alias definitions - if ((aliasDefinitions == null) || (aliasDefinitions.Length == 0)) + if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0)) { if (Full) { @@ -873,11 +873,11 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, - SessionConfigurationUtils.CombineHashtableArray(aliasDefinitions, streamWriter), streamWriter, false)); + SessionConfigurationUtils.CombineHashtableArray(_aliasDefinitions, streamWriter), streamWriter, false)); } // Function definitions - if (functionDefinitions == null) + if (_functionDefinitions == null) { if (Full) { @@ -887,7 +887,7 @@ namespace Microsoft.PowerShell.Commands } else { - Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(functionDefinitions); + Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions); if (funcHash != null) { @@ -899,21 +899,21 @@ namespace Microsoft.PowerShell.Commands if (!hashtable.ContainsKey(ConfigFileConstants.FunctionNameToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, path)); + ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, _path)); ThrowTerminatingError(e.ErrorRecord); } if (!hashtable.ContainsKey(ConfigFileConstants.FunctionValueToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, path)); + ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, _path)); ThrowTerminatingError(e.ErrorRecord); } - + if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, - ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, path)); + ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } @@ -924,7 +924,7 @@ namespace Microsoft.PowerShell.Commands !String.Equals(functionKey, ConfigFileConstants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, - functionKey, ConfigFileConstants.FunctionDefinitions, path)); + functionKey, ConfigFileConstants.FunctionDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } } @@ -939,7 +939,7 @@ namespace Microsoft.PowerShell.Commands } // Variable definitions - if (variableDefinitions == null) + if (_variableDefinitions == null) { if (Full) { @@ -949,7 +949,7 @@ namespace Microsoft.PowerShell.Commands } else { - string varString = variableDefinitions as string; + string varString = _variableDefinitions as string; if (varString != null) { @@ -958,7 +958,7 @@ namespace Microsoft.PowerShell.Commands } else { - Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(variableDefinitions); + Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions); if (varHash != null) { @@ -970,24 +970,24 @@ namespace Microsoft.PowerShell.Commands if (!hashtable.ContainsKey(ConfigFileConstants.VariableNameToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, path)); + ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, _path)); ThrowTerminatingError(e.ErrorRecord); } if (!hashtable.ContainsKey(ConfigFileConstants.VariableValueToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, path)); + ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, _path)); ThrowTerminatingError(e.ErrorRecord); } foreach (string variableKey in hashtable.Keys) { - if (!String.Equals(variableKey, ConfigFileConstants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && + if (!String.Equals(variableKey, ConfigFileConstants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(variableKey, ConfigFileConstants.VariableValueToken, StringComparison.OrdinalIgnoreCase)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, - variableKey, ConfigFileConstants.VariableDefinitions, path)); + variableKey, ConfigFileConstants.VariableDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } } @@ -1003,7 +1003,7 @@ namespace Microsoft.PowerShell.Commands } // Environment variables - if (environmentVariables == null) + if (_environmentVariables == null) { if (Full) { @@ -1015,36 +1015,36 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, - SessionConfigurationUtils.CombineHashtable(environmentVariables, streamWriter), streamWriter, false)); + SessionConfigurationUtils.CombineHashtable(_environmentVariables, streamWriter), streamWriter, false)); } // Types to process if (ShouldGenerateConfigurationSnippet("TypesToProcess")) { - resultData = (typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'"; + resultData = (_typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, - resultData, streamWriter, (typesToProcess.Length == 0))); + resultData, streamWriter, (_typesToProcess.Length == 0))); } // Formats to process if (ShouldGenerateConfigurationSnippet("FormatsToProcess")) { - resultData = (formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'"; + resultData = (_formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, - resultData, streamWriter, (formatsToProcess.Length == 0))); + resultData, streamWriter, (_formatsToProcess.Length == 0))); } // Assemblies to load if (ShouldGenerateConfigurationSnippet("AssembliesToLoad")) { isExample = false; - if ((assembliesToLoad == null) || (assembliesToLoad.Length == 0)) + if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0)) { isExample = true; - assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; + _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, - SessionConfigurationUtils.CombineStringArray(assembliesToLoad), streamWriter, isExample)); + SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample)); } result.Append("}"); @@ -1088,14 +1088,14 @@ namespace Microsoft.PowerShell.Commands { get { - return path; + return _path; } set { - path = value; + _path = value; } } - private string path; + private string _path; /// /// Configuration file GUID @@ -1105,14 +1105,14 @@ namespace Microsoft.PowerShell.Commands { get { - return guid; + return _guid; } set { - guid = value; + _guid = value; } } - private Guid guid = Guid.NewGuid(); + private Guid _guid = Guid.NewGuid(); /// /// Author of the configuration file @@ -1122,14 +1122,14 @@ namespace Microsoft.PowerShell.Commands { get { - return author; + return _author; } set { - author = value; + _author = value; } } - private string author; + private string _author; /// /// Description @@ -1139,14 +1139,14 @@ namespace Microsoft.PowerShell.Commands { get { - return description; + return _description; } set { - description = value; + _description = value; } } - private string description; + private string _description; /// /// Company name @@ -1156,14 +1156,14 @@ namespace Microsoft.PowerShell.Commands { get { - return companyName; + return _companyName; } set { - companyName = value; + _companyName = value; } } - private string companyName; + private string _companyName; /// /// Copyright information @@ -1173,14 +1173,14 @@ namespace Microsoft.PowerShell.Commands { get { - return copyright; + return _copyright; } set { - copyright = value; + _copyright = value; } } - private string copyright; + private string _copyright; /// /// A list of modules to import @@ -1191,14 +1191,14 @@ namespace Microsoft.PowerShell.Commands { get { - return modulesToImport; + return _modulesToImport; } set { - modulesToImport = value; + _modulesToImport = value; } } - private object[] modulesToImport; + private object[] _modulesToImport; /// /// A list of visible aliases @@ -1209,14 +1209,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleAliases; + return _visibleAliases; } set { - visibleAliases = value; + _visibleAliases = value; } } - private string[] visibleAliases = Utils.EmptyArray(); + private string[] _visibleAliases = Utils.EmptyArray(); /// /// A list of visible cmdlets @@ -1227,14 +1227,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleCmdlets; + return _visibleCmdlets; } set { - visibleCmdlets = value; + _visibleCmdlets = value; } } - private Object[] visibleCmdlets = null; + private Object[] _visibleCmdlets = null; /// /// A list of visible functions @@ -1245,14 +1245,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleFunctions; + return _visibleFunctions; } set { - visibleFunctions = value; + _visibleFunctions = value; } } - private Object[] visibleFunctions = null; + private Object[] _visibleFunctions = null; /// /// A list of visible external commands (scripts and applications) @@ -1263,14 +1263,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleExternalCommands; + return _visibleExternalCommands; } set { - visibleExternalCommands = value; + _visibleExternalCommands = value; } } - private string[] visibleExternalCommands = Utils.EmptyArray(); + private string[] _visibleExternalCommands = Utils.EmptyArray(); /// /// A list of providers @@ -1281,14 +1281,14 @@ namespace Microsoft.PowerShell.Commands { get { - return visibleProviders; + return _visibleProviders; } set { - visibleProviders = value; + _visibleProviders = value; } } - private string[] visibleProviders = Utils.EmptyArray(); + private string[] _visibleProviders = Utils.EmptyArray(); /// /// Scripts to process @@ -1299,14 +1299,14 @@ namespace Microsoft.PowerShell.Commands { get { - return scriptsToProcess; + return _scriptsToProcess; } set { - scriptsToProcess = value; + _scriptsToProcess = value; } } - private string[] scriptsToProcess = Utils.EmptyArray(); + private string[] _scriptsToProcess = Utils.EmptyArray(); /// /// A list of alises @@ -1317,14 +1317,14 @@ namespace Microsoft.PowerShell.Commands { get { - return aliasDefinitions; + return _aliasDefinitions; } set { - aliasDefinitions = value; + _aliasDefinitions = value; } } - private IDictionary[] aliasDefinitions; + private IDictionary[] _aliasDefinitions; /// /// A list of functions @@ -1335,14 +1335,14 @@ namespace Microsoft.PowerShell.Commands { get { - return functionDefinitions; + return _functionDefinitions; } set { - functionDefinitions = value; + _functionDefinitions = value; } } - private IDictionary[] functionDefinitions; + private IDictionary[] _functionDefinitions; /// /// A list of variables @@ -1353,14 +1353,14 @@ namespace Microsoft.PowerShell.Commands { get { - return variableDefinitions; + return _variableDefinitions; } set { - variableDefinitions = value; + _variableDefinitions = value; } } - private object variableDefinitions; + private object _variableDefinitions; /// /// A list of environment variables @@ -1372,14 +1372,14 @@ namespace Microsoft.PowerShell.Commands { get { - return environmentVariables; + return _environmentVariables; } set { - environmentVariables = value; + _environmentVariables = value; } } - private IDictionary environmentVariables; + private IDictionary _environmentVariables; /// /// A list of types to process @@ -1390,14 +1390,14 @@ namespace Microsoft.PowerShell.Commands { get { - return typesToProcess; + return _typesToProcess; } set { - typesToProcess = value; + _typesToProcess = value; } } - private string[] typesToProcess = Utils.EmptyArray(); + private string[] _typesToProcess = Utils.EmptyArray(); /// /// A list of format data to process @@ -1408,14 +1408,14 @@ namespace Microsoft.PowerShell.Commands { get { - return formatsToProcess; + return _formatsToProcess; } set { - formatsToProcess = value; + _formatsToProcess = value; } } - private string[] formatsToProcess = Utils.EmptyArray(); + private string[] _formatsToProcess = Utils.EmptyArray(); /// /// A list of assemblies to load @@ -1426,14 +1426,14 @@ namespace Microsoft.PowerShell.Commands { get { - return assembliesToLoad; + return _assembliesToLoad; } set { - assembliesToLoad = value; + _assembliesToLoad = value; } } - private string[] assembliesToLoad; + private string[] _assembliesToLoad; #endregion @@ -1444,18 +1444,18 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - Debug.Assert(!String.IsNullOrEmpty(path)); + Debug.Assert(!String.IsNullOrEmpty(_path)); ProviderInfo provider = null; PSDriveInfo drive; - string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out drive); + string filePath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_path, out provider, out drive); if (!provider.NameEquals(Context.ProviderNames.FileSystem) || !filePath.EndsWith(StringLiterals.PowerShellRoleCapabilityFileExtension, StringComparison.OrdinalIgnoreCase)) { - string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleCapabilityFilePath, path); + string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleCapabilityFilePath, _path); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "InvalidRoleCapabilityFilePath", - ErrorCategory.InvalidArgument, path); + ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } @@ -1487,55 +1487,54 @@ namespace Microsoft.PowerShell.Commands result.Append(streamWriter.NewLine); // Guid - result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(guid), streamWriter, false)); + result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Guid, RemotingErrorIdStrings.DISCGUIDComment, SessionConfigurationUtils.QuoteName(_guid), streamWriter, false)); // Author - if (String.IsNullOrEmpty(author)) + if (String.IsNullOrEmpty(_author)) { - author = Environment.UserName; + _author = Environment.UserName; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Author, RemotingErrorIdStrings.DISCAuthorComment, - SessionConfigurationUtils.QuoteName(author), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_author), streamWriter, false)); // Description result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Description, RemotingErrorIdStrings.DISCDescriptionComment, - SessionConfigurationUtils.QuoteName(description), streamWriter, String.IsNullOrEmpty(description))); + SessionConfigurationUtils.QuoteName(_description), streamWriter, String.IsNullOrEmpty(_description))); // Company name - if (String.IsNullOrEmpty(companyName)) + if (String.IsNullOrEmpty(_companyName)) { - companyName = Modules.DefaultCompanyName; + _companyName = Modules.DefaultCompanyName; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, - SessionConfigurationUtils.QuoteName(companyName), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_companyName), streamWriter, false)); // Copyright - if (String.IsNullOrEmpty(copyright)) + if (String.IsNullOrEmpty(_copyright)) { - copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, author); + _copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, _author); } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, - SessionConfigurationUtils.QuoteName(copyright), streamWriter, false)); + SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false)); // Modules to import - if (modulesToImport == null) + if (_modulesToImport == null) { string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); - } else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, - SessionConfigurationUtils.CombineHashTableOrStringArray(modulesToImport, streamWriter, this), streamWriter, false)); + SessionConfigurationUtils.CombineHashTableOrStringArray(_modulesToImport, streamWriter, this), streamWriter, false)); } // Visible aliases result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleAliases, streamWriter, this), streamWriter, visibleAliases.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0)); // Visible cmdlets - if ((visibleCmdlets == null) || (visibleCmdlets.Length == 0)) + if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, "'Invoke-Cmdlet1', @{ Name = 'Invoke-Cmdlet2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true)); @@ -1543,11 +1542,11 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleCmdlets, streamWriter, this), streamWriter, false)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleCmdlets, streamWriter, this), streamWriter, false)); } // Visible functions - if ((visibleFunctions == null) || (visibleFunctions.Length == 0)) + if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, "'Invoke-Function1', @{ Name = 'Invoke-Function2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true)); @@ -1555,24 +1554,24 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleFunctions, streamWriter, this), streamWriter, visibleFunctions.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleFunctions, streamWriter, this), streamWriter, _visibleFunctions.Length == 0)); } // Visible external commands (scripts, executables) result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleExternalCommands, RemotingErrorIdStrings.DISCVisibleExternalCommandsComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleExternalCommands, streamWriter, this), streamWriter, visibleExternalCommands.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleExternalCommands, streamWriter, this), streamWriter, _visibleExternalCommands.Length == 0)); // Visible providers result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, - SessionConfigurationUtils.GetVisibilityDefault(visibleProviders, streamWriter, this), streamWriter, visibleProviders.Length == 0)); + SessionConfigurationUtils.GetVisibilityDefault(_visibleProviders, streamWriter, this), streamWriter, _visibleProviders.Length == 0)); // Scripts to process - string resultData = (scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'"; + string resultData = (_scriptsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_scriptsToProcess) : "'C:\\ConfigData\\InitScript1.ps1', 'C:\\ConfigData\\InitScript2.ps1'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, - resultData, streamWriter, (scriptsToProcess.Length == 0))); + resultData, streamWriter, (_scriptsToProcess.Length == 0))); // Alias definitions - if ((aliasDefinitions == null) || (aliasDefinitions.Length == 0)) + if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, "@{ Name = 'Alias1'; Value = 'Invoke-Alias1'}, @{ Name = 'Alias2'; Value = 'Invoke-Alias2'}", streamWriter, true)); @@ -1580,18 +1579,18 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, - SessionConfigurationUtils.CombineHashtableArray(aliasDefinitions, streamWriter), streamWriter, false)); + SessionConfigurationUtils.CombineHashtableArray(_aliasDefinitions, streamWriter), streamWriter, false)); } // Function definitions - if (functionDefinitions == null) + if (_functionDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, "@{ Name = 'MyFunction'; ScriptBlock = { param($MyInput) $MyInput } }", streamWriter, true)); } else { - Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(functionDefinitions); + Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions); if (funcHash != null) { @@ -1603,21 +1602,21 @@ namespace Microsoft.PowerShell.Commands if (!hashtable.ContainsKey(ConfigFileConstants.FunctionNameToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, path)); + ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionNameToken, _path)); ThrowTerminatingError(e.ErrorRecord); } if (!hashtable.ContainsKey(ConfigFileConstants.FunctionValueToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, path)); + ConfigFileConstants.FunctionDefinitions, ConfigFileConstants.FunctionValueToken, _path)); ThrowTerminatingError(e.ErrorRecord); } if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, - ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, path)); + ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } @@ -1628,7 +1627,7 @@ namespace Microsoft.PowerShell.Commands !String.Equals(functionKey, ConfigFileConstants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, - functionKey, ConfigFileConstants.FunctionDefinitions, path)); + functionKey, ConfigFileConstants.FunctionDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } } @@ -1643,14 +1642,14 @@ namespace Microsoft.PowerShell.Commands } // Variable definitions - if (variableDefinitions == null) + if (_variableDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, "@{ Name = 'Variable1'; Value = { 'Dynamic' + 'InitialValue' } }, @{ Name = 'Variable2'; Value = 'StaticInitialValue' }", streamWriter, true)); } else { - string varString = variableDefinitions as string; + string varString = _variableDefinitions as string; if (varString != null) { @@ -1659,7 +1658,7 @@ namespace Microsoft.PowerShell.Commands } else { - Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(variableDefinitions); + Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions); if (varHash != null) { @@ -1671,14 +1670,14 @@ namespace Microsoft.PowerShell.Commands if (!hashtable.ContainsKey(ConfigFileConstants.VariableNameToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, path)); + ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableNameToken, _path)); ThrowTerminatingError(e.ErrorRecord); } if (!hashtable.ContainsKey(ConfigFileConstants.VariableValueToken)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, - ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, path)); + ConfigFileConstants.VariableDefinitions, ConfigFileConstants.VariableValueToken, _path)); ThrowTerminatingError(e.ErrorRecord); } @@ -1688,7 +1687,7 @@ namespace Microsoft.PowerShell.Commands !String.Equals(variableKey, ConfigFileConstants.VariableValueToken, StringComparison.OrdinalIgnoreCase)) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, - variableKey, ConfigFileConstants.VariableDefinitions, path)); + variableKey, ConfigFileConstants.VariableDefinitions, _path)); ThrowTerminatingError(e.ErrorRecord); } } @@ -1704,7 +1703,7 @@ namespace Microsoft.PowerShell.Commands } // Environment variables - if (environmentVariables == null) + if (_environmentVariables == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, "@{ Variable1 = 'Value1'; Variable2 = 'Value2' }", @@ -1713,28 +1712,28 @@ namespace Microsoft.PowerShell.Commands else { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, - SessionConfigurationUtils.CombineHashtable(environmentVariables, streamWriter), streamWriter, false)); + SessionConfigurationUtils.CombineHashtable(_environmentVariables, streamWriter), streamWriter, false)); } // Types to process - resultData = (typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'"; + resultData = (_typesToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_typesToProcess) : "'C:\\ConfigData\\MyTypes.ps1xml', 'C:\\ConfigData\\OtherTypes.ps1xml'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, - resultData, streamWriter, (typesToProcess.Length == 0))); + resultData, streamWriter, (_typesToProcess.Length == 0))); // Formats to process - resultData = (formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'"; + resultData = (_formatsToProcess.Length > 0) ? SessionConfigurationUtils.CombineStringArray(_formatsToProcess) : "'C:\\ConfigData\\MyFormats.ps1xml', 'C:\\ConfigData\\OtherFormats.ps1xml'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, - resultData, streamWriter, (formatsToProcess.Length == 0))); + resultData, streamWriter, (_formatsToProcess.Length == 0))); // Assemblies to load bool isExample = false; - if ((assembliesToLoad == null) || (assembliesToLoad.Length == 0)) + if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0)) { isExample = true; - assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; + _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; } result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, - SessionConfigurationUtils.CombineStringArray(assembliesToLoad), streamWriter, isExample)); + SessionConfigurationUtils.CombineStringArray(_assembliesToLoad), streamWriter, isExample)); result.Append("}"); @@ -1804,7 +1803,7 @@ namespace Microsoft.PowerShell.Commands /// internal static string WriteBoolean(bool booleanToEmit) { - if(booleanToEmit) + if (booleanToEmit) { return "$true"; } @@ -1914,7 +1913,7 @@ namespace Microsoft.PowerShell.Commands object[] values = keyObject as object[]; if (values != null) { - for (int i = 0; i < values.Length; ) + for (int i = 0; i < values.Length;) { WriteRequriedGroup(values[i++], sb); diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs index a7272f60a..c4c01c338 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs @@ -1,7 +1,8 @@ // // Copyright (C) Microsoft. All rights reserved. // -using System; + +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -22,7 +23,7 @@ namespace Microsoft.PowerShell.Commands internal const string AttribOutputBufferingMode = "OutputBufferingMode"; internal static System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; - private System.Management.Automation.Runspaces.OutputBufferingMode? outputBufferingMode = null; + private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null; private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec"; internal static readonly int? DefaultProcessIdleTimeout_ForPSRemoting = 0; // in seconds @@ -39,34 +40,33 @@ namespace Microsoft.PowerShell.Commands private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers"; internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue; - private int? maxConcurrentUsers = null; + private int? _maxConcurrentUsers = null; private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell"; internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue; - private int? maxProcessesPerSession = null; + private int? _maxProcessesPerSession = null; private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB"; internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue; - private int? maxMemoryPerSessionMB = null; + private int? _maxMemoryPerSessionMB = null; private const string AttribMaxSessions = "MaxShells"; internal static readonly int? DefaultMaxSessions = int.MaxValue; - private int? maxSessions = null; + private int? _maxSessions = null; private const string AttribMaxSessionsPerUser = "MaxShellsPerUser"; internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue; - private int? maxSessionsPerUser = null; + private int? _maxSessionsPerUser = null; private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell"; internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue; - private int? maxConcurrentCommandsPerSession = null; + private int? _maxConcurrentCommandsPerSession = null; /// /// Constructor that instantiates with default values /// internal WSManConfigurationOption() { - } /// @@ -76,15 +76,15 @@ namespace Microsoft.PowerShell.Commands /// protected internal override void LoadFromDefaults(PSSessionType sessionType, bool keepAssigned) { - if (!keepAssigned || !outputBufferingMode.HasValue) + if (!keepAssigned || !_outputBufferingMode.HasValue) { - outputBufferingMode = DefaultOutputBufferingMode; + _outputBufferingMode = DefaultOutputBufferingMode; } if (!keepAssigned || !_processIdleTimeoutSec.HasValue) { - _processIdleTimeoutSec - = sessionType == PSSessionType.Workflow - ? DefaultProcessIdleTimeout_ForWorkflow + _processIdleTimeoutSec + = sessionType == PSSessionType.Workflow + ? DefaultProcessIdleTimeout_ForWorkflow : DefaultProcessIdleTimeout_ForPSRemoting; } if (!keepAssigned || !_maxIdleTimeoutSec.HasValue) @@ -95,29 +95,29 @@ namespace Microsoft.PowerShell.Commands { _idleTimeoutSec = DefaultIdleTimeout; } - if (!keepAssigned || !maxConcurrentUsers.HasValue) + if (!keepAssigned || !_maxConcurrentUsers.HasValue) { - maxConcurrentUsers = DefaultMaxConcurrentUsers; + _maxConcurrentUsers = DefaultMaxConcurrentUsers; } - if (!keepAssigned || !maxProcessesPerSession.HasValue) + if (!keepAssigned || !_maxProcessesPerSession.HasValue) { - maxProcessesPerSession = DefaultMaxProcessesPerSession; + _maxProcessesPerSession = DefaultMaxProcessesPerSession; } - if (!keepAssigned || !maxMemoryPerSessionMB.HasValue) + if (!keepAssigned || !_maxMemoryPerSessionMB.HasValue) { - maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB; + _maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB; } - if (!keepAssigned || !maxSessions.HasValue) + if (!keepAssigned || !_maxSessions.HasValue) { - maxSessions = DefaultMaxSessions; + _maxSessions = DefaultMaxSessions; } - if (!keepAssigned || !maxSessionsPerUser.HasValue) + if (!keepAssigned || !_maxSessionsPerUser.HasValue) { - maxSessionsPerUser = DefaultMaxSessionsPerUser; + _maxSessionsPerUser = DefaultMaxSessionsPerUser; } - if (!keepAssigned || !maxConcurrentCommandsPerSession.HasValue) + if (!keepAssigned || !_maxConcurrentCommandsPerSession.HasValue) { - maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession; + _maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession; } } @@ -158,11 +158,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxSessions; + return _maxSessions; } internal set { - maxSessions = value; + _maxSessions = value; } } @@ -173,11 +173,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxConcurrentCommandsPerSession; + return _maxConcurrentCommandsPerSession; } internal set { - maxConcurrentCommandsPerSession = value; + _maxConcurrentCommandsPerSession = value; } } @@ -188,11 +188,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxSessionsPerUser; + return _maxSessionsPerUser; } internal set { - maxSessionsPerUser = value; + _maxSessionsPerUser = value; } } @@ -203,11 +203,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxMemoryPerSessionMB; + return _maxMemoryPerSessionMB; } internal set { - maxMemoryPerSessionMB = value; + _maxMemoryPerSessionMB = value; } } @@ -218,11 +218,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxProcessesPerSession; + return _maxProcessesPerSession; } internal set { - maxProcessesPerSession = value; + _maxProcessesPerSession = value; } } @@ -233,11 +233,11 @@ namespace Microsoft.PowerShell.Commands { get { - return maxConcurrentUsers; + return _maxConcurrentUsers; } internal set { - maxConcurrentUsers = value; + _maxConcurrentUsers = value; } } @@ -263,11 +263,11 @@ namespace Microsoft.PowerShell.Commands { get { - return outputBufferingMode; + return _outputBufferingMode; } internal set { - outputBufferingMode = value; + _outputBufferingMode = value; } } @@ -279,30 +279,30 @@ namespace Microsoft.PowerShell.Commands { quotas[AttribIdleTimeout] = (1000 * _idleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } - if (maxConcurrentUsers.HasValue) + if (_maxConcurrentUsers.HasValue) { - quotas[AttribMaxConcurrentUsers] = maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxConcurrentUsers] = _maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture); } - if (maxProcessesPerSession.HasValue) + if (_maxProcessesPerSession.HasValue) { - quotas[AttribMaxProcessesPerSession] = maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxProcessesPerSession] = _maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture); } - if (maxMemoryPerSessionMB.HasValue) + if (_maxMemoryPerSessionMB.HasValue) { - quotas[AttribMaxMemoryPerSessionMB] = maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxMemoryPerSessionMB] = _maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture); } - if (maxSessionsPerUser.HasValue) + if (_maxSessionsPerUser.HasValue) { - quotas[AttribMaxSessionsPerUser] = maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxSessionsPerUser] = _maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture); } - if (maxConcurrentCommandsPerSession.HasValue) + if (_maxConcurrentCommandsPerSession.HasValue) { - quotas[AttribMaxConcurrentCommandsPerSession] = maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxConcurrentCommandsPerSession] = _maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture); } - if (maxSessions.HasValue) + if (_maxSessions.HasValue) { - quotas[AttribMaxSessions] = maxSessions.Value.ToString(CultureInfo.InvariantCulture); + quotas[AttribMaxSessions] = _maxSessions.Value.ToString(CultureInfo.InvariantCulture); } if (_maxIdleTimeoutSec.HasValue) { @@ -323,35 +323,35 @@ namespace Microsoft.PowerShell.Commands { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribIdleTimeout, 1000 * _idleTimeoutSec)); } - if (maxConcurrentUsers.HasValue) + if (_maxConcurrentUsers.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, maxConcurrentUsers)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, _maxConcurrentUsers)); } - if (maxProcessesPerSession.HasValue) + if (_maxProcessesPerSession.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, maxProcessesPerSession)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, _maxProcessesPerSession)); } - if (maxMemoryPerSessionMB.HasValue) + if (_maxMemoryPerSessionMB.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, maxMemoryPerSessionMB)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, _maxMemoryPerSessionMB)); } - if (maxSessionsPerUser.HasValue) + if (_maxSessionsPerUser.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, maxSessionsPerUser)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, _maxSessionsPerUser)); } - if (maxConcurrentCommandsPerSession.HasValue) + if (_maxConcurrentCommandsPerSession.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, maxConcurrentCommandsPerSession)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, _maxConcurrentCommandsPerSession)); } - if (maxSessions.HasValue) + if (_maxSessions.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, maxSessions)); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, _maxSessions)); } if (_maxIdleTimeoutSec.HasValue) { // Special case max int value for unbounded default. - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, (_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec))); } @@ -367,9 +367,9 @@ namespace Microsoft.PowerShell.Commands internal override string ConstructOptionsAsXmlAttributes() { StringBuilder sb = new StringBuilder(); - if (outputBufferingMode.HasValue) + if (_outputBufferingMode.HasValue) { - sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribOutputBufferingMode, outputBufferingMode.ToString())); + sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribOutputBufferingMode, _outputBufferingMode.ToString())); } if (_processIdleTimeoutSec.HasValue) @@ -387,9 +387,9 @@ namespace Microsoft.PowerShell.Commands internal override Hashtable ConstructOptionsAsHashtable() { Hashtable table = new Hashtable(); - if (outputBufferingMode.HasValue) + if (_outputBufferingMode.HasValue) { - table[AttribOutputBufferingMode] = outputBufferingMode.ToString(); + table[AttribOutputBufferingMode] = _outputBufferingMode.ToString(); } if (_processIdleTimeoutSec.HasValue) @@ -408,7 +408,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(WSManConfigurationOption))] public sealed class NewPSTransportOptionCommand : PSCmdlet { - private WSManConfigurationOption option = new WSManConfigurationOption(); + private WSManConfigurationOption _option = new WSManConfigurationOption(); /// /// MaxIdleTimeoutSec @@ -418,11 +418,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxIdleTimeoutSec; + return _option.MaxIdleTimeoutSec; } set { - option.MaxIdleTimeoutSec = value; + _option.MaxIdleTimeoutSec = value; } } @@ -434,11 +434,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.ProcessIdleTimeoutSec; + return _option.ProcessIdleTimeoutSec; } set { - option.ProcessIdleTimeoutSec = value; + _option.ProcessIdleTimeoutSec = value; } } @@ -450,11 +450,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxSessions; + return _option.MaxSessions; } set { - option.MaxSessions = value; + _option.MaxSessions = value; } } @@ -466,11 +466,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxConcurrentCommandsPerSession; + return _option.MaxConcurrentCommandsPerSession; } set { - option.MaxConcurrentCommandsPerSession = value; + _option.MaxConcurrentCommandsPerSession = value; } } @@ -482,11 +482,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxSessionsPerUser; + return _option.MaxSessionsPerUser; } set { - option.MaxSessionsPerUser = value; + _option.MaxSessionsPerUser = value; } } @@ -498,11 +498,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxMemoryPerSessionMB; + return _option.MaxMemoryPerSessionMB; } set { - option.MaxMemoryPerSessionMB = value; + _option.MaxMemoryPerSessionMB = value; } } @@ -514,11 +514,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxProcessesPerSession; + return _option.MaxProcessesPerSession; } set { - option.MaxProcessesPerSession = value; + _option.MaxProcessesPerSession = value; } } @@ -530,11 +530,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.MaxConcurrentUsers; + return _option.MaxConcurrentUsers; } set { - option.MaxConcurrentUsers = value; + _option.MaxConcurrentUsers = value; } } @@ -546,11 +546,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.IdleTimeoutSec; + return _option.IdleTimeoutSec; } set { - option.IdleTimeoutSec = value; + _option.IdleTimeoutSec = value; } } @@ -562,11 +562,11 @@ namespace Microsoft.PowerShell.Commands { get { - return option.OutputBufferingMode; + return _option.OutputBufferingMode; } set { - option.OutputBufferingMode = value; + _option.OutputBufferingMode = value; } } @@ -575,7 +575,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void ProcessRecord() { - this.WriteObject(option); + this.WriteObject(_option); } } } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index 30ab8ad27..7ca36df07 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -67,15 +67,15 @@ namespace System.Management.Automation.Remoting { get { - return maximumConnectionRedirectionCount; + return _maximumConnectionRedirectionCount; } set { - maximumConnectionRedirectionCount = value; + _maximumConnectionRedirectionCount = value; } } - private int maximumConnectionRedirectionCount = WSManConnectionInfo.defaultMaximumConnectionRedirectionCount; - /// + private int _maximumConnectionRedirectionCount = WSManConnectionInfo.defaultMaximumConnectionRedirectionCount; + /// /// If false, underlying WSMan infrastructure will compress data sent on the network. /// If true, data will not be compressed. Compression improves performance by /// reducing the amount of data sent on the network. Compression my require extra @@ -87,14 +87,14 @@ namespace System.Management.Automation.Remoting { get { - return noCompression; + return _noCompression; } set { - noCompression = value; + _noCompression = value; } } - private bool noCompression = false; + private bool _noCompression = false; /// /// If true then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server @@ -105,14 +105,14 @@ namespace System.Management.Automation.Remoting { get { - return noMachineProfile; + return _noMachineProfile; } set { - noMachineProfile = value; + _noMachineProfile = value; } } - private bool noMachineProfile = false; + private bool _noMachineProfile = false; /// /// By default, ProxyAccessType is None, that means Proxy information (ProxyAccessType, @@ -120,10 +120,10 @@ namespace System.Management.Automation.Remoting /// public ProxyAccessType ProxyAccessType { - get { return proxyAcessType; } - set { proxyAcessType = value; } + get { return _proxyAcessType; } + set { _proxyAcessType = value; } } - private ProxyAccessType proxyAcessType = ProxyAccessType.None; + private ProxyAccessType _proxyAcessType = ProxyAccessType.None; /// /// The following is the definition of the input parameter "ProxyAuthentication". @@ -138,7 +138,7 @@ namespace System.Management.Automation.Remoting /// public AuthenticationMechanism ProxyAuthentication { - get { return proxyAuthentication; } + get { return _proxyAuthentication; } set { switch (value) @@ -146,11 +146,11 @@ namespace System.Management.Automation.Remoting case AuthenticationMechanism.Basic: case AuthenticationMechanism.Negotiate: case AuthenticationMechanism.Digest: - proxyAuthentication = value; + _proxyAuthentication = value; break; default: string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyAmbiguosAuthentication, - value, + value, AuthenticationMechanism.Basic.ToString(), AuthenticationMechanism.Negotiate.ToString(), AuthenticationMechanism.Digest.ToString()); @@ -158,17 +158,17 @@ namespace System.Management.Automation.Remoting } } } - private AuthenticationMechanism proxyAuthentication = AuthenticationMechanism.Negotiate; + private AuthenticationMechanism _proxyAuthentication = AuthenticationMechanism.Negotiate; /// /// The following is the definition of the input parameter "ProxyCredential". /// public PSCredential ProxyCredential { - get { return proxyCredential; } - set { proxyCredential = value; } + get { return _proxyCredential; } + set { _proxyCredential = value; } } - private PSCredential proxyCredential; + private PSCredential _proxyCredential; /// @@ -180,10 +180,10 @@ namespace System.Management.Automation.Remoting /// public bool SkipCACheck { - get { return skipCACheck; } - set { skipCACheck = value; } + get { return _skipCACheck; } + set { _skipCACheck = value; } } - private bool skipCACheck; + private bool _skipCACheck; /// /// Indicates that certificate common name (CN) of the server need not match the @@ -192,10 +192,10 @@ namespace System.Management.Automation.Remoting /// public bool SkipCNCheck { - get { return skipCNCheck; } - set { skipCNCheck = value; } + get { return _skipCNCheck; } + set { _skipCNCheck = value; } } - private bool skipCNCheck; + private bool _skipCNCheck; /// /// Indicates that certificate common name (CN) of the server need not match the @@ -204,10 +204,10 @@ namespace System.Management.Automation.Remoting /// public bool SkipRevocationCheck { - get { return skipRevocationCheck; } - set { skipRevocationCheck = value; } + get { return _skipRevocationCheck; } + set { _skipRevocationCheck = value; } } - private bool skipRevocationCheck; + private bool _skipRevocationCheck; /// /// The duration for which PowerShell remoting waits before timing out @@ -219,10 +219,10 @@ namespace System.Management.Automation.Remoting /// public TimeSpan OperationTimeout { - get { return operationTimeout; } - set { operationTimeout = value; } + get { return _operationTimeout; } + set { _operationTimeout = value; } } - private TimeSpan operationTimeout = + private TimeSpan _operationTimeout = TimeSpan.FromMilliseconds(BaseTransportManager.ClientDefaultOperationTimeoutMs); /// @@ -232,10 +232,10 @@ namespace System.Management.Automation.Remoting /// public bool NoEncryption { - get { return noEncryption; } - set { noEncryption = value; } + get { return _noEncryption; } + set { _noEncryption = value; } } - private bool noEncryption; + private bool _noEncryption; /// /// Indicates the request is encoded in UTF16 format rather than UTF8 format; @@ -244,10 +244,10 @@ namespace System.Management.Automation.Remoting [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] public bool UseUTF16 { - get { return useUtf16; } - set { useUtf16 = value; } + get { return _useUtf16; } + set { _useUtf16 = value; } } - private bool useUtf16; + private bool _useUtf16; /// /// Uses Service Principal Name (SPN) along with the Port number during authentication. @@ -255,10 +255,10 @@ namespace System.Management.Automation.Remoting [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] public bool IncludePortInSPN { - get { return includePortInSPN; } - set { includePortInSPN = value; } + get { return _includePortInSPN; } + set { _includePortInSPN = value; } } - bool includePortInSPN; + private bool _includePortInSPN; /// /// Determines how server in disconnected state deals with cached output @@ -268,10 +268,10 @@ namespace System.Management.Automation.Remoting /// public OutputBufferingMode OutputBufferingMode { - get { return this.outputBufferingMode; } - set { this.outputBufferingMode = value; } + get { return _outputBufferingMode; } + set { _outputBufferingMode = value; } } - private OutputBufferingMode outputBufferingMode = WSManConnectionInfo.DefaultOutputBufferingMode; + private OutputBufferingMode _outputBufferingMode = WSManConnectionInfo.DefaultOutputBufferingMode; /// /// Number of times a connection will be re-attempted when a connection fails due to network @@ -279,10 +279,10 @@ namespace System.Management.Automation.Remoting /// public int MaxConnectionRetryCount { - get { return this.maxConnectionRetryCount; } - set { this.maxConnectionRetryCount = value; } + get { return _maxConnectionRetryCount; } + set { _maxConnectionRetryCount = value; } } - private int maxConnectionRetryCount = WSManConnectionInfo.DefaultMaxConnectionRetryCount; + private int _maxConnectionRetryCount = WSManConnectionInfo.DefaultMaxConnectionRetryCount; /// /// Culture that the remote session should use @@ -291,14 +291,14 @@ namespace System.Management.Automation.Remoting { get { - return culture; + return _culture; } set { - culture = value; + _culture = value; } } - private CultureInfo culture; + private CultureInfo _culture; /// /// UI culture that the remote session should use @@ -307,14 +307,14 @@ namespace System.Management.Automation.Remoting { get { - return uiCulture; + return _uiCulture; } set { - uiCulture = value; + _uiCulture = value; } } - private CultureInfo uiCulture; + private CultureInfo _uiCulture; /// /// Total data (in bytes) that can be received from a remote machine @@ -323,10 +323,10 @@ namespace System.Management.Automation.Remoting /// public Nullable MaximumReceivedDataSizePerCommand { - get { return maxRecvdDataSizePerCommand; } - set { maxRecvdDataSizePerCommand = value; } + get { return _maxRecvdDataSizePerCommand; } + set { _maxRecvdDataSizePerCommand = value; } } - private Nullable maxRecvdDataSizePerCommand; + private Nullable _maxRecvdDataSizePerCommand; /// /// Maximum size (in bytes) of a deserialized object received from a remote machine. @@ -334,10 +334,10 @@ namespace System.Management.Automation.Remoting /// public Nullable MaximumReceivedObjectSize { - get { return maxRecvdObjectSize; } - set { maxRecvdObjectSize = value; } + get { return _maxRecvdObjectSize; } + set { _maxRecvdObjectSize = value; } } - private Nullable maxRecvdObjectSize = 200 << 20; // Default: 200MB. Bug Win8: 44870. This is to protect client from malicious server attacks. + private Nullable _maxRecvdObjectSize = 200 << 20; // Default: 200MB. Bug Win8: 44870. This is to protect client from malicious server attacks. /// /// Application arguments the server can see in @@ -345,13 +345,13 @@ namespace System.Management.Automation.Remoting [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSPrimitiveDictionary ApplicationArguments { - get { return applicationArguments; } - set + get { return _applicationArguments; } + set { - applicationArguments = value; + _applicationArguments = value; } } - private PSPrimitiveDictionary applicationArguments; + private PSPrimitiveDictionary _applicationArguments; /// /// The duration for which PowerShell remoting waits before timing out on a connection to a remote machine. @@ -363,10 +363,10 @@ namespace System.Management.Automation.Remoting /// public TimeSpan OpenTimeout { - get { return openTimeout; } - set { openTimeout = value; } + get { return _openTimeout; } + set { _openTimeout = value; } } - private TimeSpan openTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultOpenTimeout); + private TimeSpan _openTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultOpenTimeout); /// /// The duration for which PowerShell should wait before it times out on cancel operations @@ -379,10 +379,10 @@ namespace System.Management.Automation.Remoting /// public TimeSpan CancelTimeout { - get { return cancelTimeout; } - set { cancelTimeout = value; } + get { return _cancelTimeout; } + set { _cancelTimeout = value; } } - private TimeSpan cancelTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.defaultCancelTimeout); + private TimeSpan _cancelTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.defaultCancelTimeout); /// /// The duration for which a Runspace on server needs to wait before it declares the client dead and closes itself down. @@ -393,10 +393,10 @@ namespace System.Management.Automation.Remoting /// public TimeSpan IdleTimeout { - get { return idleTimeout; } - set { idleTimeout = value; } + get { return _idleTimeout; } + set { _idleTimeout = value; } } - private TimeSpan idleTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultIdleTimeout); + private TimeSpan _idleTimeout = TimeSpan.FromMilliseconds(RunspaceConnectionInfo.DefaultIdleTimeout); } } @@ -420,10 +420,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public int MaximumRedirection { - get { return maximumRedirection.Value; } - set { maximumRedirection = value; } + get { return _maximumRedirection.Value; } + set { _maximumRedirection = value; } } - private int? maximumRedirection; + private int? _maximumRedirection; /// /// If false, underlying WSMan infrastructure will compress data sent on the network. @@ -436,10 +436,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter NoCompression { - get { return noCompression; } - set { noCompression = value; } + get { return _noCompression; } + set { _noCompression = value; } } - private SwitchParameter noCompression; + private SwitchParameter _noCompression; /// /// If true then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server @@ -451,14 +451,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noMachineProfile; + return _noMachineProfile; } set { - noMachineProfile = value; + _noMachineProfile = value; } } - private SwitchParameter noMachineProfile; + private SwitchParameter _noMachineProfile; /// /// Culture that the remote session should use @@ -469,14 +469,14 @@ namespace Microsoft.PowerShell.Commands { get { - return culture; + return _culture; } set { - culture = value; + _culture = value; } } - private CultureInfo culture; + private CultureInfo _culture; /// /// UI culture that the remote session should use @@ -487,14 +487,14 @@ namespace Microsoft.PowerShell.Commands { get { - return uiCulture; + return _uiCulture; } set { - uiCulture = value; + _uiCulture = value; } } - private CultureInfo uiCulture; + private CultureInfo _uiCulture; /// /// Total data (in bytes) that can be received from a remote machine @@ -504,10 +504,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public int MaximumReceivedDataSizePerCommand { - get { return maxRecvdDataSizePerCommand.Value; } - set { maxRecvdDataSizePerCommand = value; } + get { return _maxRecvdDataSizePerCommand.Value; } + set { _maxRecvdDataSizePerCommand = value; } } - private Nullable maxRecvdDataSizePerCommand; + private Nullable _maxRecvdDataSizePerCommand; /// /// Maximum size (in bytes) of a deserialized object received from a remote machine. @@ -516,10 +516,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public int MaximumReceivedObjectSize { - get { return maxRecvdObjectSize.Value; } - set { maxRecvdObjectSize = value; } + get { return _maxRecvdObjectSize.Value; } + set { _maxRecvdObjectSize = value; } } - private Nullable maxRecvdObjectSize; + private Nullable _maxRecvdObjectSize; /// /// Specifies the output mode on the server when it is in Disconnected mode @@ -528,10 +528,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public OutputBufferingMode OutputBufferingMode { - get { return this.outputBufferingMode; } - set { this.outputBufferingMode = value; } + get { return _outputBufferingMode; } + set { _outputBufferingMode = value; } } - private OutputBufferingMode outputBufferingMode; + private OutputBufferingMode _outputBufferingMode; /// /// Maximum number of times a connection will be re-attempted when a connection fails due to network @@ -541,10 +541,10 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public int MaxConnectionRetryCount { - get { return this.maxConnectionRetryCount; } - set { this.maxConnectionRetryCount = value; } + get { return _maxConnectionRetryCount; } + set { _maxConnectionRetryCount = value; } } - private int maxConnectionRetryCount; + private int _maxConnectionRetryCount; /// /// Application arguments the server can see in @@ -554,10 +554,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public PSPrimitiveDictionary ApplicationArguments { - get { return applicationArguments; } - set { applicationArguments = value; } + get { return _applicationArguments; } + set { _applicationArguments = value; } } - private PSPrimitiveDictionary applicationArguments; + private PSPrimitiveDictionary _applicationArguments; /// /// The duration for which PowerShell remoting waits (in milliseconds) before timing @@ -572,14 +572,14 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public int OpenTimeout { - get + get { - return openTimeout.HasValue ? openTimeout.Value : + return _openTimeout.HasValue ? _openTimeout.Value : RunspaceConnectionInfo.DefaultOpenTimeout; } - set { openTimeout = value; } + set { _openTimeout = value; } } - private int? openTimeout; + private int? _openTimeout; /// /// The duration for which PowerShell should wait (in milliseconds) before it @@ -595,14 +595,14 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public int CancelTimeout { - get + get { - return cancelTimeout.HasValue ? cancelTimeout.Value : + return _cancelTimeout.HasValue ? _cancelTimeout.Value : BaseTransportManager.ClientCloseTimeoutMs; } - set { cancelTimeout = value; } + set { _cancelTimeout = value; } } - private int? cancelTimeout; + private int? _cancelTimeout; /// /// The duration for which a Runspace on server needs to wait (in milliseconds) before it @@ -615,14 +615,14 @@ namespace Microsoft.PowerShell.Commands [Alias("IdleTimeoutMSec")] public int IdleTimeout { - get - { - return idleTimeout.HasValue ? idleTimeout.Value + get + { + return _idleTimeout.HasValue ? _idleTimeout.Value : RunspaceConnectionInfo.DefaultIdleTimeout; } - set { idleTimeout = value; } + set { _idleTimeout = value; } } - private int? idleTimeout; + private int? _idleTimeout; #endregion Parameters @@ -653,10 +653,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public AuthenticationMechanism ProxyAuthentication { - get { return proxyauthentication; } - set { proxyauthentication = value; } + get { return _proxyauthentication; } + set { _proxyauthentication = value; } } - private AuthenticationMechanism proxyauthentication = AuthenticationMechanism.Negotiate; + private AuthenticationMechanism _proxyauthentication = AuthenticationMechanism.Negotiate; /// /// The following is the definition of the input parameter "ProxyCredential". @@ -682,10 +682,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter SkipCACheck { - get { return skipcacheck; } - set { skipcacheck = value; } + get { return _skipcacheck; } + set { _skipcacheck = value; } } - private bool skipcacheck; + private bool _skipcacheck; /// /// The following is the definition of the input parameter "SkipCNCheck". @@ -696,10 +696,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter SkipCNCheck { - get { return skipcncheck; } - set { skipcncheck = value; } + get { return _skipcncheck; } + set { _skipcncheck = value; } } - private bool skipcncheck; + private bool _skipcncheck; /// /// The following is the definition of the input parameter "SkipRevocation". @@ -710,10 +710,10 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter SkipRevocationCheck { - get { return skiprevocationcheck; } - set { skiprevocationcheck = value; } + get { return _skiprevocationcheck; } + set { _skiprevocationcheck = value; } } - private bool skiprevocationcheck; + private bool _skiprevocationcheck; /// /// The following is the definition of the input parameter "Timeout". @@ -724,14 +724,14 @@ namespace Microsoft.PowerShell.Commands [ValidateRange(0, Int32.MaxValue)] public Int32 OperationTimeout { - get - { - return (operationtimeout.HasValue ? operationtimeout.Value : - BaseTransportManager.ClientDefaultOperationTimeoutMs); + get + { + return (_operationtimeout.HasValue ? _operationtimeout.Value : + BaseTransportManager.ClientDefaultOperationTimeoutMs); } - set { operationtimeout = value; } + set { _operationtimeout = value; } } - private Int32? operationtimeout; + private Int32? _operationtimeout; /// /// The following is the definition of the input parameter "UnEncrypted". @@ -742,13 +742,13 @@ namespace Microsoft.PowerShell.Commands [Parameter] public SwitchParameter NoEncryption { - get { return noencryption; } + get { return _noencryption; } set { - noencryption = value; + _noencryption = value; } } - private bool noencryption; + private bool _noencryption; /// /// The following is the definition of the input parameter "UTF16". @@ -759,13 +759,13 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] public SwitchParameter UseUTF16 { - get { return useutf16; } + get { return _useutf16; } set { - useutf16 = value; + _useutf16 = value; } } - private bool useutf16; + private bool _useutf16; /// /// Uses Service Principal Name (SPN) along with the Port number during authentication. @@ -774,15 +774,15 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] public SwitchParameter IncludePortInSPN { - get { return includePortInSPN; } - set { includePortInSPN = value; } + get { return _includePortInSPN; } + set { _includePortInSPN = value; } } - private bool includePortInSPN; + private bool _includePortInSPN; #endregion #region Implementation - + /// /// Performs initialization of cmdlet execution. /// @@ -796,15 +796,15 @@ namespace Microsoft.PowerShell.Commands result.SkipCACheck = this.SkipCACheck; result.SkipCNCheck = this.SkipCNCheck; result.SkipRevocationCheck = this.SkipRevocationCheck; - if (this.operationtimeout.HasValue) + if (_operationtimeout.HasValue) { - result.OperationTimeout = TimeSpan.FromMilliseconds(this.operationtimeout.Value); + result.OperationTimeout = TimeSpan.FromMilliseconds(_operationtimeout.Value); } result.NoEncryption = this.NoEncryption; result.UseUTF16 = this.UseUTF16; result.IncludePortInSPN = this.IncludePortInSPN; // End: WSMan specific options - if (this.maximumRedirection.HasValue) + if (_maximumRedirection.HasValue) { result.MaximumConnectionRedirectionCount = this.MaximumRedirection; } @@ -812,8 +812,8 @@ namespace Microsoft.PowerShell.Commands result.NoCompression = this.NoCompression.IsPresent; result.NoMachineProfile = this.NoMachineProfile.IsPresent; - result.MaximumReceivedDataSizePerCommand = this.maxRecvdDataSizePerCommand; - result.MaximumReceivedObjectSize = this.maxRecvdObjectSize; + result.MaximumReceivedDataSizePerCommand = _maxRecvdDataSizePerCommand; + result.MaximumReceivedObjectSize = _maxRecvdObjectSize; if (this.Culture != null) { @@ -824,22 +824,22 @@ namespace Microsoft.PowerShell.Commands result.UICulture = this.UICulture; } - if (this.openTimeout.HasValue) + if (_openTimeout.HasValue) { - result.OpenTimeout = TimeSpan.FromMilliseconds(this.openTimeout.Value); + result.OpenTimeout = TimeSpan.FromMilliseconds(_openTimeout.Value); } - if (this.cancelTimeout.HasValue) + if (_cancelTimeout.HasValue) { - result.CancelTimeout = TimeSpan.FromMilliseconds(this.cancelTimeout.Value); + result.CancelTimeout = TimeSpan.FromMilliseconds(_cancelTimeout.Value); } - if (this.idleTimeout.HasValue) + if (_idleTimeout.HasValue) { - result.IdleTimeout = TimeSpan.FromMilliseconds(this.idleTimeout.Value); + result.IdleTimeout = TimeSpan.FromMilliseconds(_idleTimeout.Value); } - result.OutputBufferingMode = this.outputBufferingMode; + result.OutputBufferingMode = _outputBufferingMode; - result.MaxConnectionRetryCount = this.maxConnectionRetryCount; + result.MaxConnectionRetryCount = _maxConnectionRetryCount; if (this.ApplicationArguments != null) { diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index d2e4c5c10..07f40a35d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -96,7 +96,7 @@ namespace Microsoft.PowerShell.Commands //tracer.WriteEvent(ref PSEventDescriptors.PS_EVENT_HOSTNAMERESOLVE); //tracer.Dispose(); //tracer.OperationalChannel.WriteVerbose(PSEventId.HostNameResolve, PSOpcode.Method, PSTask.CreateRunspace); - return LOCALHOST; + return s_LOCALHOST; } else { @@ -116,7 +116,6 @@ namespace Microsoft.PowerShell.Commands String message = GetMessage(resourceString, null); return message; - }// GetMessage /// @@ -144,7 +143,7 @@ namespace Microsoft.PowerShell.Commands #region Private Members - private static string LOCALHOST = "localhost"; + private static string s_LOCALHOST = "localhost"; //private PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Cmdlets); @@ -209,7 +208,7 @@ namespace Microsoft.PowerShell.Commands } set { - _skipWinRMCheck = value; + _skipWinRMCheck = value; } } #endregion Internal Members @@ -289,133 +288,133 @@ namespace Microsoft.PowerShell.Commands /// /// Other. Corresponds to CIM_EnabledLogicalElement.EnabledState = Other. /// - Other = 1, - + Other = 1, + /// /// Running. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled. /// - Running = 2, - + Running = 2, + /// /// Off. Corresponds to CIM_EnabledLogicalElement.EnabledState = Disabled. /// - Off = 3, - + Off = 3, + /// /// Stopping. Corresponds to CIM_EnabledLogicalElement.EnabledState = ShuttingDown. /// - Stopping = 4, - + Stopping = 4, + /// /// Saved. Corresponds to CIM_EnabledLogicalElement.EnabledState = Enabled but offline. /// - Saved = 6, - + Saved = 6, + /// /// Paused. Corresponds to CIM_EnabledLogicalElement.EnabledState = Quiesce. /// - Paused = 9, - + Paused = 9, + /// /// Starting. EnabledStateStarting. State transition from PowerOff or Saved to Running. /// - Starting = 10, - + Starting = 10, + /// /// Reset. Corresponds to CIM_EnabledLogicalElement.EnabledState = Reset. /// - Reset = 11, - + Reset = 11, + /// /// Saving. Corresponds to EnabledStateSaving. /// - Saving = 32773, - + Saving = 32773, + /// /// Pausing. Corresponds to EnabledStatePausing. /// - Pausing = 32776, - + Pausing = 32776, + /// /// Resuming. Corresponds to EnabledStateResuming. /// - Resuming = 32777, - + Resuming = 32777, + /// /// FastSaved. EnabledStateFastSuspend. /// - FastSaved = 32779, - + FastSaved = 32779, + /// /// FastSaving. EnabledStateFastSuspending. /// - FastSaving = 32780, - + FastSaving = 32780, + /// /// ForceShutdown. Used to force a graceful shutdown of the virtual machine. /// ForceShutdown = 32781, - + /// /// ForceReboot. Used to force a graceful reboot of the virtual machine. /// - ForceReboot = 32782, - + ForceReboot = 32782, + /// /// RunningCritical. Critical states. /// RunningCritical, - + /// /// OffCritical. Critical states. /// OffCritical, - + /// /// StoppingCritical. Critical states. /// StoppingCritical, - + /// /// SavedCritical. Critical states. /// SavedCritical, - + /// /// PausedCritical. Critical states. /// PausedCritical, - + /// /// StartingCritical. Critical states. /// StartingCritical, - + /// /// ResetCritical. Critical states. /// ResetCritical, - + /// /// SavingCritical. Critical states. /// SavingCritical, - + /// /// PausingCritical. Critical states. /// PausingCritical, - + /// /// ResumingCritical. Critical states. /// ResumingCritical, - + /// /// FastSavedCritical. Critical states. /// FastSavedCritical, - + /// /// FastSavingCritical. Critical states. /// @@ -443,15 +442,15 @@ namespace Microsoft.PowerShell.Commands { get { - return remoteRunspaceInfos; + return _remoteRunspaceInfos; } set { - remoteRunspaceInfos = value; + _remoteRunspaceInfos = value; } } - private PSSession[] remoteRunspaceInfos; + private PSSession[] _remoteRunspaceInfos; /// /// This parameter represents the address(es) of the remote @@ -469,15 +468,15 @@ namespace Microsoft.PowerShell.Commands { get { - return computerNames; + return _computerNames; } set { - computerNames = value; + _computerNames = value; } } - private String[] computerNames; + private String[] _computerNames; /// /// Computer names after they have been resolved @@ -490,14 +489,14 @@ namespace Microsoft.PowerShell.Commands { get { - return resolvedComputerNames; + return _resolvedComputerNames; } set { - resolvedComputerNames = value; + _resolvedComputerNames = value; } } - private String[] resolvedComputerNames; + private String[] _resolvedComputerNames; /// /// Guid of target virtual machine. @@ -512,16 +511,16 @@ namespace Microsoft.PowerShell.Commands [Alias("VMGuid")] public virtual Guid[] VMId { - get + get { - return vmId; + return _vmId; } set { - vmId = value; + _vmId = value; } } - private Guid[] vmId; + private Guid[] _vmId; /// /// Name of target virtual machine. @@ -534,16 +533,16 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public virtual string[] VMName { - get + get { - return vmName; + return _vmName; } set { - vmName = value; + _vmName = value; } } - private string[] vmName; + private string[] _vmName; /// /// Specifies the credentials of the user to impersonate in the @@ -563,16 +562,16 @@ namespace Microsoft.PowerShell.Commands { get { - return pscredential; + return _pscredential; } set { - pscredential = value; + _pscredential = value; ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private PSCredential pscredential; + private PSCredential _pscredential; /// /// ID of target container. @@ -587,14 +586,14 @@ namespace Microsoft.PowerShell.Commands { get { - return containerId; + return _containerId; } set { - containerId = value; + _containerId = value; } } - private string[] containerId; + private string[] _containerId; /// /// When set, PowerShell process inside container will be launched with @@ -605,16 +604,16 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = PSRemotingBaseCmdlet.ContainerIdParameterSet)] public virtual SwitchParameter RunAsAdministrator { - get + get { - return runAsAdministrator; + return _runAsAdministrator; } set { - runAsAdministrator = value; + _runAsAdministrator = value; } } - private SwitchParameter runAsAdministrator; + private SwitchParameter _runAsAdministrator; /// /// Port specifies the alternate port to be used in case the @@ -633,14 +632,14 @@ namespace Microsoft.PowerShell.Commands { get { - return port; + return _port; } set { - port = value; + _port = value; } } - private Int32 port; + private Int32 _port; /// /// This parameter suggests that the transport scheme to be used for @@ -655,15 +654,15 @@ namespace Microsoft.PowerShell.Commands { get { - return useSSL; + return _useSSL; } set { - useSSL = value; + _useSSL = value; } } - private SwitchParameter useSSL; - + private SwitchParameter _useSSL; + /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified @@ -676,15 +675,15 @@ namespace Microsoft.PowerShell.Commands { get { - return appName; + return _appName; } set { - appName = ResolveAppName(value); + _appName = ResolveAppName(value); } } - private String appName; + private String _appName; /// /// Allows the user of the cmdlet to specify a throttling value @@ -701,15 +700,15 @@ namespace Microsoft.PowerShell.Commands { set { - throttleLimit = value; + _throttleLimit = value; } get { - return throttleLimit; + return _throttleLimit; } } - private int throttleLimit = 0; + private int _throttleLimit = 0; /// /// A complete URI(s) specified for the remote computer and shell to @@ -724,14 +723,14 @@ namespace Microsoft.PowerShell.Commands { get { - return uris; + return _uris; } set { - uris = value; + _uris = value; } } - private Uri[] uris; + private Uri[] _uris; /// /// The AllowRediraction parameter enables the implicit redirection functionality @@ -739,10 +738,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)] public virtual SwitchParameter AllowRedirection { - get { return this.allowRedirection; } - set { this.allowRedirection = value; } + get { return _allowRedirection; } + set { _allowRedirection = value; } } - private bool allowRedirection = false; + private bool _allowRedirection = false; /// /// Extended Session Options for controlling the session creation. Use @@ -755,20 +754,20 @@ namespace Microsoft.PowerShell.Commands { get { - if (this.sessionOption == null) + if (_sessionOption == null) { object tmp = this.SessionState.PSVariable.GetValue(DEFAULT_SESSION_OPTION); - if (tmp == null || !LanguagePrimitives.TryConvertTo(tmp, out this.sessionOption)) + if (tmp == null || !LanguagePrimitives.TryConvertTo(tmp, out _sessionOption)) { - this.sessionOption = new PSSessionOption(); + _sessionOption = new PSSessionOption(); } } - return this.sessionOption; + return _sessionOption; } - set { this.sessionOption = value; } + set { _sessionOption = value; } } - private PSSessionOption sessionOption; + private PSSessionOption _sessionOption; internal const string DEFAULT_SESSION_OPTION = "PSSessionOption"; // Quota related variables. @@ -781,16 +780,16 @@ namespace Microsoft.PowerShell.Commands { get { - return authMechanism; + return _authMechanism; } set { - authMechanism = value; + _authMechanism = value; // Validate if a user can specify this authentication. ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private AuthenticationMechanism authMechanism = AuthenticationMechanism.Default; + private AuthenticationMechanism _authMechanism = AuthenticationMechanism.Default; /// /// Specifies the certificate thumbprint to be used to impersonate the user on the @@ -800,14 +799,14 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)] public virtual string CertificateThumbprint { - get { return thumbPrint; } + get { return _thumbPrint; } set { - thumbPrint = value; + _thumbPrint = value; ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private string thumbPrint = null; + private string _thumbPrint = null; #endregion Properties @@ -888,7 +887,6 @@ namespace Microsoft.PowerShell.Commands PSRemotingErrorId.RemoteRunspaceInfoLimitExceeded.ToString(), ErrorCategory.InvalidArgument, Session)); } - } // ValidateRemoteRunspacesSpecified /// @@ -913,7 +911,7 @@ namespace Microsoft.PowerShell.Commands connectionInfo.MaximumConnectionRedirectionCount = 0; } - if (!this.allowRedirection) + if (!_allowRedirection) { // uri redirection required explicit user consent connectionInfo.MaximumConnectionRedirectionCount = 0; @@ -941,7 +939,7 @@ namespace Microsoft.PowerShell.Commands { ThrowTerminatingError(new ErrorRecord( new ArgumentException(PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.InvalidComputerName)), "PSSessionInvalidComputerName", + RemotingErrorIdStrings.InvalidComputerName)), "PSSessionInvalidComputerName", ErrorCategory.InvalidArgument, computerNames)); } } @@ -968,9 +966,9 @@ namespace Microsoft.PowerShell.Commands idleTimeout / 1000, BaseTransportManager.MinimumIdleTimeout / 1000)); } - if (String.IsNullOrEmpty(appName)) + if (String.IsNullOrEmpty(_appName)) { - appName = ResolveAppName(null); + _appName = ResolveAppName(null); } } @@ -1016,15 +1014,15 @@ namespace Microsoft.PowerShell.Commands { get { - return inputObject; + return _inputObject; } set { - inputObject = value; + _inputObject = value; } } - private PSObject inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull.Value; /// /// Command to execute specified as a string. This can be a single @@ -1035,14 +1033,14 @@ namespace Microsoft.PowerShell.Commands { get { - return scriptBlock; + return _scriptBlock; } set { - scriptBlock = value; + _scriptBlock = value; } } - private ScriptBlock scriptBlock; + private ScriptBlock _scriptBlock; /// /// The file containing the script that the user has specified in the @@ -1063,15 +1061,15 @@ namespace Microsoft.PowerShell.Commands { get { - return filePath; + return _filePath; } set { - filePath = value; + _filePath = value; } } - private string filePath; - + private string _filePath; + /// /// True if FilePath should be processed as a literal path /// @@ -1087,14 +1085,14 @@ namespace Microsoft.PowerShell.Commands { get { - return args; + return _args; } set { - args = value; + _args = value; } } - private Object[] args; + private Object[] _args; /// @@ -1104,10 +1102,10 @@ namespace Microsoft.PowerShell.Commands /// protected bool InvokeAndDisconnect { - get { return this.invokeAndDisconnect; } - set { this.invokeAndDisconnect = value; } + get { return _invokeAndDisconnect; } + set { _invokeAndDisconnect = value; } } - private bool invokeAndDisconnect = false; + private bool _invokeAndDisconnect = false; /// /// Session names optionally provided for Disconnected parameter. @@ -1115,10 +1113,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected string[] DisconnectedSessionName { - get { return sessionName; } - set { sessionName = value; } + get { return _sessionName; } + set { _sessionName = value; } } - private string[] sessionName; + private string[] _sessionName; /// /// When set and in loopback scenario (localhost) this enables creation of WSMan @@ -1128,10 +1126,10 @@ namespace Microsoft.PowerShell.Commands /// public virtual SwitchParameter EnableNetworkAccess { - get { return enableNetworkAccess; } - set { enableNetworkAccess = value; } + get { return _enableNetworkAccess; } + set { _enableNetworkAccess = value; } } - private SwitchParameter enableNetworkAccess; + private SwitchParameter _enableNetworkAccess; /// /// Guid of target virtual machine. @@ -1148,10 +1146,10 @@ namespace Microsoft.PowerShell.Commands [Alias("VMGuid")] public override Guid[] VMId { - get { return vmId; } - set { vmId = value; } + get { return _vmId; } + set { _vmId = value; } } - private Guid[] vmId; + private Guid[] _vmId; /// /// Name of target virtual machine. @@ -1167,10 +1165,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public override string[] VMName { - get { return vmName; } - set { vmName = value; } + get { return _vmName; } + set { _vmName = value; } } - private string[] vmName; + private string[] _vmName; /// /// ID of target container. @@ -1186,10 +1184,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public override string[] ContainerId { - get { return containerId; } - set { containerId = value; } + get { return _containerId; } + set { _containerId = value; } } - private string[] containerId; + private string[] _containerId; /// /// For WSMan session: @@ -1224,16 +1222,16 @@ namespace Microsoft.PowerShell.Commands { get { - return shell; + return _shell; } set { // Only InvokeCommandCommand may enter here, // which will call ResolveShell() if needed. - shell = value; + _shell = value; } } - private String shell; + private String _shell; #endregion Parameters @@ -1268,7 +1266,7 @@ namespace Microsoft.PowerShell.Commands else { connectionInfo.Credential = Credential; - } + } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -1299,11 +1297,10 @@ namespace Microsoft.PowerShell.Commands Pipeline pipeline = CreatePipeline(remoteRunspace); IThrottleOperation operation = - new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, this.invokeAndDisconnect); + new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, _invokeAndDisconnect); Operations.Add(operation); } - }// CreateHelpersForSpecifiedComputerNames /// @@ -1337,7 +1334,6 @@ namespace Microsoft.PowerShell.Commands IThrottleOperation operation = new ExecutionCmdletHelperRunspace(pipelines[i]); Operations.Add(operation); } - } // CreateHelpersForSpecifiedRunspaces /// @@ -1372,7 +1368,7 @@ namespace Microsoft.PowerShell.Commands connectionInfo.EnableNetworkAccess = EnableNetworkAccess; - remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, + remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, Utils.GetTypeTableFromExecutionContextTLS(), this.SessionOption.ApplicationArguments); @@ -1400,11 +1396,10 @@ namespace Microsoft.PowerShell.Commands Pipeline pipeline = CreatePipeline(remoteRunspace); IThrottleOperation operation = - new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, this.invokeAndDisconnect); + new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, _invokeAndDisconnect); Operations.Add(operation); } - } // CreateHelpersForSpecifiedUris /// @@ -1429,7 +1424,7 @@ namespace Microsoft.PowerShell.Commands for (index = 0; index < inputArraySize; index++) { vmIsRunning[index] = false; - + command = "Get-VM -Id $args[0]"; try @@ -1448,7 +1443,7 @@ namespace Microsoft.PowerShell.Commands return; } - + if (results.Count != 1) { this.VMName[index] = string.Empty; @@ -1469,7 +1464,7 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet) || (ParameterSetName == PSExecutionCmdlet.FilePathVMNameParameterSet), "Expected ParameterSetName == VMName or FilePathVMName"); - + inputArraySize = this.VMName.Length; this.VMId = new Guid[inputArraySize]; vmIsRunning = new bool[inputArraySize]; @@ -1477,7 +1472,7 @@ namespace Microsoft.PowerShell.Commands for (index = 0; index < inputArraySize; index++) { vmIsRunning[index] = false; - + command = "Get-VM -Name $args"; try @@ -1496,7 +1491,7 @@ namespace Microsoft.PowerShell.Commands return; } - + if (results.Count != 1) { this.VMId[index] = Guid.Empty; @@ -1515,7 +1510,7 @@ namespace Microsoft.PowerShell.Commands } ResolvedComputerNames = this.VMName; - + for (index = 0; index < ResolvedComputerNames.Length; index++) { if ((this.VMId[index] == Guid.Empty) && @@ -1524,7 +1519,7 @@ namespace Microsoft.PowerShell.Commands { WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, this.VMName[index])), PSRemotingErrorId.InvalidVMNameNotSingle.ToString(), ErrorCategory.InvalidArgument, @@ -1538,7 +1533,7 @@ namespace Microsoft.PowerShell.Commands { WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, this.VMId[index].ToString(null))), PSRemotingErrorId.InvalidVMIdNotSingle.ToString(), ErrorCategory.InvalidArgument, @@ -1550,15 +1545,15 @@ namespace Microsoft.PowerShell.Commands { WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName[index])), PSRemotingErrorId.InvalidVMState.ToString(), ErrorCategory.InvalidArgument, null)); - + continue; } - + // create helper objects for VM GUIDs or names RemoteRunspace remoteRunspace = null; VMConnectionInfo connectionInfo; @@ -1566,37 +1561,36 @@ namespace Microsoft.PowerShell.Commands try { connectionInfo = new VMConnectionInfo(this.Credential, this.VMId[index], this.VMName[index], this.ConfigurationName); - + remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, null, -1); - + remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; - } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); } - + Pipeline pipeline = CreatePipeline(remoteRunspace); - + IThrottleOperation operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, false); - + Operations.Add(operation); } }// CreateHelpersForSpecifiedVMSession @@ -1612,7 +1606,7 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet) || (ParameterSetName == PSExecutionCmdlet.FilePathContainerIdParameterSet), "Expected ParameterSetName == ContainerId or FilePathContainerId"); - + foreach (var input in ContainerId) { // @@ -1628,52 +1622,52 @@ namespace Microsoft.PowerShell.Commands // Windows Server container uses named pipe as transport. // connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName); - + resolvedNameList.Add(connectionInfo.ComputerName); - + connectionInfo.CreateContainerProcess(); - + remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, null, -1); - + remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); continue; } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); continue; } catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); continue; - } - + } + Pipeline pipeline = CreatePipeline(remoteRunspace); - + IThrottleOperation operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, false); - + Operations.Add(operation); } @@ -1762,7 +1756,7 @@ namespace Microsoft.PowerShell.Commands /// internal void OnRunspacePSEventReceived(object sender, PSEventArgs e) { - if(this.Events != null) + if (this.Events != null) this.Events.AddForwardedEvent(e); } @@ -1777,11 +1771,11 @@ namespace Microsoft.PowerShell.Commands { get { - return operations; + return _operations; } } - private List operations = + private List _operations = new List(); @@ -1814,7 +1808,6 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.InvalidArgument, uri); WriteError(errorRecord); - } // WriteErrorCreateRemoteRunspaceFailed /// @@ -1857,7 +1850,7 @@ namespace Microsoft.PowerShell.Commands protected ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath) { //Make sure filepath doesn't contain wildcards - if ((! isLiteralPath) && WildcardPattern.ContainsWildcardCharacters(filePath)) + if ((!isLiteralPath) && WildcardPattern.ContainsWildcardCharacters(filePath)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter), "filePath"); } @@ -1906,10 +1899,10 @@ namespace Microsoft.PowerShell.Commands } base.BeginProcessing(); - - if (filePath != null) + + if (_filePath != null) { - scriptBlock = GetScriptBlockFromFile(filePath, IsLiteralPath); + _scriptBlock = GetScriptBlockFromFile(_filePath, IsLiteralPath); } switch (ParameterSetName) @@ -1959,7 +1952,7 @@ namespace Microsoft.PowerShell.Commands break; } } - + #endregion Overrides @@ -2007,10 +2000,10 @@ namespace Microsoft.PowerShell.Commands string scriptTextAdaptedForPSv2 = GetConvertedScript(out newParameterNames, out newParameterValues); _powershellV2 = System.Management.Automation.PowerShell.Create().AddScript(scriptTextAdaptedForPSv2); - - if (args != null) + + if (_args != null) { - foreach (object arg in args) + foreach (object arg in _args) { _powershellV2.AddArgument(arg); } @@ -2076,7 +2069,7 @@ namespace Microsoft.PowerShell.Commands // Value of 'serverPsVersion' should be either 'PSv3Orv4' or 'PSv5OrLater' if (serverPsVersion == PSv3Orv4) { - usingValuesInArray = ScriptBlockToPowerShellConverter.GetUsingValuesAsArray(scriptBlock, allowUsingExpressions, Context, null); + usingValuesInArray = ScriptBlockToPowerShellConverter.GetUsingValuesAsArray(_scriptBlock, allowUsingExpressions, Context, null); if (usingValuesInArray == null) { // 'usingValuesInArray' will be null only if there are UsingExpressions used in different scopes. @@ -2087,18 +2080,18 @@ namespace Microsoft.PowerShell.Commands else { // Remote server is PSv5 or later version - usingValuesInDict = ScriptBlockToPowerShellConverter.GetUsingValuesAsDictionary(scriptBlock, allowUsingExpressions, Context, null); + usingValuesInDict = ScriptBlockToPowerShellConverter.GetUsingValuesAsDictionary(_scriptBlock, allowUsingExpressions, Context, null); } string textOfScriptBlock = this.MyInvocation.ExpectingInput - ? scriptBlock.GetWithInputHandlingForInvokeCommand() - : scriptBlock.ToString(); + ? _scriptBlock.GetWithInputHandlingForInvokeCommand() + : _scriptBlock.ToString(); _powershellV3 = System.Management.Automation.PowerShell.Create().AddScript(textOfScriptBlock); - if (args != null) + if (_args != null) { - foreach (object arg in args) + foreach (object arg in _args) { _powershellV3.AddArgument(arg); } @@ -2124,7 +2117,7 @@ namespace Microsoft.PowerShell.Commands { // This is trusted input as long as we're in FullLanguage mode bool isTrustedInput = (Context.LanguageMode == PSLanguageMode.FullLanguage); - powershell = scriptBlock.GetPowerShell(isTrustedInput, args); + powershell = _scriptBlock.GetPowerShell(isTrustedInput, _args); } catch (ScriptBlockToPowerShellNotSupportedException) { @@ -2136,35 +2129,35 @@ namespace Microsoft.PowerShell.Commands return powershell; } -#endregion "Get PowerShell instance" + #endregion "Get PowerShell instance" -#region "UsingExpression Utilities" + #region "UsingExpression Utilities" -/// -/// Get the converted script for a remote PSv2 end -/// -/// -/// The new parameter names that we added to the param block -/// -/// -/// The new parameter values that need to be added to the powershell instance -/// -/// -private string GetConvertedScript(out List newParameterNames, out List newParameterValues) + /// + /// Get the converted script for a remote PSv2 end + /// + /// + /// The new parameter names that we added to the param block + /// + /// + /// The new parameter values that need to be added to the powershell instance + /// + /// + private string GetConvertedScript(out List newParameterNames, out List newParameterValues) { newParameterNames = null; newParameterValues = null; string textOfScriptBlock = null; // Scan for the using variables - List usingVariables = GetUsingVariables(scriptBlock); + List usingVariables = GetUsingVariables(_scriptBlock); if (usingVariables == null || usingVariables.Count == 0) { // No using variable is used, then we don't change the script textOfScriptBlock = this.MyInvocation.ExpectingInput - ? scriptBlock.GetWithInputHandlingForInvokeCommand() - : scriptBlock.ToString(); + ? _scriptBlock.GetWithInputHandlingForInvokeCommand() + : _scriptBlock.ToString(); } else { @@ -2194,8 +2187,8 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List(paramUsingVars.Count); VariableExpressionAst currentVarAst = null; Version oldStrictVersion = Context.EngineSessionState.CurrentScope.StrictModeVersion; - + try { Context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion; @@ -2256,7 +2249,7 @@ private string GetConvertedScript(out List newParameterNames, out List UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst) usingExpr)).ToList(); + return allUsingExprs.Select(usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); } #endregion "UsingExpression Utilities" @@ -2301,22 +2294,22 @@ private string GetConvertedScript(out List newParameterNames, out List /// Session Id of the remoterunspace info object /// [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, - Mandatory=true, + Mandatory = true, ParameterSetName = PSRunspaceCmdlet.IdParameterSet)] [ValidateNotNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -2324,15 +2317,15 @@ private string GetConvertedScript(out List newParameterNames, out List /// Name of the remote runspaceinfo object @@ -2344,15 +2337,15 @@ private string GetConvertedScript(out List newParameterNames, out List /// Name of the computer for which the runspace needs to be @@ -2368,15 +2361,15 @@ private string GetConvertedScript(out List newParameterNames, out List /// ID of target container. @@ -2392,10 +2385,10 @@ private string GetConvertedScript(out List newParameterNames, out List /// Guid of target virtual machine. @@ -2412,10 +2405,10 @@ private string GetConvertedScript(out List newParameterNames, out List /// Name of target virtual machine. @@ -2431,10 +2424,10 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List GetMatchingRunspacesByComputerName(bool writeobject, bool writeErrorOnNoMatch) { - if (computerNames == null || computerNames.Length == 0) + if (_computerNames == null || _computerNames.Length == 0) { return GetAllRunspaces(writeobject, writeErrorOnNoMatch); } @@ -2580,7 +2573,7 @@ private string GetConvertedScript(out List newParameterNames, out List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; // Loop through all computer-name patterns and runspaces to find matches. - foreach (string computerName in computerNames) + foreach (string computerName in _computerNames) { WildcardPattern computerNamePattern = WildcardPattern.Get(computerName, WildcardOptions.IgnoreCase); @@ -2639,7 +2632,7 @@ private string GetConvertedScript(out List newParameterNames, out List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; // Loop through all computer-name patterns and runspaces to find matches. - foreach (string name in names) + foreach (string name in _names) { WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase); @@ -2698,7 +2691,7 @@ private string GetConvertedScript(out List newParameterNames, out List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; // Loop through all computer-name patterns and runspaces to find matches. - foreach (Guid remoteRunspaceId in remoteRunspaceIds) + foreach (Guid remoteRunspaceId in _remoteRunspaceIds) { // Match the computer-name patterns against all the runspaces and remember the matches. bool found = false; @@ -2754,7 +2747,7 @@ private string GetConvertedScript(out List newParameterNames, out List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; // Loop through all computer-name patterns and runspaces to find matches. - foreach (int sessionId in sessionIds) + foreach (int sessionId in _sessionIds) { // Match the computer-name patterns against all the runspaces and remember the matches. bool found = false; @@ -2810,8 +2803,8 @@ private string GetConvertedScript(out List newParameterNames, out List matches = new Dictionary(); List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; @@ -2842,7 +2835,7 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List matches = new Dictionary(); List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; @@ -2888,13 +2881,13 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List matches = new Dictionary(); List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; @@ -2975,8 +2968,8 @@ private string GetConvertedScript(out List newParameterNames, out List matches = new Dictionary(); List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; @@ -3103,7 +3096,6 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3163,7 +3155,6 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3213,7 +3204,6 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3223,7 +3213,6 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3251,9 +3240,7 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3275,7 +3262,7 @@ private string GetConvertedScript(out List newParameterNames, out List - private bool invokeAndDisconnect; + private bool _invokeAndDisconnect; /// /// The remote runspace created using the computer name @@ -3285,10 +3272,10 @@ private string GetConvertedScript(out List newParameterNames, out List /// Constructor @@ -3303,9 +3290,9 @@ private string GetConvertedScript(out List newParameterNames, out List(HandleRunspaceStateChanged); @@ -3315,7 +3302,6 @@ private string GetConvertedScript(out List newParameterNames, out List(HandlePipelineStateChanged); - } // IREHelperComputerName /// @@ -3325,14 +3311,13 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3363,7 +3348,6 @@ private string GetConvertedScript(out List newParameterNames, out List OperationComplete; @@ -3391,7 +3375,7 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List newParameterNames, out List @@ -3456,13 +3438,12 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3472,7 +3453,6 @@ private string GetConvertedScript(out List newParameterNames, out List @@ -3490,11 +3470,11 @@ private string GetConvertedScript(out List newParameterNames, out List newParameterNames, out List @@ -3654,7 +3632,5 @@ private string GetConvertedScript(out List newParameterNames, out List /// Disable ThrottleLimit parameter inherited from base class. /// public new Int32 ThrottleLimit { set { } get { return 0; } } - private ObjectStream stream; + private ObjectStream _stream; #endregion @@ -52,11 +53,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public new string ComputerName { - get { return computerName; } - set { computerName = value; } + get { return _computerName; } + set { _computerName = value; } } - private string computerName; + private string _computerName; /// /// Runspace parameter. @@ -67,11 +68,11 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public new PSSession Session { - get { return remoteRunspaceInfo; } - set { remoteRunspaceInfo = value; } + get { return _remoteRunspaceInfo; } + set { _remoteRunspaceInfo = value; } } - private PSSession remoteRunspaceInfo; + private PSSession _remoteRunspaceInfo; /// /// ConnectionUri parameter. @@ -82,11 +83,11 @@ namespace Microsoft.PowerShell.Commands [Alias("URI", "CU")] public new Uri ConnectionUri { - get { return connectionUri; } - set { connectionUri = value; } + get { return _connectionUri; } + set { _connectionUri = value; } } - private Uri connectionUri; + private Uri _connectionUri; /// /// RemoteRunspaceId of the remote runspace info object. @@ -97,11 +98,11 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public Guid InstanceId { - get { return remoteRunspaceId; } - set { remoteRunspaceId = value; } + get { return _remoteRunspaceId; } + set { _remoteRunspaceId = value; } } - private Guid remoteRunspaceId; + private Guid _remoteRunspaceId; /// /// SessionId of the remote runspace info object. @@ -112,11 +113,11 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNull] public int Id { - get { return sessionId; } - set { sessionId = value; } + get { return _sessionId; } + set { _sessionId = value; } } - private int sessionId; + private int _sessionId; /// /// Name of the remote runspace info object. @@ -125,11 +126,11 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = NameParameterSet)] public String Name { - get { return name; } - set { name = value; } + get { return _name; } + set { _name = value; } } - private String name; + private String _name; /// /// When set and in loopback scenario (localhost) this enables creation of WSMan @@ -141,37 +142,37 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = UriParameterSet)] public SwitchParameter EnableNetworkAccess { - get { return enableNetworkAccess; } - set { enableNetworkAccess = value; } + get { return _enableNetworkAccess; } + set { _enableNetworkAccess = value; } } - private SwitchParameter enableNetworkAccess; + private SwitchParameter _enableNetworkAccess; /// /// Virtual machine ID. /// [ValidateNotNullOrEmpty] - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMIdParameterSet)] [Alias("VMGuid")] public new Guid VMId { - get { return vmId; } - set { vmId = value; } + get { return _vmId; } + set { _vmId = value; } } - private Guid vmId; + private Guid _vmId; /// /// Virtual machine name. /// [ValidateNotNullOrEmpty] - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMNameParameterSet)] public new string VMName { - get { return vmName; } - set { vmName = value; } + get { return _vmName; } + set { _vmName = value; } } - private string vmName; + private string _vmName; /// /// Specifies the credentials of the user to impersonate in the @@ -197,14 +198,14 @@ namespace Microsoft.PowerShell.Commands /// The Id of the target container. /// [ValidateNotNullOrEmpty] - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, + [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerIdParameterSet)] public new string ContainerId { - get { return containerId; } - set { containerId = value; } + get { return _containerId; } + set { _containerId = value; } } - private string containerId; + private string _containerId; /// /// For WSMan sessions: @@ -229,14 +230,14 @@ namespace Microsoft.PowerShell.Commands { get { - return shell; + return _shell; } set { - shell = value; + _shell = value; } } - private String shell; + private String _shell; #endregion @@ -305,10 +306,10 @@ namespace Microsoft.PowerShell.Commands // for the console host and Graphical PowerShell host // we want to skip pushing into the the runspace if // the host is in a nested prompt - System.Management.Automation.Internal.Host.InternalHost chost = + System.Management.Automation.Internal.Host.InternalHost chost = this.Host as System.Management.Automation.Internal.Host.InternalHost; - if (!IsParameterSetForVM() && + if (!IsParameterSetForVM() && !IsParameterSetForContainer() && !IsParameterSetForVMContainerSession() && chost != null && chost.HostInNestedPrompt()) @@ -316,7 +317,6 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(new ErrorRecord( new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HostInNestedPrompt)), "HostInNestedPrompt", ErrorCategory.InvalidOperation, chost)); - } /*Microsoft.Windows.PowerShell.Gui.Internal.GPSHost ghost = this.Host as Microsoft.Windows.PowerShell.Gui.Internal.GPSHost; @@ -341,7 +341,7 @@ namespace Microsoft.PowerShell.Commands break; case SessionParameterSet: - remoteRunspace = (RemoteRunspace)remoteRunspaceInfo.Runspace; + remoteRunspace = (RemoteRunspace)_remoteRunspaceInfo.Runspace; break; case InstanceIdParameterSet: @@ -421,7 +421,7 @@ namespace Microsoft.PowerShell.Commands { if (ParameterSetName == SessionParameterSet) { - string sessionName = (this.remoteRunspaceInfo != null) ? this.remoteRunspaceInfo.Name : string.Empty; + string sessionName = (_remoteRunspaceInfo != null) ? _remoteRunspaceInfo.Name : string.Empty; WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession, @@ -470,7 +470,7 @@ namespace Microsoft.PowerShell.Commands WriteError( new ErrorRecord( new RuntimeException(message), "EnterPSSessionConnectSessionNotAvailable", - ErrorCategory.InvalidOperation, remoteRunspaceInfo)); + ErrorCategory.InvalidOperation, _remoteRunspaceInfo)); // Leave session in original disconnected state. remoteRunspace.DisconnectAsync(); @@ -499,7 +499,7 @@ namespace Microsoft.PowerShell.Commands } else { - if(remoteRunspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug) + if (remoteRunspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug) { msg = StringUtil.Format( RunspaceStrings.RunningCmdDebugStop); @@ -516,9 +516,9 @@ namespace Microsoft.PowerShell.Commands } // Make sure any PSSession object passed in is saved in the local runspace repository. - if (remoteRunspaceInfo != null) + if (_remoteRunspaceInfo != null) { - this.RunspaceRepository.AddOrReplace(remoteRunspaceInfo); + this.RunspaceRepository.AddOrReplace(_remoteRunspaceInfo); } // prepare runspace for prompt @@ -548,16 +548,16 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - if (null != stream) + if (null != _stream) { while (true) { // Keep reading objects until end of stream is encountered - stream.ObjectReader.WaitHandle.WaitOne(); + _stream.ObjectReader.WaitHandle.WaitOne(); - if (!stream.ObjectReader.EndOfPipeline) + if (!_stream.ObjectReader.EndOfPipeline) { - Object streamObject = stream.ObjectReader.Read(); + Object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action)streamObject); } else @@ -609,7 +609,7 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); remoteRunspace.URIRedirectionReported += HandleURIDirectionReported; - stream = new ObjectStream(); + _stream = new ObjectStream(); try { remoteRunspace.Open(); @@ -624,7 +624,7 @@ namespace Microsoft.PowerShell.Commands // close the internal object stream after runspace is opened // Runspace.Open() might throw exceptions..this will make sure // the stream is always closed. - stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); // make sure we dispose the temporary runspace if something bad happens if (remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) @@ -666,7 +666,7 @@ namespace Microsoft.PowerShell.Commands } ErrorRecord errorRecord = new ErrorRecord(exception, argument, - "CreateRemoteRunspaceFailed", + "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, null, null, null, null, null, errorDetails, null); @@ -676,7 +676,7 @@ namespace Microsoft.PowerShell.Commands /// /// Write invalid argument error. /// - private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourceString, object errorArgument) + private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourceString, object errorArgument) { String message = GetMessage(resourceString, errorArgument); WriteError(new ErrorRecord(new ArgumentException(message), errorId.ToString(), @@ -692,11 +692,11 @@ namespace Microsoft.PowerShell.Commands private void HandleURIDirectionReported(object sender, RemoteDataEventArgs eventArgs) { string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString); - Action streamObject = delegate(Cmdlet cmdlet) + Action streamObject = delegate (Cmdlet cmdlet) { cmdlet.WriteWarning(message); }; - stream.Write(streamObject); + _stream.Write(streamObject); } /// @@ -705,7 +705,7 @@ namespace Microsoft.PowerShell.Commands private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified() { RemoteRunspace remoteRunspace = null; - string resolvedComputerName = ResolveComputerName(computerName); + string resolvedComputerName = ResolveComputerName(_computerName); try { WSManConnectionInfo connectionInfo = null; @@ -723,7 +723,7 @@ namespace Microsoft.PowerShell.Commands else { connectionInfo.Credential = Credential; - } + } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -800,9 +800,9 @@ namespace Microsoft.PowerShell.Commands /// Get runspace matching condition. /// private RemoteRunspace GetRunspaceMatchingCondition( - Predicate condition, - PSRemotingErrorId tooFew, - PSRemotingErrorId tooMany, + Predicate condition, + PSRemotingErrorId tooFew, + PSRemotingErrorId tooMany, string tooFewResourceString, string tooManyResourceString, object errorArgument) @@ -834,7 +834,7 @@ namespace Microsoft.PowerShell.Commands /// private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { - Predicate condition = delegate(PSSession info) + Predicate condition = delegate (PSSession info) { return info.InstanceId == remoteRunspaceId; }; @@ -850,7 +850,7 @@ namespace Microsoft.PowerShell.Commands /// private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { - Predicate condition = delegate(PSSession info) + Predicate condition = delegate (PSSession info) { return info.Id == sessionId; }; @@ -866,7 +866,7 @@ namespace Microsoft.PowerShell.Commands /// private RemoteRunspace GetRunspaceMatchingName(string name) { - Predicate condition = delegate(PSSession info) + Predicate condition = delegate (PSSession info) { // doing case-insensitive match for session name return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); @@ -982,10 +982,10 @@ namespace Microsoft.PowerShell.Commands PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), ErrorCategory.NotInstalled, null)); - + return null; } - + if (results.Count != 1) { WriteError( @@ -1003,7 +1003,7 @@ namespace Microsoft.PowerShell.Commands else { Dbg.Assert(ParameterSetName == VMNameParameterSet, "Expected ParameterSetName == VMName"); - + command = "Get-VM -Name $args"; try @@ -1019,7 +1019,7 @@ namespace Microsoft.PowerShell.Commands PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), ErrorCategory.NotInstalled, null)); - + return null; } @@ -1057,7 +1057,7 @@ namespace Microsoft.PowerShell.Commands { WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName)), PSRemotingErrorId.InvalidVMState.ToString(), ErrorCategory.InvalidArgument, @@ -1065,7 +1065,7 @@ namespace Microsoft.PowerShell.Commands return null; } - + try { VMConnectionInfo connectionInfo; @@ -1076,19 +1076,19 @@ namespace Microsoft.PowerShell.Commands catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); } catch (PSRemotingDataStructureException e) @@ -1102,14 +1102,14 @@ namespace Microsoft.PowerShell.Commands if ((e.InnerException != null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, - null); + null); } else { errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); } @@ -1119,10 +1119,10 @@ namespace Microsoft.PowerShell.Commands catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } @@ -1138,7 +1138,7 @@ namespace Microsoft.PowerShell.Commands TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, host, typeTable) as RemoteRunspace; remoteRunspace.Name = "PowerShellDirectAttach"; - + Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); try { @@ -1167,7 +1167,7 @@ namespace Microsoft.PowerShell.Commands { if (IsParameterSetForVM() || IsParameterSetForContainer() || - IsParameterSetForVMContainerSession()) + IsParameterSetForVMContainerSession()) { string targetName = string.Empty; @@ -1186,7 +1186,7 @@ namespace Microsoft.PowerShell.Commands case SessionParameterSet: targetName = (this.Session != null) ? this.Session.ComputerName : string.Empty; break; - + case InstanceIdParameterSet: case IdParameterSet: case NameParameterSet: @@ -1201,17 +1201,17 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(false, "Unrecognized parameter set."); break; } - + string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterVMSessionPrompt, @"function global:prompt { """, targetName, @"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }"); - + // Set prompt in pushed named pipe runspace. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { ps.Runspace = remoteRunspace; - + try { // Set pushed runspace prompt. @@ -1222,7 +1222,7 @@ namespace Microsoft.PowerShell.Commands // Ignore all non-severe errors. CommandProcessorBase.CheckForSevereException(e); } - } + } } return; @@ -1253,19 +1253,19 @@ namespace Microsoft.PowerShell.Commands catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); } catch (PSRemotingDataStructureException e) @@ -1279,14 +1279,14 @@ namespace Microsoft.PowerShell.Commands if ((e.InnerException != null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, - null); + null); } else { errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); } @@ -1296,10 +1296,10 @@ namespace Microsoft.PowerShell.Commands catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } @@ -1376,7 +1376,6 @@ namespace Microsoft.PowerShell.Commands RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; if (remoteDebugger != null) { - // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. remoteDebugger.SendBreakpointUpdatedEvents(); diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index 537477501..1459c4e60 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -86,14 +86,14 @@ namespace Microsoft.PowerShell.Commands { get { - return jobs; + return _jobs; } set { - jobs = value; + _jobs = value; } } - private Job[] jobs; + private Job[] _jobs; /// /// Name of the computer for which the results needs to be @@ -109,14 +109,14 @@ namespace Microsoft.PowerShell.Commands { get { - return computerNames; + return _computerNames; } set { - computerNames = value; + _computerNames = value; } } - private String[] computerNames; + private String[] _computerNames; /// /// Locations for which the results needs to be returned. @@ -131,14 +131,14 @@ namespace Microsoft.PowerShell.Commands { get { - return locations; + return _locations; } set { - locations = value; + _locations = value; } } - private String[] locations; + private String[] _locations; /// /// Runspaces for which the results needs to be @@ -153,14 +153,14 @@ namespace Microsoft.PowerShell.Commands { get { - return remoteRunspaceInfos; + return _remoteRunspaceInfos; } set { - remoteRunspaceInfos = value; + _remoteRunspaceInfos = value; } } - private PSSession[] remoteRunspaceInfos; + private PSSession[] _remoteRunspaceInfos; /// /// If the results need to be not removed from the store @@ -171,15 +171,15 @@ namespace Microsoft.PowerShell.Commands { get { - return !flush; + return !_flush; } set { - flush = !value; + _flush = !value; ValidateWait(); } } - private bool flush = true; + private bool _flush = true; /// /// @@ -189,14 +189,14 @@ namespace Microsoft.PowerShell.Commands { get { - return !recurse; + return !_recurse; } set { - recurse = !value; + _recurse = !value; } } - private bool recurse = true; + private bool _recurse = true; /// /// @@ -346,7 +346,7 @@ namespace Microsoft.PowerShell.Commands { case SessionParameterSet: { - foreach (Job job in jobs) + foreach (Job job in _jobs) { PSRemotingJob remoteJob = job as PSRemotingJob; @@ -363,7 +363,7 @@ namespace Microsoft.PowerShell.Commands } //Runspace parameter is supported only on PSRemotingJob objects - foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos) + foreach (PSSession remoteRunspaceInfo in _remoteRunspaceInfos) { // get the required child jobs List childJobs = remoteJob.GetJobsForRunspace(remoteRunspaceInfo); @@ -377,7 +377,7 @@ namespace Microsoft.PowerShell.Commands case ComputerNameParameterSet: { - foreach (Job job in jobs) + foreach (Job job in _jobs) { // the job can either be a remoting job or another one PSRemotingJob remoteJob = @@ -396,7 +396,7 @@ namespace Microsoft.PowerShell.Commands } String[] resolvedComputernames = null; - ResolveComputerNames(computerNames, out resolvedComputernames); + ResolveComputerNames(_computerNames, out resolvedComputernames); foreach (String resolvedComputerName in resolvedComputernames) { @@ -412,17 +412,17 @@ namespace Microsoft.PowerShell.Commands case "Location": { - if (locations == null) + if (_locations == null) { //WriteAll(); - jobsToWrite.AddRange(jobs); + jobsToWrite.AddRange(_jobs); checkForRecurse = true; } else { - foreach (Job job in jobs) + foreach (Job job in _jobs) { - foreach (String location in locations) + foreach (String location in _locations) { // get the required child Job objects List childJobs = job.GetJobsForLocation(location); @@ -887,7 +887,7 @@ namespace Microsoft.PowerShell.Commands // If it was generated by a job that gave location information, unpack the // base exception. JobFailedException exceptionWithLocation = baseReason as JobFailedException; - if(exceptionWithLocation != null) + if (exceptionWithLocation != null) { resultReason = exceptionWithLocation.Reason; } @@ -917,7 +917,7 @@ namespace Microsoft.PowerShell.Commands /// collection with copy of data private Collection ReadAll(PSDataCollection psDataCollection) { - if (flush) + if (_flush) { return psDataCollection.ReadAll(); } @@ -1103,7 +1103,7 @@ namespace Microsoft.PowerShell.Commands _tracer.WriteMessage(ClassNameTrace, "HandleJobStateChanged", Guid.Empty, job, "END wait for write existing data", null); - lock(_syncObject) + lock (_syncObject) { if (!_jobsBeingAggregated.Contains(job)) { @@ -1320,7 +1320,7 @@ namespace Microsoft.PowerShell.Commands private T GetData(PSDataCollection collection, int index) { - if (flush) + if (_flush) { Collection data = collection.ReadAndRemove(1); if (data.Count > 0) @@ -1380,7 +1380,7 @@ namespace Microsoft.PowerShell.Commands if (!_autoRemoveJob) return; if (!_jobsSpecifiedInParameters.Contains(job.InstanceId)) return; if (!job.IsFinishedState(job.JobStateInfo.State)) return; - + // Only finished jobs that were specified by the user on the cmdline // (computed in processRecord) should reach this point. if (job.HasMoreData) @@ -1451,7 +1451,7 @@ namespace Microsoft.PowerShell.Commands { foreach (Job job in jobs) { - if(JobManager.IsJobFromAdapter(job.InstanceId, "PSWorkflowJob") && + if (JobManager.IsJobFromAdapter(job.InstanceId, "PSWorkflowJob") && job.JobStateInfo.State == JobState.Stopped) { MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; @@ -1461,7 +1461,7 @@ namespace Microsoft.PowerShell.Commands } } - if (checkForRecurse && recurse) + if (checkForRecurse && _recurse) { WriteJobResultsRecursively(job, registerInsteadOfWrite); } @@ -1525,7 +1525,7 @@ namespace Microsoft.PowerShell.Commands private void ValidateWait() { - if (_wait && !flush) + if (_wait && !_flush) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.BlockCannotBeUsedWithKeep); } diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index e47713d16..f015e11be 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -90,10 +90,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public PSSession Session { - get { return this.remotePSSessionInfo; } - set { this.remotePSSessionInfo = value; } + get { return _remotePSSessionInfo; } + set { _remotePSSessionInfo = value; } } - private PSSession remotePSSessionInfo; + private PSSession _remotePSSessionInfo; /// @@ -106,10 +106,10 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = ReceivePSSessionCommand.IdParameterSet)] public Int32 Id { - get { return this.id; } - set { this.id = value; } + get { return _id; } + set { _id = value; } } - private Int32 id; + private Int32 _id; /// @@ -127,10 +127,10 @@ namespace Microsoft.PowerShell.Commands [Alias("Cn")] public String ComputerName { - get { return this.computerName; } - set { this.computerName = value; } + get { return _computerName; } + set { _computerName = value; } } - private String computerName; + private String _computerName; /// /// This parameters specifies the appname which identifies the connection @@ -144,13 +144,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = ReceivePSSessionCommand.ComputerInstanceIdParameterSet)] public String ApplicationName { - get { return appName; } + get { return _appName; } set { - appName = ResolveAppName(value); + _appName = ResolveAppName(value); } } - private String appName; + private String _appName; /// /// If this parameter is not specified then the value specified in @@ -167,13 +167,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public String ConfigurationName { - get { return shell; } + get { return _shell; } set { - shell = ResolveShell(value); + _shell = ResolveShell(value); } } - private String shell; + private String _shell; /// /// A complete URI(s) specified for the remote computer and shell to @@ -189,10 +189,10 @@ namespace Microsoft.PowerShell.Commands [Alias("URI", "CU")] public Uri ConnectionUri { - get { return uris; } - set { uris = value; } + get { return _uris; } + set { _uris = value; } } - private Uri uris; + private Uri _uris; /// /// The AllowRedirection parameter enables the implicit redirection functionality. @@ -201,10 +201,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public SwitchParameter AllowRedirection { - get { return this.allowRedirection; } - set { this.allowRedirection = value; } + get { return _allowRedirection; } + set { _allowRedirection = value; } } - private bool allowRedirection = false; + private bool _allowRedirection = false; /// /// Instance Id of PSSession object to receive data from. @@ -221,10 +221,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public Guid InstanceId { - get { return this.instanceId; } - set { this.instanceId = value; } + get { return _instanceId; } + set { _instanceId = value; } } - private Guid instanceId; + private Guid _instanceId; /// @@ -242,10 +242,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string Name { - get { return this.name; } - set { this.name = value; } + get { return _name; } + set { _name = value; } } - private string name; + private string _name; /// @@ -261,10 +261,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public OutTarget OutTarget { - get { return this.outputMode; } - set { this.outputMode = value; } + get { return _outputMode; } + set { _outputMode = value; } } - private OutTarget outputMode = OutTarget.Default; + private OutTarget _outputMode = OutTarget.Default; /// /// Provides job name when job is created for returned data. @@ -280,10 +280,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public string JobName { - get { return this.jobName; } - set { this.jobName = value; } + get { return _jobName; } + set { _jobName = value; } } - private string jobName = string.Empty; + private string _jobName = string.Empty; /// @@ -298,15 +298,15 @@ namespace Microsoft.PowerShell.Commands [Credential()] public PSCredential Credential { - get { return this.psCredential; } + get { return _psCredential; } set { - this.psCredential = value; + _psCredential = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private PSCredential psCredential; + private PSCredential _psCredential; /// @@ -318,15 +318,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public AuthenticationMechanism Authentication { - get { return this.authentication; } + get { return _authentication; } set { - this.authentication = value; + _authentication = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private AuthenticationMechanism authentication; + private AuthenticationMechanism _authentication; /// @@ -339,15 +339,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public string CertificateThumbprint { - get { return this.thumbprint; } + get { return _thumbprint; } set { - this.thumbprint = value; + _thumbprint = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private string thumbprint; + private string _thumbprint; /// @@ -368,14 +368,14 @@ namespace Microsoft.PowerShell.Commands { get { - return port; + return _port; } set { - port = value; + _port = value; } } - private Int32 port; + private Int32 _port; /// @@ -392,14 +392,14 @@ namespace Microsoft.PowerShell.Commands { get { - return useSSL; + return _useSSL; } set { - useSSL = value; + _useSSL = value; } } - private SwitchParameter useSSL; + private SwitchParameter _useSSL; /// /// Session options. @@ -410,10 +410,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public PSSessionOption SessionOption { - get { return this.sessionOption; } - set { this.sessionOption = value; } + get { return _sessionOption; } + set { _sessionOption = value; } } - private PSSessionOption sessionOption; + private PSSessionOption _sessionOption; #endregion @@ -423,7 +423,7 @@ namespace Microsoft.PowerShell.Commands /// Process input. /// protected override void ProcessRecord() - { + { if (ParameterSetName == ReceivePSSessionCommand.ComputerSessionNameParameterSet || ParameterSetName == ReceivePSSessionCommand.ConnectionUriSessionNameParameterSet) { @@ -674,7 +674,7 @@ namespace Microsoft.PowerShell.Commands connectionInfo.MaximumConnectionRedirectionCount = 0; } - if (!this.allowRedirection) + if (!_allowRedirection) { // uri redirection required explicit user consent connectionInfo.MaximumConnectionRedirectionCount = 0; @@ -706,7 +706,7 @@ namespace Microsoft.PowerShell.Commands session = GetSessionById(Id); if (session == null) { - WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, + WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, Id); @@ -730,7 +730,7 @@ namespace Microsoft.PowerShell.Commands session = GetSessionByInstanceId(InstanceId); if (session == null) { - WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, InstanceId); @@ -752,7 +752,7 @@ namespace Microsoft.PowerShell.Commands WriteError(errorRecord); return; } - + if (ShouldProcess(session.Name, VerbsCommunications.Receive)) { Exception ex; @@ -991,8 +991,8 @@ namespace Microsoft.PowerShell.Commands break; } - int index = WaitHandle.WaitAny(new WaitHandle[] { - _stopPipelineReceive, + int index = WaitHandle.WaitAny(new WaitHandle[] { + _stopPipelineReceive, _remotePipeline.Output.WaitHandle }); if (index == 0) @@ -1039,8 +1039,8 @@ namespace Microsoft.PowerShell.Commands } // Wait for pipeline to finish. - int wIndex = WaitHandle.WaitAny(new WaitHandle[] { - _stopPipelineReceive, + int wIndex = WaitHandle.WaitAny(new WaitHandle[] { + _stopPipelineReceive, _remotePipeline.PipelineFinishedEvent }); if (wIndex == 0) @@ -1260,7 +1260,7 @@ namespace Microsoft.PowerShell.Commands // will have to be created. return null; } - + foreach (Job repJob in this.JobRepository.Jobs) { if (repJob is PSRemotingJob) @@ -1362,7 +1362,6 @@ namespace Microsoft.PowerShell.Commands private object _syncObject = new object(); #endregion - } #region OutTarget Enum diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 15d2ae11c..85a87cddb 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -54,17 +54,17 @@ namespace Microsoft.PowerShell.Commands /// recurse and check in child jobs /// list of matching jobs internal List FindJobsMatchingByName( - bool recurse, - bool writeobject, - bool writeErrorOnNoMatch, + bool recurse, + bool writeobject, + bool writeErrorOnNoMatch, bool checkIfJobCanBeRemoved) { List matches = new List(); Hashtable duplicateDetector = new Hashtable(); - if (names == null) return matches; + if (_names == null) return matches; - foreach (String name in names) + foreach (String name in _names) { if (string.IsNullOrEmpty(name)) continue; @@ -114,7 +114,7 @@ namespace Microsoft.PowerShell.Commands string message = PSRemotingErrorInvariants.FormatResourceString(resourceString, args); Exception ex = new ArgumentException(message, parameterName); WriteError(new ErrorRecord(ex, "JobObjectNotFinishedCannotBeRemoved", ErrorCategory.InvalidOperation, job2)); - return false; + return false; } return true; @@ -192,9 +192,9 @@ namespace Microsoft.PowerShell.Commands Hashtable duplicateDetector = new Hashtable(); - if (instanceIds == null) return matches; + if (_instanceIds == null) return matches; - foreach (Guid id in instanceIds) + foreach (Guid id in _instanceIds) { // search all jobs in Job repository duplicateDetector.Clear(); @@ -306,11 +306,11 @@ namespace Microsoft.PowerShell.Commands { List matches = new List(); - if (sessionIds == null) return matches; + if (_sessionIds == null) return matches; Hashtable duplicateDetector = new Hashtable(); - foreach (int id in sessionIds) + foreach (int id in _sessionIds) { // check jobs in job repository bool jobFound = FindJobsMatchingBySessionIdHelper(matches, JobRepository.Jobs, id, @@ -408,19 +408,19 @@ namespace Microsoft.PowerShell.Commands { List matches = new List(); - if (commands == null) return matches; + if (_commands == null) return matches; List jobs = new List(); jobs.AddRange(JobRepository.Jobs); - foreach (string command in commands) + foreach (string command in _commands) { List jobs2 = JobManager.GetJobsByCommand(command, this, false, false, false, null); if (jobs2 != null) { - foreach(Job2 job2 in jobs2) + foreach (Job2 job2 in jobs2) { jobs.Add(job2); } @@ -464,7 +464,7 @@ namespace Microsoft.PowerShell.Commands jobs.AddRange(JobRepository.Jobs); - List jobs2 = JobManager.GetJobsByState(jobstate, this, false, false, false, null); + List jobs2 = JobManager.GetJobsByState(_jobstate, this, false, false, false, null); if (jobs2 != null) { @@ -476,7 +476,7 @@ namespace Microsoft.PowerShell.Commands foreach (Job job in jobs) { - if (job.JobStateInfo.State != jobstate) continue; + if (job.JobStateInfo.State != _jobstate) continue; if (writeobject) { @@ -499,14 +499,14 @@ namespace Microsoft.PowerShell.Commands { List matches = new List(); List jobs = new List(); - + // add Jobs from JobRepository -- only job property based filters are supported. FindJobsMatchingByFilterHelper(jobs, JobRepository.Jobs); var filterDictionary = new Dictionary(); - foreach (string item in filter.Keys) + foreach (string item in _filter.Keys) { - filterDictionary.Add(item, filter[item]); + filterDictionary.Add(item, _filter[item]); } List jobs2 = JobManager.GetJobsByFilter(filterDictionary, this, false, false, true); @@ -584,7 +584,7 @@ namespace Microsoft.PowerShell.Commands /// Resource String in case of error /// Parameters for resource message /// true if object should be removed, else false - bool CheckJobCanBeRemoved(Job job, string parameterName, string resourceString, params object[] list) + private bool CheckJobCanBeRemoved(Job job, string parameterName, string resourceString, params object[] list) { if (job.IsFinishedState(job.JobStateInfo.State)) return true; @@ -609,18 +609,18 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } /// /// /// - private String[] names; + private String[] _names; /// /// InstanceIds for which job @@ -634,25 +634,25 @@ namespace Microsoft.PowerShell.Commands { get { - return instanceIds; + return _instanceIds; } set { - instanceIds = value; + _instanceIds = value; } } /// /// /// - private Guid[] instanceIds; + private Guid[] _instanceIds; /// /// SessionId for which job /// need to be obtained /// [Parameter(ValueFromPipelineByPropertyName = true, Position = 0, - Mandatory=true, + Mandatory = true, ParameterSetName = JobCmdletBase.SessionIdParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -660,18 +660,18 @@ namespace Microsoft.PowerShell.Commands { get { - return sessionIds; + return _sessionIds; } set { - sessionIds = value; + _sessionIds = value; } } /// /// /// - private int[] sessionIds; + private int[] _sessionIds; /// /// All the job objects having this state. @@ -683,18 +683,18 @@ namespace Microsoft.PowerShell.Commands { get { - return jobstate; + return _jobstate; } set { - jobstate = value; + _jobstate = value; } } /// /// /// - private JobState jobstate; + private JobState _jobstate; /// /// All the job objects having this command. @@ -706,18 +706,18 @@ namespace Microsoft.PowerShell.Commands { get { - return commands; + return _commands; } set { - commands = value; + _commands = value; } } /// /// /// - private String[] commands; + private String[] _commands; /// /// All the job objects matching the values in filter @@ -729,11 +729,11 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual Hashtable Filter { - get { return filter; } - set { filter = value; } + get { return _filter; } + set { _filter = value; } } - private Hashtable filter; + private Hashtable _filter; #endregion Parameters @@ -765,7 +765,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Remove, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113377")] - [OutputType(typeof(Job), ParameterSetName = new string[] { JobCmdletBase.JobParameterSet})] + [OutputType(typeof(Job), ParameterSetName = new string[] { JobCmdletBase.JobParameterSet })] public class RemoveJobCommand : JobCmdletBase, IDisposable { #region Parameters @@ -776,7 +776,7 @@ namespace Microsoft.PowerShell.Commands /// [Parameter(Mandatory = true, Position = 0, - ValueFromPipeline = true, + ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveJobCommand.JobParameterSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -785,14 +785,14 @@ namespace Microsoft.PowerShell.Commands { get { - return jobs; + return _jobs; } set { - jobs = value; + _jobs = value; } } - private Job[] jobs; + private Job[] _jobs; /// /// If state of the job is running or notstarted, this will forcefully stop it. @@ -807,14 +807,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force = false; + private bool _force = false; #endregion Parameters @@ -831,19 +831,19 @@ namespace Microsoft.PowerShell.Commands { case NameParameterSet: { - listOfJobsToRemove = FindJobsMatchingByName(false, false, true, !force); + listOfJobsToRemove = FindJobsMatchingByName(false, false, true, !_force); } break; case InstanceIdParameterSet: { - listOfJobsToRemove = FindJobsMatchingByInstanceId(true, false, true, !force); + listOfJobsToRemove = FindJobsMatchingByInstanceId(true, false, true, !_force); } break; case SessionIdParameterSet: { - listOfJobsToRemove = FindJobsMatchingBySessionId(true, false, true, !force); + listOfJobsToRemove = FindJobsMatchingBySessionId(true, false, true, !_force); } break; @@ -867,7 +867,7 @@ namespace Microsoft.PowerShell.Commands default: { - listOfJobsToRemove = CopyJobsToList(jobs, false, !force); + listOfJobsToRemove = CopyJobsToList(_jobs, false, !_force); } break; } @@ -890,7 +890,7 @@ namespace Microsoft.PowerShell.Commands _cleanUpActions.Add(job2, HandleStopJobCompleted); job2.StopJobCompleted += HandleStopJobCompleted; - lock(_syncObject) + lock (_syncObject) { if (!job2.IsFinishedState(job2.JobStateInfo.State) && !_pendingJobs.Contains(job2.InstanceId)) @@ -898,7 +898,7 @@ namespace Microsoft.PowerShell.Commands _pendingJobs.Add(job2.InstanceId); } } - + job2.StopJobAsync(); } else @@ -909,7 +909,7 @@ namespace Microsoft.PowerShell.Commands } else { - RemoveJobAndDispose(job, job2 != null); + RemoveJobAndDispose(job, job2 != null); } } } // ProcessRecord @@ -920,7 +920,7 @@ namespace Microsoft.PowerShell.Commands protected override void EndProcessing() { bool haveToWait = false; - lock(_syncObject) + lock (_syncObject) { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) @@ -952,7 +952,7 @@ namespace Microsoft.PowerShell.Commands { job2TypeFound = JobManager.RemoveJob(job as Job2, this, true, false); } - + if (!job2TypeFound) { JobRepository.Remove(job); @@ -982,7 +982,7 @@ namespace Microsoft.PowerShell.Commands { _pendingJobs.Remove(job.InstanceId); } - if (_needToCheckForWaitingJobs && _pendingJobs.Count ==0) + if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } // end processing has been called @@ -1023,7 +1023,7 @@ namespace Microsoft.PowerShell.Commands protected void Dispose(bool disposing) { if (!disposing) return; - foreach(var pair in _cleanUpActions) + foreach (var pair in _cleanUpActions) { pair.Key.StopJobCompleted -= pair.Value; } diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs index 34d77fa10..47e13dbf6 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.ComponentModel; @@ -39,14 +40,14 @@ namespace Microsoft.PowerShell.Commands { get { - return jobs; + return _jobs; } set { - jobs = value; + _jobs = value; } } - private Job[] jobs; + private Job[] _jobs; /// /// @@ -112,7 +113,7 @@ namespace Microsoft.PowerShell.Commands default: { - jobsToResume = CopyJobsToList(jobs, false, false); + jobsToResume = CopyJobsToList(_jobs, false, false); } break; } diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 2411a2903..e8cb28731 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Commands { #region Private members - private static readonly string StartJobType = "BackgroundJob"; + private static readonly string s_startJobType = "BackgroundJob"; #endregion @@ -59,7 +59,7 @@ namespace Microsoft.PowerShell.Commands /// /// Job SourceAdapter type for this job definition. /// - [Parameter(Position = 2, + [Parameter(Position = 2, ParameterSetName = StartJobCommand.DefinitionNameParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] @@ -83,17 +83,17 @@ namespace Microsoft.PowerShell.Commands { get { - return name; + return _name; } set { if (!String.IsNullOrEmpty(value)) { - name = value; + _name = value; } } } - private String name; + private String _name; /// /// Command to execute specified as a string. This can be a single @@ -303,9 +303,9 @@ namespace Microsoft.PowerShell.Commands /// public override string CertificateThumbprint { - get - { - return base.CertificateThumbprint; + get + { + return base.CertificateThumbprint; } set { @@ -313,16 +313,16 @@ namespace Microsoft.PowerShell.Commands } } - /// - /// Overriding to suppress this parameter - /// - public override SwitchParameter AllowRedirection - { - get - { - return false; - } - } + /// + /// Overriding to suppress this parameter + /// + public override SwitchParameter AllowRedirection + { + get + { + return false; + } + } /// /// Overriding to suppress this parameter @@ -362,9 +362,9 @@ namespace Microsoft.PowerShell.Commands /// public override SwitchParameter RunAsAdministrator { - get + get { - return false; + return false; } } @@ -399,10 +399,10 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)] public virtual ScriptBlock InitializationScript { - get { return initScript; } - set { initScript = value; } + get { return _initScript; } + set { _initScript = value; } } - private ScriptBlock initScript; + private ScriptBlock _initScript; /// /// Launces the background job as a 32-bit process. This can be used on @@ -413,10 +413,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)] public virtual SwitchParameter RunAs32 { - get { return shouldRunAs32; } - set { shouldRunAs32 = value; } + get { return _shouldRunAs32; } + set { _shouldRunAs32 = value; } } - private bool shouldRunAs32; + private bool _shouldRunAs32; /// /// Powershell Version to execute the background job @@ -427,18 +427,18 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public virtual Version PSVersion { - get { return psVersion; } + get { return _psVersion; } set { PSSessionConfigurationCommandBase.CheckPSVersion(value); - + // Check if specified version of PowerShell is installed PSSessionConfigurationCommandUtilities.CheckIfPowerShellVersionIsInstalled(value); - psVersion = value; + _psVersion = value; } } - private Version psVersion; + private Version _psVersion; /// /// InputObject. @@ -517,12 +517,12 @@ namespace Microsoft.PowerShell.Commands } NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential); - connectionInfo.RunAs32 = this.shouldRunAs32; - connectionInfo.InitializationScript = this.initScript; + connectionInfo.RunAs32 = _shouldRunAs32; + connectionInfo.InitializationScript = _initScript; connectionInfo.AuthenticationMechanism = this.Authentication; connectionInfo.PSVersion = this.PSVersion; - RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, + RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, Utils.GetTypeTableFromExecutionContextTLS()); remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; @@ -550,7 +550,7 @@ namespace Microsoft.PowerShell.Commands if (!string.IsNullOrEmpty(_definitionPath)) { ProviderInfo provider = null; - System.Collections.ObjectModel.Collection paths = + System.Collections.ObjectModel.Collection paths = this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider); // Only file system paths are allowed. @@ -613,14 +613,14 @@ namespace Microsoft.PowerShell.Commands return; } - if (firstProcessRecord) + if (_firstProcessRecord) { - firstProcessRecord = false; + _firstProcessRecord = false; PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations, - ScriptBlock.ToString(), ThrottleLimit, name); + ScriptBlock.ToString(), ThrottleLimit, _name); - job.PSJobTypeName = StartJobType; + job.PSJobTypeName = s_startJobType; this.JobRepository.Add(job); WriteObject(job); @@ -636,7 +636,7 @@ namespace Microsoft.PowerShell.Commands } } } // ProcessRecord - private bool firstProcessRecord = true; + private bool _firstProcessRecord = true; /// /// InvokeAsync would have been called in ProcessRecord. Wait here @@ -671,10 +671,8 @@ namespace Microsoft.PowerShell.Commands { CloseAllInputStreams(); } - } // Dipose #endregion IDisposable Overrides - } } diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index 6dea373a8..bea04791a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.ComponentModel; @@ -31,19 +32,19 @@ namespace Microsoft.PowerShell.Commands ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveJobCommand.JobParameterSet)] [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get { - return jobs; + return _jobs; } set { - jobs = value; + _jobs = value; } } - private Job[] jobs; + private Job[] _jobs; /// /// Pass the Job object through the pipeline. @@ -53,14 +54,14 @@ namespace Microsoft.PowerShell.Commands { get { - return passThru; + return _passThru; } set { - passThru = value; + _passThru = value; } } - private bool passThru; + private bool _passThru; /// /// @@ -119,7 +120,7 @@ namespace Microsoft.PowerShell.Commands default: { - jobsToStop = CopyJobsToList(jobs, false, false); + jobsToStop = CopyJobsToList(_jobs, false, false); } break; } @@ -193,7 +194,7 @@ namespace Microsoft.PowerShell.Commands _waitForJobs.WaitOne(); foreach (var e in _errorsToWrite) WriteError(e); - if (passThru) + if (_passThru) { foreach (var job in _allJobsToStop) WriteObject(job); } diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs index 7341e1892..a33872f49 100644 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -36,19 +37,19 @@ namespace Microsoft.PowerShell.Commands ValueFromPipelineByPropertyName = true, ParameterSetName = JobParameterSet)] [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get { - return jobs; + return _jobs; } set { - jobs = value; + _jobs = value; } } - private Job[] jobs; + private Job[] _jobs; /// /// @@ -75,14 +76,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force = false; + private bool _force = false; /// /// @@ -148,7 +149,7 @@ namespace Microsoft.PowerShell.Commands default: { - jobsToSuspend = CopyJobsToList(jobs, false, false); + jobsToSuspend = CopyJobsToList(_jobs, false, false); } break; } @@ -165,7 +166,7 @@ namespace Microsoft.PowerShell.Commands WriteError( new ErrorRecord( PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id), - "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object) job)); + "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); continue; } @@ -188,9 +189,8 @@ namespace Microsoft.PowerShell.Commands if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended) continue; - - job2.StateChanged += noWait_Job2_StateChanged; + job2.StateChanged += noWait_Job2_StateChanged; } job2.SuspendJobCompleted += HandleSuspendJobCompleted; @@ -210,7 +210,7 @@ namespace Microsoft.PowerShell.Commands this.ProcessExecutionErrorsAndReleaseWaitHandle(job2); } - job2.SuspendJobAsync(force, RemotingErrorIdStrings.ForceSuspendJob); + job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob); } } } @@ -225,7 +225,7 @@ namespace Microsoft.PowerShell.Commands private readonly object _syncObject = new object(); private bool _needToCheckForWaitingJobs; - void noWait_Job2_StateChanged(object sender, JobStateEventArgs e) + private void noWait_Job2_StateChanged(object sender, JobStateEventArgs e) { Job job = sender as Job; diff --git a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs index 4a0bb4250..55ae357c2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Management.Automation; using System.Management.Automation.Remoting; @@ -28,10 +29,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ValueFromPipelineByPropertyName = true)] public string Path { - get { return path; } - set { path = value; } + get { return _path; } + set { _path = value; } } - string path; + private string _path; #endregion @@ -49,20 +50,20 @@ namespace Microsoft.PowerShell.Commands { if (this.Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem)) { - filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); + filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider); } else { filePaths = new Collection(); - filePaths.Add(path); + filePaths.Add(_path); } } catch (ItemNotFoundException) { - string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, path); + string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound", - ErrorCategory.ResourceUnavailable, path); + ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } @@ -71,17 +72,17 @@ namespace Microsoft.PowerShell.Commands if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { // "The current provider ({0}) cannot open a file" - throw InterpreterError.NewInterpreterException(path, typeof(RuntimeException), + throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName); } // Make sure at least one file was found... if (filePaths == null || filePaths.Count < 1) { - string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, path); + string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound", - ErrorCategory.ResourceUnavailable, path); + ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } @@ -130,7 +131,7 @@ namespace Microsoft.PowerShell.Commands string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, filePath); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath", - ErrorCategory.InvalidArgument, path); + ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } } diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 0625de293..42f6d308c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -57,7 +58,7 @@ namespace Microsoft.PowerShell.Commands _timeoutInSeconds = value; } } - int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. + private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. /// /// Forces the cmdlet to wait for Finished states (Completed, Failed, Stopped) instead of @@ -81,25 +82,25 @@ namespace Microsoft.PowerShell.Commands private void SetEndProcessingAction(Action endProcessingAction) { Dbg.Assert(endProcessingAction != null, "Caller should verify endProcessingAction != null"); - lock (this._endProcessingActionLock) + lock (_endProcessingActionLock) { - if (this._endProcessingAction == null) + if (_endProcessingAction == null) { - Dbg.Assert(!this._endProcessingActionIsReady.IsSet, "This line should execute only once"); - this._endProcessingAction = endProcessingAction; - this._endProcessingActionIsReady.Set(); + Dbg.Assert(!_endProcessingActionIsReady.IsSet, "This line should execute only once"); + _endProcessingAction = endProcessingAction; + _endProcessingActionIsReady.Set(); } } } private void InvokeEndProcesingAction() { - this._endProcessingActionIsReady.Wait(); + _endProcessingActionIsReady.Wait(); Action endProcessingAction; - lock (this._endProcessingActionLock) + lock (_endProcessingActionLock) { - endProcessingAction = this._endProcessingAction; + endProcessingAction = _endProcessingAction; } // Inovke action outside lock. @@ -111,13 +112,13 @@ namespace Microsoft.PowerShell.Commands private void CleanUpEndProcessing() { - this._endProcessingActionIsReady.Dispose(); + _endProcessingActionIsReady.Dispose(); } #endregion #region Support for triggering EndProcesing when jobs are finished or blocked - + private readonly HashSet _finishedJobs = new HashSet(); private readonly HashSet _blockedJobs = new HashSet(); private readonly List _jobsToWaitFor = new List(); @@ -128,20 +129,20 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert(source is Job, "Caller should verify source is Job"); Dbg.Assert(eventArgs != null, "Caller should verify eventArgs != null"); - var job = (Job) source; + var job = (Job)source; lock (_jobTrackingLock) { - Dbg.Assert(this._blockedJobs.All(j => !this._finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); + Dbg.Assert(_blockedJobs.All(j => !_finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); if (eventArgs.JobStateInfo.State == JobState.Blocked) { - this._blockedJobs.Add(job); - } + _blockedJobs.Add(job); + } else { - this._blockedJobs.Remove(job); - } - + _blockedJobs.Remove(job); + } + // Treat jobs in Disconnected state as finished jobs since the user // will have to reconnect the job before more information can be // obtained. @@ -156,33 +157,33 @@ namespace Microsoft.PowerShell.Commands { _warnNotTerminal = true; } - this._finishedJobs.Add(job); + _finishedJobs.Add(job); } else { - this._finishedJobs.Remove(job); + _finishedJobs.Remove(job); } - Dbg.Assert(this._blockedJobs.All(j => !this._finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); + Dbg.Assert(_blockedJobs.All(j => !_finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); if (this.Any.IsPresent) { - if (this._finishedJobs.Count > 0) + if (_finishedJobs.Count > 0) { this.SetEndProcessingAction(this.EndProcessingOutputSingleFinishedJob); } - else if (this._blockedJobs.Count == this._jobsToWaitFor.Count) + else if (_blockedJobs.Count == _jobsToWaitFor.Count) { this.SetEndProcessingAction(this.EndProcessingBlockedJobsError); } } else { - if (this._finishedJobs.Count == this._jobsToWaitFor.Count) + if (_finishedJobs.Count == _jobsToWaitFor.Count) { this.SetEndProcessingAction(this.EndProcessingOutputAllFinishedJobs); } - else if (this._blockedJobs.Count > 0) + else if (_blockedJobs.Count > 0) { this.SetEndProcessingAction(this.EndProcessingBlockedJobsError); } @@ -194,23 +195,23 @@ namespace Microsoft.PowerShell.Commands { Dbg.Assert(jobsToAdd != null, "Caller should verify jobs != null"); - lock (this._jobTrackingLock) + lock (_jobTrackingLock) { - this._jobsToWaitFor.AddRange(jobsToAdd); + _jobsToWaitFor.AddRange(jobsToAdd); } } private void StartJobChangesTracking() { - lock (this._jobTrackingLock) + lock (_jobTrackingLock) { - if (this._jobsToWaitFor.Count == 0) + if (_jobsToWaitFor.Count == 0) { this.SetEndProcessingAction(this.EndProcessingDoNothing); return; } - foreach (Job job in this._jobsToWaitFor) + foreach (Job job in _jobsToWaitFor) { job.StateChanged += this.HandleJobStateChangedEvent; this.HandleJobStateChangedEvent(job, new JobStateEventArgs(job.JobStateInfo)); @@ -220,9 +221,9 @@ namespace Microsoft.PowerShell.Commands private void CleanUpJobChangesTracking() { - lock (this._jobTrackingLock) + lock (_jobTrackingLock) { - foreach (Job job in this._jobsToWaitFor) + foreach (Job job in _jobsToWaitFor) { job.StateChanged -= this.HandleJobStateChangedEvent; } @@ -232,18 +233,18 @@ namespace Microsoft.PowerShell.Commands private List GetFinishedJobs() { List jobsToOutput; - lock (this._jobTrackingLock) + lock (_jobTrackingLock) { - jobsToOutput = this._jobsToWaitFor.Where(j => ((!Force && j.IsPersistentState(j.JobStateInfo.State)) || (Force && j.IsFinishedState(j.JobStateInfo.State)))).ToList(); + jobsToOutput = _jobsToWaitFor.Where(j => ((!Force && j.IsPersistentState(j.JobStateInfo.State)) || (Force && j.IsFinishedState(j.JobStateInfo.State)))).ToList(); } return jobsToOutput; } private Job GetOneBlockedJob() { - lock (this._jobTrackingLock) + lock (_jobTrackingLock) { - return this._jobsToWaitFor.FirstOrDefault(j => j.JobStateInfo.State == JobState.Blocked); + return _jobsToWaitFor.FirstOrDefault(j => j.JobStateInfo.State == JobState.Blocked); } } @@ -262,21 +263,21 @@ namespace Microsoft.PowerShell.Commands } else if (timeoutInSeconds > 0) { - lock (this._timerLock) + lock (_timerLock) { - this._timer = new Timer((_) => this.SetEndProcessingAction(this.EndProcessingDoNothing), null, timeoutInSeconds * 1000, System.Threading.Timeout.Infinite); + _timer = new Timer((_) => this.SetEndProcessingAction(this.EndProcessingDoNothing), null, timeoutInSeconds * 1000, System.Threading.Timeout.Infinite); } } } private void CleanUpTimoutTracking() { - lock (this._timerLock) + lock (_timerLock) { - if (this._timer != null) + if (_timer != null) { - this._timer.Dispose(); - this._timer = null; + _timer.Dispose(); + _timer = null; } } } @@ -298,7 +299,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - this.StartTimeoutTracking(this._timeoutInSeconds); + this.StartTimeoutTracking(_timeoutInSeconds); } /// diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index 82a8e8a35..d8809e9a3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -71,10 +71,10 @@ namespace Microsoft.PowerShell.Commands [Alias("Cn")] public override String[] ComputerName { - get { return this.computerNames; } - set { this.computerNames = value; } + get { return _computerNames; } + set { _computerNames = value; } } - private String[] computerNames; + private String[] _computerNames; /// /// This parameters specifies the appname which identifies the connection @@ -88,13 +88,13 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)] public String ApplicationName { - get { return appName; } + get { return _appName; } set { - appName = ResolveAppName(value); + _appName = ResolveAppName(value); } } - private String appName; + private String _appName; /// /// A complete URI(s) specified for the remote computer and shell to @@ -111,10 +111,10 @@ namespace Microsoft.PowerShell.Commands [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Uri[] ConnectionUri { - get { return uris; } - set { uris = value; } + get { return _uris; } + set { _uris = value; } } - private Uri[] uris; + private Uri[] _uris; /// /// For WSMan sessions: @@ -147,10 +147,10 @@ namespace Microsoft.PowerShell.Commands ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet)] public String ConfigurationName { - get { return shell; } - set { shell = value; } + get { return _shell; } + set { _shell = value; } } - private String shell; + private String _shell; /// /// The AllowRediraction parameter enables the implicit redirection functionality. @@ -159,10 +159,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] public SwitchParameter AllowRedirection { - get { return this.allowRedirection; } - set { this.allowRedirection = value; } + get { return _allowRedirection; } + set { _allowRedirection = value; } } - private bool allowRedirection = false; + private bool _allowRedirection = false; /// /// Session names to filter on. @@ -216,15 +216,15 @@ namespace Microsoft.PowerShell.Commands [Credential()] public PSCredential Credential { - get { return this.psCredential; } + get { return _psCredential; } set { - this.psCredential = value; + _psCredential = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private PSCredential psCredential; + private PSCredential _psCredential; /// @@ -236,15 +236,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] public AuthenticationMechanism Authentication { - get { return this.authentication; } + get { return _authentication; } set { - this.authentication = value; + _authentication = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private AuthenticationMechanism authentication; + private AuthenticationMechanism _authentication; /// @@ -257,15 +257,15 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] public string CertificateThumbprint { - get { return this.thumbprint; } + get { return _thumbprint; } set { - this.thumbprint = value; + _thumbprint = value; PSRemotingBaseCmdlet.ValidateSpecifiedAuthentication(Credential, CertificateThumbprint, Authentication); } } - private string thumbprint; + private string _thumbprint; /// @@ -286,14 +286,14 @@ namespace Microsoft.PowerShell.Commands { get { - return port; + return _port; } set { - port = value; + _port = value; } } - private Int32 port; + private Int32 _port; /// @@ -310,14 +310,14 @@ namespace Microsoft.PowerShell.Commands { get { - return useSSL; + return _useSSL; } set { - useSSL = value; + _useSSL = value; } } - private SwitchParameter useSSL; + private SwitchParameter _useSSL; /// /// Allows the user of the cmdlet to specify a throttling value @@ -330,10 +330,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] public Int32 ThrottleLimit { - get { return this.throttleLimit; } - set { this.throttleLimit = value; } + get { return _throttleLimit; } + set { _throttleLimit = value; } } - private Int32 throttleLimit = 0; + private Int32 _throttleLimit = 0; /// @@ -351,10 +351,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.VMNameInstanceIdParameterSet)] public SessionFilterState State { - get { return this.filterState; } - set { this.filterState = value; } + get { return _filterState; } + set { _filterState = value; } } - private SessionFilterState filterState; + private SessionFilterState _filterState; /// @@ -366,10 +366,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] public PSSessionOption SessionOption { - get { return this.sessionOption; } - set { this.sessionOption = value; } + get { return _sessionOption; } + set { _sessionOption = value; } } - private PSSessionOption sessionOption; + private PSSessionOption _sessionOption; #endregion @@ -419,7 +419,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - this.stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); } /// @@ -427,7 +427,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void StopProcessing() { - this.queryRunspaces.StopAllOperations(); + _queryRunspaces.StopAllOperations(); } #endregion Overrides @@ -445,12 +445,12 @@ namespace Microsoft.PowerShell.Commands Collection connectionInfos = GetConnectionObjects(); // Query for sessions. - Collection results = this.queryRunspaces.GetDisconnectedSessions(connectionInfos, this.Host, this.stream, - this.RunspaceRepository, this.throttleLimit, - this.filterState, InstanceId, Name, ConfigurationName); + Collection results = _queryRunspaces.GetDisconnectedSessions(connectionInfos, this.Host, _stream, + this.RunspaceRepository, _throttleLimit, + _filterState, InstanceId, Name, ConfigurationName); // Write any error output from stream object. - Collection streamObjects = this.stream.ObjectReader.NonBlockingRead(); + Collection streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { if (this.IsStopping) @@ -543,7 +543,7 @@ namespace Microsoft.PowerShell.Commands connectionInfo.MaximumConnectionRedirectionCount = 0; } - if (!this.allowRedirection) + if (!_allowRedirection) { // uri redirection required explicit user consent connectionInfo.MaximumConnectionRedirectionCount = 0; @@ -565,7 +565,7 @@ namespace Microsoft.PowerShell.Commands /// public void Dispose() { - this.stream.Dispose(); + _stream.Dispose(); GC.SuppressFinalize(this); } @@ -574,12 +574,11 @@ namespace Microsoft.PowerShell.Commands #region Private Members // Object used for querying remote runspaces. - QueryRunspaces queryRunspaces = new QueryRunspaces(); + private QueryRunspaces _queryRunspaces = new QueryRunspaces(); // Object to collect output data from multiple threads. - private ObjectStream stream = new ObjectStream(); + private ObjectStream _stream = new ObjectStream(); #endregion - } } diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index c35bea9c3..9f7f5fee8 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -78,14 +78,14 @@ namespace Microsoft.PowerShell.Commands { get { - return computerNames; + return _computerNames; } set { - computerNames = value; + _computerNames = value; } } - private String[] computerNames; + private String[] _computerNames; /// /// Specifies the credentials of the user to impersonate in the @@ -125,14 +125,14 @@ namespace Microsoft.PowerShell.Commands { get { - return remoteRunspaceInfos; + return _remoteRunspaceInfos; } set { - remoteRunspaceInfos = value; + _remoteRunspaceInfos = value; } } - private PSSession[] remoteRunspaceInfos; + private PSSession[] _remoteRunspaceInfos; /// /// Friendly names for the new PSSessions @@ -143,14 +143,14 @@ namespace Microsoft.PowerShell.Commands { get { - return names; + return _names; } set { - names = value; + _names = value; } } - private String[] names; + private String[] _names; /// /// When set and in loopback scenario (localhost) this enables creation of WSMan @@ -163,10 +163,10 @@ namespace Microsoft.PowerShell.Commands [Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)] public SwitchParameter EnableNetworkAccess { - get { return enableNetworkAccess; } - set { enableNetworkAccess = value; } + get { return _enableNetworkAccess; } + set { _enableNetworkAccess = value; } } - private SwitchParameter enableNetworkAccess; + private SwitchParameter _enableNetworkAccess; /// /// For WSMan sessions: @@ -191,14 +191,14 @@ namespace Microsoft.PowerShell.Commands { get { - return shell; + return _shell; } set { - shell = value; + _shell = value; } } - private String shell; + private String _shell; #endregion Parameters @@ -211,9 +211,9 @@ namespace Microsoft.PowerShell.Commands protected override void BeginProcessing() { base.BeginProcessing(); - operationsComplete.Reset(); - throttleManager.ThrottleLimit = ThrottleLimit; - throttleManager.ThrottleComplete += + _operationsComplete.Reset(); + _throttleManager.ThrottleLimit = ThrottleLimit; + _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); if (String.IsNullOrEmpty(ConfigurationName)) @@ -269,7 +269,7 @@ namespace Microsoft.PowerShell.Commands remoteRunspaces = CreateRunspacesWhenVMParameterSpecified(); } break; - + case NewPSSessionCommand.ContainerIdParameterSet: { remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified(); @@ -299,24 +299,22 @@ namespace Microsoft.PowerShell.Commands // submit list of operations to throttle manager to start opening // runspaces - throttleManager.SubmitOperations(operations); + _throttleManager.SubmitOperations(operations); // Add to list for clean up. - this.allOperations.Add(operations); + _allOperations.Add(operations); // If there are any runspaces opened asynchronously // that are ready now, check their status and do // necessary action. If there are any error records // or verbose messages write them as well Collection streamObjects = - stream.ObjectReader.NonBlockingRead(); + _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action)streamObject); } // foreach - - }// ProcessRecord() /// @@ -327,16 +325,16 @@ namespace Microsoft.PowerShell.Commands protected override void EndProcessing() { // signal to throttle manager end of submit operations - throttleManager.EndSubmitOperations(); + _throttleManager.EndSubmitOperations(); while (true) { // Keep reading objects until end of pipeline is encountered - stream.ObjectReader.WaitHandle.WaitOne(); + _stream.ObjectReader.WaitHandle.WaitOne(); - if (!stream.ObjectReader.EndOfPipeline) + if (!_stream.ObjectReader.EndOfPipeline) { - Object streamObject = stream.ObjectReader.Read(); + Object streamObject = _stream.ObjectReader.Read(); WriteStreamObject((Action)streamObject); } else @@ -361,12 +359,11 @@ namespace Microsoft.PowerShell.Commands { // close the outputStream so that futher writes to the outputStream // are not possible - stream.ObjectWriter.Close(); + _stream.ObjectWriter.Close(); // for all the runspaces that have been submitted for opening // call StopOperation on each object and quit - throttleManager.StopAllOperations(); - + _throttleManager.StopAllOperations(); }// StopProcessing() #endregion Cmdlet Overrides @@ -394,7 +391,7 @@ namespace Microsoft.PowerShell.Commands /// private void OnRunspacePSEventReceived(object sender, PSEventArgs e) { - if(this.Events != null) + if (this.Events != null) this.Events.AddForwardedEvent(e); } @@ -407,11 +404,11 @@ namespace Microsoft.PowerShell.Commands private void HandleURIDirectionReported(object sender, RemoteDataEventArgs eventArgs) { string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString); - Action warningWriter = delegate(Cmdlet cmdlet) + Action warningWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteWarning(message); }; - stream.Write(warningWriter); + _stream.Write(warningWriter); } /// @@ -446,7 +443,7 @@ namespace Microsoft.PowerShell.Commands remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported; } - PipelineWriter writer = stream.ObjectWriter; + PipelineWriter writer = _stream.ObjectWriter; Exception reason = runspaceStateEventArgs.RunspaceStateInfo.Reason; switch (state) @@ -460,7 +457,7 @@ namespace Microsoft.PowerShell.Commands this.RunspaceRepository.Add(remoteRunspaceInfo); - Action outputWriter = delegate(Cmdlet cmdlet) + Action outputWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteObject(remoteRunspaceInfo); }; @@ -505,7 +502,6 @@ namespace Microsoft.PowerShell.Commands "AllowRedirection"); errorDetails = "[" + host + "] " + message; - } else { @@ -520,7 +516,6 @@ namespace Microsoft.PowerShell.Commands } } } - } // add host identification information in data structure handler message @@ -556,25 +551,25 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { // // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((errorRecord.Exception != null) && + if ((errorRecord.Exception != null) && (errorRecord.Exception.InnerException != null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; if (ex != null) { - errorRecord = new ErrorRecord(errorRecord.Exception.InnerException, - errorRecord.FullyQualifiedErrorId, - errorRecord.CategoryInfo.Category, + errorRecord = new ErrorRecord(errorRecord.Exception.InnerException, + errorRecord.FullyQualifiedErrorId, + errorRecord.CategoryInfo.Category, errorRecord.TargetObject); } } - + cmdlet.WriteError(errorRecord); }; if (writer.IsOpen) @@ -582,7 +577,7 @@ namespace Microsoft.PowerShell.Commands writer.Write(errorWriter); } - toDispose.Add(remoteRunspace); + _toDispose.Add(remoteRunspace); } break; @@ -595,10 +590,10 @@ namespace Microsoft.PowerShell.Commands "ConnectionUri", null); String message = GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, - (connectionUri != null ) ? + (connectionUri != null) ? connectionUri.AbsoluteUri : string.Empty); - Action verboseWriter = delegate(Cmdlet cmdlet) + Action verboseWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteVerbose(message); }; @@ -616,7 +611,7 @@ namespace Microsoft.PowerShell.Commands "PSSessionStateClosed", ErrorCategory.OpenError, remoteRunspace); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; @@ -627,9 +622,7 @@ namespace Microsoft.PowerShell.Commands } } break; - }// switch - } // HandleRunspaceStateChanged /// @@ -648,7 +641,7 @@ namespace Microsoft.PowerShell.Commands ValidateRemoteRunspacesSpecified(); int rsIndex = 0; - foreach (PSSession remoteRunspaceInfo in remoteRunspaceInfos) + foreach (PSSession remoteRunspaceInfo in _remoteRunspaceInfos) { if (remoteRunspaceInfo == null || remoteRunspaceInfo.Runspace == null) { @@ -679,7 +672,7 @@ namespace Microsoft.PowerShell.Commands // WSMan case WSManConnectionInfo originalWSManConnectionInfo = remoteRunspace.ConnectionInfo as WSManConnectionInfo; WSManConnectionInfo newWSManConnectionInfo = null; - + if (null != originalWSManConnectionInfo) { newWSManConnectionInfo = originalWSManConnectionInfo.Copy(); @@ -700,10 +693,10 @@ namespace Microsoft.PowerShell.Commands newConnectionInfo = newWSManConnectionInfo; } } - + RemoteRunspacePoolInternal rrsPool = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal; TypeTable typeTable = null; - if ((rrsPool != null) && + if ((rrsPool != null) && (rrsPool.DataStructureHandler != null) && (rrsPool.DataStructureHandler.TransportManager != null)) { @@ -721,12 +714,12 @@ namespace Microsoft.PowerShell.Commands } catch (UriFormatException e) { - PipelineWriter writer = stream.ObjectWriter; + PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, remoteRunspaceInfo); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; @@ -738,7 +731,6 @@ namespace Microsoft.PowerShell.Commands } // foreach return remoteRunspaces; - } // CreateRunspacesWhenRunspaceParameterSpecified /// @@ -776,12 +768,12 @@ namespace Microsoft.PowerShell.Commands int rsId; string rsName = GetRunspaceName(i, out rsId); RemoteRunspace remoteRunspace = new RemoteRunspace( - Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, + Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); Dbg.Assert(remoteRunspace != null, "RemoteRunspace object created using URI is null"); - + remoteRunspaces.Add(remoteRunspace); } catch (UriFormatException e) @@ -841,7 +833,7 @@ namespace Microsoft.PowerShell.Commands else { connectionInfo.Credential = Credential; - } + } connectionInfo.AuthenticationMechanism = Authentication; UpdateConnectionInfo(connectionInfo); @@ -853,17 +845,17 @@ namespace Microsoft.PowerShell.Commands RemoteRunspace runspace = new RemoteRunspace( Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); - + remoteRunspaces.Add(runspace); } catch (UriFormatException e) { - PipelineWriter writer = stream.ObjectWriter; + PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, resolvedComputerNames[i]); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; @@ -872,7 +864,6 @@ namespace Microsoft.PowerShell.Commands }// end of for return remoteRunspaces; - }// CreateRunspacesWhenComputerNameParameterSpecified /// @@ -899,7 +890,7 @@ namespace Microsoft.PowerShell.Commands { Dbg.Assert((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet), "Expected ParameterSetName == VMId or VMName"); - + inputArraySize = this.VMName.Length; this.VMId = new Guid[inputArraySize]; command = "Get-VM -Name $args"; @@ -910,7 +901,7 @@ namespace Microsoft.PowerShell.Commands try { results = this.InvokeCommand.InvokeScript( - command, false, PipelineResultTypes.None, null, + command, false, PipelineResultTypes.None, null, isVMIdSet ? this.VMId[index].ToString() : this.VMName[index]); } catch (CommandNotFoundException) @@ -921,7 +912,7 @@ namespace Microsoft.PowerShell.Commands PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), ErrorCategory.NotInstalled, null)); - + return null; } @@ -934,7 +925,7 @@ namespace Microsoft.PowerShell.Commands WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, this.VMId[index].ToString(null))), PSRemotingErrorId.InvalidVMIdNotSingle.ToString(), ErrorCategory.InvalidArgument, @@ -948,7 +939,7 @@ namespace Microsoft.PowerShell.Commands WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, this.VMName[index])), PSRemotingErrorId.InvalidVMNameNotSingle.ToString(), ErrorCategory.InvalidArgument, @@ -969,12 +960,12 @@ namespace Microsoft.PowerShell.Commands { WriteError( new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, + new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName[index])), PSRemotingErrorId.InvalidVMState.ToString(), ErrorCategory.InvalidArgument, null)); - + continue; } } @@ -984,32 +975,32 @@ namespace Microsoft.PowerShell.Commands VMConnectionInfo connectionInfo; int rsId; string rsName = GetRunspaceName(index, out rsId); - + try { connectionInfo = new VMConnectionInfo(this.Credential, this.VMId[index], this.VMName[index], this.ConfigurationName); - + runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, rsName, rsId); - + remoteRunspaces.Add(runspace); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForVMFailed", + "CreateRemoteRunspaceForVMFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); } } @@ -1030,7 +1021,7 @@ namespace Microsoft.PowerShell.Commands Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet), "Expected ParameterSetName == ContainerId"); - + foreach (var input in ContainerId) { // @@ -1049,46 +1040,46 @@ namespace Microsoft.PowerShell.Commands // Windows Server container uses named pipe as transport. // connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName); - + resolvedNameList.Add(connectionInfo.ComputerName); - + connectionInfo.CreateContainerProcess(); - + runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, null, rsName, rsId); - + remoteRunspaces.Add(runspace); } catch (InvalidOperationException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); continue; } catch (ArgumentException e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidArgument, null); - + WriteError(errorRecord); continue; } catch (Exception e) { ErrorRecord errorRecord = new ErrorRecord(e, - "CreateRemoteRunspaceForContainerFailed", + "CreateRemoteRunspaceForContainerFailed", ErrorCategory.InvalidOperation, null); - + WriteError(errorRecord); continue; - } + } } ResolvedComputerNames = resolvedNameList.ToArray(); @@ -1112,9 +1103,9 @@ namespace Microsoft.PowerShell.Commands // runspace pool object, which in turn passes it on to the server during // construction. This way the friendly name can be returned when querying // the sever for disconnected sessions/runspaces. - if (names != null && rsIndex < names.Length) + if (_names != null && rsIndex < _names.Length) { - rsName = names[rsIndex]; + rsName = _names[rsIndex]; } return rsName; @@ -1130,22 +1121,22 @@ namespace Microsoft.PowerShell.Commands { if (disposing) { - throttleManager.Dispose(); + _throttleManager.Dispose(); // wait for all runspace operations to be complete - operationsComplete.WaitOne(); - operationsComplete.Dispose(); + _operationsComplete.WaitOne(); + _operationsComplete.Dispose(); - throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); - throttleManager = null; + _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + _throttleManager = null; - foreach (RemoteRunspace remoteRunspace in toDispose) + foreach (RemoteRunspace remoteRunspace in _toDispose) { remoteRunspace.Dispose(); } // Dispose all open operation objects, to remove runspace event callback. - foreach (List operationList in this.allOperations) + foreach (List operationList in _allOperations) { foreach (OpenRunspaceOperation operation in operationList) { @@ -1153,9 +1144,8 @@ namespace Microsoft.PowerShell.Commands } } - stream.Dispose(); + _stream.Dispose(); } - } // Dispose /// @@ -1166,10 +1156,9 @@ namespace Microsoft.PowerShell.Commands private void HandleThrottleComplete(object sender, EventArgs eventArgs) { // all operations are complete close the stream - stream.ObjectWriter.Close(); - - operationsComplete.Set(); + _stream.ObjectWriter.Close(); + _operationsComplete.Set(); } // HandleThrottleComplete /// @@ -1185,12 +1174,12 @@ namespace Microsoft.PowerShell.Commands e is ArgumentException || e is NotSupportedException, "Exception has to be of type UriFormatException or InvalidOperationException or ArgumentException or NotSupportedException"); - PipelineWriter writer = stream.ObjectWriter; + PipelineWriter writer = _stream.ObjectWriter; ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, uri); - Action errorWriter = delegate(Cmdlet cmdlet) + Action errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; @@ -1201,11 +1190,11 @@ namespace Microsoft.PowerShell.Commands #region Private Members - private ThrottleManager throttleManager = new ThrottleManager(); - private ObjectStream stream = new ObjectStream(); + private ThrottleManager _throttleManager = new ThrottleManager(); + private ObjectStream _stream = new ObjectStream(); // event that signals that all operations are // complete (including closing if any) - private ManualResetEvent operationsComplete = new ManualResetEvent(true); + private ManualResetEvent _operationsComplete = new ManualResetEvent(true); // the initial state is true because when no // operations actually take place as in case of a // parameter binding exception, then Dispose is @@ -1214,16 +1203,15 @@ namespace Microsoft.PowerShell.Commands // BeginProcessing() // list of runspaces to dispose - private List toDispose = new List(); + private List _toDispose = new List(); // List of runspace connect operations. Need to keep for cleanup. - private Collection> allOperations = new Collection>(); + private Collection> _allOperations = new Collection>(); // Default FQEID. private string _defaultFQEID = "PSSessionOpenFailed"; #endregion Private Members - }// NewRunspace #region Helper Classes @@ -1236,8 +1224,8 @@ namespace Microsoft.PowerShell.Commands { // Member variables to ensure that the ThrottleManager gets StartComplete // or StopComplete called only once per Start or Stop operation. - private bool startComplete; - private bool stopComplete; + private bool _startComplete; + private bool _stopComplete; private object _syncObject = new object(); @@ -1245,17 +1233,17 @@ namespace Microsoft.PowerShell.Commands { get { - return runspace; + return _runspace; } } - private RemoteRunspace runspace; + private RemoteRunspace _runspace; internal OpenRunspaceOperation(RemoteRunspace runspace) { - this.startComplete = true; - this.stopComplete = true; - this.runspace = runspace; - this.runspace.StateChanged += + _startComplete = true; + _stopComplete = true; + _runspace = runspace; + _runspace.StateChanged += new EventHandler(HandleRunspaceStateChanged); } @@ -1266,9 +1254,9 @@ namespace Microsoft.PowerShell.Commands { lock (_syncObject) { - this.startComplete = false; + _startComplete = false; } - runspace.OpenAsync(); + _runspace.OpenAsync(); } // StartOperation /// @@ -1281,17 +1269,17 @@ namespace Microsoft.PowerShell.Commands lock (_syncObject) { // Ignore stop operation if start operation has completed. - if (this.startComplete) + if (_startComplete) { - this.stopComplete = true; - this.startComplete = true; + _stopComplete = true; + _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); - operationStateEventArgs.BaseEvent = new RunspaceStateEventArgs(runspace.RunspaceStateInfo); + operationStateEventArgs.BaseEvent = new RunspaceStateEventArgs(_runspace.RunspaceStateInfo); operationStateEventArgs.OperationState = OperationState.StopComplete; } else { - this.stopComplete = false; + _stopComplete = false; } } @@ -1301,7 +1289,7 @@ namespace Microsoft.PowerShell.Commands } else { - runspace.CloseAsync(); + _runspace.CloseAsync(); } } @@ -1365,20 +1353,20 @@ namespace Microsoft.PowerShell.Commands lock (_syncObject) { // We must call OperationComplete ony *once* for each Start/Stop operation. - if (!this.stopComplete) + if (!_stopComplete) { // Note that the StopComplete callback removes *both* the Start and Stop // operations from their respective queues. So update the member vars // accordingly. - this.stopComplete = true; - this.startComplete = true; + _stopComplete = true; + _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StopComplete; } - else if (!this.startComplete) + else if (!_startComplete) { - this.startComplete = true; + _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StartComplete; @@ -1421,13 +1409,11 @@ namespace Microsoft.PowerShell.Commands { // Must remove the event callback from the new runspace or it will block other event // handling by throwing an exception on the event thread. - this.runspace.StateChanged -= HandleRunspaceStateChanged; + _runspace.StateChanged -= HandleRunspaceStateChanged; GC.SuppressFinalize(this); } - } // OpenRunspaceOperation #endregion Helper Classes - }//End namespace diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 854c80d1d..d2bfe024d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System; using System.Threading; using System.Collections.ObjectModel; @@ -18,7 +19,6 @@ using System.Management.Automation.Remoting.Client; namespace Microsoft.PowerShell.Commands { - /// /// This enum is used to distinguish two sets of parameters on some of the remoting cmdlets. /// @@ -102,7 +102,7 @@ namespace Microsoft.PowerShell.Commands #else bool notSupported = true; String WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; - + CheckHostRemotingPrerequisites(); try @@ -116,7 +116,7 @@ namespace Microsoft.PowerShell.Commands wsManStackValue = (string)wsManKey.GetValue("ServiceStackVersion"); } - Version wsManStackVersion = !string.IsNullOrEmpty(wsManStackValue) ? + Version wsManStackVersion = !string.IsNullOrEmpty(wsManStackValue) ? new Version(wsManStackValue.Trim()) : System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STACK_VERSION; diff --git a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs index 5778cd6d1..003f1650c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Remoting; - + using System.Management.Automation.Runspaces; using System.Management.Automation.Host; using System.Diagnostics.CodeAnalysis; @@ -47,20 +47,20 @@ namespace Microsoft.PowerShell.Commands Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, - ParameterSetName=RemovePSSessionCommand.SessionParameterSet)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] + ParameterSetName = RemovePSSessionCommand.SessionParameterSet)] + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSSession[] Session { get { - return remoteRunspaceInfos; + return _remoteRunspaceInfos; } set { - remoteRunspaceInfos = value; + _remoteRunspaceInfos = value; } } - private PSSession[] remoteRunspaceInfos; + private PSSession[] _remoteRunspaceInfos; /// /// ID of target container. @@ -73,10 +73,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public override string[] ContainerId { - get { return containerId; } - set { containerId = value; } + get { return _containerId; } + set { _containerId = value; } } - private string[] containerId; + private string[] _containerId; /// /// Guid of target virtual machine. @@ -90,10 +90,10 @@ namespace Microsoft.PowerShell.Commands [Alias("VMGuid")] public override Guid[] VMId { - get { return vmId; } - set { vmId = value; } + get { return _vmId; } + set { _vmId = value; } } - private Guid[] vmId; + private Guid[] _vmId; /// /// Name of target virtual machine. @@ -106,10 +106,10 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty] public override string[] VMName { - get { return vmName; } - set { vmName = value; } + get { return _vmName; } + set { _vmName = value; } } - private string[] vmName; + private string[] _vmName; #endregion Parameters @@ -143,7 +143,7 @@ namespace Microsoft.PowerShell.Commands break; case RemovePSSessionCommand.SessionParameterSet: { - toRemove = remoteRunspaceInfos; + toRemove = _remoteRunspaceInfos; } break; default: @@ -185,7 +185,7 @@ namespace Microsoft.PowerShell.Commands string msg = System.Management.Automation.Internal.StringUtil.Format( RemotingErrorIdStrings.RemoveRunspaceNotConnected, remoteRunspace.PSSessionName); Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "RemoveSessionCannotConnectToServer", + ErrorRecord errorRecord = new ErrorRecord(reason, "RemoveSessionCannotConnectToServer", ErrorCategory.InvalidOperation, remoteRunspace); WriteError(errorRecord); diff --git a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs index e3fb25f3c..eb0a96bc7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs @@ -8,7 +8,7 @@ using System.Collections; using System.Text; using System.Management.Automation; using System.Management.Automation.Runspaces; - + namespace System.Management.Automation { diff --git a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs index bc9df63f8..37755c8bc 100644 --- a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs index b93614a43..b7e6ac8a6 100644 --- a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs +++ b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/common/Indexer.cs b/src/System.Management.Automation/engine/remoting/common/Indexer.cs index 3fa7a999d..c4751a784 100644 --- a/src/System.Management.Automation/engine/remoting/common/Indexer.cs +++ b/src/System.Management.Automation/engine/remoting/common/Indexer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -61,7 +62,7 @@ namespace System.Management.Automation.Remoting [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private bool CheckLengthsNonNegative(int[] lengths) { - for (int i = 0 ; i < lengths.Length ; ++i) + for (int i = 0; i < lengths.Length; ++i) { if (lengths[i] < 0) { @@ -86,7 +87,7 @@ namespace System.Management.Automation.Remoting /// public void Reset() { - for (int i = 0 ; i < _current.Length ; ++i) + for (int i = 0; i < _current.Length; ++i) { _current[i] = 0; } @@ -103,7 +104,7 @@ namespace System.Management.Automation.Remoting /// public bool MoveNext() { - for (int i = _lengths.Length - 1 ; i >= 0 ; --i) + for (int i = _lengths.Length - 1; i >= 0; --i) { // See if we can increment this dimension. if (_current[i] < _lengths[i] - 1) diff --git a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs index ef258dadf..b0924a58f 100644 --- a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs +++ b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs index 57cc708b2..949d59de7 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Text; @@ -14,7 +15,7 @@ namespace System.Management.Automation.Internal /// /// Defines enumerations for the keywords /// - enum PSKeyword : ulong + internal enum PSKeyword : ulong { Runspace = 0x1, Pipeline = 0x2, @@ -32,7 +33,7 @@ namespace System.Management.Automation.Internal /// /// Define enumerations for levels /// - enum PSLevel : byte + internal enum PSLevel : byte { LogAlways = 0x0, Critical = 0x1, @@ -46,7 +47,7 @@ namespace System.Management.Automation.Internal /// /// Defines enumerations for op codes /// - enum PSOpcode : byte + internal enum PSOpcode : byte { WinStart = 0x1, WinStop = 0x2, @@ -54,7 +55,7 @@ namespace System.Management.Automation.Internal Close = 0xB, Connect = 0xC, Disconnect = 0xD, - Negotiate = 0xE, + Negotiate = 0xE, Create = 0xF, Constructor = 0x10, Dispose = 0x11, @@ -74,7 +75,7 @@ namespace System.Management.Automation.Internal /// add an entry for a new event that you /// add to the manifest. Set it to the same value /// that was set in the manifest - enum PSEventId : int + internal enum PSEventId : int { HostNameResolve = 0x1001, SchemeResolve = 0x1002, @@ -199,7 +200,7 @@ namespace System.Management.Automation.Internal /// /// Defines enumerations for channels /// - enum PSChannel : byte + internal enum PSChannel : byte { Operational = 0x10, Analytic = 0x11 @@ -208,7 +209,7 @@ namespace System.Management.Automation.Internal /// /// Defines enumerations for tasks /// - enum PSTask : int + internal enum PSTask : int { None = 0x0, CreateRunspace = 0x1, @@ -232,7 +233,7 @@ namespace System.Management.Automation.Internal /// /// all messages in V2 timeframe /// should be of version 1 - enum PSEventVersion : byte + internal enum PSEventVersion : byte { One = 0x1, } diff --git a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs index 8805e43ac..63f683902 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Collections; using System.Management.Automation.Runspaces; @@ -11,25 +12,25 @@ using Microsoft.PowerShell.CoreClr.Stubs; namespace System.Management.Automation { - /// - /// This is the base class from which other classes should derive. - /// This class defines the options for the specified configuration type. - /// - public abstract class PSSessionTypeOption - { - /// - /// Returns a xml formatted data that represents the options - /// - /// - protected internal virtual string ConstructPrivateData() - { - throw new NotImplementedException(); - } + /// + /// This is the base class from which other classes should derive. + /// This class defines the options for the specified configuration type. + /// + public abstract class PSSessionTypeOption + { + /// + /// Returns a xml formatted data that represents the options + /// + /// + protected internal virtual string ConstructPrivateData() + { + throw new NotImplementedException(); + } - /// - /// Returns a new instance constructed from privateData string. - /// - /// + /// + /// Returns a new instance constructed from privateData string. + /// + /// protected internal virtual PSSessionTypeOption ConstructObjectFromPrivateData(string privateData) { throw new NotImplementedException(); @@ -43,21 +44,21 @@ namespace System.Management.Automation { throw new NotImplementedException(); } - } + } - /// - /// This the abstract class that defines the options for underlying transport layer. - /// - public abstract class PSTransportOption : ICloneable - { - /// - /// Returns all the non-quota options set in this object in a format of xml attributes. - /// - /// - internal virtual string ConstructOptionsAsXmlAttributes() - { - throw new NotImplementedException(); - } + /// + /// This the abstract class that defines the options for underlying transport layer. + /// + public abstract class PSTransportOption : ICloneable + { + /// + /// Returns all the non-quota options set in this object in a format of xml attributes. + /// + /// + internal virtual string ConstructOptionsAsXmlAttributes() + { + throw new NotImplementedException(); + } /// /// Returns all the non-quota options set in this object in a name-value pair (hashtable). @@ -86,7 +87,8 @@ namespace System.Management.Automation throw new NotImplementedException(); } - internal void LoadFromDefaults(PSSessionType sessionType) { + internal void LoadFromDefaults(PSSessionType sessionType) + { LoadFromDefaults(sessionType, false); } @@ -97,7 +99,8 @@ namespace System.Management.Automation /// /// /// - protected internal virtual void LoadFromDefaults(PSSessionType sessionType, bool keepAssigned) { + protected internal virtual void LoadFromDefaults(PSSessionType sessionType, bool keepAssigned) + { throw new NotImplementedException(); } @@ -108,5 +111,5 @@ namespace System.Management.Automation { return this.MemberwiseClone(); } - } + } } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 2819e8c99..55fb1248d 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -28,10 +28,10 @@ namespace System.Management.Automation.Remoting internal class HyperVSocketEndPoint : EndPoint { #region Members - - private System.Net.Sockets.AddressFamily m_AddressFamily; - private Guid m_VmId; - private Guid m_ServiceId; + + private System.Net.Sockets.AddressFamily _addressFamily; + private Guid _vmId; + private Guid _serviceId; public const System.Net.Sockets.AddressFamily AF_HYPERV = (System.Net.Sockets.AddressFamily)34; public const int HYPERV_SOCK_ADDR_SIZE = 36; @@ -41,29 +41,29 @@ namespace System.Management.Automation.Remoting #region Constructor public HyperVSocketEndPoint(System.Net.Sockets.AddressFamily AddrFamily, - Guid VmId, - Guid ServiceId) + Guid VmId, + Guid ServiceId) { - m_AddressFamily = AddrFamily; - m_VmId = VmId; - m_ServiceId = ServiceId; + _addressFamily = AddrFamily; + _vmId = VmId; + _serviceId = ServiceId; } public override System.Net.Sockets.AddressFamily AddressFamily { - get { return m_AddressFamily; } + get { return _addressFamily; } } public Guid VmId { - get { return m_VmId; } - set { m_VmId = value; } + get { return _vmId; } + set { _vmId = value; } } - + public Guid ServiceId { - get { return m_ServiceId; } - set { m_VmId = value; } + get { return _serviceId; } + set { _vmId = value; } } #endregion @@ -73,22 +73,22 @@ namespace System.Management.Automation.Remoting public override EndPoint Create(SocketAddress SockAddr) { if (SockAddr == null || - SockAddr.Family != AF_HYPERV || + SockAddr.Family != AF_HYPERV || SockAddr.Size != 34) { return null; } - + HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(SockAddr.Family, Guid.Empty, Guid.Empty); - + string sockAddress = SockAddr.ToString(); endpoint.VmId = new Guid(sockAddress.Substring(4, 16)); endpoint.ServiceId = new Guid(sockAddress.Substring(20, 16)); - + return endpoint; } - + public override bool Equals(Object obj) { HyperVSocketEndPoint endpoint = (HyperVSocketEndPoint)obj; @@ -97,47 +97,47 @@ namespace System.Management.Automation.Remoting { return false; } - - if ((m_AddressFamily == endpoint.AddressFamily) && - (m_VmId == endpoint.VmId) && - (m_ServiceId == endpoint.ServiceId)) + + if ((_addressFamily == endpoint.AddressFamily) && + (_vmId == endpoint.VmId) && + (_serviceId == endpoint.ServiceId)) { return true; } - + return false; } - + public override int GetHashCode() { return Serialize().GetHashCode(); } - + public override SocketAddress Serialize() { - SocketAddress sockAddress = new SocketAddress((System.Net.Sockets.AddressFamily)m_AddressFamily, HYPERV_SOCK_ADDR_SIZE); - - byte[] vmId = m_VmId.ToByteArray(); - byte[] serviceId = m_ServiceId.ToByteArray(); + SocketAddress sockAddress = new SocketAddress((System.Net.Sockets.AddressFamily)_addressFamily, HYPERV_SOCK_ADDR_SIZE); + + byte[] vmId = _vmId.ToByteArray(); + byte[] serviceId = _serviceId.ToByteArray(); sockAddress[2] = (byte)0; - + for (int i = 0; i < vmId.Length; i++) { sockAddress[i + 4] = vmId[i]; } - + for (int i = 0; i < serviceId.Length; i++) { sockAddress[i + 4 + vmId.Length] = serviceId[i]; } - + return sockAddress; } - + public override string ToString() { - return m_VmId.ToString() + m_ServiceId.ToString(); + return _vmId.ToString() + _serviceId.ToString(); } #endregion @@ -212,7 +212,7 @@ namespace System.Management.Automation.Remoting int bytesRead; */ _syncObject = new object(); - + Exception ex = null; try @@ -265,15 +265,15 @@ namespace System.Management.Automation.Remoting // TODO: remove below 6 lines of code when .NET supports Hyper-V socket duplication Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2 HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, Guid.Empty, serviceId); - + Socket listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1); listenSocket.Bind(endpoint); - + listenSocket.Listen(1); _socket = listenSocket.Accept(); _networkStream = new NetworkStream(_socket, true); - + // Create reader/writer streams. _streamReader = new StreamReader(_networkStream); _streamWriter = new StreamWriter(_networkStream); @@ -286,8 +286,8 @@ namespace System.Management.Automation.Remoting // explicitly close listenSocket here for safe. // if (listenSocket != null) - { - try { listenSocket.Dispose(); } + { + try { listenSocket.Dispose(); } catch (ObjectDisposedException) { } } } @@ -296,11 +296,11 @@ namespace System.Management.Automation.Remoting CommandProcessorBase.CheckForSevereException(e); ex = e; } - + if (ex != null) { Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer."); - + // Unexpected error. string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty; _tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty, @@ -311,7 +311,7 @@ namespace System.Management.Automation.Remoting ex, PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure.ToString(), ErrorCategory.InvalidOperation, - null); + null); } } @@ -329,7 +329,7 @@ namespace System.Management.Automation.Remoting if (_disposed) { return; } _disposed = true; } - + if (_streamReader != null) { try { _streamReader.Dispose(); } @@ -345,14 +345,14 @@ namespace System.Management.Automation.Remoting } if (_networkStream != null) - { - try { _networkStream.Dispose(); } + { + try { _networkStream.Dispose(); } catch (ObjectDisposedException) { } } if (_socket != null) - { - try { _socket.Dispose(); } + { + try { _socket.Dispose(); } catch (ObjectDisposedException) { } } } @@ -373,7 +373,7 @@ namespace System.Management.Automation.Remoting private bool _disposed; private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - private static ManualResetEvent connectDone = + private static ManualResetEvent s_connectDone = new ManualResetEvent(false); #endregion @@ -445,7 +445,7 @@ namespace System.Management.Automation.Remoting bool isContainer = false) { Guid serviceId; - + _syncObject = new object(); if (isFirstConnection) @@ -474,7 +474,7 @@ namespace System.Management.Automation.Remoting try { - _socket.SetSocketOption((System.Net.Sockets.SocketOptionLevel)HV_PROTOCOL_RAW, + _socket.SetSocketOption((System.Net.Sockets.SocketOptionLevel)HV_PROTOCOL_RAW, (System.Net.Sockets.SocketOptionName)HVSOCKET_CONTAINER_PASSTHRU, (byte[])value); } @@ -500,7 +500,7 @@ namespace System.Management.Automation.Remoting if (_disposed) { return; } _disposed = true; } - + if (_streamReader != null) { try { _streamReader.Dispose(); } @@ -516,14 +516,14 @@ namespace System.Management.Automation.Remoting } if (_networkStream != null) - { - try { _networkStream.Dispose(); } + { + try { _networkStream.Dispose(); } catch (ObjectDisposedException) { } } if (_socket != null) - { - try { _socket.Dispose(); } + { + try { _socket.Dispose(); } catch (ObjectDisposedException) { } } } @@ -558,9 +558,9 @@ namespace System.Management.Automation.Remoting PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername)); } } - + _socket.Connect(_endPoint); - + if (_socket.Connected) { _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty, @@ -590,7 +590,7 @@ namespace System.Management.Automation.Remoting // _socket.Send(domain); _socket.Receive(response); - + _socket.Send(userName); _socket.Receive(response); @@ -608,7 +608,7 @@ namespace System.Management.Automation.Remoting { _socket.Send(Encoding.ASCII.GetBytes("NONEMPTYPW")); _socket.Receive(response); - + _socket.Send(password); _socket.Receive(response); responseString = Encoding.ASCII.GetString(response); @@ -620,7 +620,7 @@ namespace System.Management.Automation.Remoting // - "PASS": credentail is valid, but PowerShell Direct in VM does not support configuration (Server 2016 TP4 and before) // - "CONF": credentail is valid, and PowerShell Direct in VM supports configuration (Server 2016 TP5 and later) // - + // // Credential is invalid. // @@ -646,7 +646,7 @@ namespace System.Management.Automation.Remoting _socket.Send(Encoding.ASCII.GetBytes("NONEMPTYCF")); _socket.Receive(response); - Byte[] configName = Encoding.Unicode.GetBytes(configurationName); + Byte[] configName = Encoding.Unicode.GetBytes(configurationName); _socket.Send(configName); } } @@ -655,7 +655,7 @@ namespace System.Management.Automation.Remoting _socket.Send(response); } } - + _streamReader = new StreamReader(_networkStream); _streamWriter = new StreamWriter(_networkStream); _streamWriter.AutoFlush = true; @@ -664,7 +664,7 @@ namespace System.Management.Automation.Remoting } else { - _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty, + _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty, "Client unable to connect."); result = false; @@ -676,7 +676,7 @@ namespace System.Management.Automation.Remoting public void Close() { _networkStream.Dispose(); - _socket.Dispose(); + _socket.Dispose(); } #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index cc9ed26d3..f57805693 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -88,7 +88,7 @@ namespace System.Management.Automation.Remoting { throw new PSArgumentNullException("proc"); } - + if (string.IsNullOrEmpty(appDomainName)) { appDomainName = DefaultAppDomainName; @@ -329,7 +329,7 @@ namespace System.Management.Automation.Remoting private const int _namedPipeBufferSizeForRemoting = 32768; // Singleton server. - private static object SyncObject; + private static object s_syncObject; internal static RemoteSessionNamedPipeServer IPCNamedPipeServer; internal static bool IPCNamedPipeServerEnabled; @@ -530,7 +530,7 @@ namespace System.Management.Automation.Remoting static RemoteSessionNamedPipeServer() { - SyncObject = new object(); + s_syncObject = new object(); // All PowerShell instances will start with the named pipe // and listner created and running. @@ -575,8 +575,8 @@ namespace System.Management.Automation.Remoting } if (_serverPipeStream != null) - { - try { _serverPipeStream.Dispose(); } + { + try { _serverPipeStream.Dispose(); } catch (ObjectDisposedException) { } } } @@ -621,7 +621,7 @@ namespace System.Management.Automation.Remoting #region Private Methods private static CommonSecurityDescriptor GetServerPipeSecurity() - { + { // Built-in Admin SID SecurityIdentifier adminSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1); @@ -687,7 +687,7 @@ namespace System.Management.Automation.Remoting { // Begin listening for a client connect. this.WaitForConnection(); - + try { userName = WindowsIdentity.GetCurrent().Name; @@ -837,7 +837,7 @@ namespace System.Management.Automation.Remoting /// internal static void CreateIPCNamedPipeServerSingleton() { - lock (SyncObject) + lock (s_syncObject) { if (!IPCNamedPipeServerEnabled) { return; } @@ -975,7 +975,7 @@ namespace System.Management.Automation.Remoting { if (_streamReader != null) { - try { _streamReader.Dispose(); } + try { _streamReader.Dispose(); } catch (ObjectDisposedException) { } _streamReader = null; } @@ -989,7 +989,7 @@ namespace System.Management.Automation.Remoting if (_clientPipeStream != null) { - try { _clientPipeStream.Dispose(); } + try { _clientPipeStream.Dispose(); } catch (ObjectDisposedException) { } } } @@ -1033,7 +1033,7 @@ namespace System.Management.Automation.Remoting { } protected virtual NamedPipeClientStream DoConnect(int timeout) - { + { return null; } @@ -1074,7 +1074,7 @@ namespace System.Management.Automation.Remoting /// Target process Id for pipe. /// AppDomain name or null for default AppDomain public RemoteSessionNamedPipeClient( - int procId, string appDomainName) : + int procId, string appDomainName) : this(NamedPipeUtils.CreateProcessPipeName(procId, appDomainName)) { } @@ -1095,7 +1095,7 @@ namespace System.Management.Automation.Remoting // Defer creating the .Net NamedPipeClientStream object until we connect. // _clientPipeStream == null. } - + /// /// Constructor. /// @@ -1132,14 +1132,14 @@ namespace System.Management.Automation.Remoting #endregion #region Protected Methods - + protected override NamedPipeClientStream DoConnect(int timeout) { // Repeatedly attempt connection to pipe until timeout expires. int startTime = Environment.TickCount; int elapsedTime = 0; _connecting = true; - + do { // Wait in 100 mSec increments. @@ -1151,7 +1151,6 @@ namespace System.Management.Automation.Remoting _connecting = false; return OpenNamedPipe(); - } while (_connecting && (elapsedTime < timeout)); _connecting = false; @@ -1187,7 +1186,7 @@ namespace System.Management.Automation.Remoting { throw new System.ComponentModel.Win32Exception(lastError); } - + try { return new NamedPipeClientStream( @@ -1223,8 +1222,8 @@ namespace System.Management.Automation.Remoting /// AppDomain name or null for default AppDomain /// Container OB root. public ContainerSessionNamedPipeClient( - int procId, - string appDomainName, + int procId, + string appDomainName, string containerObRoot) { if (String.IsNullOrEmpty(containerObRoot)) @@ -1242,7 +1241,7 @@ namespace System.Management.Automation.Remoting #endregion #region Protected Methods - + /// /// Helper method to open a named pipe via native APIs and return in /// .Net NamedPipeClientStream wrapper object. @@ -1259,7 +1258,7 @@ namespace System.Management.Automation.Remoting int startTime = Environment.TickCount; int elapsedTime = 0; SafePipeHandle pipeHandle = null; - + do { // Get handle to pipe. @@ -1292,7 +1291,7 @@ namespace System.Management.Automation.Remoting break; } } while (elapsedTime < timeout); - + try { return new NamedPipeClientStream( diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index c567567a4..f878dfc35 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -19,6 +19,7 @@ using Dbg = System.Management.Automation.Diagnostics; using WSManAuthenticationMechanism = System.Management.Automation.Remoting.Client.WSManNativeApi.WSManAuthenticationMechanism; // ReSharper disable CheckNamespace + namespace System.Management.Automation.Runspaces // ReSharper restore CheckNamespace { @@ -156,7 +157,7 @@ namespace System.Management.Automation.Runspaces /// /// Authentication mechanism to use while connecting to the server /// - public abstract AuthenticationMechanism AuthenticationMechanism { get; set; } + public abstract AuthenticationMechanism AuthenticationMechanism { get; set; } /// /// ThumbPrint of a certificate used for connecting to a remote machine. @@ -172,7 +173,7 @@ namespace System.Management.Automation.Runspaces { get { - return culture; + return _culture; } set { @@ -180,11 +181,11 @@ namespace System.Management.Automation.Runspaces { throw new ArgumentNullException("value"); } - culture = value; + _culture = value; } } - - private CultureInfo culture = CultureInfo.CurrentCulture; + + private CultureInfo _culture = CultureInfo.CurrentCulture; /// /// UI culture that the remote session should use @@ -193,7 +194,7 @@ namespace System.Management.Automation.Runspaces { get { - return uiCulture; + return _uiCulture; } set { @@ -201,11 +202,11 @@ namespace System.Management.Automation.Runspaces { throw new ArgumentNullException("value"); } - uiCulture = value; + _uiCulture = value; } } - - private CultureInfo uiCulture = CultureInfo.CurrentUICulture; + + private CultureInfo _uiCulture = CultureInfo.CurrentUICulture; /// /// The duration (in ms) for which PowerShell remoting waits before timing out on a connection to a remote machine. @@ -215,16 +216,16 @@ namespace System.Management.Automation.Runspaces /// public int OpenTimeout { - get { return openTimeout; } + get { return _openTimeout; } set { - openTimeout = value; + _openTimeout = value; - if (this is WSManConnectionInfo && openTimeout == DefaultTimeout) + if (this is WSManConnectionInfo && _openTimeout == DefaultTimeout) { - openTimeout = DefaultOpenTimeout; + _openTimeout = DefaultOpenTimeout; } - else if (this is WSManConnectionInfo && openTimeout == InfiniteTimeout) + else if (this is WSManConnectionInfo && _openTimeout == InfiniteTimeout) { // this timeout value gets passed to a // timer associated with the session @@ -232,12 +233,11 @@ namespace System.Management.Automation.Runspaces // The timer constructor will throw an exception // for any value greater than Int32.MaxValue // hence this is the maximum possible limit - openTimeout = Int32.MaxValue; + _openTimeout = Int32.MaxValue; } - } } - private int openTimeout = DefaultOpenTimeout; + private int _openTimeout = DefaultOpenTimeout; internal const int DefaultOpenTimeout = 3 * 60 * 1000; // 3 minutes internal const int DefaultTimeout = -1; internal const int InfiniteTimeout = 0; @@ -252,12 +252,12 @@ namespace System.Management.Automation.Runspaces /// public int CancelTimeout { - get { return cancelTimeout; } - set { cancelTimeout = value; } + get { return _cancelTimeout; } + set { _cancelTimeout = value; } } - private int cancelTimeout = defaultCancelTimeout; + private int _cancelTimeout = defaultCancelTimeout; internal const int defaultCancelTimeout = BaseTransportManager.ClientCloseTimeoutMs; - + /// /// The duration for which PowerShell remoting waits before timing out /// for any operation. The user would like to tweak this timeout @@ -268,10 +268,10 @@ namespace System.Management.Automation.Runspaces /// public int OperationTimeout { - get { return operationTimeout; } - set { operationTimeout = value; } + get { return _operationTimeout; } + set { _operationTimeout = value; } } - private int operationTimeout = BaseTransportManager.ClientDefaultOperationTimeoutMs; + private int _operationTimeout = BaseTransportManager.ClientDefaultOperationTimeoutMs; /// /// The duration (in ms) for which a Runspace on server needs to wait before it declares the client dead and closes itself down. @@ -280,13 +280,13 @@ namespace System.Management.Automation.Runspaces /// public int IdleTimeout { - get { return idleTimeout; } + get { return _idleTimeout; } set { - idleTimeout = value; + _idleTimeout = value; } } - private int idleTimeout = DefaultIdleTimeout; + private int _idleTimeout = DefaultIdleTimeout; internal const int DefaultIdleTimeout = BaseTransportManager.UseServerDefaultIdleTimeout; /// @@ -295,10 +295,10 @@ namespace System.Management.Automation.Runspaces /// public int MaxIdleTimeout { - get { return maxIdleTimeout; } - internal set { maxIdleTimeout = value; } + get { return _maxIdleTimeout; } + internal set { _maxIdleTimeout = value; } } - private int maxIdleTimeout = Int32.MaxValue; + private int _maxIdleTimeout = Int32.MaxValue; /// /// Populates session options from a PSSessionOption instance. @@ -321,14 +321,14 @@ namespace System.Management.Automation.Runspaces this.UICulture = options.UICulture; } - this.openTimeout = TimeSpanToTimeOutMs(options.OpenTimeout); - this.cancelTimeout = TimeSpanToTimeOutMs(options.CancelTimeout); - this.operationTimeout = TimeSpanToTimeOutMs(options.OperationTimeout); + _openTimeout = TimeSpanToTimeOutMs(options.OpenTimeout); + _cancelTimeout = TimeSpanToTimeOutMs(options.CancelTimeout); + _operationTimeout = TimeSpanToTimeOutMs(options.OperationTimeout); // Special case for idle timeout. A value of milliseconds == -1 // (BaseTransportManager.UseServerDefaultIdleTimeout) is allowed for // specifying the default value on the server. - this.idleTimeout = (options.IdleTimeout.TotalMilliseconds >= BaseTransportManager.UseServerDefaultIdleTimeout && + _idleTimeout = (options.IdleTimeout.TotalMilliseconds >= BaseTransportManager.UseServerDefaultIdleTimeout && options.IdleTimeout.TotalMilliseconds < int.MaxValue) ? (int)(options.IdleTimeout.TotalMilliseconds) : int.MaxValue; } @@ -386,7 +386,7 @@ namespace System.Management.Automation.Runspaces /// /// Uri associated with this connection path /// - public Uri ConnectionUri + public Uri ConnectionUri { get { @@ -475,7 +475,7 @@ namespace System.Management.Automation.Runspaces { return _credential; } - set + set { // null or empty value allowed _credential = value; @@ -485,10 +485,10 @@ namespace System.Management.Automation.Runspaces /// /// /// - [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#ShellUri")] + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#ShellUri")] public string ShellUri { - get + get { return _shellUri; } @@ -526,7 +526,7 @@ namespace System.Management.Automation.Runspaces default: Dbg.Assert(false, "Invalid authentication mechanism detected."); return AuthenticationMechanism.Default; - } + } } set { @@ -725,7 +725,7 @@ namespace System.Management.Automation.Runspaces public PSCredential ProxyCredential { get { return _proxyCredential; } - set + set { if (_proxyAcessType == ProxyAccessType.None) { @@ -734,7 +734,7 @@ namespace System.Management.Automation.Runspaces throw new ArgumentException(message); } - _proxyCredential = value; + _proxyCredential = value; } } @@ -801,7 +801,7 @@ namespace System.Management.Automation.Runspaces /// Determines how server in disconnected state deals with cached output /// data when the cache becomes filled. /// - public OutputBufferingMode OutputBufferingMode + public OutputBufferingMode OutputBufferingMode { get { return _outputBufferingMode; } set { _outputBufferingMode = value; } @@ -858,7 +858,7 @@ namespace System.Management.Automation.Runspaces /// call on Runspace to finish /// Invalid /// scheme or invalid port is specified - [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.String,System.String,System.Int32,System.String,System.String,System.Management.Automation.PSCredential,System.Int64,System.Int64)", MessageId = "4#")] + [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.String,System.String,System.Int32,System.String,System.String,System.Management.Automation.PSCredential,System.Int64,System.Int64)", MessageId = "4#")] public WSManConnectionInfo(String scheme, String computerName, Int32 port, String appName, String shellUri, PSCredential credential, int openTimeout) @@ -889,7 +889,7 @@ namespace System.Management.Automation.Runspaces /// default in this case [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.String,System.String,System.Int32,System.String,System.String,System.Management.Automation.PSCredential)", MessageId = "4#")] public WSManConnectionInfo(String scheme, String computerName, Int32 port, String appName, - String shellUri, PSCredential credential): + String shellUri, PSCredential credential) : this(scheme, computerName, port, appName, shellUri, credential, DefaultOpenTimeout) { @@ -925,7 +925,7 @@ namespace System.Management.Automation.Runspaces public WSManConnectionInfo(bool useSsl, String computerName, Int32 port, String appName, String shellUri, PSCredential credential, int openTimeout) : - this(useSsl ? DefaultSslScheme : DefaultScheme, computerName, + this(useSsl ? DefaultSslScheme : DefaultScheme, computerName, port, appName, shellUri, credential, openTimeout) { } @@ -956,7 +956,7 @@ namespace System.Management.Automation.Runspaces /// When an /// uri representing an invalid path is specified [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.Uri,System.String,System.Management.Automation.PSCredential)", MessageId = "1#")] - public WSManConnectionInfo(Uri uri, String shellUri, PSCredential credential) + public WSManConnectionInfo(Uri uri, String shellUri, PSCredential credential) { if (uri == null) { @@ -983,7 +983,7 @@ namespace System.Management.Automation.Runspaces ConstructUri(uri.Scheme, uri.Host, uri.Port, - DefaultAppName); + s_defaultAppName); } else { @@ -1004,7 +1004,7 @@ namespace System.Management.Automation.Runspaces /// [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] public WSManConnectionInfo(Uri uri, String shellUri, String certificateThumbprint) - :this(uri, shellUri, (PSCredential)null) + : this(uri, shellUri, (PSCredential)null) { _thumbPrint = certificateThumbprint; } @@ -1021,7 +1021,6 @@ namespace System.Management.Automation.Runspaces public WSManConnectionInfo(Uri uri) : this(uri, DefaultShellUri, DefaultCredential) { - } #endregion Constructors @@ -1062,18 +1061,18 @@ namespace System.Management.Automation.Runspaces this.UseCompression = !(options.NoCompression); this.NoMachineProfile = options.NoMachineProfile; - this._proxyAcessType = options.ProxyAccessType; - this._proxyAuthentication = options.ProxyAuthentication; - this._proxyCredential = options.ProxyCredential; - this._skipCaCheck = options.SkipCACheck; - this._skipCnCheck = options.SkipCNCheck; - this._skipRevocationCheck = options.SkipRevocationCheck; - this._noEncryption = options.NoEncryption; - this._useUtf16 = options.UseUTF16; - this._includePortInSPN = options.IncludePortInSPN; + _proxyAcessType = options.ProxyAccessType; + _proxyAuthentication = options.ProxyAuthentication; + _proxyCredential = options.ProxyCredential; + _skipCaCheck = options.SkipCACheck; + _skipCnCheck = options.SkipCNCheck; + _skipRevocationCheck = options.SkipRevocationCheck; + _noEncryption = options.NoEncryption; + _useUtf16 = options.UseUTF16; + _includePortInSPN = options.IncludePortInSPN; - this._outputBufferingMode = options.OutputBufferingMode; - this._maxConnectionRetryCount = options.MaxConnectionRetryCount; + _outputBufferingMode = options.OutputBufferingMode; + _maxConnectionRetryCount = options.MaxConnectionRetryCount; } /// @@ -1100,10 +1099,10 @@ namespace System.Management.Automation.Runspaces result._shellUri = _shellUri; result._credential = _credential; result.UseDefaultWSManPort = UseDefaultWSManPort; - result._authMechanism = this._authMechanism; - result._maxUriRedirectionCount = this._maxUriRedirectionCount; - result._maxRecvdDataSizePerCommand = this._maxRecvdDataSizePerCommand; - result._maxRecvdObjectSize = this._maxRecvdObjectSize; + result._authMechanism = _authMechanism; + result._maxUriRedirectionCount = _maxUriRedirectionCount; + result._maxRecvdDataSizePerCommand = _maxRecvdDataSizePerCommand; + result._maxRecvdObjectSize = _maxRecvdObjectSize; result.OpenTimeout = this.OpenTimeout; result.IdleTimeout = this.IdleTimeout; result.MaxIdleTimeout = this.MaxIdleTimeout; @@ -1111,10 +1110,10 @@ namespace System.Management.Automation.Runspaces result.OperationTimeout = base.OperationTimeout; result.Culture = this.Culture; result.UICulture = this.UICulture; - result._thumbPrint = this._thumbPrint; - result._allowImplicitCredForNegotiate = this._allowImplicitCredForNegotiate; - result.UseCompression = this._useCompression; - result.NoMachineProfile = this._noMachineProfile; + result._thumbPrint = _thumbPrint; + result._allowImplicitCredForNegotiate = _allowImplicitCredForNegotiate; + result.UseCompression = _useCompression; + result.NoMachineProfile = _noMachineProfile; result._proxyAcessType = this.ProxyAccessType; result._proxyAuthentication = this.ProxyAuthentication; result._proxyCredential = this.ProxyCredential; @@ -1126,11 +1125,11 @@ namespace System.Management.Automation.Runspaces result._includePortInSPN = this.IncludePortInSPN; result._enableNetworkAccess = this.EnableNetworkAccess; result.UseDefaultWSManPort = this.UseDefaultWSManPort; - result._outputBufferingMode = this._outputBufferingMode; + result._outputBufferingMode = _outputBufferingMode; result.DisconnectedOn = this.DisconnectedOn; result.ExpiresOn = this.ExpiresOn; result.MaxConnectionRetryCount = this.MaxConnectionRetryCount; - + return result; } @@ -1195,7 +1194,7 @@ namespace System.Management.Automation.Runspaces return defaultValue; } - return (T) typeof(WSManConnectionInfo).GetProperty(property, typeof(T)).GetValue(wsCI, null); + return (T)typeof(WSManConnectionInfo).GetProperty(property, typeof(T)).GetValue(wsCI, null); } internal void SetConnectionUri(Uri newUri) @@ -1220,7 +1219,7 @@ namespace System.Management.Automation.Runspaces // Default scheme is http _scheme = scheme; if (string.IsNullOrEmpty(_scheme)) - { + { _scheme = DefaultScheme; } @@ -1257,7 +1256,7 @@ namespace System.Management.Automation.Runspaces } } } - PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method, + PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method, PSTask.CreateRunspace, PSKeyword.Runspace | PSKeyword.UseAlwaysAnalytic, _computerName); @@ -1295,7 +1294,7 @@ namespace System.Management.Automation.Runspaces _appName = appName; if (String.IsNullOrEmpty(_appName)) { - _appName = DefaultAppName; + _appName = s_defaultAppName; } // construct Uri @@ -1330,7 +1329,7 @@ namespace System.Management.Automation.Runspaces else { return result.Substring(WSManConnectionInfo.HttpScheme.Length + 3); - } + } } /// @@ -1346,7 +1345,7 @@ namespace System.Management.Automation.Runspaces /// private void ValidateSpecifiedAuthentication() { - if ((_authMechanism != WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION) + if ((_authMechanism != WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION) && (_thumbPrint != null)) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NewRunspaceAmbiguosAuthentication, @@ -1376,7 +1375,7 @@ namespace System.Management.Automation.Runspaces if (uri.AbsolutePath.Equals("/", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment)) { - appname = DefaultAppName; + appname = s_defaultAppName; ConstructUri(uri.Scheme, uri.Host, uri.Port, @@ -1399,7 +1398,7 @@ namespace System.Management.Automation.Runspaces private string _scheme = HttpScheme; private string _computerName = DefaultComputerName; - private string _appName = DefaultAppName; + private string _appName = s_defaultAppName; private Int32 _port = -1; private Uri _connectionUri = new Uri(LocalHostUriString); // uri of this connection private PSCredential _credential; // credentials to be used for this connection @@ -1440,7 +1439,7 @@ namespace System.Management.Automation.Runspaces /// Default maximum connection retry count. /// internal const int DefaultMaxConnectionRetryCount = 5; - + #if NOT_APPLY_PORT_DCR private static string DEFAULT_SCHEME = HTTP_SCHEME; internal static string DEFAULT_SSL_SCHEME = HTTPS_SCHEME; @@ -1461,7 +1460,7 @@ namespace System.Management.Automation.Runspaces /// for this. Look at /// get-item WSMan:\localhost\Client\URLPrefix /// - private static readonly String DefaultAppName = "/wsman"; + private static readonly String s_defaultAppName = "/wsman"; /// /// Default scheme. @@ -1530,7 +1529,7 @@ namespace System.Management.Automation.Runspaces /// current user /// private const PSCredential DefaultCredential = null; - + #endregion constants #region Internal members @@ -1639,12 +1638,12 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private PSCredential credential; - private AuthenticationMechanism authMechanism; - private ScriptBlock initScript; - private bool shouldRunsAs32; - private Version psVersion; - private PowerShellProcessInstance process; + private PSCredential _credential; + private AuthenticationMechanism _authMechanism; + private ScriptBlock _initScript; + private bool _shouldRunsAs32; + private Version _psVersion; + private PowerShellProcessInstance _process; #endregion @@ -1655,8 +1654,8 @@ namespace System.Management.Automation.Runspaces /// public ScriptBlock InitializationScript { - get { return initScript; } - set { initScript = value; } + get { return _initScript; } + set { _initScript = value; } } /// @@ -1665,8 +1664,8 @@ namespace System.Management.Automation.Runspaces /// public bool RunAs32 { - get { return shouldRunsAs32; } - set { shouldRunsAs32 = value; } + get { return _shouldRunsAs32; } + set { _shouldRunsAs32 = value; } } /// @@ -1674,14 +1673,14 @@ namespace System.Management.Automation.Runspaces /// public Version PSVersion { - get { return psVersion; } - set { psVersion = value; } + get { return _psVersion; } + set { _psVersion = value; } } internal PowerShellProcessInstance Process { - get { return process; } - set { process = value; } + get { return _process; } + set { _process = value; } } #endregion @@ -1702,11 +1701,11 @@ namespace System.Management.Automation.Runspaces /// public override PSCredential Credential { - get { return credential; } + get { return _credential; } set { - credential = value; - authMechanism = AuthenticationMechanism.Default; + _credential = value; + _authMechanism = AuthenticationMechanism.Default; } } @@ -1718,7 +1717,7 @@ namespace System.Management.Automation.Runspaces { get { - return authMechanism; + return _authMechanism; } set { @@ -1728,7 +1727,7 @@ namespace System.Management.Automation.Runspaces value.ToString(), AuthenticationMechanism.Default.ToString()); } - authMechanism = value; + _authMechanism = value; } } @@ -1746,7 +1745,7 @@ namespace System.Management.Automation.Runspaces public NewProcessConnectionInfo Copy() { - NewProcessConnectionInfo result = new NewProcessConnectionInfo(this.credential); + NewProcessConnectionInfo result = new NewProcessConnectionInfo(_credential); result.AuthenticationMechanism = this.AuthenticationMechanism; result.InitializationScript = this.InitializationScript; result.RunAs32 = this.RunAs32; @@ -1778,8 +1777,8 @@ namespace System.Management.Automation.Runspaces /// internal NewProcessConnectionInfo(PSCredential credential) { - this.credential = credential; - authMechanism = AuthenticationMechanism.Default; + _credential = credential; + _authMechanism = AuthenticationMechanism.Default; } #endregion @@ -1884,7 +1883,7 @@ namespace System.Management.Automation.Runspaces public override string ComputerName { get { return "localhost"; } - set { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } } /// @@ -1892,7 +1891,7 @@ namespace System.Management.Automation.Runspaces /// public override PSCredential Credential { - get { return _credential; } + get { return _credential; } set { @@ -1941,7 +1940,7 @@ namespace System.Management.Automation.Runspaces newCopy._authMechanism = this.AuthenticationMechanism; newCopy._credential = this.Credential; newCopy.ProcessId = this.ProcessId; - newCopy._appDomainName = this._appDomainName; + newCopy._appDomainName = _appDomainName; newCopy.OpenTimeout = this.OpenTimeout; return newCopy; @@ -1965,7 +1964,7 @@ namespace System.Management.Automation.Runspaces public sealed class VMConnectionInfo : RunspaceConnectionInfo { #region Private Data - + private AuthenticationMechanism _authMechanism; private PSCredential _credential; private const int _defaultOpenTimeout = 20000; /* 20 seconds. */ @@ -2168,7 +2167,7 @@ namespace System.Management.Automation.Runspaces /// public override PSCredential Credential { - get { return _credential; } + get { return _credential; } set { _credential = value; @@ -2252,7 +2251,7 @@ namespace System.Management.Automation.Runspaces { ContainerProc.CreateContainerProcess(); } - + /// /// Terminate process inside container. /// @@ -2274,15 +2273,15 @@ namespace System.Management.Automation.Runspaces { #region Private Data - private Guid runtimeId; - private string containerObRoot; - private string containerId; - private int processId; - private bool runAsAdmin = false; - private string configurationName; - private bool processTerminated = false; - private uint errorCode = 0; - private string errorMessage = string.Empty; + private Guid _runtimeId; + private string _containerObRoot; + private string _containerId; + private int _processId; + private bool _runAsAdmin = false; + private string _configurationName; + private bool _processTerminated = false; + private uint _errorCode = 0; + private string _errorMessage = string.Empty; private const uint NoError = 0; private const uint InvalidContainerId = 1; @@ -2299,8 +2298,8 @@ namespace System.Management.Automation.Runspaces /// public Guid RuntimeId { - get { return runtimeId; } - set { runtimeId = value; } + get { return _runtimeId; } + set { _runtimeId = value; } } /// @@ -2308,8 +2307,8 @@ namespace System.Management.Automation.Runspaces /// public string ContainerObRoot { - get { return containerObRoot; } - set { containerObRoot = value; } + get { return _containerObRoot; } + set { _containerObRoot = value; } } /// @@ -2317,8 +2316,8 @@ namespace System.Management.Automation.Runspaces /// public string ContainerId { - get { return containerId; } - set { containerId = value; } + get { return _containerId; } + set { _containerId = value; } } /// @@ -2326,8 +2325,8 @@ namespace System.Management.Automation.Runspaces /// internal int ProcessId { - get { return processId; } - set { processId = value; } + get { return _processId; } + set { _processId = value; } } /// @@ -2336,8 +2335,8 @@ namespace System.Management.Automation.Runspaces /// internal bool RunAsAdmin { - get { return runAsAdmin; } - set { runAsAdmin = value; } + get { return _runAsAdmin; } + set { _runAsAdmin = value; } } /// @@ -2345,8 +2344,8 @@ namespace System.Management.Automation.Runspaces /// internal string ConfigurationName { - get { return configurationName; } - set { configurationName = value; } + get { return _configurationName; } + set { _configurationName = value; } } /// @@ -2354,8 +2353,8 @@ namespace System.Management.Automation.Runspaces /// internal bool ProcessTerminated { - get { return processTerminated; } - set { processTerminated = value; } + get { return _processTerminated; } + set { _processTerminated = value; } } /// @@ -2363,8 +2362,8 @@ namespace System.Management.Automation.Runspaces /// internal uint ErrorCode { - get { return errorCode; } - set { errorCode = value; } + get { return _errorCode; } + set { _errorCode = value; } } /// @@ -2372,8 +2371,8 @@ namespace System.Management.Automation.Runspaces /// internal string ErrorMessage { - get { return errorMessage; } - set { errorMessage = value; } + get { return _errorMessage; } + set { _errorMessage = value; } } #endregion @@ -2411,35 +2410,35 @@ namespace System.Management.Automation.Runspaces [DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint HcsOpenComputeSystem( - string id, + string id, ref IntPtr computeSystem, ref string result); [DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint HcsGetComputeSystemProperties( - IntPtr computeSystem, - string propertyQuery, + IntPtr computeSystem, + string propertyQuery, ref string properties, ref string result); [DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint HcsCreateProcess( - IntPtr computeSystem, - string processParameters, + IntPtr computeSystem, + string processParameters, ref HCS_PROCESS_INFORMATION processInformation, - ref IntPtr process, - ref string reslt); + ref IntPtr process, + ref string reslt); [DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint HcsOpenProcess( - IntPtr computeSystem, - int processId, + IntPtr computeSystem, + int processId, ref IntPtr process, ref string result); [DllImport(PinvokeDllNames.CreateProcessInComputeSystemDllName, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint HcsTerminateProcess( - IntPtr process, + IntPtr process, ref string result); #endregion @@ -2463,9 +2462,9 @@ namespace System.Management.Automation.Runspaces } #endregion - + #region Public methods - + /// /// Create process inside container. /// @@ -2480,7 +2479,7 @@ namespace System.Management.Automation.Runspaces { case NoError: break; - + case InvalidContainerId: throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidContainerId, ContainerId)); @@ -2498,7 +2497,7 @@ namespace System.Management.Automation.Runspaces ContainerId)); } } - + /// /// Terminate process inside container. /// @@ -2533,7 +2532,7 @@ namespace System.Management.Automation.Runspaces } #endregion - + #region Private methods /// @@ -2549,7 +2548,7 @@ namespace System.Management.Automation.Runspaces Assembly hostComputeInteropAssembly = Assembly.Load(new AssemblyName("Microsoft.HostCompute.Interop, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); hostComputeInteropType = hostComputeInteropAssembly.GetType("Microsoft.HostCompute.Interop.HostComputeInterop"); } - + /// /// Create process inside container. /// @@ -2567,7 +2566,7 @@ namespace System.Management.Automation.Runspaces { IntPtr ComputeSystem = IntPtr.Zero; string resultString = String.Empty; - + result = HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString); if (result != 0) { @@ -2604,7 +2603,7 @@ namespace System.Management.Automation.Runspaces } } } - catch (Exception e) + catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); @@ -2631,7 +2630,7 @@ namespace System.Management.Automation.Runspaces ProcessId = processId; ErrorCode = error; } - + /// /// Terminate the process inside container. /// @@ -2642,7 +2641,7 @@ namespace System.Management.Automation.Runspaces IntPtr process = IntPtr.Zero; ProcessTerminated = false; - + if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0) { if (HcsOpenProcess(ComputeSystem, ProcessId, ref process, ref resultString) == 0) @@ -2664,20 +2663,20 @@ namespace System.Management.Automation.Runspaces { IntPtr ComputeSystem = IntPtr.Zero; string resultString = String.Empty; - + if (HcsOpenComputeSystem(ContainerId, ref ComputeSystem, ref resultString) == 0) { Type computeSystemPropertiesType; Type hostComputeInteropType; - + GetHostComputeInteropTypes(out computeSystemPropertiesType, out hostComputeInteropType); - + MethodInfo getComputeSystemPropertiesInfo = hostComputeInteropType.GetMethod("HcsGetComputeSystemProperties"); - - var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[]{ ComputeSystem }); + + var computeSystemPropertiesHandle = getComputeSystemPropertiesInfo.Invoke(null, new object[] { ComputeSystem }); RuntimeId = (Guid)computeSystemPropertiesType.GetProperty("RuntimeId").GetValue(computeSystemPropertiesHandle); - + // // Get container object root for Windows Server container. // @@ -2736,7 +2735,7 @@ namespace System.Management.Automation.Runspaces else { Thread executionThread = new Thread(new ThreadStart(threadProc)); - + executionThread.SetApartmentState(ApartmentState.MTA); executionThread.Start(); executionThread.Join(); @@ -2758,7 +2757,7 @@ namespace System.Management.Automation.Runspaces return errorMessage; } - + #endregion } } diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs index 535623189..65dcfd2af 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs @@ -23,25 +23,23 @@ namespace System.Management.Automation.Remoting /// /// Min Runspaces setting on the server runspace pool /// - internal int MinRunspaces + internal int MinRunspaces { get { - return minRunspaces; + return _minRunspaces; } - } /// /// Max Runspaces setting on the server runspace pool /// - internal int MaxRunspaces + internal int MaxRunspaces { get { - return maxRunspaces; + return _maxRunspaces; } - } /// @@ -51,13 +49,11 @@ namespace System.Management.Automation.Remoting /// internal RunspacePoolInitInfo(int minRS, int maxRS) { - minRunspaces = minRS; - maxRunspaces = maxRS; + _minRunspaces = minRS; + _maxRunspaces = maxRS; } - private int minRunspaces; - private int maxRunspaces; - + private int _minRunspaces; + private int _maxRunspaces; } - } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs index 830d9def6..7923bfec2 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs @@ -27,23 +27,22 @@ namespace System.Management.Automation /// /// State of the runspace pool when this event occured /// - public RunspacePoolState State + public RunspacePoolState State { get { - return state; + return _state; } - } /// /// Exception associated with that state /// - public Exception Reason + public Exception Reason { get { - return reason; + return _reason; } } @@ -55,12 +54,11 @@ namespace System.Management.Automation /// state change. Can be null public RunspacePoolStateInfo(RunspacePoolState state, Exception reason) { - this.state = state; - this.reason = reason; + _state = state; + _reason = reason; } - private RunspacePoolState state; - private Exception reason; + private RunspacePoolState _state; + private Exception _reason; } - } \ No newline at end of file diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index 192d741f0..7aa340f27 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -27,7 +27,7 @@ namespace System.Management.Automation /// public class RemotingEncodingException : RuntimeException { - #region Constructors + #region Constructors /// /// @@ -67,7 +67,7 @@ namespace System.Management.Automation { } - #endregion Constructors + #endregion Constructors } #endif // NOT_USED @@ -373,8 +373,8 @@ namespace System.Management.Automation internal const string ObjectType = "T"; internal const string ObjectValue = "V"; - - #endregion + + #endregion #region Command discovery pipeline @@ -441,14 +441,14 @@ namespace System.Management.Automation /// /// Properties used for serialization of PSEventArgs /// - internal const string PSEventArgsComputerName = "PSEventArgs.ComputerName"; - internal const string PSEventArgsRunspaceId = "PSEventArgs.RunspaceId"; - internal const string PSEventArgsEventIdentifier = "PSEventArgs.EventIdentifier"; + internal const string PSEventArgsComputerName = "PSEventArgs.ComputerName"; + internal const string PSEventArgsRunspaceId = "PSEventArgs.RunspaceId"; + internal const string PSEventArgsEventIdentifier = "PSEventArgs.EventIdentifier"; internal const string PSEventArgsSourceIdentifier = "PSEventArgs.SourceIdentifier"; - internal const string PSEventArgsTimeGenerated = "PSEventArgs.TimeGenerated"; - internal const string PSEventArgsSender = "PSEventArgs.Sender"; - internal const string PSEventArgsSourceArgs = "PSEventArgs.SourceArgs"; - internal const string PSEventArgsMessageData = "PSEventArgs.MessageData"; + internal const string PSEventArgsTimeGenerated = "PSEventArgs.TimeGenerated"; + internal const string PSEventArgsSender = "PSEventArgs.Sender"; + internal const string PSEventArgsSourceArgs = "PSEventArgs.SourceArgs"; + internal const string PSEventArgsMessageData = "PSEventArgs.MessageData"; #endregion PSEventArgs @@ -490,7 +490,7 @@ namespace System.Management.Automation InvalidDestination = 0x0, Client = 0x1, Server = 0x2, - Listener = 0x4, + Listener = 0x4, } /// @@ -572,7 +572,7 @@ namespace System.Management.Automation RemoteHostCallUsingPowerShellHost = 0x00041100, RemotePowerShellHostResponseData = 0x00041101, } - + /// /// Converts C# types to PSObject properties for embedding in PSObjects transported across the wire. /// @@ -581,7 +581,7 @@ namespace System.Management.Automation #region NotePropertyHelpers internal delegate T ValueGetterDelegate(); - + internal static void AddNoteProperty(PSObject pso, string propertyName, ValueGetterDelegate valueGetter) { T value = default(T); @@ -602,7 +602,6 @@ namespace System.Management.Automation valueGetter.Target == null ? string.Empty : valueGetter.Target.GetType().FullName, e.ToString(), e.InnerException == null ? string.Empty : e.InnerException.ToString()); - } try @@ -671,9 +670,9 @@ namespace System.Management.Automation /// internal static RemoteDataObject GenerateCreateRunspacePool( Guid clientRunspacePoolId, - int minRunspaces, - int maxRunspaces, - RemoteRunspacePoolInternal runspacePool, + int minRunspaces, + int maxRunspaces, + RemoteRunspacePoolInternal runspacePool, PSHost host, PSPrimitiveDictionary applicationArguments) { @@ -755,7 +754,6 @@ namespace System.Management.Automation Guid.Empty, string.Empty); } - } /// @@ -856,7 +854,7 @@ namespace System.Management.Automation Guid.Empty, dataAsPSObject); } - + /// /// This method generates a Remoting data structure handler message for /// that contains a repsonse to SetMaxRunspaces or SetMinRunspaces @@ -993,7 +991,7 @@ namespace System.Management.Automation Guid.Empty, dataAsPSObject); } - + /// /// This methods generates a Remoting data structure handler message for /// creating a command discovery pipeline on the server @@ -1100,7 +1098,7 @@ namespace System.Management.Automation PSInvocationSettings settings = shell.Settings; PSObject dataAsPSObject = CreateEmptyPSObject(); - Guid clientRunspacePoolId = Guid.Empty; + Guid clientRunspacePoolId = Guid.Empty; HostInfo hostInfo; PSNoteProperty hostInfoProperty; @@ -1170,7 +1168,7 @@ namespace System.Management.Automation /// | | Pool | | | | data | Dictionary| /// -------------------------------------------------------------------------------------- internal static RemoteDataObject GenerateApplicationPrivateData( - Guid clientRunspacePoolId, + Guid clientRunspacePoolId, PSPrimitiveDictionary applicationPrivateData) { PSObject dataAsPSObject = CreateEmptyPSObject(); @@ -1199,15 +1197,15 @@ namespace System.Management.Automation /// | | Pool | | | | StateInfo | Info | /// -------------------------------------------------------------------------------------- internal static RemoteDataObject GenerateRunspacePoolStateInfo( - Guid clientRunspacePoolId, + Guid clientRunspacePoolId, RunspacePoolStateInfo stateInfo) { // BUGBUG: This object creation needs to be relooked PSObject dataAsPSObject = CreateEmptyPSObject(); //Add State Property - PSNoteProperty stateProperty = - new PSNoteProperty(RemoteDataNameStrings.RunspaceState, + PSNoteProperty stateProperty = + new PSNoteProperty(RemoteDataNameStrings.RunspaceState, (int)(stateInfo.State)); dataAsPSObject.Properties.Add(stateProperty); @@ -1302,7 +1300,7 @@ namespace System.Management.Automation #endregion RunspacePool related #region PowerShell related - + /// /// This method creates a remoting data structure handler message for sending a powershell /// input data from the client to the server @@ -1524,7 +1522,7 @@ namespace System.Management.Automation { //Encode Pipeline StateInfo as PSObject PSObject dataAsPSObject = CreateEmptyPSObject(); - + //Convert the state to int and add as property PSNoteProperty stateProperty = new PSNoteProperty( RemoteDataNameStrings.PipelineState, (int)(stateInfo.State)); @@ -1587,7 +1585,7 @@ namespace System.Management.Automation private static PSNoteProperty GetExceptionProperty(Exception exception, string errorId, ErrorCategory category) { Dbg.Assert(exception != null, "Caller should validate the data"); - + ErrorRecord er = GetErrorRecordFromException(exception); if (er == null) { @@ -1615,13 +1613,13 @@ namespace System.Management.Automation /// | / | | | | | capability | | /// | S | | | | | | | /// -------------------------------------------------------------------------------------- - internal static RemoteDataObject GenerateClientSessionCapability(RemoteSessionCapability capability, + internal static RemoteDataObject GenerateClientSessionCapability(RemoteSessionCapability capability, Guid runspacePoolId) { PSObject temp = GenerateSessionCapability(capability); temp.Properties.Add( new PSNoteProperty(RemoteDataNameStrings.TimeZone, RemoteSessionCapability.GetCurrentTimeZoneInByteFormat())); - return RemoteDataObject.CreateFrom(capability.RemotingDestination, + return RemoteDataObject.CreateFrom(capability.RemotingDestination, RemotingDataType.SessionCapability, runspacePoolId, Guid.Empty, temp); } @@ -1646,7 +1644,6 @@ namespace System.Management.Automation } #endregion Session related - } /// @@ -1710,7 +1707,7 @@ namespace System.Management.Automation } else if (propertyValue == null) { - TypeInfo typeInfo = typeof (T).GetTypeInfo(); + TypeInfo typeInfo = typeof(T).GetTypeInfo(); if (!typeInfo.IsValueType) { @@ -1897,7 +1894,6 @@ namespace System.Management.Automation } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PublicKey); - } /// @@ -1942,12 +1938,12 @@ namespace System.Management.Automation } PSEventArgs eventArgs = new PSEventArgs( - computerName, - runspaceId, - eventIdentifier, - sourceIdentifier, - sender, - sourceArgs.ToArray(), + computerName, + runspaceId, + eventIdentifier, + sourceIdentifier, + sender, + sourceArgs.ToArray(), messageData == null ? null : PSObject.AsPSObject(messageData)); eventArgs.TimeGenerated = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PSEventArgsTimeGenerated); @@ -2017,8 +2013,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); } - int maxRS = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces); - int minRS = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MinRunspaces); + int maxRS = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces); + int minRS = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MinRunspaces); return new RunspacePoolInitInfo(minRS, maxRS); } @@ -2081,7 +2077,7 @@ namespace System.Management.Automation internal static Exception GetExceptionFromSerializedErrorRecord(object serializedErrorRecord) { ErrorRecord er = ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(serializedErrorRecord)); - + if (er == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord); @@ -2091,7 +2087,7 @@ namespace System.Management.Automation return er.Exception; } } - + /// /// Gets the output from the message /// @@ -2265,8 +2261,8 @@ namespace System.Management.Automation } ModuleSpecification[] fullyQualifiedName = null; - if(null != DeserializingTypeConverter.GetPropertyValue(dataAsPSObject, - RemoteDataNameStrings.DiscoveryFullyQualifiedModule, + if (null != DeserializingTypeConverter.GetPropertyValue(dataAsPSObject, + RemoteDataNameStrings.DiscoveryFullyQualifiedModule, DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk)) { IEnumerable tmp = EnumerateListProperty(dataAsPSObject, RemoteDataNameStrings.DiscoveryFullyQualifiedModule); @@ -2294,7 +2290,7 @@ namespace System.Management.Automation } else { - powerShell.AddParameter("Module", module); + powerShell.AddParameter("Module", module); } powerShell.AddParameter("ArgumentList", argumentList); return powerShell; @@ -2325,7 +2321,7 @@ namespace System.Management.Automation internal static bool GetAddToHistory(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); @@ -2393,11 +2389,11 @@ namespace System.Management.Automation Version psVersion = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PSVersion); Version serializationVersion = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.SerializationVersion); - + RemoteSessionCapability result = new RemoteSessionCapability( RemotingDestination.InvalidDestination, protocolVersion, psVersion, serializationVersion); - + if (dataAsPSObject.Properties[RemoteDataNameStrings.TimeZone] != null) { // Binary deserialization of timezone info via BinaryFormatter is unsafe, diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index 581d20f30..ae57dab60 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -99,7 +99,7 @@ namespace System.Management.Automation.Remoting { // Encode the parameters and wrap the array into an ArrayList and then into a PSObject. ArrayList parameterList = new ArrayList(); - for (int i = 0 ; i < parameters.Length ; ++i) + for (int i = 0; i < parameters.Length; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.EncodeObject(parameters[i]); parameterList.Add(parameter); @@ -114,10 +114,10 @@ namespace System.Management.Automation.Remoting private static object[] DecodeParameters(PSObject parametersPSObject, Type[] parameterTypes) { // Extract the ArrayList and decode the parameters. - ArrayList parameters = (ArrayList) parametersPSObject.BaseObject; + ArrayList parameters = (ArrayList)parametersPSObject.BaseObject; List decodedParameters = new List(); Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length"); - for (int i = 0 ; i < parameters.Count ; ++i) + for (int i = 0; i < parameters.Count; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]); decodedParameters.Add(parameter); @@ -242,7 +242,7 @@ namespace System.Management.Automation.Remoting { get { - return (MethodBase) _methodInfo.InterfaceType.GetMethod(_methodInfo.Name, _methodInfo.ParameterTypes); + return (MethodBase)_methodInfo.InterfaceType.GetMethod(_methodInfo.Name, _methodInfo.ParameterTypes); } } @@ -299,12 +299,12 @@ namespace System.Management.Automation.Remoting /// private object SelectTargetObject(PSHost host) { - if (host == null || host.UI == null ) { return null; } - if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } - if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; } - if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; } + if (host == null || host.UI == null) { return null; } + if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } + if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; } + if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; } if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return host.UI; } - if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; } + if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; } throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString()); } @@ -356,7 +356,7 @@ namespace System.Management.Automation.Remoting // (b) prepend "Message from Server XXXXX" to the text message if (_methodId == RemoteHostMethodId.PromptForCredential1 || _methodId == RemoteHostMethodId.PromptForCredential2) - { + { // modify the caption which is _parameters[0] string modifiedCaption = ModifyCaption((string)_parameters[0]); @@ -478,7 +478,7 @@ namespace System.Management.Automation.Remoting private String ModifyMessage(string message, string computerName) { string modifiedMessage = PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, + RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, computerName.ToUpper(), message); @@ -499,11 +499,11 @@ namespace System.Management.Automation.Remoting string resourceString) { string warning = PSRemotingErrorInvariants.FormatResourceString( - resourceString, + resourceString, computerName.ToUpper()); - return new RemoteHostCall(ServerDispatchTable.VoidCallId, - RemoteHostMethodId.WriteWarningLine, new object[] {warning}); + return new RemoteHostCall(ServerDispatchTable.VoidCallId, + RemoteHostMethodId.WriteWarningLine, new object[] { warning }); } /// @@ -628,7 +628,7 @@ namespace System.Management.Automation.Remoting { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); if (result == null) { return null; } - if (result is Exception) { return (Exception) result; } + if (result is Exception) { return (Exception)result; } throw RemoteHostExceptions.NewDecodingFailedException(); } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index 3ef503eaa..1748104db 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -141,7 +141,7 @@ namespace System.Management.Automation.Remoting // Rehydrate the collection from the array list. ArrayList arrayList = SafelyGetBaseObject(psObject); - IList collection = (IList) Activator.CreateInstance(collectionType); + IList collection = (IList)Activator.CreateInstance(collectionType); foreach (object element in arrayList) { collection.Add(DecodeObject(element, elementType)); @@ -197,7 +197,7 @@ namespace System.Management.Automation.Remoting // Rehydrate the dictionary from the hashtable. Hashtable hashtable = SafelyGetBaseObject(psObject); - IDictionary dictionary = (IDictionary) Activator.CreateInstance(dictionaryType); + IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType); foreach (object key in hashtable.Keys) { dictionary.Add( @@ -232,7 +232,7 @@ namespace System.Management.Automation.Remoting { if (obj is PSObject) { - return (PSObject) obj; + return (PSObject)obj; } else { @@ -325,7 +325,7 @@ namespace System.Management.Automation.Remoting if (obj is PSObject) { // The "is" keyword takes care of PSObject and subclasses. - return EncodePSObject((PSObject) obj); + return EncodePSObject((PSObject)obj); } else if (obj is ProgressRecord) { @@ -443,7 +443,7 @@ namespace System.Management.Automation.Remoting cred = new PSCredential((String)objAsPSObject.Properties["UserName"].Value, (SecureString)objAsPSObject.Properties["Password"].Value); } - catch(GetValueException) + catch (GetValueException) { cred = null; } @@ -557,7 +557,7 @@ namespace System.Management.Automation.Remoting // Rehydrate the array from the array list. ArrayList arrayList = SafelyGetBaseObject(psObject); object[] objects = new object[arrayList.Count]; - for (int i = 0 ; i < arrayList.Count ; ++i) + for (int i = 0; i < arrayList.Count; ++i) { objects[i] = DecodeObjectWithType(arrayList[i]); } @@ -605,7 +605,7 @@ namespace System.Management.Automation.Remoting private static bool ArrayIsZeroBased(Array array) { int rank = array.Rank; - for (int i = 0 ; i < rank ; ++i) + for (int i = 0; i < rank; ++i) { if (array.GetLowerBound(i) != 0) { @@ -627,7 +627,7 @@ namespace System.Management.Automation.Remoting Type elementType = arrayType.GetElementType(); int rank = array.Rank; int[] lengths = new int[rank]; - for (int i = 0 ; i < rank ; ++i) + for (int i = 0; i < rank; ++i) { lengths[i] = array.GetUpperBound(i) + 1; } @@ -662,7 +662,7 @@ namespace System.Management.Automation.Remoting // Extract lengths from psObject. PSObject psObjectContainingLengths = SafelyGetPropertyValue(psObject, RemoteDataNameStrings.MethodArrayLengths); ArrayList lengthsArrayList = SafelyGetBaseObject(psObjectContainingLengths); - int[] lengths = (int[]) lengthsArrayList.ToArray(typeof(int)); + int[] lengths = (int[])lengthsArrayList.ToArray(typeof(int)); // Reconstitute the array. Indexer indexer = new Indexer(lengths); @@ -723,7 +723,7 @@ namespace System.Management.Automation.Remoting // Rehydrate the dictionary from the hashtable. Hashtable hashtable = SafelyGetBaseObject(psObject); - IDictionary dictionary = (IDictionary) Activator.CreateInstance(dictionaryType); + IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType); foreach (object key in hashtable.Keys) { dictionary.Add( @@ -744,7 +744,7 @@ namespace System.Management.Automation.Remoting throw RemoteHostExceptions.NewDecodingFailedException(); } - return (T) psObject.BaseObject; + return (T)psObject.BaseObject; } /// @@ -754,7 +754,7 @@ namespace System.Management.Automation.Remoting { if (obj is T) { - return (T) obj; + return (T)obj; } throw RemoteHostExceptions.NewDecodingFailedException(); @@ -771,7 +771,7 @@ namespace System.Management.Automation.Remoting throw RemoteHostExceptions.NewDecodingFailedException(); } - return (T) propertyInfo.Value; + return (T)propertyInfo.Value; } } } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 12245fb70..e069bc3cc 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.IO; using System.Management.Automation.Host; @@ -25,11 +26,11 @@ namespace System.Management.Automation.Remoting private Version _psversion; private Version _serversion; private Version _protocolVersion; - internal Version ProtocolVersion - { - get - { - return _protocolVersion; + internal Version ProtocolVersion + { + get + { + return _protocolVersion; } set { @@ -45,7 +46,7 @@ namespace System.Management.Automation.Remoting private TimeZone _timeZone; #endif - private static byte[] _timeZoneInByteFormat; + private static byte[] s_timeZoneInByteFormat; /// /// Constructor for RemoteSessionCapability. @@ -58,7 +59,7 @@ namespace System.Management.Automation.Remoting // PS Version 3 is fully backward compatible with Version 2 // In the remoting protocol sense, nothing is changing between PS3 and PS2 // For negotiation to succeed with old client/servers we have to use 2. - _psversion = new Version(2,0); //PSVersionInfo.PSVersion; + _psversion = new Version(2, 0); //PSVersionInfo.PSVersion; _serversion = PSVersionInfo.SerializationVersion; _remotingDestination = remotingDestination; } @@ -103,11 +104,10 @@ namespace System.Management.Automation.Remoting /// internal static byte[] GetCurrentTimeZoneInByteFormat() { - if (null == _timeZoneInByteFormat) + if (null == s_timeZoneInByteFormat) { - #if CORECLR //TODO:CORECLR 'BinaryFormatter' is not in CORE CLR. Since this is TimeZone related and TimeZone is not available on CORE CLR so wait until we solve TimeZone issue. - _timeZoneInByteFormat = Utils.EmptyArray(); + s_timeZoneInByteFormat = Utils.EmptyArray(); #else Exception e = null; try @@ -119,19 +119,18 @@ namespace System.Management.Automation.Remoting stream.Seek(0, SeekOrigin.Begin); byte[] result = new byte[stream.Length]; stream.Read(result, 0, (int)stream.Length); - _timeZoneInByteFormat = result; + s_timeZoneInByteFormat = result; } - } - catch(ArgumentNullException ane) + catch (ArgumentNullException ane) { e = ane; } - catch(System.Runtime.Serialization.SerializationException sre) + catch (System.Runtime.Serialization.SerializationException sre) { e = sre; } - catch(System.Security.SecurityException se) + catch (System.Security.SecurityException se) { e = se; } @@ -140,12 +139,12 @@ namespace System.Management.Automation.Remoting // ignore it and dont try to serialize again. if (null != e) { - _timeZoneInByteFormat = Utils.EmptyArray(); + s_timeZoneInByteFormat = Utils.EmptyArray(); } #endif } - return _timeZoneInByteFormat; + return s_timeZoneInByteFormat; } #if !CORECLR // TimeZone Not In CoreCLR @@ -186,14 +185,14 @@ namespace System.Management.Automation.Remoting /// /// Data. /// - private Dictionary data; + private Dictionary _data; /// /// Private constructor to force use of Create. /// private HostDefaultData() { - this.data = new Dictionary(); + _data = new Dictionary(); } /// @@ -212,7 +211,7 @@ namespace System.Management.Automation.Remoting /// internal bool HasValue(HostDefaultDataId id) { - return this.data.ContainsKey(id); + return _data.ContainsKey(id); } /// @@ -220,7 +219,7 @@ namespace System.Management.Automation.Remoting /// internal void SetValue(HostDefaultDataId id, object dataValue) { - this.data[id] = dataValue; + _data[id] = dataValue; } /// @@ -229,7 +228,7 @@ namespace System.Management.Automation.Remoting internal object GetValue(HostDefaultDataId id) { object result; - this.data.TryGetValue(id, out result); + _data.TryGetValue(id, out result); return result; } @@ -481,7 +480,7 @@ namespace System.Management.Automation.Remoting else if (host is InternalHost) { // This nesting can only be one level deep. - host = ((InternalHost) host).ExternalHost; + host = ((InternalHost)host).ExternalHost; } // At this point we know for sure that the host is not null. diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index ed59b4902..749f26ba7 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -27,11 +27,11 @@ namespace System.Management.Automation.Remoting { #region Private Members - private RemotingDestination destination; - private RemotingDataType dataType; - private Guid runspacePoolId; - private Guid powerShellId; - private T data; + private RemotingDestination _destination; + private RemotingDataType _dataType; + private Guid _runspacePoolId; + private Guid _powerShellId; + private T _data; private const int destinationOffset = 0; private const int dataTypeOffset = 4; @@ -67,19 +67,19 @@ namespace System.Management.Automation.Remoting /// /// Actual payload. /// - protected RemoteDataObject(RemotingDestination destination, + protected RemoteDataObject(RemotingDestination destination, RemotingDataType dataType, - Guid runspacePoolId, - Guid powerShellId, + Guid runspacePoolId, + Guid powerShellId, T data) { - this.destination = destination; - this.dataType = dataType; - this.runspacePoolId = runspacePoolId; - this.powerShellId = powerShellId; - this.data = data; + _destination = destination; + _dataType = dataType; + _runspacePoolId = runspacePoolId; + _powerShellId = powerShellId; + _data = data; } - + #endregion Constructors #region Properties @@ -88,7 +88,7 @@ namespace System.Management.Automation.Remoting { get { - return destination; + return _destination; } } @@ -100,8 +100,8 @@ namespace System.Management.Automation.Remoting { get { - int dt = (int)dataType; - + int dt = (int)_dataType; + // get the most used ones in the top. if ((dt & PowerShellMask) == PowerShellMask) { @@ -126,7 +126,7 @@ namespace System.Management.Automation.Remoting { get { - return dataType; + return _dataType; } } @@ -134,7 +134,7 @@ namespace System.Management.Automation.Remoting { get { - return runspacePoolId; + return _runspacePoolId; } } @@ -142,7 +142,7 @@ namespace System.Management.Automation.Remoting { get { - return powerShellId; + return _powerShellId; } } @@ -150,7 +150,7 @@ namespace System.Management.Automation.Remoting { get { - return data; + return _data; } } @@ -167,7 +167,7 @@ namespace System.Management.Automation.Remoting /// internal static RemoteDataObject CreateFrom(RemotingDestination destination, RemotingDataType dataType, - Guid runspacePoolId, + Guid runspacePoolId, Guid powerShellId, T data) { @@ -191,7 +191,7 @@ namespace System.Management.Automation.Remoting if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength) { PSRemotingTransportException e = - new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject, + new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject, RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject, headerLength + FragmentedRemoteObject.HeaderLength); throw e; @@ -208,7 +208,7 @@ namespace System.Management.Automation.Remoting actualData = defragmentor.DeserializeToPSObject(serializedDataStream); } - T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T), + T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T), System.Globalization.CultureInfo.CurrentCulture); return new RemoteDataObject(destination, dataType, runspacePoolId, powerShellId, deserializedObject); @@ -230,9 +230,9 @@ namespace System.Management.Automation.Remoting Dbg.Assert(null != fragmentor, "Fragmentor cannot be null."); SerializeHeader(streamToWriteTo); - if (null != data) + if (null != _data) { - fragmentor.SerializeToBytes(data, streamToWriteTo); + fragmentor.SerializeToBytes(_data, streamToWriteTo); } return; @@ -255,9 +255,9 @@ namespace System.Management.Automation.Remoting // Serialize data type SerializeUInt((uint)DataType, streamToWriteTo); // Serialize runspace guid - SerializeGuid(runspacePoolId, streamToWriteTo); + SerializeGuid(_runspacePoolId, streamToWriteTo); // Serialize powershell guid - SerializeGuid(powerShellId, streamToWriteTo); + SerializeGuid(_powerShellId, streamToWriteTo); return; } @@ -302,7 +302,7 @@ namespace System.Management.Automation.Remoting private static Guid DeserializeGuid(Stream serializedDataStream) { Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid."); - + byte[] guidarray = new byte[16]; // Size of GUID. for (int idx = 0; idx < 16; idx++) @@ -347,14 +347,14 @@ namespace System.Management.Automation.Remoting /// internal new static RemoteDataObject CreateFrom(RemotingDestination destination, RemotingDataType dataType, - Guid runspacePoolId, + Guid runspacePoolId, Guid powerShellId, object data) { return new RemoteDataObject(destination, dataType, runspacePoolId, powerShellId, data); - } - + } + #endregion Constructors } } diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 00a8017c2..ff5d10cc0 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -33,7 +33,7 @@ namespace System.Management.Automation.Remoting private bool _isStartFragment; private bool _isEndFragment; private byte[] _blob; - private int _blobLength; + private int _blobLength; /// /// SFlag stands for the IsStartFragment. It is the bit value in the binary encoding. @@ -99,7 +99,7 @@ namespace System.Management.Automation.Remoting /// /// true if this is a EndFragment. /// - internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, + internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, bool isEndFragment) { Dbg.Assert((null != blob) || (blob.Length == 0), "Cannot create a fragment for null or empty data."); @@ -163,11 +163,10 @@ namespace System.Management.Automation.Remoting internal int BlobLength { get { return _blobLength; } - set + set { - - Dbg.Assert(value >= 0 , "BlobLength cannot be less than 0."); - _blobLength = value; + Dbg.Assert(value >= 0, "BlobLength cannot be less than 0."); + _blobLength = value; } } @@ -177,10 +176,10 @@ namespace System.Management.Automation.Remoting internal byte[] Blob { get { return _blob; } - set + set { Dbg.Assert(null != value, "Blob cannot be null"); - _blob = value; + _blob = value; } } @@ -235,7 +234,7 @@ namespace System.Management.Automation.Remoting byte[] result = new byte[totalLength]; int idx = 0; - + // release build will optimize the calculation of the constants // ObjectId @@ -263,9 +262,9 @@ namespace System.Management.Automation.Remoting // E-flag and S-Flag idx = _flagsOffset; byte s_flag = IsStartFragment ? SFlag : (byte)0; - byte e_flag = IsEndFragment? EFlag : (byte)0; + byte e_flag = IsEndFragment ? EFlag : (byte)0; - result[idx++] = (byte)(s_flag | e_flag ); + result[idx++] = (byte)(s_flag | e_flag); // BlobLength idx = _blobLengthOffset; @@ -426,7 +425,7 @@ namespace System.Management.Automation.Remoting { Dbg.Assert(null != fragmentBytes, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode blob length."); - + int blobLength = 0; int idx = startIndex + _blobLengthOffset; @@ -436,7 +435,7 @@ namespace System.Management.Automation.Remoting blobLength += ((int)fragmentBytes[idx++]) & 0xFF; return blobLength; - } + } } @@ -448,35 +447,35 @@ namespace System.Management.Automation.Remoting internal class SerializedDataStream : Stream, IDisposable { [TraceSourceAttribute("SerializedDataStream", "SerializedDataStream")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); #region Global Constants - - static private long _objectIdSequenceNumber = 0; - + + static private long s_objectIdSequenceNumber = 0; + #endregion #region Private Data - private bool isEntered; - private FragmentedRemoteObject currentFragment; - private long fragmentId; + private bool _isEntered; + private FragmentedRemoteObject _currentFragment; + private long _fragmentId; - private int fragmentSize; - private object syncObject; - private bool isDisposed; - private bool notifyOnWriteFragmentImmediately; + private int _fragmentSize; + private object _syncObject; + private bool _isDisposed; + private bool _notifyOnWriteFragmentImmediately; // MemoryStream does not dynamically resize as data is read. This will waste // lot of memory as data sent on the network will still be there in memory. // To avoid this a queue of memory streams (each stream is of fragmentsize) // is created..so after data is sent the MemoryStream is disposed there by // clearing resources. - private Queue queuedStreams; - private MemoryStream writeStream; - private MemoryStream readStream; - private int writeOffset; - private int readOffSet; - private long length; + private Queue _queuedStreams; + private MemoryStream _writeStream; + private MemoryStream _readStream; + private int _writeOffset; + private int _readOffSet; + private long _length; /// /// Callback that is called once a fragmented data is available. @@ -487,8 +486,8 @@ namespace System.Management.Automation.Remoting /// /// true if data represents EndFragment of an object. /// - internal delegate void OnDataAvailableCallback(byte[] data, bool isEndFragment); - private OnDataAvailableCallback onDataAvailableCallback; + internal delegate void OnDataAvailableCallback(byte[] data, bool isEndFragment); + private OnDataAvailableCallback _onDataAvailableCallback; #endregion @@ -502,12 +501,12 @@ namespace System.Management.Automation.Remoting /// internal SerializedDataStream(int fragmentSize) { - _trace.WriteLine("Creating SerializedDataStream with fragmentsize : {0}", fragmentSize); + s_trace.WriteLine("Creating SerializedDataStream with fragmentsize : {0}", fragmentSize); Dbg.Assert(fragmentSize > 0, "fragmentsize should be greater than 0."); - syncObject = new object(); - currentFragment = new FragmentedRemoteObject(); - queuedStreams = new Queue(); - this.fragmentSize = fragmentSize; + _syncObject = new object(); + _currentFragment = new FragmentedRemoteObject(); + _queuedStreams = new Queue(); + _fragmentSize = fragmentSize; } /// @@ -528,8 +527,8 @@ namespace System.Management.Automation.Remoting { if (null != callbackToNotify) { - notifyOnWriteFragmentImmediately = true; - onDataAvailableCallback = callbackToNotify; + _notifyOnWriteFragmentImmediately = true; + _onDataAvailableCallback = callbackToNotify; } } @@ -544,16 +543,16 @@ namespace System.Management.Automation.Remoting /// internal void Enter() { - Dbg.Assert(!isEntered, "Stream is already entered. You cannot enter into stream again."); - isEntered = true; - fragmentId = 0; + Dbg.Assert(!_isEntered, "Stream is already entered. You cannot enter into stream again."); + _isEntered = true; + _fragmentId = 0; // Initialize the current fragment - currentFragment.ObjectId = GetObjectId(); - currentFragment.FragmentId = fragmentId; - currentFragment.IsStartFragment = true; - currentFragment.BlobLength = 0; - currentFragment.Blob = new byte[fragmentSize]; + _currentFragment.ObjectId = GetObjectId(); + _currentFragment.FragmentId = _fragmentId; + _currentFragment.IsStartFragment = true; + _currentFragment.BlobLength = 0; + _currentFragment.Blob = new byte[_fragmentSize]; } /// @@ -562,12 +561,12 @@ namespace System.Management.Automation.Remoting /// internal void Exit() { - isEntered = false; + _isEntered = false; // write left over data - if (currentFragment.BlobLength > 0) + if (_currentFragment.BlobLength > 0) { // this is endfragment...as we are in Exit - currentFragment.IsEndFragment = true; + _currentFragment.IsEndFragment = true; WriteCurrentFragmentAndReset(); } } @@ -587,22 +586,22 @@ namespace System.Management.Automation.Remoting /// public override void Write(byte[] buffer, int offset, int count) { - Dbg.Assert(isEntered, "Stream should be Entered before writing into."); + Dbg.Assert(_isEntered, "Stream should be Entered before writing into."); int offsetToReadFrom = offset; int amountLeft = count; while (amountLeft > 0) { - int dataLeftInTheFragment = fragmentSize - FragmentedRemoteObject.HeaderLength - currentFragment.BlobLength; + int dataLeftInTheFragment = _fragmentSize - FragmentedRemoteObject.HeaderLength - _currentFragment.BlobLength; if (dataLeftInTheFragment > 0) { int amountToWriteIntoFragment = (amountLeft > dataLeftInTheFragment) ? dataLeftInTheFragment : amountLeft; amountLeft = amountLeft - amountToWriteIntoFragment; // Write data into fragment - Array.Copy(buffer, offsetToReadFrom, currentFragment.Blob, currentFragment.BlobLength, amountToWriteIntoFragment); - currentFragment.BlobLength += amountToWriteIntoFragment; + Array.Copy(buffer, offsetToReadFrom, _currentFragment.Blob, _currentFragment.BlobLength, amountToWriteIntoFragment); + _currentFragment.BlobLength += amountToWriteIntoFragment; offsetToReadFrom += amountToWriteIntoFragment; // write only if amountLeft is more than 0. I dont write if amountLeft is 0 as we are not @@ -625,7 +624,7 @@ namespace System.Management.Automation.Remoting /// public override void WriteByte(byte value) { - Dbg.Assert(isEntered, "Stream should be Entered before writing into."); + Dbg.Assert(_isEntered, "Stream should be Entered before writing into."); byte[] buffer = new byte[1]; buffer[0] = value; Write(buffer, 0, 1); @@ -644,15 +643,15 @@ namespace System.Management.Automation.Remoting /// internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback) { - lock (syncObject) + lock (_syncObject) { - if (length <= 0) + if (_length <= 0) { - onDataAvailableCallback = callback; + _onDataAvailableCallback = callback; return null; } - int bytesToRead = length > fragmentSize ? fragmentSize : (int)length; + int bytesToRead = _length > _fragmentSize ? _fragmentSize : (int)_length; byte[] result = new byte[bytesToRead]; Read(result, 0, bytesToRead); return result; @@ -665,15 +664,14 @@ namespace System.Management.Automation.Remoting /// internal byte[] Read() { - lock (syncObject) + lock (_syncObject) { - - if (isDisposed) + if (_isDisposed) { return null; } - int bytesToRead = length > fragmentSize ? fragmentSize : (int)length; + int bytesToRead = _length > _fragmentSize ? _fragmentSize : (int)_length; if (bytesToRead > 0) { byte[] result = new byte[bytesToRead]; @@ -683,7 +681,7 @@ namespace System.Management.Automation.Remoting else { return null; - } + } } } @@ -701,58 +699,58 @@ namespace System.Management.Automation.Remoting Collection memoryStreamsToDispose = new Collection(); MemoryStream prevReadStream = null; - lock (syncObject) + lock (_syncObject) { // technically this should throw an exception..but remoting callstack // is optimized ie., we are not locking in every layer (in powershell) // to save on performance..as a result there may be cases where // upper layer is trying to add stuff and stream is disposed while // adding stuff. - if (isDisposed) + if (_isDisposed) { return 0; } - while(dataWritten < count) + while (dataWritten < count) { - if (null == readStream) + if (null == _readStream) { - if (queuedStreams.Count > 0) + if (_queuedStreams.Count > 0) { - readStream = queuedStreams.Dequeue(); - if ((!readStream.CanRead) || (prevReadStream == readStream)) + _readStream = _queuedStreams.Dequeue(); + if ((!_readStream.CanRead) || (prevReadStream == _readStream)) { // if the stream is disposed CanRead returns false // this will happen if a Write enqueues the stream // and a Read reads the data without dequeuing - readStream = null; + _readStream = null; continue; } } else { - readStream = writeStream; + _readStream = _writeStream; } - Dbg.Assert(readStream.Length > 0, "Not enough data to read."); - readOffSet = 0; + Dbg.Assert(_readStream.Length > 0, "Not enough data to read."); + _readOffSet = 0; } - readStream.Position = readOffSet; - int result = readStream.Read(buffer, offSetToWriteTo, count - dataWritten); - _trace.WriteLine("Read {0} data from readstream: {1}", result, readStream.GetHashCode()); + _readStream.Position = _readOffSet; + int result = _readStream.Read(buffer, offSetToWriteTo, count - dataWritten); + s_trace.WriteLine("Read {0} data from readstream: {1}", result, _readStream.GetHashCode()); dataWritten += result; offSetToWriteTo += result; - readOffSet += result; - length -= result; + _readOffSet += result; + _length -= result; // dispose only if we dont read from the current write stream. - if ((readStream.Capacity == readOffSet) && (readStream != writeStream)) + if ((_readStream.Capacity == _readOffSet) && (_readStream != _writeStream)) { - _trace.WriteLine("Adding readstream {0} to dispose collection.", readStream.GetHashCode()); - memoryStreamsToDispose.Add(readStream); - prevReadStream = readStream; - readStream = null; + s_trace.WriteLine("Adding readstream {0} to dispose collection.", _readStream.GetHashCode()); + memoryStreamsToDispose.Add(_readStream); + prevReadStream = _readStream; + _readStream = null; } } } @@ -760,7 +758,7 @@ namespace System.Management.Automation.Remoting // Dispose the memory streams outside of the lock foreach (MemoryStream streamToDispose in memoryStreamsToDispose) { - _trace.WriteLine("Disposing stream: {0}", streamToDispose.GetHashCode()); + s_trace.WriteLine("Disposing stream: {0}", streamToDispose.GetHashCode()); streamToDispose.Dispose(); } @@ -773,15 +771,15 @@ namespace System.Management.Automation.Remoting PSEtwLog.LogAnalyticVerbose( PSEventId.SentRemotingFragment, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - (Int64)(currentFragment.ObjectId), - (Int64)(currentFragment.FragmentId), - currentFragment.IsStartFragment ? 1 : 0, - currentFragment.IsEndFragment ? 1 : 0, - (UInt32)(currentFragment.BlobLength), - new PSETWBinaryBlob(currentFragment.Blob, 0, currentFragment.BlobLength)); + (Int64)(_currentFragment.ObjectId), + (Int64)(_currentFragment.FragmentId), + _currentFragment.IsStartFragment ? 1 : 0, + _currentFragment.IsEndFragment ? 1 : 0, + (UInt32)(_currentFragment.BlobLength), + new PSETWBinaryBlob(_currentFragment.Blob, 0, _currentFragment.BlobLength)); // finally write into memory stream - byte[] data = currentFragment.GetBytes(); + byte[] data = _currentFragment.GetBytes(); int amountLeft = data.Length; int offSetToReadFrom = 0; @@ -789,72 +787,72 @@ namespace System.Management.Automation.Remoting // to write into memory stream..instead give the // data directly to user and let him figure out what to do. // This will save write + read + dispose!! - if (!notifyOnWriteFragmentImmediately) + if (!_notifyOnWriteFragmentImmediately) { - lock (syncObject) + lock (_syncObject) { // technically this should throw an exception..but remoting callstack // is optimized ie., we are not locking in every layer (in powershell) // to save on performance..as a result there may be cases where // upper layer is trying to add stuff and stream is disposed while // adding stuff. - if (isDisposed) + if (_isDisposed) { return; } - if (null == writeStream) + if (null == _writeStream) { - writeStream = new MemoryStream(fragmentSize); - _trace.WriteLine("Created write stream: {0}", writeStream.GetHashCode()); - writeOffset = 0; + _writeStream = new MemoryStream(_fragmentSize); + s_trace.WriteLine("Created write stream: {0}", _writeStream.GetHashCode()); + _writeOffset = 0; } while (amountLeft > 0) { - int dataLeftInWriteStream = writeStream.Capacity - writeOffset; + int dataLeftInWriteStream = _writeStream.Capacity - _writeOffset; if (dataLeftInWriteStream == 0) { // enqueue the current write stream and create a new one. EnqueueWriteStream(); - dataLeftInWriteStream = writeStream.Capacity - writeOffset; + dataLeftInWriteStream = _writeStream.Capacity - _writeOffset; } int amountToWriteIntoStream = (amountLeft > dataLeftInWriteStream) ? dataLeftInWriteStream : amountLeft; amountLeft = amountLeft - amountToWriteIntoStream; // write data - writeStream.Position = writeOffset; - writeStream.Write(data, offSetToReadFrom, amountToWriteIntoStream); + _writeStream.Position = _writeOffset; + _writeStream.Write(data, offSetToReadFrom, amountToWriteIntoStream); offSetToReadFrom += amountToWriteIntoStream; - writeOffset += amountToWriteIntoStream; - length += amountToWriteIntoStream; + _writeOffset += amountToWriteIntoStream; + _length += amountToWriteIntoStream; } } } // call the callback since we have data available - if (null != onDataAvailableCallback) + if (null != _onDataAvailableCallback) { - onDataAvailableCallback(data, currentFragment.IsEndFragment); + _onDataAvailableCallback(data, _currentFragment.IsEndFragment); } // prepare a new fragment - currentFragment.FragmentId = ++fragmentId; - currentFragment.IsStartFragment = false; - currentFragment.IsEndFragment = false; - currentFragment.BlobLength = 0; - currentFragment.Blob = new byte[fragmentSize]; + _currentFragment.FragmentId = ++_fragmentId; + _currentFragment.IsStartFragment = false; + _currentFragment.IsEndFragment = false; + _currentFragment.BlobLength = 0; + _currentFragment.Blob = new byte[_fragmentSize]; } private void EnqueueWriteStream() { - _trace.WriteLine("Queuing write stream: {0} Length: {1} Capacity: {2}", - writeStream.GetHashCode(), writeStream.Length, writeStream.Capacity); - queuedStreams.Enqueue(writeStream); - - writeStream = new MemoryStream(fragmentSize); - writeOffset = 0; - _trace.WriteLine("Created write stream: {0}", writeStream.GetHashCode()); + s_trace.WriteLine("Queuing write stream: {0} Length: {1} Capacity: {2}", + _writeStream.GetHashCode(), _writeStream.Length, _writeStream.Capacity); + _queuedStreams.Enqueue(_writeStream); + + _writeStream = new MemoryStream(_fragmentSize); + _writeOffset = 0; + s_trace.WriteLine("Created write stream: {0}", _writeStream.GetHashCode()); } /// /// This method provides a thread safe way to get an object id. @@ -864,7 +862,7 @@ namespace System.Management.Automation.Remoting /// private static long GetObjectId() { - return System.Threading.Interlocked.Increment(ref _objectIdSequenceNumber); + return System.Threading.Interlocked.Increment(ref s_objectIdSequenceNumber); } #endregion @@ -875,9 +873,9 @@ namespace System.Management.Automation.Remoting { if (disposing) { - lock (syncObject) + lock (_syncObject) { - foreach (MemoryStream streamToDispose in queuedStreams) + foreach (MemoryStream streamToDispose in _queuedStreams) { // make sure we dispose only once. if (streamToDispose.CanRead) @@ -886,17 +884,17 @@ namespace System.Management.Automation.Remoting } } - if ((null != readStream) && (readStream.CanRead)) + if ((null != _readStream) && (_readStream.CanRead)) { - readStream.Dispose(); + _readStream.Dispose(); } - if ((null != writeStream) && (writeStream.CanRead)) + if ((null != _writeStream) && (_writeStream.CanRead)) { - writeStream.Dispose(); + _writeStream.Dispose(); } - isDisposed = true; + _isDisposed = true; } } } @@ -904,7 +902,7 @@ namespace System.Management.Automation.Remoting #endregion #region Stream Overrides - + /// /// /// @@ -920,7 +918,7 @@ namespace System.Management.Automation.Remoting /// /// Gets the length of the stream in bytes. /// - public override long Length { get { return length; } } + public override long Length { get { return _length; } } /// /// /// @@ -954,19 +952,19 @@ namespace System.Management.Automation.Remoting { throw new NotSupportedException(); } - + #endregion #region IDisposable Members - private bool disposed = false; + private bool _disposed = false; public new void Dispose() { - if (!this.disposed) + if (!_disposed) { GC.SuppressFinalize(this); - this.disposed = true; + _disposed = true; } base.Dispose(); } @@ -983,7 +981,7 @@ namespace System.Management.Automation.Remoting internal class Fragmentor { #region Global Constants - static private UTF8Encoding _utf8Encoding = new UTF8Encoding(); + static private UTF8Encoding s_utf8Encoding = new UTF8Encoding(); // This const defines the default depth to be used for serializing objects for remoting. private const int SerializationDepthForRemoting = 1; #endregion @@ -1007,8 +1005,8 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fragmentSize > 0, "fragment size cannot be less than 0."); _fragmentSize = fragmentSize; _serializationContext = new SerializationContext( - SerializationDepthForRemoting, - SerializationOptions.RemotingOptions, + SerializationDepthForRemoting, + SerializationOptions.RemotingOptions, cryptoHelper); _deserializationContext = new DeserializationContext( DeserializationOptions.RemotingOptions, @@ -1147,6 +1145,6 @@ namespace System.Management.Automation.Remoting } return PSObject.AsPSObject(result); - } + } } } diff --git a/src/System.Management.Automation/engine/remoting/common/misc.cs b/src/System.Management.Automation/engine/remoting/common/misc.cs index fc5ed1f87..6c712a73f 100644 --- a/src/System.Management.Automation/engine/remoting/common/misc.cs +++ b/src/System.Management.Automation/engine/remoting/common/misc.cs @@ -99,7 +99,7 @@ namespace System.Management.Automation { #region Private Members - private T data; + private T _data; #endregion Private Members @@ -112,7 +112,7 @@ namespace System.Management.Automation { get { - return data; + return _data; } } @@ -124,7 +124,7 @@ namespace System.Management.Automation { //Dbg.Assert(data != null, "data passed should not be null"); - this.data = (T)data; + _data = (T)data; } #endregion Constructor @@ -138,29 +138,29 @@ namespace System.Management.Automation /// /// Undefined state /// - UndefinedState = 0, + UndefinedState = 0, /// /// This is the state a connect start with. When a connection is closed, /// the connection will eventually come back to this Idle state. /// /// - Idle = 1, + Idle = 1, /// /// A connection operation has been initiated. /// - Connecting = 2, + Connecting = 2, /// /// A connection operation has completed successfully. /// - Connected = 3, + Connected = 3, /// /// The capability negotiation message is in the process being sent on a create operation /// - NegotiationSending = 4, + NegotiationSending = 4, /// /// The capability negotiation message is in the process being sent on a connect operation @@ -170,46 +170,46 @@ namespace System.Management.Automation /// /// The capability negotiation message is sent successfully from a sender point of view. /// - NegotiationSent = 6, + NegotiationSent = 6, /// /// A capability negotiation message is received. /// - NegotiationReceived = 7, + NegotiationReceived = 7, /// /// Used by server to wait for negotation from client. /// - NegotiationPending = 8, + NegotiationPending = 8, /// /// The connection is in the progress of getting closed. /// - ClosingConnection = 9, + ClosingConnection = 9, /// /// The connection is closed completely. /// - Closed = 10, + Closed = 10, /// /// The capability negotiation has been successfully completed. /// - Established = 11, + Established = 11, /// /// Have sent a public key to the remote end, /// awaiting a response /// /// Applicable only to client - EstablishedAndKeySent = 12, + EstablishedAndKeySent = 12, /// /// Have received a public key from the remote /// end, need to send a response /// /// Applicable only to server - EstablishedAndKeyReceived = 13, + EstablishedAndKeyReceived = 13, /// /// for Server - Have sent a request to the remote end to @@ -254,7 +254,7 @@ namespace System.Management.Automation /// /// Number of states /// - MaxState = 20 + MaxState = 20 } /// @@ -263,39 +263,39 @@ namespace System.Management.Automation /// internal enum RemoteSessionEvent { - InvalidEvent = 0, - CreateSession = 1, - ConnectSession = 2, - NegotiationSending = 3, - NegotiationSendingOnConnect= 4, - NegotiationSendCompleted = 5, - NegotiationReceived = 6, - NegotiationCompleted = 7, - NegotiationPending = 8, - Close = 9, - CloseCompleted = 10, - CloseFailed = 11, - ConnectFailed = 12, - NegotiationFailed = 13, - NegotiationTimeout = 14, - SendFailed = 15, - ReceiveFailed = 16, - FatalError = 17, - MessageReceived = 18, - KeySent = 19, - KeySendFailed = 20, - KeyReceived = 21, - KeyReceiveFailed = 22, - KeyRequested = 23, - KeyRequestFailed = 24, - DisconnectStart = 25, - DisconnectCompleted = 26, - DisconnectFailed = 27, - ReconnectStart = 28, - ReconnectCompleted = 29, - ReconnectFailed = 30, - RCDisconnectStarted = 31, - MaxEvent = 32 + InvalidEvent = 0, + CreateSession = 1, + ConnectSession = 2, + NegotiationSending = 3, + NegotiationSendingOnConnect = 4, + NegotiationSendCompleted = 5, + NegotiationReceived = 6, + NegotiationCompleted = 7, + NegotiationPending = 8, + Close = 9, + CloseCompleted = 10, + CloseFailed = 11, + ConnectFailed = 12, + NegotiationFailed = 13, + NegotiationTimeout = 14, + SendFailed = 15, + ReceiveFailed = 16, + FatalError = 17, + MessageReceived = 18, + KeySent = 19, + KeySendFailed = 20, + KeyReceived = 21, + KeyReceiveFailed = 22, + KeyRequested = 23, + KeyRequestFailed = 24, + DisconnectStart = 25, + DisconnectCompleted = 26, + DisconnectFailed = 27, + ReconnectStart = 28, + ReconnectCompleted = 29, + ReconnectFailed = 30, + RCDisconnectStarted = 31, + MaxEvent = 32 } /// @@ -405,7 +405,7 @@ namespace System.Management.Automation #region Constructors internal RemoteSessionStateMachineEventArgs(RemoteSessionEvent stateEvent) - : this (stateEvent, null) + : this(stateEvent, null) { } diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index ee83b871a..243f3d375 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -82,7 +82,7 @@ namespace System.Management.Automation.Remoting.Internal /// PSStreamObject is for internal (PowerShell) consumption /// and should not be treated as a public API. /// - public class PSStreamObject + public class PSStreamObject { /// /// @@ -103,7 +103,7 @@ namespace System.Management.Automation.Remoting.Internal /// /// /// - public PSStreamObject(PSStreamObjectType objectType, Object value): + public PSStreamObject(PSStreamObjectType objectType, Object value) : this(objectType, value, Guid.Empty) { } @@ -128,7 +128,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Error: { - ErrorRecord errorRecord = (ErrorRecord) this.Value; + ErrorRecord errorRecord = (ErrorRecord)this.Value; errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -140,7 +140,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Debug: { - string debug = (string) Value; + string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -152,7 +152,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Warning: { - string warning = (string) Value; + string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -164,7 +164,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Verbose: { - string verbose = (string) Value; + string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -179,7 +179,7 @@ namespace System.Management.Automation.Remoting.Internal MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { - mshCommandRuntime.WriteProgress((ProgressRecord) Value, overrideInquire); + mshCommandRuntime.WriteProgress((ProgressRecord)Value, overrideInquire); } } break; @@ -196,7 +196,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.WarningRecord: { - WarningRecord warningRecord = (WarningRecord) Value; + WarningRecord warningRecord = (WarningRecord)Value; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -209,28 +209,28 @@ namespace System.Management.Automation.Remoting.Internal { Dbg.Assert(this.Value is ClientMethodExecutor, "Expected psstreamObject.value is ClientMethodExecutor"); - ClientMethodExecutor methodExecutor = (ClientMethodExecutor) Value; + ClientMethodExecutor methodExecutor = (ClientMethodExecutor)Value; methodExecutor.Execute(cmdlet); } break; case PSStreamObjectType.BlockingError: { - CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker) Value; + CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker)Value; InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet); } break; case PSStreamObjectType.ShouldMethod: { - CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker) Value; + CmdletMethodInvoker methodInvoker = (CmdletMethodInvoker)Value; InvokeCmdletMethodAndWaitForResults(methodInvoker, cmdlet); } break; case PSStreamObjectType.Exception: { - Exception e = (Exception) Value; + Exception e = (Exception)Value; throw e; } } @@ -277,7 +277,7 @@ namespace System.Management.Automation.Remoting.Internal PSObject o = Value as PSObject; if (o != null) AddSourceJobNoteProperty(o, instanceId); - } + } cmdlet.WriteObject(Value); } break; @@ -285,7 +285,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Error: { ErrorRecord errorRecord = (ErrorRecord)this.Value; - RemotingErrorRecord remoteErrorRecord = errorRecord as RemotingErrorRecord; + RemotingErrorRecord remoteErrorRecord = errorRecord as RemotingErrorRecord; if (remoteErrorRecord == null) { @@ -319,7 +319,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Warning: { - string warning = (string) Value; + string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -331,7 +331,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Verbose: { - string verbose = (string) Value; + string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -343,7 +343,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Progress: { - ProgressRecord progressRecord = (ProgressRecord) Value; + ProgressRecord progressRecord = (ProgressRecord)Value; RemotingProgressRecord remotingProgressRecord = progressRecord as RemotingProgressRecord; if (remotingProgressRecord == null) @@ -370,7 +370,7 @@ namespace System.Management.Automation.Remoting.Internal case PSStreamObjectType.Debug: { - string debug = (string) Value; + string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) @@ -389,7 +389,7 @@ namespace System.Management.Automation.Remoting.Internal { // if we get a base InformationRecord object, check if the computerName is // populated in the Source field - if (! String.IsNullOrEmpty(informationRecord.Source)) + if (!String.IsNullOrEmpty(informationRecord.Source)) { string computerName; Guid jobInstanceId; @@ -493,7 +493,6 @@ namespace System.Management.Automation.Remoting.Internal errorRecord.ErrorDetails.RecommendedAction = CreateInformationalMessage(sourceId, errorRecord.ErrorDetails.RecommendedAction); return errorRecord; } - } } @@ -512,7 +511,7 @@ namespace System.Management.Automation.Remoting /// /// /// - public Exception ExceptionThrownOnCmdletThread { get; set;} + public Exception ExceptionThrownOnCmdletThread { get; set; } /// /// @@ -522,11 +521,11 @@ namespace System.Management.Automation.Remoting /// /// /// - public object SyncObject { get; set;} + public object SyncObject { get; set; } /// /// /// - public T MethodResult { get; set;} + public T MethodResult { get; set; } } } diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index 94a00961b..7c1be35b5 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -50,7 +50,7 @@ namespace System.Management.Automation.Remoting RemoteHostReadLineAsSecureStringPrompt = 215, RemoteHostGetBufferContents = 216, RemoteHostPromptSecureStringPrompt = 217, - WinPERemotingNotSupported = 218, + WinPERemotingNotSupported = 218, // reserved range: 300-399 @@ -109,12 +109,12 @@ namespace System.Management.Automation.Remoting // reserved range: 700-799 // Transport related range: 800-899 - + ConnectFailed = 801, CloseIsCalled = 802, ForceClosed = 803, CloseFailed = 804, - CloseCompleted = 805, + CloseCompleted = 805, UnsupportedWaitHandleType = 806, ReceivedDataStreamIsNotStdout = 807, StdInIsNotOpen = 808, @@ -151,8 +151,8 @@ namespace System.Management.Automation.Remoting CloseExCallBackError = 866, // END: Error codes added to support new WSMan Fan-In Model API // BEGIN: Error IDs introduced for URI redirection - RedirectedURINotWellFormatted=867, - URIEndPointNotResolved=868, + RedirectedURINotWellFormatted = 867, + URIEndPointNotResolved = 868, // END: Error IDs introduced for URI redirection // BEGIN: Error IDs introduced for Quota Management ReceivedObjectSizeExceededMaximumClient = 869, @@ -242,22 +242,22 @@ namespace System.Management.Automation.Remoting PSSenderInfoDescription = 1004, // IPC for Backgroud jobs related errors: 2000 - IPCUnknownNodeType=2001, + IPCUnknownNodeType = 2001, IPCInsufficientDataforElement = 2002, - IPCWrongAttributeCountForDataElement=2003, - IPCOnlyTextExpectedInDataElement=2004, - IPCWrongAttributeCountForElement=2005, - IPCUnknownElementReceived=2006, - IPCSupportsOnlyDefaultAuth=2007, - IPCWowComponentNotPresent=2008, - IPCServerProcessReportedError=2100, - IPCServerProcessExited=2101, - IPCErrorProcessingServerData=2102, - IPCUnknownCommandGuid=2103, - IPCNoSignalForSession=2104, - IPCSignalTimedOut=2105, - IPCCloseTimedOut=2106, - IPCExceptionLaunchingProcess=2107, + IPCWrongAttributeCountForDataElement = 2003, + IPCOnlyTextExpectedInDataElement = 2004, + IPCWrongAttributeCountForElement = 2005, + IPCUnknownElementReceived = 2006, + IPCSupportsOnlyDefaultAuth = 2007, + IPCWowComponentNotPresent = 2008, + IPCServerProcessReportedError = 2100, + IPCServerProcessExited = 2101, + IPCErrorProcessingServerData = 2102, + IPCUnknownCommandGuid = 2103, + IPCNoSignalForSession = 2104, + IPCSignalTimedOut = 2105, + IPCCloseTimedOut = 2106, + IPCExceptionLaunchingProcess = 2107, } @@ -326,7 +326,7 @@ namespace System.Management.Automation.Remoting /// Inner exception. /// public PSRemotingDataStructureException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetDefaultErrorRecord(); } @@ -359,7 +359,7 @@ namespace System.Management.Automation.Remoting /// Optional parameters required to format the resource string. /// internal PSRemotingDataStructureException(Exception innerException, string resourceString, params object[] args) - : base (PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) + : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } @@ -387,7 +387,7 @@ namespace System.Management.Automation.Remoting } } - + /// /// This exception is used by remoting code to indicate an error condition in network operations. /// @@ -420,7 +420,7 @@ namespace System.Management.Automation.Remoting SetDefaultErrorRecord(); } - + /// /// This constructor takes a localized message and an inner exception. @@ -432,7 +432,7 @@ namespace System.Management.Automation.Remoting /// Inner exception. /// public PSRemotingTransportException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetDefaultErrorRecord(); } @@ -453,7 +453,7 @@ namespace System.Management.Automation.Remoting : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args)) { SetDefaultErrorRecord(); - this._errorCode = (int)errorId; + _errorCode = (int)errorId; } /// @@ -469,7 +469,7 @@ namespace System.Management.Automation.Remoting /// Optional parameters required to format the resource string. /// internal PSRemotingTransportException(Exception innerException, string resourceString, params object[] args) - : base (PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) + : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException) { SetDefaultErrorRecord(); } @@ -537,7 +537,6 @@ namespace System.Management.Automation.Remoting { _errorCode = value; } - } /// @@ -583,7 +582,7 @@ namespace System.Management.Automation.Remoting public PSRemotingTransportRedirectException(string message) : base(message) { - } + } /// /// This constructor takes a localized message and an inner exception. @@ -595,7 +594,7 @@ namespace System.Management.Automation.Remoting /// Inner exception. /// public PSRemotingTransportRedirectException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } @@ -612,7 +611,7 @@ namespace System.Management.Automation.Remoting /// Optional parameters required to format the resource string. /// internal PSRemotingTransportRedirectException(Exception innerException, string resourceString, params object[] args) - : base (innerException, resourceString, args) + : base(innerException, resourceString, args) { } @@ -632,7 +631,7 @@ namespace System.Management.Automation.Remoting throw new PSArgumentNullException("info"); } - redirectLocation = info.GetString("RedirectLocation"); + _redirectLocation = info.GetString("RedirectLocation"); } /// @@ -653,7 +652,7 @@ namespace System.Management.Automation.Remoting internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotingErrorId errorId, string resourceString, params object[] args) : base(errorId, resourceString, args) { - this.redirectLocation = redirectLocation; + _redirectLocation = redirectLocation; } #endregion @@ -675,7 +674,7 @@ namespace System.Management.Automation.Remoting base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue - info.AddValue("RedirectLocation", redirectLocation); + info.AddValue("RedirectLocation", _redirectLocation); } #endregion @@ -688,11 +687,11 @@ namespace System.Management.Automation.Remoting { get { - return redirectLocation; + return _redirectLocation; } } - private string redirectLocation; + private string _redirectLocation; #endregion } diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index 90a65c4ac..b32f917a7 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -39,14 +39,14 @@ namespace System.Management.Automation.Remoting { get { - return operationState; + return _operationState; } set { - operationState = value; + _operationState = value; } } - private OperationState operationState; + private OperationState _operationState; /// /// the original event which actually resulted in this @@ -56,18 +56,18 @@ namespace System.Management.Automation.Remoting { get { - return baseEvent; + return _baseEvent; } set { - baseEvent = value; + _baseEvent = value; } } - private EventArgs baseEvent; + private EventArgs _baseEvent; } #endregion OperationState - + #region IThrottleOperation /// @@ -152,7 +152,6 @@ namespace System.Management.Automation.Remoting } } private bool _ignoreStop = false; - } // IThrottleOperation #endregion IThrottleOperation @@ -192,17 +191,17 @@ namespace System.Management.Automation.Remoting { set { - if (value > 0 && value <= THROTTLE_LIMIT_MAX) + if (value > 0 && value <= s_THROTTLE_LIMIT_MAX) { - throttleLimit = value; + _throttleLimit = value; } } get { - return throttleLimit; + return _throttleLimit; } } - private Int32 throttleLimit = DEFAULT_THROTTLE_LIMIT; + private Int32 _throttleLimit = s_DEFAULT_THROTTLE_LIMIT; #endregion Public (internal) Properties @@ -217,18 +216,18 @@ namespace System.Management.Automation.Remoting /// internal void SubmitOperations(List operations) { - lock (syncObject) + lock (_syncObject) { // operations can be submitted only until submitComplete // is not set to true (happens when EndSubmitOperations is called) - if (!submitComplete) + if (!_submitComplete) { // add items to the queue foreach (IThrottleOperation operation in operations) { Dbg.Assert(operation != null, "Operation submitComplete to throttle manager cannot be null"); - operationsQueue.Add(operation); + _operationsQueue.Add(operation); } } else @@ -236,7 +235,7 @@ namespace System.Management.Automation.Remoting throw new InvalidOperationException(); } } - + // schedule operations here if possible StartOperationsFromQueue(); } // SubmitOperations @@ -248,16 +247,16 @@ namespace System.Management.Automation.Remoting internal void AddOperation(IThrottleOperation operation) { // add item to the queue - lock (syncObject) + lock (_syncObject) { // operations can be submitted only until submitComplete // is not set to true (happens when EndSubmitOperations is called) - if (!submitComplete) + if (!_submitComplete) { Dbg.Assert(operation != null, "Operation submitComplete to throttle manager cannot be null"); - operationsQueue.Add(operation); + _operationsQueue.Add(operation); } else { @@ -267,7 +266,6 @@ namespace System.Management.Automation.Remoting // start operations from queue if possible StartOperationsFromQueue(); - }// AddOperation /// @@ -283,11 +281,11 @@ namespace System.Management.Automation.Remoting // if stopping is already in progress, make it a no op bool needToReturn = false; - lock (syncObject) + lock (_syncObject) { - if (!stopping) + if (!_stopping) { - stopping = true; + _stopping = true; } else { @@ -303,20 +301,20 @@ namespace System.Management.Automation.Remoting IThrottleOperation[] startOperationsInProcessArray; - lock (syncObject) + lock (_syncObject) { // no more submissions possible once stopped - submitComplete = true; + _submitComplete = true; // Clear all pending operations in queue so that they are not // scheduled when a stop operation completes - operationsQueue.Clear(); + _operationsQueue.Clear(); // Make a copy of the in process queue so as to stop all // operations in progress startOperationsInProcessArray = - new IThrottleOperation[startOperationQueue.Count]; - startOperationQueue.CopyTo(startOperationsInProcessArray); + new IThrottleOperation[_startOperationQueue.Count]; + _startOperationQueue.CopyTo(startOperationsInProcessArray); // stop all operations in process (using the copy) foreach (IThrottleOperation operation in startOperationsInProcessArray) @@ -332,22 +330,20 @@ namespace System.Management.Automation.Remoting // removal. In case the stop succeeds before start succeeds then // both will get removed (it goes without saying that there cannot // be a situation where start succeeds after stop succeeded) - stopOperationQueue.Add(operation); + _stopOperationQueue.Add(operation); operation.IgnoreStop = true; - } // foreach... } // lock... - foreach(IThrottleOperation operation in startOperationsInProcessArray) + foreach (IThrottleOperation operation in startOperationsInProcessArray) { operation.StopOperation(); - } + } // Raise event as it can be that at this point, all operations are // complete RaiseThrottleManagerEvents(); - } // StopAllOperations /// @@ -366,13 +362,13 @@ namespace System.Management.Automation.Remoting // If the operation has not yet been started, then // remove it from the pending queue - if (operationsQueue.IndexOf(operation) != -1) + if (_operationsQueue.IndexOf(operation) != -1) { - lock (syncObject) + lock (_syncObject) { - if (operationsQueue.IndexOf(operation) != -1) + if (_operationsQueue.IndexOf(operation) != -1) { - operationsQueue.Remove(operation); + _operationsQueue.Remove(operation); RaiseThrottleManagerEvents(); return; } @@ -383,9 +379,9 @@ namespace System.Management.Automation.Remoting // to the inprocess queue and call stop. Refer to // comment in StopAllOperations() as to why this is // being added a second time - lock (syncObject) + lock (_syncObject) { - stopOperationQueue.Add(operation); + _stopOperationQueue.Add(operation); operation.IgnoreStop = true; } @@ -400,13 +396,12 @@ namespace System.Management.Automation.Remoting /// internal void EndSubmitOperations() { - lock (syncObject) + lock (_syncObject) { - submitComplete = true; + _submitComplete = true; } RaiseThrottleManagerEvents(); - } // EndSubmitOperations #endregion Public (internal) Methods @@ -427,11 +422,10 @@ namespace System.Management.Automation.Remoting /// public ThrottleManager() { - operationsQueue = new List(); - startOperationQueue = new List(); - stopOperationQueue = new List(); - syncObject = new Object(); - + _operationsQueue = new List(); + _startOperationQueue = new List(); + _stopOperationQueue = new List(); + _syncObject = new Object(); }// ThrottleManager #endregion Constructors @@ -451,8 +445,8 @@ namespace System.Management.Automation.Remoting // An item has completed operation. If its a start operation which completed // remove the instance from the startOperationqueue. If its a stop operation // which completed, then remove the instance from both queues - lock (syncObject) - { + lock (_syncObject) + { IThrottleOperation operation = source as IThrottleOperation; Dbg.Assert(operation != null, "Source of event should not be null"); @@ -465,10 +459,10 @@ namespace System.Management.Automation.Remoting // A stop operation handler cleans up an outstanding start operation. // So it is possible that a start operation complete callback will find the // operation removed from the queue by an earlier stop operation complete. - index = startOperationQueue.IndexOf(operation); + index = _startOperationQueue.IndexOf(operation); if (index != -1) { - startOperationQueue.RemoveAt(index); + _startOperationQueue.RemoveAt(index); } } else @@ -476,16 +470,16 @@ namespace System.Management.Automation.Remoting // for a stop operation, the same operation object would have been // added to the stopOperationQueue as well. So we need to // remove both the instances. - index = startOperationQueue.IndexOf(operation); + index = _startOperationQueue.IndexOf(operation); if (index != -1) { - startOperationQueue.RemoveAt(index); + _startOperationQueue.RemoveAt(index); } - index = stopOperationQueue.IndexOf(operation); + index = _stopOperationQueue.IndexOf(operation); if (index != -1) { - stopOperationQueue.RemoveAt(index); + _stopOperationQueue.RemoveAt(index); } // if an operation signals a stopcomplete, it can mean @@ -501,7 +495,6 @@ namespace System.Management.Automation.Remoting // Do necessary things for starting operation for the next item in the queue StartOneOperationFromQueue(); - } // OperationCompleteHandler /// @@ -511,15 +504,15 @@ namespace System.Management.Automation.Remoting { IThrottleOperation operation = null; - lock (syncObject) + lock (_syncObject) { - if (operationsQueue.Count > 0) + if (_operationsQueue.Count > 0) { - operation = operationsQueue[0]; - operationsQueue.RemoveAt(0); + operation = _operationsQueue[0]; + _operationsQueue.RemoveAt(0); operation.OperationComplete += new EventHandler(OperationCompleteHandler); - startOperationQueue.Add(operation); + _startOperationQueue.Add(operation); } } @@ -527,7 +520,6 @@ namespace System.Management.Automation.Remoting { operation.StartOperation(); } - } //StartOneOperationFromQueue /// @@ -538,13 +530,13 @@ namespace System.Management.Automation.Remoting int operationsInProcessCount = 0; int operationsQueueCount = 0; - lock (syncObject) + lock (_syncObject) { - operationsInProcessCount = startOperationQueue.Count; - operationsQueueCount = operationsQueue.Count; + operationsInProcessCount = _startOperationQueue.Count; + operationsQueueCount = _operationsQueue.Count; } - - int remainingCap = throttleLimit - operationsInProcessCount; + + int remainingCap = _throttleLimit - operationsInProcessCount; if (remainingCap > 0) { @@ -564,14 +556,14 @@ namespace System.Management.Automation.Remoting { bool readyToRaise = false; - lock (syncObject) + lock (_syncObject) { // if submit is complete, there are no operations in progress and // the pending queue is empty, then raise events - if (submitComplete && - startOperationQueue.Count == 0 && - stopOperationQueue.Count == 0 && - operationsQueue.Count == 0) + if (_submitComplete && + _startOperationQueue.Count == 0 && + _stopOperationQueue.Count == 0 && + _operationsQueue.Count == 0) { readyToRaise = true; } @@ -581,7 +573,6 @@ namespace System.Management.Automation.Remoting { ThrottleComplete.SafeInvoke(this, EventArgs.Empty); } - } // RaiseThrottleManagerEvents #endregion Private Methods @@ -592,37 +583,37 @@ namespace System.Management.Automation.Remoting /// default throttle limit - the maximum number of operations /// to be processed at a time /// - private static int DEFAULT_THROTTLE_LIMIT = 32; + private static int s_DEFAULT_THROTTLE_LIMIT = 32; /// /// Maximum value that the throttle limit can be set to /// - private static int THROTTLE_LIMIT_MAX = int.MaxValue; + private static int s_THROTTLE_LIMIT_MAX = int.MaxValue; /// /// All pending operations /// - private List operationsQueue; - + private List _operationsQueue; + /// /// List of items on which a StartOperation has /// been called /// - private List startOperationQueue; - + private List _startOperationQueue; + /// /// List of items on which a StopOperation has /// been called /// - private List stopOperationQueue; + private List _stopOperationQueue; /// /// Object used to synchronize access to the queues /// - private Object syncObject; + private Object _syncObject; - bool submitComplete = false; // to check if operations have been submitComplete - bool stopping = false; // if stop is in process + private bool _submitComplete = false; // to check if operations have been submitComplete + private bool _stopping = false; // if stop is in process #endregion Private Members @@ -652,11 +643,9 @@ namespace System.Management.Automation.Remoting { StopAllOperations(); } - } // Dispose #endregion IDisposable Overrides - } #endregion ThrottleManager @@ -746,7 +735,7 @@ namespace System.Management.Automation.Remoting } } - void Operation_OperationComplete(object sender, OperationStateEventArgs e) + private void Operation_OperationComplete(object sender, OperationStateEventArgs e) { InternalEvent.SafeInvoke(sender, e); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 5864db3fb..a77283038 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -63,8 +63,8 @@ namespace System.Management.Automation.Remoting /// internal class TransportErrorOccuredEventArgs : EventArgs { - private PSRemotingTransportException exception; - private TransportMethodEnum method; + private PSRemotingTransportException _exception; + private TransportMethodEnum _method; /// /// Constructor @@ -78,8 +78,8 @@ namespace System.Management.Automation.Remoting internal TransportErrorOccuredEventArgs(PSRemotingTransportException e, TransportMethodEnum m) { - exception = e; - method = m; + _exception = e; + _method = m; } /// @@ -87,14 +87,14 @@ namespace System.Management.Automation.Remoting /// internal PSRemotingTransportException Exception { - get { return exception; } - set { exception = value; } + get { return _exception; } + set { _exception = value; } } /// /// Transport method that is reporting this error. /// - internal TransportMethodEnum ReportingTransportMethod { get { return method; } } + internal TransportMethodEnum ReportingTransportMethod { get { return _method; } } } #endregion @@ -165,7 +165,7 @@ namespace System.Management.Automation.Remoting #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] - static private PSTraceSource baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); + static private PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion @@ -202,13 +202,13 @@ namespace System.Management.Automation.Remoting #region Private Data // fragmentor used to fragment & defragment objects added to this collection. - private Fragmentor fragmentor; - private PriorityReceiveDataCollection recvdData;// callbacks - private ReceiveDataCollection.OnDataAvailableCallback onDataAvailableCallback; + private Fragmentor _fragmentor; + private PriorityReceiveDataCollection _recvdData;// callbacks + private ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; // crypto helper used for encrypting/decrypting // secure string - private PSRemotingCryptoHelper cryptoHelper; + private PSRemotingCryptoHelper _cryptoHelper; #endregion @@ -235,13 +235,13 @@ namespace System.Management.Automation.Remoting protected BaseTransportManager(PSRemotingCryptoHelper cryptoHelper) { - this.cryptoHelper = cryptoHelper; + _cryptoHelper = cryptoHelper; // create a common fragmentor used by this transport manager to send and receive data. // so type information is serialized only the first time an object of a particular type // is sent. only data is serialized for the rest of the objects of the same type. - fragmentor = new Fragmentor(DefaultFragmentSize, cryptoHelper); - recvdData = new PriorityReceiveDataCollection(fragmentor, (this is BaseClientTransportManager)); - onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); + _fragmentor = new Fragmentor(DefaultFragmentSize, cryptoHelper); + _recvdData = new PriorityReceiveDataCollection(_fragmentor, (this is BaseClientTransportManager)); + _onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); } #endregion @@ -250,8 +250,8 @@ namespace System.Management.Automation.Remoting internal Fragmentor Fragmentor { - get { return fragmentor; } - set { fragmentor = value; } + get { return _fragmentor; } + set { _fragmentor = value; } } /// @@ -264,10 +264,10 @@ namespace System.Management.Automation.Remoting /// internal TypeTable TypeTable { - get { return fragmentor.TypeTable; } - set { fragmentor.TypeTable = value; } + get { return _fragmentor.TypeTable; } + set { _fragmentor.TypeTable = value; } } - + /// /// Uses the "OnDataAvailableCallback" to handle Deserialized objects /// @@ -281,7 +281,7 @@ namespace System.Management.Automation.Remoting { try { - ProcessRawData(data, stream, onDataAvailableCallback); + ProcessRawData(data, stream, _onDataAvailableCallback); } catch (Exception exception) { @@ -289,7 +289,7 @@ namespace System.Management.Automation.Remoting // so we need to protect that thread, hence catching // all exceptions CommandProcessorBase.CheckForSevereException(exception); - baseTracer.WriteLine("Exception processing data. {0}", exception.Message); + s_baseTracer.WriteLine("Exception processing data. {0}", exception.Message); PSRemotingTransportException e = new PSRemotingTransportException(exception.Message, exception); TransportErrorOccuredEventArgs eventargs = @@ -321,7 +321,7 @@ namespace System.Management.Automation.Remoting { Dbg.Assert(null != data, "Cannot process null data"); - baseTracer.WriteLine("Processing incoming data for stream {0}.", stream); + s_baseTracer.WriteLine("Processing incoming data for stream {0}.", stream); bool shouldProcess = false; @@ -345,10 +345,10 @@ namespace System.Management.Automation.Remoting WSManNativeApi.WSMAN_STREAM_ID_STDIN, WSManNativeApi.WSMAN_STREAM_ID_STDOUT, WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE)); - baseTracer.WriteLine("{0} is not a valid stream", stream); + s_baseTracer.WriteLine("{0} is not a valid stream", stream); } // process data - recvdData.ProcessRawData(data, dataPriority, dataAvailableCallback); + _recvdData.ProcessRawData(data, dataPriority, dataAvailableCallback); } /// @@ -407,11 +407,11 @@ namespace System.Management.Automation.Remoting { get { - return cryptoHelper; + return _cryptoHelper; } set { - cryptoHelper = value; + _cryptoHelper = value; } } @@ -420,7 +420,7 @@ namespace System.Management.Automation.Remoting /// internal PriorityReceiveDataCollection ReceivedDataCollection { - get { return recvdData; } + get { return _recvdData; } } #endregion @@ -443,7 +443,7 @@ namespace System.Management.Automation.Remoting { if (isDisposing) { - recvdData.Dispose(); + _recvdData.Dispose(); } } @@ -466,14 +466,14 @@ namespace System.Management.Automation.Remoting.Client protected object syncObject = new object(); protected PrioritySendDataCollection dataToBeSent; // used to handle callbacks from the server..these are used to synchronize received callbacks - private Queue callbackNotificationQueue; - private ReceiveDataCollection.OnDataAvailableCallback onDataAvailableCallback; - private bool isServicingCallbacks; - private bool suspendQueueServicing; - private bool isDebuggerSuspend; + private Queue _callbackNotificationQueue; + private ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; + private bool _isServicingCallbacks; + private bool _suspendQueueServicing; + private bool _isDebuggerSuspend; // this is used log crimson messages. - private Guid runspacePoolInstanceId; + private Guid _runspacePoolInstanceId; //keeps track of whether a receive request has been placed on transport protected bool receiveDataInitiated; @@ -485,10 +485,10 @@ namespace System.Management.Automation.Remoting.Client protected BaseClientTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(cryptoHelper) { - runspacePoolInstanceId = runspaceId; + _runspacePoolInstanceId = runspaceId; dataToBeSent = new PrioritySendDataCollection(); - onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableHandler); - callbackNotificationQueue = new Queue(); + _onDataAvailableCallback = new ReceiveDataCollection.OnDataAvailableCallback(OnDataAvailableHandler); + _callbackNotificationQueue = new Queue(); } #endregion @@ -582,7 +582,7 @@ namespace System.Management.Automation.Remoting.Client /// internal Guid RunspacePoolInstanceId { - get { return runspacePoolInstanceId; } + get { return _runspacePoolInstanceId; } } /// @@ -606,7 +606,7 @@ namespace System.Management.Automation.Remoting.Client internal void RaiseReconnectCompleted() { ReconnectCompleted.SafeInvoke(this, EventArgs.Empty); - } + } /// /// Raise the close completed handler @@ -690,7 +690,7 @@ namespace System.Management.Automation.Remoting.Client try { - base.ProcessRawData(data, stream, onDataAvailableCallback); + base.ProcessRawData(data, stream, _onDataAvailableCallback); } catch (PSRemotingTransportException pte) { @@ -748,7 +748,7 @@ namespace System.Management.Automation.Remoting.Client return; } - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { if ((null != remoteObject) || (null != transportErrorArgs) || (null != privateData)) { @@ -765,26 +765,26 @@ namespace System.Management.Automation.Remoting.Client } else { - callbackNotificationQueue.Enqueue(rcvdDataInfo); + _callbackNotificationQueue.Enqueue(rcvdDataInfo); } } - if (suspendQueueServicing && isDebuggerSuspend) + if (_suspendQueueServicing && _isDebuggerSuspend) { // Remove debugger queue suspension if remoteObject requires user response. - suspendQueueServicing = !CheckForInteractiveHostCall(remoteObject); + _suspendQueueServicing = !CheckForInteractiveHostCall(remoteObject); } - if (isServicingCallbacks || suspendQueueServicing) + if (_isServicingCallbacks || _suspendQueueServicing) { // a thread pool thread is already processing callbacks or // the queue processing is suspended. return; } - if (callbackNotificationQueue.Count > 0) + if (_callbackNotificationQueue.Count > 0) { - isServicingCallbacks = true; + _isServicingCallbacks = true; // Start a thread pool thread to process callbacks. #if !CORECLR @@ -850,7 +850,7 @@ namespace System.Management.Automation.Remoting.Client internal void ServicePendingCallbacks(object objectToProcess) { tracer.WriteLine("ServicePendingCallbacks thread is starting"); - PSEtwLog.ReplaceActivityIdForCurrentThread(runspacePoolInstanceId, + PSEtwLog.ReplaceActivityIdForCurrentThread(_runspacePoolInstanceId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Transport, @@ -867,16 +867,16 @@ namespace System.Management.Automation.Remoting.Client } CallbackNotificationInformation rcvdDataInfo = null; - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { // If queue is empty or if queue servicing is suspended // then break out of loop. - if (callbackNotificationQueue.Count <= 0 || suspendQueueServicing) + if (_callbackNotificationQueue.Count <= 0 || _suspendQueueServicing) { break; } - rcvdDataInfo = callbackNotificationQueue.Dequeue(); + rcvdDataInfo = _callbackNotificationQueue.Dequeue(); } // Handle callback. if (null != rcvdDataInfo) @@ -914,10 +914,10 @@ namespace System.Management.Automation.Remoting.Client } finally { - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { tracer.WriteLine("ServicePendingCallbacks thread is exiting"); - isServicingCallbacks = false; + _isServicingCallbacks = false; // check if any new runspace request has arrived.. EnqueueAndStartProcessingThread(null, null, null); } @@ -928,31 +928,31 @@ namespace System.Management.Automation.Remoting.Client { get { - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { - return isServicingCallbacks; + return _isServicingCallbacks; } } } internal void SuspendQueue(bool debuggerSuspend = false) { - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { - isDebuggerSuspend = debuggerSuspend; - suspendQueueServicing = true; + _isDebuggerSuspend = debuggerSuspend; + _suspendQueueServicing = true; } } internal void ResumeQueue() { - lock (callbackNotificationQueue) + lock (_callbackNotificationQueue) { - isDebuggerSuspend = false; + _isDebuggerSuspend = false; - if (suspendQueueServicing) + if (_suspendQueueServicing) { - suspendQueueServicing = false; + _suspendQueueServicing = false; // Process any items in queue. EnqueueAndStartProcessingThread(null, null, null); @@ -1024,7 +1024,7 @@ namespace System.Management.Automation.Remoting.Client #endregion #region Clean up - + /// /// Finalizer /// @@ -1035,9 +1035,9 @@ namespace System.Management.Automation.Remoting.Client Dispose(false); } else - { + { // wait for the close to be completed and then release the resources. - this.CloseCompleted += delegate(object source, EventArgs args) + this.CloseCompleted += delegate (object source, EventArgs args) { Dispose(false); }; @@ -1065,7 +1065,7 @@ namespace System.Management.Automation.Remoting.Client this.ReconnectCompleted = null; // let base dispose its resources. - base.Dispose(isDisposing); + base.Dispose(isDisposing); } #endregion @@ -1076,7 +1076,7 @@ namespace System.Management.Automation.Remoting.Client #region Constructors protected BaseClientSessionTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) - :base(runspaceId, cryptoHelper) + : base(runspaceId, cryptoHelper) { } @@ -1159,7 +1159,7 @@ namespace System.Management.Automation.Remoting.Client internal abstract class BaseClientCommandTransportManager : BaseClientTransportManager, IDisposable { #region Private / Protected Data - + // pipeline in the form cmd1 | cmd2.. this is used by authz module for early validation. protected StringBuilder cmdText; protected SerializedDataStream serializedPipeline; @@ -1177,7 +1177,7 @@ namespace System.Management.Automation.Remoting.Client #region Constructors protected BaseClientCommandTransportManager(ClientRemotePowerShell shell, - PSRemotingCryptoHelper cryptoHelper, + PSRemotingCryptoHelper cryptoHelper, BaseClientSessionTransportManager sessnTM) : base(sessnTM.RunspacePoolInstanceId, cryptoHelper) { Fragmentor.FragmentSize = sessnTM.Fragmentor.FragmentSize; @@ -1185,7 +1185,7 @@ namespace System.Management.Automation.Remoting.Client dataToBeSent.Fragmentor = base.Fragmentor; // used for Crimson logging. powershellInstanceId = shell.PowerShell.InstanceId; - + cmdText = new StringBuilder(); foreach (System.Management.Automation.Runspaces.Command cmd in shell.PowerShell.Commands.Commands) { @@ -1237,7 +1237,7 @@ namespace System.Management.Automation.Remoting.Client #endregion #region Abstract / Virtual Methods - + /// /// Reconnects a previously disconnected commandTM. Implemented by WSMan transport /// Note that there is not explicit disconnect on commandTM. It is implicity disconnected @@ -1248,7 +1248,7 @@ namespace System.Management.Automation.Remoting.Client { throw new NotImplementedException(); } - + /// /// Used by powershell/pipeline to send a stop message to the server command /// @@ -1271,19 +1271,19 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private object syncObject = new object(); + private object _syncObject = new object(); // used to listen to data available events from serialized datastream. - private SerializedDataStream.OnDataAvailableCallback onDataAvailable; + private SerializedDataStream.OnDataAvailableCallback _onDataAvailable; // the following variable are used by onDataAvailableCallback. - private bool shouldFlushData; - private bool reportAsPending; - private Guid runpacePoolInstanceId; - private Guid powerShellInstanceId; - private RemotingDataType dataType; - private RemotingTargetInterface targetInterface; + private bool _shouldFlushData; + private bool _reportAsPending; + private Guid _runpacePoolInstanceId; + private Guid _powerShellInstanceId; + private RemotingDataType _dataType; + private RemotingTargetInterface _targetInterface; // End: the following variable are used by onDataAvailableCallback. - private Queue> dataToBeSentQueue; - private bool isSerializing; + private Queue> _dataToBeSentQueue; + private bool _isSerializing; #endregion #region Constructor @@ -1292,7 +1292,7 @@ namespace System.Management.Automation.Remoting.Server : base(cryptoHelper) { base.Fragmentor.FragmentSize = fragmentSize; - onDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); + _onDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); } #endregion @@ -1316,7 +1316,7 @@ namespace System.Management.Automation.Remoting.Server { // make sure only one data packet can be sent in its entirity at any // given point of time using this transport manager. - lock (syncObject) + lock (_syncObject) { // Win8: 491001 Icm -computername $env:COMPUTERNAME {Get-NetIpInterface} fails with Unexpected ObjectId // This is because the output object has some extentded script properties. Getter of one of the @@ -1344,40 +1344,39 @@ namespace System.Management.Automation.Remoting.Server RemoteDataObject dataToBeSent = RemoteDataObject.CreateFrom(data.Destination, data.DataType, data.RunspacePoolId, data.PowerShellId, data.Data); - if (isSerializing) + if (_isSerializing) { - if (dataToBeSentQueue == null) + if (_dataToBeSentQueue == null) { - dataToBeSentQueue = new Queue>(); + _dataToBeSentQueue = new Queue>(); } - dataToBeSentQueue.Enqueue(new Tuple(dataToBeSent, flush, reportPending)); + _dataToBeSentQueue.Enqueue(new Tuple(dataToBeSent, flush, reportPending)); return; } - isSerializing = true; + _isSerializing = true; try { - do { // tell stream to notify us whenever a fragment is available instead of writing data // into internal buffers. This will save write + read + dispose.) using (SerializedDataStream serializedData = - new SerializedDataStream(Fragmentor.FragmentSize, onDataAvailable)) + new SerializedDataStream(Fragmentor.FragmentSize, _onDataAvailable)) { - shouldFlushData = flush; - reportAsPending = reportPending; - runpacePoolInstanceId = dataToBeSent.RunspacePoolId; - powerShellInstanceId = dataToBeSent.PowerShellId; - dataType = dataToBeSent.DataType; - targetInterface = dataToBeSent.TargetInterface; + _shouldFlushData = flush; + _reportAsPending = reportPending; + _runpacePoolInstanceId = dataToBeSent.RunspacePoolId; + _powerShellInstanceId = dataToBeSent.PowerShellId; + _dataType = dataToBeSent.DataType; + _targetInterface = dataToBeSent.TargetInterface; Fragmentor.Fragment(dataToBeSent, serializedData); } - if ((dataToBeSentQueue != null) && (dataToBeSentQueue.Count > 0)) + if ((_dataToBeSentQueue != null) && (_dataToBeSentQueue.Count > 0)) { - Tuple dataToBeSentQueueItem = dataToBeSentQueue.Dequeue(); + Tuple dataToBeSentQueueItem = _dataToBeSentQueue.Dequeue(); dataToBeSent = dataToBeSentQueueItem.Item1; flush = dataToBeSentQueueItem.Item2; reportPending = dataToBeSentQueueItem.Item3; @@ -1386,12 +1385,11 @@ namespace System.Management.Automation.Remoting.Server { dataToBeSent = null; } - } while (dataToBeSent != null); } finally { - isSerializing = false; + _isSerializing = false; } } } @@ -1402,13 +1400,13 @@ namespace System.Management.Automation.Remoting.Server // log to crimson log. PSEtwLog.LogAnalyticInformational(PSEventId.ServerSendData, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - runpacePoolInstanceId.ToString(), - powerShellInstanceId.ToString(), + _runpacePoolInstanceId.ToString(), + _powerShellInstanceId.ToString(), dataToSend.Length.ToString(CultureInfo.InvariantCulture), - (UInt32)dataType, - (UInt32)targetInterface); + (UInt32)_dataType, + (UInt32)_targetInterface); - SendDataToClient(dataToSend, (isEndFragment & shouldFlushData) ? true : false, reportAsPending, isEndFragment); + SendDataToClient(dataToSend, (isEndFragment & _shouldFlushData) ? true : false, _reportAsPending, isEndFragment); } /// @@ -1447,7 +1445,7 @@ namespace System.Management.Automation.Remoting.Server // Use thread-pool thread to raise the error handler..see explanation // in the method summary ThreadPool.QueueUserWorkItem(new WaitCallback( - delegate(object state) + delegate (object state) { TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.Unknown); diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 5b2057fcd..c2ec4452b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -21,7 +21,7 @@ using System; namespace System.Management.Automation.Remoting -{ +{ /// /// This struct is used to represent contents from configuration xml. The /// XML is passed to plugins by WSMan API. @@ -51,12 +51,12 @@ namespace System.Management.Automation.Remoting internal const string SESSIONCONFIGTOKEN = "sessionconfigurationdata"; internal const string PSVERSIONTOKEN = "PSVersion"; internal const string MAXPSVERSIONTOKEN = "MaxPSVersion"; - internal const string MODULESTOIMPORT = "ModulesToImport"; - internal const string HOSTMODE = "hostmode"; - internal const string ENDPOINTCONFIGURATIONTYPE = "sessiontype"; - internal const string WORKFLOWCOREASSEMBLY = "Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"; - internal const string WORKFLOWCORETYPENAME = "Microsoft.PowerShell.Workflow.PSWorkflowSessionConfiguration"; - internal const string PSWORKFLOWMODULE = "%windir%\\system32\\windowspowershell\\v1.0\\Modules\\PSWorkflow"; + internal const string MODULESTOIMPORT = "ModulesToImport"; + internal const string HOSTMODE = "hostmode"; + internal const string ENDPOINTCONFIGURATIONTYPE = "sessiontype"; + internal const string WORKFLOWCOREASSEMBLY = "Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"; + internal const string WORKFLOWCORETYPENAME = "Microsoft.PowerShell.Workflow.PSWorkflowSessionConfiguration"; + internal const string PSWORKFLOWMODULE = "%windir%\\system32\\windowspowershell\\v1.0\\Modules\\PSWorkflow"; internal const string CONFIGFILEPATH = "configfilepath"; internal const string CONFIGFILEPATH_CamelCase = "ConfigFilePath"; @@ -125,7 +125,7 @@ namespace System.Management.Automation.Remoting break; case MAXRCVDCMDSIZETOKEN: AssertValueNotAssigned(MAXRCVDCMDSIZETOKEN, MaxReceivedCommandSizeMB); - MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue); + MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue); break; case THREADOPTIONSTOKEN: AssertValueNotAssigned(THREADOPTIONSTOKEN, ShellThreadOptions); @@ -171,7 +171,7 @@ namespace System.Management.Automation.Remoting if (originalValue != null) { throw PSTraceSource.NewArgumentException(optionName, - RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN); + RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN); } } @@ -315,7 +315,7 @@ namespace System.Management.Automation.Remoting { try { - return (PSSessionConfiguration)Activator.CreateInstance(EndPointConfigurationType); + return (PSSessionConfiguration)Activator.CreateInstance(EndPointConfigurationType); } catch (TypeLoadException) { @@ -351,7 +351,7 @@ namespace System.Management.Automation.Remoting /// Tracer for Server Remote session /// [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] - private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); #endregion tracer #region public interfaces @@ -371,7 +371,7 @@ namespace System.Management.Automation.Remoting /// /// /// - /// + /// /// public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) @@ -423,7 +423,7 @@ namespace System.Management.Automation.Remoting } #endregion - + #region IDisposable Overrides /// @@ -447,7 +447,7 @@ namespace System.Management.Automation.Remoting #endregion #region GetInitialSessionState from 3rd party shell ids - + /// /// /// @@ -472,14 +472,14 @@ namespace System.Management.Automation.Remoting { ConfigurationDataFromXML configData = null; - if (!ssnStateProviders.ContainsKey(initializationParameters)) + if (!s_ssnStateProviders.ContainsKey(initializationParameters)) { LoadRSConfigProvider(shellId, initializationParameters); } - lock (syncObject) + lock (s_syncObject) { - if (!ssnStateProviders.TryGetValue(initializationParameters, out configData)) + if (!s_ssnStateProviders.TryGetValue(initializationParameters, out configData)) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NonExistentInitialSessionStateProvider, shellId); } @@ -493,16 +493,16 @@ namespace System.Management.Automation.Remoting ConfigurationDataFromXML configData = ConfigurationDataFromXML.Create(initializationParameters); Type endPointConfigType = LoadAndAnalyzeAssembly(shellId, - configData.ApplicationBase, - configData.AssemblyName, + configData.ApplicationBase, + configData.AssemblyName, configData.EndPointConfigurationTypeName); Dbg.Assert(endPointConfigType != null, "EndPointConfiguration type cannot be null"); configData.EndPointConfigurationType = endPointConfigType; - lock (syncObject) + lock (s_syncObject) { - if (!ssnStateProviders.ContainsKey(initializationParameters)) + if (!s_ssnStateProviders.ContainsKey(initializationParameters)) { - ssnStateProviders.Add(initializationParameters, configData); + s_ssnStateProviders.Add(initializationParameters, configData); } } } @@ -524,16 +524,16 @@ namespace System.Management.Automation.Remoting /// Type instance representing the EndPointConfiguration to load. /// This Type can be instantiated when needed. /// - private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase, + private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase, string assemblyName, string typeToLoad) - { + { if ((string.IsNullOrEmpty(assemblyName) && !string.IsNullOrEmpty(typeToLoad)) || (!string.IsNullOrEmpty(assemblyName) && string.IsNullOrEmpty(typeToLoad))) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.TypeNeedsAssembly, ConfigurationDataFromXML.ASSEMBLYTOKEN, ConfigurationDataFromXML.SHELLCONFIGTYPETOKEN, - ConfigurationDataFromXML.INITPARAMETERSTOKEN); + ConfigurationDataFromXML.INITPARAMETERSTOKEN); } Assembly assembly = null; @@ -550,7 +550,7 @@ namespace System.Management.Automation.Remoting assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } } - + // configuration xml specified an assembly and typetoload. if (null != assembly) { @@ -596,7 +596,7 @@ namespace System.Management.Automation.Remoting // load the default PowerShell since plugin config // did not specify a typename to load. - return typeof(DefaultRemotePowerShellConfiguration); + return typeof(DefaultRemotePowerShellConfiguration); } /// @@ -625,32 +625,32 @@ namespace System.Management.Automation.Remoting } catch (ArgumentException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (PathTooLongException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (FileNotFoundException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (IOException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (System.Security.SecurityException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } catch (UnauthorizedAccessException e) { - tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", + s_tracer.TraceWarning("Not able to change curent working directory to {0}: {1}", applicationBase, e.Message); } } @@ -666,22 +666,22 @@ namespace System.Management.Automation.Remoting } catch (FileLoadException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (BadImageFormatException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (FileNotFoundException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } if (null != result) { return result; } - tracer.WriteLine("Loading assembly from path {0}", applicationBase); + s_tracer.WriteLine("Loading assembly from path {0}", applicationBase); try { String assemblyPath; @@ -705,15 +705,15 @@ namespace System.Management.Automation.Remoting } catch (FileLoadException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (BadImageFormatException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } catch (FileNotFoundException e) { - tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); + s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } } finally @@ -780,7 +780,7 @@ namespace System.Management.Automation.Remoting object value = registryKey.GetValue(name); if (value == null && mandatory == true) { - tracer.TraceError("Mandatory property {0} not specified for registry key {1}", + s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, registryKey.Name); throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name); } @@ -788,7 +788,7 @@ namespace System.Management.Automation.Remoting string s = value as string; if (string.IsNullOrEmpty(s) && mandatory == true) { - tracer.TraceError("Value is null or empty for mandatory property {0} in {1}", + s_tracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, registryKey.Name); throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name); } @@ -799,9 +799,9 @@ namespace System.Management.Automation.Remoting private const string configProvidersKeyName = "PSConfigurationProviders"; private const string configProviderApplicationBaseKeyName = "ApplicationBase"; private const string configProviderAssemblyNameKeyName = "AssemblyName"; - private static Dictionary ssnStateProviders = + private static Dictionary s_ssnStateProviders = new Dictionary(StringComparer.OrdinalIgnoreCase); - private static object syncObject = new object(); + private static object s_syncObject = new object(); #endregion } @@ -818,7 +818,7 @@ namespace System.Management.Automation.Remoting /// public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { - InitialSessionState result = InitialSessionState.CreateDefault2(); + InitialSessionState result = InitialSessionState.CreateDefault2(); // TODO: Remove this after RDS moved to $using if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } @@ -987,7 +987,7 @@ namespace System.Management.Automation.Remoting new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)), + new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)), new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)), @@ -1010,7 +1010,7 @@ namespace System.Management.Automation.Remoting { bool validKey = false; - foreach (ConfigTypeEntry configEntry in ConfigFileKeys) + foreach (ConfigTypeEntry configEntry in ConfigFileKeys) { if (String.Equals(configEntry.Key, de.Key.ToString(), StringComparison.OrdinalIgnoreCase)) { @@ -1086,7 +1086,7 @@ namespace System.Management.Automation.Remoting catch (ArgumentException) { // Do nothing here - } + } } cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, typeof(PSLanguageMode).FullName, @@ -1124,7 +1124,7 @@ namespace System.Management.Automation.Remoting cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, key, DISCUtils.ExecutionPolicyType.FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(DISCUtils.ExecutionPolicyType), path)); - return false; + return false; } /// @@ -1139,7 +1139,7 @@ namespace System.Management.Automation.Remoting { Hashtable hash = obj as Hashtable; - if(hash == null) + if (hash == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtable, key, path)); return false; @@ -1166,23 +1166,23 @@ namespace System.Management.Automation.Remoting return false; } - foreach(Hashtable hashtable in hashtables) + foreach (Hashtable hashtable in hashtables) { - if(!hashtable.ContainsKey(AliasNameToken)) + if (!hashtable.ContainsKey(AliasNameToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasNameToken, path)); return false; } - if(!hashtable.ContainsKey(AliasValueToken)) + if (!hashtable.ContainsKey(AliasValueToken)) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, key, AliasValueToken, path)); return false; } - + foreach (string aliasKey in hashtable.Keys) { - if(!String.Equals(aliasKey, AliasNameToken, StringComparison.OrdinalIgnoreCase) && + if (!String.Equals(aliasKey, AliasNameToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasValueToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasDescriptionToken, StringComparison.OrdinalIgnoreCase) && !String.Equals(aliasKey, AliasOptionsToken, StringComparison.OrdinalIgnoreCase)) @@ -1233,7 +1233,7 @@ namespace System.Management.Automation.Remoting cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, FunctionValueToken, key, path)); return false; } - + foreach (string functionKey in hashtable.Keys) { if (!String.Equals(functionKey, FunctionNameToken, StringComparison.OrdinalIgnoreCase) && @@ -1389,7 +1389,7 @@ namespace System.Management.Automation.Remoting /// /// !! NOTE that this list MUST be updated when new capability session configuration properties are added. /// - private static readonly HashSet AllowedRoleCapabilityKeys = new HashSet(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet s_allowedRoleCapabilityKeys = new HashSet(StringComparer.OrdinalIgnoreCase) { "RoleCapabilities", "ModulesToImport", @@ -1689,7 +1689,7 @@ namespace System.Management.Automation.Remoting throw invalidOperationEx; } - if (!AllowedRoleCapabilityKeys.Contains(roleCapabilityKey)) + if (!s_allowedRoleCapabilityKeys.Contains(roleCapabilityKey)) { var invalidOperationEx = new PSInvalidOperationException( string.Format(RemotingErrorIdStrings.InvalidRoleCapabilityKey, roleCapabilityKey)); @@ -1708,15 +1708,15 @@ namespace System.Management.Automation.Remoting /// internal sealed class DISCPowerShellConfiguration : PSSessionConfiguration { - private string configFile; - private Hashtable configHash; + private string _configFile; + private Hashtable _configHash; /// /// Gets the configuration hashtable that results from parsing the specified configuration file /// internal Hashtable ConfigHash { - get { return configHash; } + get { return _configHash; } } /// @@ -1730,8 +1730,8 @@ namespace System.Management.Automation.Remoting /// internal DISCPowerShellConfiguration(string configFile, Func roleVerifier) { - this.configFile = configFile; - if(roleVerifier == null) + _configFile = configFile; + if (roleVerifier == null) { roleVerifier = (role) => false; } @@ -1747,7 +1747,7 @@ namespace System.Management.Automation.Remoting ExternalScriptInfo script = DISCUtils.GetScriptInfoForFile(Runspace.DefaultRunspace.ExecutionContext, configFile, out scriptName); - configHash = DISCUtils.LoadConfigFile(Runspace.DefaultRunspace.ExecutionContext, script); + _configHash = DISCUtils.LoadConfigFile(Runspace.DefaultRunspace.ExecutionContext, script); MergeRoleRulesIntoConfigHash(roleVerifier); MergeRoleCapabilitiesIntoConfigHash(); @@ -1770,13 +1770,13 @@ namespace System.Management.Automation.Remoting // Takes the "Roles" node in the config hash, and merges all that apply into the base configuration. private void MergeRoleRulesIntoConfigHash(Func roleVerifier) { - if (configHash.ContainsKey(ConfigFileConstants.RoleDefinitions)) + if (_configHash.ContainsKey(ConfigFileConstants.RoleDefinitions)) { // Extract the 'Roles' hashtable - IDictionary roleEntry = configHash[ConfigFileConstants.RoleDefinitions] as IDictionary; - if(roleEntry == null) + IDictionary roleEntry = _configHash[ConfigFileConstants.RoleDefinitions] as IDictionary; + if (roleEntry == null) { - string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleEntry, configHash["Roles"].GetType().FullName); + string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleEntry, _configHash["Roles"].GetType().FullName); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidRoleDefinitionNotHashtable"); throw ioe; @@ -1811,9 +1811,9 @@ namespace System.Management.Automation.Remoting // Takes the "RoleCapabilities" node in the config hash, and merges its values into the base configuration. private void MergeRoleCapabilitiesIntoConfigHash() { - if (configHash.ContainsKey(ConfigFileConstants.RoleCapabilities)) + if (_configHash.ContainsKey(ConfigFileConstants.RoleCapabilities)) { - string[] roleCapabilities = TryGetStringArray(configHash[ConfigFileConstants.RoleCapabilities]); + string[] roleCapabilities = TryGetStringArray(_configHash[ConfigFileConstants.RoleCapabilities]); if (roleCapabilities != null) { @@ -1846,9 +1846,9 @@ namespace System.Management.Automation.Remoting ArrayList customizationValue = new ArrayList(); // First, take all values from the master config table - if (configHash.ContainsKey(customizationString)) + if (_configHash.ContainsKey(customizationString)) { - IEnumerable existingValueAsCollection = LanguagePrimitives.GetEnumerable(configHash[customization]); + IEnumerable existingValueAsCollection = LanguagePrimitives.GetEnumerable(_configHash[customization]); if (existingValueAsCollection != null) { foreach (Object value in existingValueAsCollection) @@ -1858,7 +1858,7 @@ namespace System.Management.Automation.Remoting } else { - customizationValue.Add(configHash[customization]); + customizationValue.Add(_configHash[customization]); } } @@ -1877,7 +1877,7 @@ namespace System.Management.Automation.Remoting } // Now update the config table for this role. - configHash[customization] = customizationValue.ToArray(); + _configHash[customization] = customizationValue.ToArray(); } } @@ -1934,7 +1934,7 @@ namespace System.Management.Automation.Remoting InitialSessionState iss = null; // Create the initial session state - string initialSessionState = TryGetValue(configHash, ConfigFileConstants.SessionType); + string initialSessionState = TryGetValue(_configHash, ConfigFileConstants.SessionType); SessionType sessionType = SessionType.Default; bool cmdletVisibilityApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleCmdlets); bool functionVisiblityApplied = IsNonDefaultVisibiltySpecified(ConfigFileConstants.VisibleFunctions); @@ -1985,7 +1985,7 @@ namespace System.Management.Automation.Remoting // Add providers if (providerVisibiltyApplied) { - string[] providers = TryGetStringArray(configHash[ConfigFileConstants.VisibleProviders]); + string[] providers = TryGetStringArray(_configHash[ConfigFileConstants.VisibleProviders]); if (providers != null) { @@ -2011,9 +2011,9 @@ namespace System.Management.Automation.Remoting } // Add assemblies and modules); - if (configHash.ContainsKey(ConfigFileConstants.AssembliesToLoad)) + if (_configHash.ContainsKey(ConfigFileConstants.AssembliesToLoad)) { - string[] assemblies = TryGetStringArray(configHash[ConfigFileConstants.AssembliesToLoad]); + string[] assemblies = TryGetStringArray(_configHash[ConfigFileConstants.AssembliesToLoad]); if (assemblies != null) { @@ -2024,18 +2024,18 @@ namespace System.Management.Automation.Remoting } } - if (configHash.ContainsKey(ConfigFileConstants.ModulesToImport)) + if (_configHash.ContainsKey(ConfigFileConstants.ModulesToImport)) { - object[] modules = TryGetObjectsOfType(configHash[ConfigFileConstants.ModulesToImport], - new Type[] {typeof (string), typeof (Hashtable)}); - if ((configHash[ConfigFileConstants.ModulesToImport] != null) && (modules == null)) + object[] modules = TryGetObjectsOfType(_configHash[ConfigFileConstants.ModulesToImport], + new Type[] { typeof(string), typeof(Hashtable) }); + if ((_configHash[ConfigFileConstants.ModulesToImport] != null) && (modules == null)) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.ModulesToImport); PSInvalidOperationException ioe = new PSInvalidOperationException(message); ioe.SetErrorId("InvalidModulesToImportKeyEntries"); - throw ioe; + throw ioe; } if (null != modules) @@ -2047,7 +2047,7 @@ namespace System.Management.Automation.Remoting string moduleName = module as string; if (!string.IsNullOrEmpty(moduleName)) { - moduleSpec = new ModuleSpecification(moduleName); + moduleSpec = new ModuleSpecification(moduleName); } else { @@ -2085,9 +2085,9 @@ namespace System.Management.Automation.Remoting } // Define members - if (configHash.ContainsKey(ConfigFileConstants.VisibleCmdlets)) + if (_configHash.ContainsKey(ConfigFileConstants.VisibleCmdlets)) { - object[] cmdlets = TryGetObjectsOfType(configHash[ConfigFileConstants.VisibleCmdlets], + object[] cmdlets = TryGetObjectsOfType(_configHash[ConfigFileConstants.VisibleCmdlets], new Type[] { typeof(string), typeof(Hashtable) }); if (cmdlets == null) @@ -2103,9 +2103,9 @@ namespace System.Management.Automation.Remoting ProcessVisibleCommands(iss, cmdlets); } - if (configHash.ContainsKey(ConfigFileConstants.AliasDefinitions)) + if (_configHash.ContainsKey(ConfigFileConstants.AliasDefinitions)) { - Hashtable[] aliases = TryGetHashtableArray(configHash[ConfigFileConstants.AliasDefinitions]); + Hashtable[] aliases = TryGetHashtableArray(_configHash[ConfigFileConstants.AliasDefinitions]); if (aliases != null) { @@ -2121,16 +2121,16 @@ namespace System.Management.Automation.Remoting { iss.Commands.Remove(entry.Name, typeof(SessionStateAliasEntry)); } - + iss.Commands.Add(entry); } } } } - if (configHash.ContainsKey(ConfigFileConstants.VisibleAliases)) + if (_configHash.ContainsKey(ConfigFileConstants.VisibleAliases)) { - string[] aliases = DISCPowerShellConfiguration.TryGetStringArray(configHash[ConfigFileConstants.VisibleAliases]); + string[] aliases = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.VisibleAliases]); if (aliases != null) { @@ -2160,9 +2160,9 @@ namespace System.Management.Automation.Remoting } } - if (configHash.ContainsKey(ConfigFileConstants.FunctionDefinitions)) + if (_configHash.ContainsKey(ConfigFileConstants.FunctionDefinitions)) { - Hashtable[] functions = TryGetHashtableArray(configHash[ConfigFileConstants.FunctionDefinitions]); + Hashtable[] functions = TryGetHashtableArray(_configHash[ConfigFileConstants.FunctionDefinitions]); if (functions != null) { @@ -2178,9 +2178,9 @@ namespace System.Management.Automation.Remoting } } - if (configHash.ContainsKey(ConfigFileConstants.VisibleFunctions)) + if (_configHash.ContainsKey(ConfigFileConstants.VisibleFunctions)) { - object[] functions = TryGetObjectsOfType(configHash[ConfigFileConstants.VisibleFunctions], + object[] functions = TryGetObjectsOfType(_configHash[ConfigFileConstants.VisibleFunctions], new Type[] { typeof(string), typeof(Hashtable) }); if (functions == null) @@ -2196,15 +2196,15 @@ namespace System.Management.Automation.Remoting ProcessVisibleCommands(iss, functions); } - if (configHash.ContainsKey(ConfigFileConstants.VariableDefinitions)) + if (_configHash.ContainsKey(ConfigFileConstants.VariableDefinitions)) { - Hashtable[] variables = TryGetHashtableArray(configHash[ConfigFileConstants.VariableDefinitions]); + Hashtable[] variables = TryGetHashtableArray(_configHash[ConfigFileConstants.VariableDefinitions]); if (variables != null) { foreach (Hashtable variable in variables) { - if (variable.ContainsKey(ConfigFileConstants.VariableValueToken) && + if (variable.ContainsKey(ConfigFileConstants.VariableValueToken) && ((variable[ConfigFileConstants.VariableValueToken] as ScriptBlock) != null)) { iss.DynamicVariablesToDefine.Add(variable); @@ -2221,9 +2221,9 @@ namespace System.Management.Automation.Remoting } } - if (configHash.ContainsKey(ConfigFileConstants.EnvironmentVariables)) + if (_configHash.ContainsKey(ConfigFileConstants.EnvironmentVariables)) { - Hashtable[] variablesList = TryGetHashtableArray(configHash[ConfigFileConstants.EnvironmentVariables]); + Hashtable[] variablesList = TryGetHashtableArray(_configHash[ConfigFileConstants.EnvironmentVariables]); if (variablesList != null) { @@ -2239,9 +2239,9 @@ namespace System.Management.Automation.Remoting } // Update type data - if (configHash.ContainsKey(ConfigFileConstants.TypesToProcess)) + if (_configHash.ContainsKey(ConfigFileConstants.TypesToProcess)) { - string[] types = DISCPowerShellConfiguration.TryGetStringArray(configHash[ConfigFileConstants.TypesToProcess]); + string[] types = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.TypesToProcess]); if (types != null) { @@ -2256,9 +2256,9 @@ namespace System.Management.Automation.Remoting } // Update format data - if (configHash.ContainsKey(ConfigFileConstants.FormatsToProcess)) + if (_configHash.ContainsKey(ConfigFileConstants.FormatsToProcess)) { - string[] formats = DISCPowerShellConfiguration.TryGetStringArray(configHash[ConfigFileConstants.FormatsToProcess]); + string[] formats = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.FormatsToProcess]); if (formats != null) { @@ -2273,12 +2273,12 @@ namespace System.Management.Automation.Remoting } // Add external commands - if (configHash.ContainsKey(ConfigFileConstants.VisibleExternalCommands)) + if (_configHash.ContainsKey(ConfigFileConstants.VisibleExternalCommands)) { - string[] externalCommands = TryGetStringArray(configHash[ConfigFileConstants.VisibleExternalCommands]); + string[] externalCommands = TryGetStringArray(_configHash[ConfigFileConstants.VisibleExternalCommands]); if (externalCommands != null) { - foreach(string command in externalCommands) + foreach (string command in externalCommands) { if (command.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { @@ -2301,9 +2301,9 @@ namespace System.Management.Automation.Remoting } // Register startup scripts - if (configHash.ContainsKey(ConfigFileConstants.ScriptsToProcess)) + if (_configHash.ContainsKey(ConfigFileConstants.ScriptsToProcess)) { - string[] startupScripts = DISCPowerShellConfiguration.TryGetStringArray(configHash[ConfigFileConstants.ScriptsToProcess]); + string[] startupScripts = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.ScriptsToProcess]); if (startupScripts != null) { @@ -2352,39 +2352,39 @@ namespace System.Management.Automation.Remoting } // Set the execution policy - if (configHash.ContainsKey(ConfigFileConstants.ExecutionPolicy)) + if (_configHash.ContainsKey(ConfigFileConstants.ExecutionPolicy)) { - Microsoft.PowerShell.ExecutionPolicy executionPolicy = (Microsoft.PowerShell.ExecutionPolicy) Enum.Parse( - typeof(Microsoft.PowerShell.ExecutionPolicy), configHash[ConfigFileConstants.ExecutionPolicy].ToString(), true); + Microsoft.PowerShell.ExecutionPolicy executionPolicy = (Microsoft.PowerShell.ExecutionPolicy)Enum.Parse( + typeof(Microsoft.PowerShell.ExecutionPolicy), _configHash[ConfigFileConstants.ExecutionPolicy].ToString(), true); iss.ExecutionPolicy = executionPolicy; } // Set the language mode - if (configHash.ContainsKey(ConfigFileConstants.LanguageMode)) + if (_configHash.ContainsKey(ConfigFileConstants.LanguageMode)) { - System.Management.Automation.PSLanguageMode languageMode = (System.Management.Automation.PSLanguageMode) Enum.Parse( - typeof(System.Management.Automation.PSLanguageMode), configHash[ConfigFileConstants.LanguageMode].ToString(), true); + System.Management.Automation.PSLanguageMode languageMode = (System.Management.Automation.PSLanguageMode)Enum.Parse( + typeof(System.Management.Automation.PSLanguageMode), _configHash[ConfigFileConstants.LanguageMode].ToString(), true); iss.LanguageMode = languageMode; } // Set the transcript directory - if (configHash.ContainsKey(ConfigFileConstants.TranscriptDirectory)) + if (_configHash.ContainsKey(ConfigFileConstants.TranscriptDirectory)) { - iss.TranscriptDirectory = configHash[ConfigFileConstants.TranscriptDirectory].ToString(); + iss.TranscriptDirectory = _configHash[ConfigFileConstants.TranscriptDirectory].ToString(); } // Process User Drive - if (configHash.ContainsKey(ConfigFileConstants.MountUserDrive)) + if (_configHash.ContainsKey(ConfigFileConstants.MountUserDrive)) { - if (Convert.ToBoolean(configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture) == true) + if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture) == true) { iss.UserDriveEnabled = true; iss.UserDriveUserName = (senderInfo != null) ? senderInfo.UserInfo.Identity.Name : null; // Set user drive max drive if provided. - if (configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) + if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) { - long userDriveMaxSize = Convert.ToInt64(configHash[ConfigFileConstants.UserDriveMaxSize]); + long userDriveMaxSize = Convert.ToInt64(_configHash[ConfigFileConstants.UserDriveMaxSize]); if (userDriveMaxSize > 0) { iss.UserDriveMaximumSize = userDriveMaxSize; @@ -2409,7 +2409,7 @@ namespace System.Management.Automation.Remoting foreach (var copyToRemoteFn in CopyFileRemoteUtils.GetAllCopyToRemoteScriptFunctions()) { var functionEntry = new SessionStateFunctionEntry( - copyToRemoteFn["Name"] as string, + copyToRemoteFn["Name"] as string, copyToRemoteFn["Definition"] as string); iss.Commands.Add(functionEntry); } @@ -2631,7 +2631,7 @@ namespace System.Management.Automation.Remoting } SessionStateEntryVisibility visibility = SessionStateEntryVisibility.Private; - if (! isAliasVisibilityDefined) + if (!isAliasVisibilityDefined) { visibility = SessionStateEntryVisibility.Public; } @@ -2672,7 +2672,7 @@ namespace System.Management.Automation.Remoting newFunction.LanguageMode = PSLanguageMode.FullLanguage; SessionStateEntryVisibility functionVisibility = SessionStateEntryVisibility.Private; - if (! isFunctionVisibilityDefined) + if (!isFunctionVisibilityDefined) { functionVisibility = SessionStateEntryVisibility.Public; } @@ -2711,7 +2711,7 @@ namespace System.Management.Automation.Remoting } SessionStateEntryVisibility visibility = SessionStateEntryVisibility.Private; - if(languageMode == PSLanguageMode.FullLanguage) + if (languageMode == PSLanguageMode.FullLanguage) { visibility = SessionStateEntryVisibility.Public; } @@ -2726,11 +2726,11 @@ namespace System.Management.Automation.Remoting /// private bool IsNonDefaultVisibiltySpecified(string configFileKey) { - if (configHash.ContainsKey(configFileKey)) + if (_configHash.ContainsKey(configFileKey)) { string[] commands = - DISCPowerShellConfiguration.TryGetStringArray(configHash[configFileKey]); - + DISCPowerShellConfiguration.TryGetStringArray(_configHash[configFileKey]); + if ((commands == null) || (commands.Length == 0)) { return false; @@ -2741,7 +2741,7 @@ namespace System.Management.Automation.Remoting return false; } - + /// /// Attempts to get a value from a hashtable /// @@ -2849,7 +2849,7 @@ namespace System.Management.Automation.Remoting { if (obj.GetType().Equals(type)) { - return new T[] {obj as T}; + return new T[] { obj as T }; } } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 1b09af736..9ce961d9b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -64,7 +64,7 @@ namespace System.Management.Automation.Remoting XmlReaderSettings = new XmlReaderSettings(); XmlReaderSettings.CheckCharacters = false; XmlReaderSettings.IgnoreComments = true; - XmlReaderSettings.IgnoreProcessingInstructions = true; + XmlReaderSettings.IgnoreProcessingInstructions = true; #if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR XmlReaderSettings.XmlResolver = null; #endif @@ -105,8 +105,8 @@ namespace System.Management.Automation.Remoting } internal static string CreateClosePacket(Guid psGuid) - { - return CreatePSGuidPacket(PS_OUT_OF_PROC_CLOSE_TAG, psGuid); + { + return CreatePSGuidPacket(PS_OUT_OF_PROC_CLOSE_TAG, psGuid); } internal static string CreateCloseAckPacket(Guid psGuid) @@ -165,7 +165,7 @@ namespace System.Management.Automation.Remoting internal ClosePacketReceived ClosePacketReceived; internal CloseAckPacketReceived CloseAckPacketReceived; } - + /// /// Process's data. Data should be a valid XML. /// @@ -199,7 +199,7 @@ namespace System.Management.Automation.Remoting XmlNodeType.Element.ToString(), XmlNodeType.EndElement.ToString()); } - } + } } /// @@ -217,9 +217,9 @@ namespace System.Management.Automation.Remoting { Dbg.Assert(null != xmlReader, "xmlReader cannot be null."); Dbg.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader's NodeType should be of type Element"); - + PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource(); - + switch (xmlReader.LocalName) { case OutOfProcessUtils.PS_OUT_OF_PROC_DATA_TAG: @@ -227,7 +227,7 @@ namespace System.Management.Automation.Remoting // A should have 1 attribute identifying the stream if (xmlReader.AttributeCount != 2) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForDataElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForDataElement, RemotingErrorIdStrings.IPCWrongAttributeCountForDataElement, OutOfProcessUtils.PS_OUT_OF_PROC_STREAM_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, @@ -240,14 +240,14 @@ namespace System.Management.Automation.Remoting // Now move the reader to the data portion if (!xmlReader.Read()) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCInsufficientDataforElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCInsufficientDataforElement, RemotingErrorIdStrings.IPCInsufficientDataforElement, OutOfProcessUtils.PS_OUT_OF_PROC_DATA_TAG); } if (xmlReader.NodeType != XmlNodeType.Text) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCOnlyTextExpectedInDataElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCOnlyTextExpectedInDataElement, RemotingErrorIdStrings.IPCOnlyTextExpectedInDataElement, xmlReader.NodeType, OutOfProcessUtils.PS_OUT_OF_PROC_DATA_TAG, XmlNodeType.Text); } @@ -263,7 +263,7 @@ namespace System.Management.Automation.Remoting { if (xmlReader.AttributeCount != 1) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, RemotingErrorIdStrings.IPCWrongAttributeCountForElement, OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG); @@ -271,7 +271,7 @@ namespace System.Management.Automation.Remoting string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); - tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_DATA_ACK received, psGuid : " + psGuid.ToString()); + tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_DATA_ACK received, psGuid : " + psGuid.ToString()); callbacks.DataAckPacketReceived(psGuid); } break; @@ -279,7 +279,7 @@ namespace System.Management.Automation.Remoting { if (xmlReader.AttributeCount != 1) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, RemotingErrorIdStrings.IPCWrongAttributeCountForElement, OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_TAG); @@ -287,7 +287,7 @@ namespace System.Management.Automation.Remoting string psGuidString = xmlReader.GetAttribute(OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE); Guid psGuid = new Guid(psGuidString); - tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_COMMAND received, psGuid : " + psGuid.ToString()); + tracer.WriteMessage("OutOfProcessUtils.ProcessElement : PS_OUT_OF_PROC_COMMAND received, psGuid : " + psGuid.ToString()); callbacks.CommandCreationPacketReceived(psGuid); } break; @@ -295,7 +295,7 @@ namespace System.Management.Automation.Remoting { if (xmlReader.AttributeCount != 1) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, RemotingErrorIdStrings.IPCWrongAttributeCountForElement, OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG); @@ -310,7 +310,7 @@ namespace System.Management.Automation.Remoting { if (xmlReader.AttributeCount != 1) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, + throw new PSRemotingTransportException(PSRemotingErrorId.IPCWrongAttributeCountForElement, RemotingErrorIdStrings.IPCWrongAttributeCountForElement, OutOfProcessUtils.PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_TAG); @@ -388,9 +388,9 @@ namespace System.Management.Automation.Remoting { #region Private Data - private TextWriter writer; - private bool isStopped; - private object syncObject = new object(); + private TextWriter _writer; + private bool _isStopped; + private object _syncObject = new object(); #endregion @@ -403,7 +403,7 @@ namespace System.Management.Automation.Remoting internal OutOfProcessTextWriter(TextWriter writerToWrap) { Dbg.Assert(null != writerToWrap, "Cannot wrap a null writer."); - writer = writerToWrap; + _writer = writerToWrap; } #endregion @@ -416,14 +416,14 @@ namespace System.Management.Automation.Remoting /// internal virtual void WriteLine(string data) { - if (isStopped) + if (_isStopped) { return; } - lock (syncObject) + lock (_syncObject) { - writer.WriteLine(data); + _writer.WriteLine(data); } } @@ -436,7 +436,7 @@ namespace System.Management.Automation.Remoting /// internal void StopWriting() { - isStopped = true; + _isStopped = true; } #endregion @@ -449,10 +449,10 @@ namespace System.Management.Automation.Remoting.Client { #region Data - private PrioritySendDataCollection.OnDataAvailableCallback onDataAvailableToSendCallback; - private OutOfProcessUtils.DataProcessingDelegates dataProcessingCallbacks; - private Dictionary cmdTransportManagers; - private Timer closeTimeOutTimer; + private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private OutOfProcessUtils.DataProcessingDelegates _dataProcessingCallbacks; + private Dictionary _cmdTransportManagers; + private Timer _closeTimeOutTimer; protected OutOfProcessTextWriter stdInWriter; protected PowerShellTraceSource _tracer; @@ -466,20 +466,20 @@ namespace System.Management.Automation.Remoting.Client PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { - onDataAvailableToSendCallback = + _onDataAvailableToSendCallback = new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); - cmdTransportManagers = new Dictionary(); + _cmdTransportManagers = new Dictionary(); - dataProcessingCallbacks = new OutOfProcessUtils.DataProcessingDelegates(); - dataProcessingCallbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived); - dataProcessingCallbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived); - dataProcessingCallbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived); - dataProcessingCallbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived); - dataProcessingCallbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived); - dataProcessingCallbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSiganlAckPacketReceived); - dataProcessingCallbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived); - dataProcessingCallbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckReceived); + _dataProcessingCallbacks = new OutOfProcessUtils.DataProcessingDelegates(); + _dataProcessingCallbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived); + _dataProcessingCallbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived); + _dataProcessingCallbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived); + _dataProcessingCallbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived); + _dataProcessingCallbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived); + _dataProcessingCallbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSiganlAckPacketReceived); + _dataProcessingCallbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived); + _dataProcessingCallbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckReceived); dataToBeSent.Fragmentor = base.Fragmentor; // session transport manager can recieve unlimited data..however each object is limited @@ -491,7 +491,7 @@ namespace System.Management.Automation.Remoting.Client ReceivedDataCollection.MaximumReceivedDataSize = null; ReceivedDataCollection.MaximumReceivedObjectSize = BaseTransportManager.MaximumReceivedObjectSize; // timers initialization - closeTimeOutTimer = new Timer(OnCloseTimeOutTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); + _closeTimeOutTimer = new Timer(OnCloseTimeOutTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); _tracer = PowerShellTraceSourceFactory.GetTraceSource(); } @@ -543,7 +543,7 @@ namespace System.Management.Automation.Remoting.Client PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); - _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.CloseAsync, when sending close session packet, progress command count should be zero, current cmd count: " + cmdTransportManagers.Count + ", RunSpacePool Id : " + this.RunspacePoolInstanceId); + _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.CloseAsync, when sending close session packet, progress command count should be zero, current cmd count: " + _cmdTransportManagers.Count + ", RunSpacePool Id : " + this.RunspacePoolInstanceId); try { @@ -551,7 +551,7 @@ namespace System.Management.Automation.Remoting.Client stdInWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(Guid.Empty)); // start the timer..so client can fail deterministically - closeTimeOutTimer.Change(60 * 1000, Timeout.Infinite); + _closeTimeOutTimer.Change(60 * 1000, Timeout.Infinite); } catch (IOException) { @@ -595,8 +595,8 @@ namespace System.Management.Automation.Remoting.Client base.Dispose(isDisposing); if (isDisposing) { - cmdTransportManagers.Clear(); - closeTimeOutTimer.Dispose(); + _cmdTransportManagers.Clear(); + _closeTimeOutTimer.Dispose(); } } @@ -616,8 +616,8 @@ namespace System.Management.Automation.Remoting.Client return; } - Dbg.Assert(!cmdTransportManagers.ContainsKey(key), "key already exists"); - cmdTransportManagers.Add(key, cmdTM); + Dbg.Assert(!_cmdTransportManagers.ContainsKey(key), "key already exists"); + _cmdTransportManagers.Add(key, cmdTM); } } @@ -628,7 +628,7 @@ namespace System.Management.Automation.Remoting.Client // We always need to remove commands from collection, even if isClosed is true. // If we don't then we hang because CloseAsync() will not complete until all // commands are closed. - if (!cmdTransportManagers.Remove(key)) + if (!_cmdTransportManagers.Remove(key)) { _tracer.WriteMessage("key does not exist to remove from cmdTransportManagers"); } @@ -640,7 +640,7 @@ namespace System.Management.Automation.Remoting.Client lock (syncObject) { OutOfProcessClientCommandTransportManager result = null; - cmdTransportManagers.TryGetValue(key, out result); + _cmdTransportManagers.TryGetValue(key, out result); return result; } } @@ -648,7 +648,7 @@ namespace System.Management.Automation.Remoting.Client private void OnCloseSessionCompleted() { //stop timer - closeTimeOutTimer.Change(Timeout.Infinite, Timeout.Infinite); + _closeTimeOutTimer.Change(Timeout.Infinite, Timeout.Infinite); RaiseCloseCompleted(); CleanupConnection(); } @@ -663,7 +663,7 @@ namespace System.Management.Automation.Remoting.Client { try { - OutOfProcessUtils.ProcessData(data, dataProcessingCallbacks); + OutOfProcessUtils.ProcessData(data, _dataProcessingCallbacks); } catch (Exception exception) { @@ -724,7 +724,7 @@ namespace System.Management.Automation.Remoting.Client { DataPriorityType priorityType; // This will either return data or register callback but doesn't do both. - byte[] data = dataToBeSent.ReadOrRegisterCallback(onDataAvailableToSendCallback, + byte[] data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); if (null != data) { @@ -849,8 +849,7 @@ namespace System.Management.Automation.Remoting.Client cmdTM.OnCreateCmdCompleted(); - _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.OnCommandCreationAckReceived, in progress command count after cmd creation ACK : " + cmdTransportManagers.Count + ", psGuid : " + psGuid.ToString()); - + _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.OnCommandCreationAckReceived, in progress command count after cmd creation ACK : " + _cmdTransportManagers.Count + ", psGuid : " + psGuid.ToString()); } private void OnSignalPacketReceived(Guid psGuid) @@ -890,7 +889,7 @@ namespace System.Management.Automation.Remoting.Client int commandCount; lock (syncObject) { - commandCount = cmdTransportManagers.Count; + commandCount = _cmdTransportManagers.Count; } if (psGuid == Guid.Empty) @@ -930,8 +929,8 @@ namespace System.Management.Automation.Remoting.Client { #region Private Data - private Process serverProcess; - private NewProcessConnectionInfo connectionInfo; + private Process _serverProcess; + private NewProcessConnectionInfo _connectionInfo; private bool _processCreated = true; private PowerShellProcessInstance _processInstance; @@ -939,12 +938,12 @@ namespace System.Management.Automation.Remoting.Client #region Constructor - internal OutOfProcessClientSessionTransportManager(Guid runspaceId, + internal OutOfProcessClientSessionTransportManager(Guid runspaceId, NewProcessConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) - { - this.connectionInfo = connectionInfo; + { + _connectionInfo = connectionInfo; } #endregion @@ -963,21 +962,21 @@ namespace System.Management.Automation.Remoting.Client /// internal override void CreateAsync() { - if (null != connectionInfo) + if (null != _connectionInfo) { - _processInstance = connectionInfo.Process ?? new PowerShellProcessInstance(connectionInfo.PSVersion, - connectionInfo.Credential, - connectionInfo.InitializationScript, - connectionInfo.RunAs32); - if (connectionInfo.Process != null) + _processInstance = _connectionInfo.Process ?? new PowerShellProcessInstance(_connectionInfo.PSVersion, + _connectionInfo.Credential, + _connectionInfo.InitializationScript, + _connectionInfo.RunAs32); + if (_connectionInfo.Process != null) { _processCreated = false; } // _processInstance.Start(); } - + PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, - PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); try @@ -990,7 +989,7 @@ namespace System.Management.Automation.Remoting.Client } // Attach handlers and start the process - serverProcess = _processInstance.Process; + _serverProcess = _processInstance.Process; if (_processInstance.RunspacePool != null) { @@ -1001,29 +1000,29 @@ namespace System.Management.Automation.Remoting.Client stdInWriter = _processInstance.StdInWriter; //if (stdInWriter == null) { - serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); - serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); + _serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); + _serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); } - serverProcess.Exited += new EventHandler(OnExited); + _serverProcess.Exited += new EventHandler(OnExited); //serverProcess.Start(); _processInstance.Start(); if (stdInWriter != null) { - serverProcess.CancelErrorRead(); - serverProcess.CancelOutputRead(); + _serverProcess.CancelErrorRead(); + _serverProcess.CancelOutputRead(); } // Start asynchronous reading of output/errors - serverProcess.BeginOutputReadLine(); - serverProcess.BeginErrorReadLine(); + _serverProcess.BeginOutputReadLine(); + _serverProcess.BeginErrorReadLine(); - stdInWriter = new OutOfProcessTextWriter(serverProcess.StandardInput); + stdInWriter = new OutOfProcessTextWriter(_serverProcess.StandardInput); _processInstance.StdInWriter = stdInWriter; } } - catch(System.ComponentModel.Win32Exception w32e) + catch (System.ComponentModel.Win32Exception w32e) { PSRemotingTransportException psrte = new PSRemotingTransportException(w32e, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, w32e.Message); @@ -1058,10 +1057,10 @@ namespace System.Management.Automation.Remoting.Client if (isDisposing) { KillServerProcess(); - if (null != serverProcess && _processCreated) + if (null != _serverProcess && _processCreated) { // null can happen if Dispose is called before ConnectAsync() - serverProcess.Dispose(); + _serverProcess.Dispose(); } } } @@ -1092,27 +1091,27 @@ namespace System.Management.Automation.Remoting.Client private void KillServerProcess() { - if (null == serverProcess) + if (null == _serverProcess) { // this can happen if Dispose is called before ConnectAsync() return; } - + try { - if (!serverProcess.HasExited) + if (!_serverProcess.HasExited) { - serverProcess.Exited -= OnExited; + _serverProcess.Exited -= OnExited; if (_processCreated) { - serverProcess.CancelOutputRead(); - serverProcess.CancelErrorRead(); - serverProcess.Kill(); + _serverProcess.CancelOutputRead(); + _serverProcess.CancelErrorRead(); + _serverProcess.Kill(); } - serverProcess.OutputDataReceived -= new DataReceivedEventHandler(OnOutputDataReceived); - serverProcess.ErrorDataReceived -= new DataReceivedEventHandler(OnErrorDataReceived); + _serverProcess.OutputDataReceived -= new DataReceivedEventHandler(OnOutputDataReceived); + _serverProcess.ErrorDataReceived -= new DataReceivedEventHandler(OnErrorDataReceived); } } catch (System.ComponentModel.Win32Exception) @@ -1122,7 +1121,7 @@ namespace System.Management.Automation.Remoting.Client // For processes running in an NTVDM, trying to kill with // the original handle fails with a Win32 error, so we'll // use the ID and try to get a new handle... - Process newHandle = Process.GetProcessById(serverProcess.Id); + Process newHandle = Process.GetProcessById(_serverProcess.Id); // If the process was not found, we won't get here... if (_processCreated) newHandle.Kill(); } @@ -1206,7 +1205,7 @@ namespace System.Management.Automation.Remoting.Client while (true) { string data = reader.ReadLine(); - if (data == null) + if (data == null) { // End of stream indicates the target process was lost. // Raise transport exception to invalidate the client remote runspace. @@ -1486,7 +1485,7 @@ namespace System.Management.Automation.Remoting.Client while (true) { string data = reader.ReadLine(); - if (data == null) + if (data == null) { // End of stream indicates the target process was lost. // Raise transport exception to invalidate the client remote runspace. @@ -1619,7 +1618,7 @@ namespace System.Management.Automation.Remoting.Client { throw new PSArgumentNullException("connectionInfo"); } - + _connectionInfo = connectionInfo; } @@ -1634,7 +1633,7 @@ namespace System.Management.Automation.Remoting.Client internal override void CreateAsync() { _clientPipe = new ContainerSessionNamedPipeClient( - _connectionInfo.ContainerProc.ProcessId, + _connectionInfo.ContainerProc.ProcessId, string.Empty, // AppDomainName _connectionInfo.ContainerProc.ContainerObRoot); @@ -1665,29 +1664,29 @@ namespace System.Management.Automation.Remoting.Client #endregion } - + internal class OutOfProcessClientCommandTransportManager : BaseClientCommandTransportManager { #region Private Data - private OutOfProcessTextWriter stdInWriter; - private PrioritySendDataCollection.OnDataAvailableCallback onDataAvailableToSendCallback; - private Timer signalTimeOutTimer; + private OutOfProcessTextWriter _stdInWriter; + private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private Timer _signalTimeOutTimer; #endregion #region Constructors internal OutOfProcessClientCommandTransportManager( - ClientRemotePowerShell cmd, + ClientRemotePowerShell cmd, bool noInput, OutOfProcessClientSessionTransportManagerBase sessnTM, OutOfProcessTextWriter stdInWriter) : base(cmd, sessnTM.CryptoHelper, sessnTM) { - this.stdInWriter = stdInWriter; - onDataAvailableToSendCallback = + _stdInWriter = stdInWriter; + _onDataAvailableToSendCallback = new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); - signalTimeOutTimer = new Timer(OnSignalTimeOutTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); + _signalTimeOutTimer = new Timer(OnSignalTimeOutTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); } #endregion @@ -1706,7 +1705,7 @@ namespace System.Management.Automation.Remoting.Client PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); - stdInWriter.WriteLine(OutOfProcessUtils.CreateCommandPacket(powershellInstanceId)); + _stdInWriter.WriteLine(OutOfProcessUtils.CreateCommandPacket(powershellInstanceId)); } internal override void CloseAsync() @@ -1724,18 +1723,18 @@ namespace System.Management.Automation.Remoting.Client } base.CloseAsync(); - + PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommand, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); // Send Close information to the server - if (stdInWriter != null) + if (_stdInWriter != null) { try { - stdInWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(powershellInstanceId)); + _stdInWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(powershellInstanceId)); } catch (IOException e) { @@ -1756,11 +1755,11 @@ namespace System.Management.Automation.Remoting.Client base.CloseAsync(); // Stop is equivalent to closing on the server.. - stdInWriter.WriteLine(OutOfProcessUtils.CreateSignalPacket(powershellInstanceId)); + _stdInWriter.WriteLine(OutOfProcessUtils.CreateSignalPacket(powershellInstanceId)); // start the timer..so client can fail deterministically // set the interval to 60 seconds. - signalTimeOutTimer.Change(60 * 1000, Timeout.Infinite); + _signalTimeOutTimer.Change(60 * 1000, Timeout.Infinite); } internal override void Dispose(bool isDisposing) @@ -1769,14 +1768,14 @@ namespace System.Management.Automation.Remoting.Client if (isDisposing) { StopSignalTimerAndDecrementOperations(); - signalTimeOutTimer.Dispose(); + _signalTimeOutTimer.Dispose(); } } #endregion #region Helper Methods - + internal void OnCreateCmdCompleted() { PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommandCallbackReceived, @@ -1794,7 +1793,7 @@ namespace System.Management.Automation.Remoting.Client } // Start sending data if any..and see if we can initiate a receive. - SendOneItem(); + SendOneItem(); } } @@ -1873,7 +1872,7 @@ namespace System.Management.Automation.Remoting.Client { lock (syncObject) { - signalTimeOutTimer.Change(Timeout.Infinite, Timeout.Infinite); + _signalTimeOutTimer.Change(Timeout.Infinite, Timeout.Infinite); } } @@ -1917,12 +1916,12 @@ namespace System.Management.Automation.Remoting.Client // and data is accessed by only one thread at any given time..so we can depend on this count if (serializedPipeline.Length > 0) { - data = serializedPipeline.ReadOrRegisterCallback(null); + data = serializedPipeline.ReadOrRegisterCallback(null); } else { // This will either return data or register callback but doesn't do both. - data = dataToBeSent.ReadOrRegisterCallback(onDataAvailableToSendCallback, out priorityType); + data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); } if (null != data) @@ -1947,7 +1946,7 @@ namespace System.Management.Automation.Remoting.Client return; } - stdInWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, + _stdInWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, priorityType, powershellInstanceId)); } @@ -1971,10 +1970,10 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private OutOfProcessTextWriter stdOutWriter; - private OutOfProcessTextWriter stdErrWriter; - private Dictionary cmdTransportManagers; - private object syncObject = new object(); + private OutOfProcessTextWriter _stdOutWriter; + private OutOfProcessTextWriter _stdErrWriter; + private Dictionary _cmdTransportManagers; + private object _syncObject = new object(); #endregion @@ -1985,9 +1984,9 @@ namespace System.Management.Automation.Remoting.Server { Dbg.Assert(null != outWriter, "outWriter cannot be null."); Dbg.Assert(null != errWriter, "errWriter cannot be null."); - stdOutWriter = outWriter; - stdErrWriter = errWriter; - cmdTransportManagers = new Dictionary(); + _stdOutWriter = outWriter; + _stdErrWriter = errWriter; + _cmdTransportManagers = new Dictionary(); } #endregion @@ -1999,7 +1998,7 @@ namespace System.Management.Automation.Remoting.Server base.ProcessRawData(data, stream); // Send ACK back to the client as we have processed data. - stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(Guid.Empty)); + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(Guid.Empty)); } internal override void Prepare() @@ -2009,7 +2008,7 @@ namespace System.Management.Automation.Remoting.Server protected override void SendDataToClient(byte[] data, bool flush, bool reportAsPending, bool reportAsDataBoundary) { - stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, DataPriorityType.Default, Guid.Empty)); } @@ -2020,48 +2019,48 @@ namespace System.Management.Automation.Remoting.Server internal void CreateCommandTransportManager(Guid powerShellCmdId) { - OutOfProcessServerTransportManager cmdTM = new OutOfProcessServerTransportManager(stdOutWriter, stdErrWriter, + OutOfProcessServerTransportManager cmdTM = new OutOfProcessServerTransportManager(_stdOutWriter, _stdErrWriter, powerShellCmdId, this.TypeTable, this.Fragmentor.FragmentSize, this.CryptoHelper); // this will make the Session's DataReady event handler handle // the commands data as well. This is because the state machine // is per session. cmdTM.MigrateDataReadyEventHandlers(this); - - lock (syncObject) + + lock (_syncObject) { // the dictinoary is cleared by ServerPowershellDataStructure handler // once the clean up is complete for the transport manager - Dbg.Assert(!cmdTransportManagers.ContainsKey(powerShellCmdId), "key already exists"); - cmdTransportManagers.Add(powerShellCmdId, cmdTM); + Dbg.Assert(!_cmdTransportManagers.ContainsKey(powerShellCmdId), "key already exists"); + _cmdTransportManagers.Add(powerShellCmdId, cmdTM); } // send command ack..so that client can start sending data - stdOutWriter.WriteLine(OutOfProcessUtils.CreateCommandAckPacket(powerShellCmdId)); + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateCommandAckPacket(powerShellCmdId)); } internal override AbstractServerTransportManager GetCommandTransportManager(Guid powerShellCmdId) { - lock (syncObject) + lock (_syncObject) { OutOfProcessServerTransportManager result = null; - cmdTransportManagers.TryGetValue(powerShellCmdId, out result); + _cmdTransportManagers.TryGetValue(powerShellCmdId, out result); return result; } } internal override void RemoveCommandTransportManager(Guid powerShellCmdId) { - lock (syncObject) + lock (_syncObject) { - cmdTransportManagers.Remove(powerShellCmdId); - } + _cmdTransportManagers.Remove(powerShellCmdId); + } } internal override void Close(Exception reasonForClose) { RaiseClosingEvent(); } - + #endregion } @@ -2069,10 +2068,10 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private OutOfProcessTextWriter stdOutWriter; - private OutOfProcessTextWriter stdErrWriter; - private Guid powershellInstanceId; - private bool isDataAckSendPending; + private OutOfProcessTextWriter _stdOutWriter; + private OutOfProcessTextWriter _stdErrWriter; + private Guid _powershellInstanceId; + private bool _isDataAckSendPending; #endregion @@ -2081,13 +2080,13 @@ namespace System.Management.Automation.Remoting.Server internal OutOfProcessServerTransportManager(OutOfProcessTextWriter stdOutWriter, OutOfProcessTextWriter stdErrWriter, Guid powershellInstanceId, TypeTable typeTableToUse, - int fragmentSize, + int fragmentSize, PSRemotingCryptoHelper cryptoHelper) : base(fragmentSize, cryptoHelper) { - this.stdOutWriter = stdOutWriter; - this.stdErrWriter = stdErrWriter; - this.powershellInstanceId = powershellInstanceId; + _stdOutWriter = stdOutWriter; + _stdErrWriter = stdErrWriter; + _powershellInstanceId = powershellInstanceId; this.TypeTable = typeTableToUse; this.WSManTransportErrorOccured += HandleWSManTransportError; @@ -2099,7 +2098,7 @@ namespace System.Management.Automation.Remoting.Server private void HandleWSManTransportError(object sender, TransportErrorOccuredEventArgs e) { - this.stdErrWriter.WriteLine(StringUtil.Format(RemotingErrorIdStrings.RemoteTransportError, e.Exception.TransportMessage)); + _stdErrWriter.WriteLine(StringUtil.Format(RemotingErrorIdStrings.RemoteTransportError, e.Exception.TransportMessage)); } #endregion @@ -2108,14 +2107,14 @@ namespace System.Management.Automation.Remoting.Server internal override void ProcessRawData(byte[] data, string stream) { - isDataAckSendPending = true; + _isDataAckSendPending = true; base.ProcessRawData(data, stream); - if (isDataAckSendPending) + if (_isDataAckSendPending) { - isDataAckSendPending = false; + _isDataAckSendPending = false; // Send ACK back to the client as we have processed data. - stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(powershellInstanceId)); + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(_powershellInstanceId)); } } @@ -2126,19 +2125,19 @@ namespace System.Management.Automation.Remoting.Server protected override void SendDataToClient(byte[] data, bool flush, bool reportAsPending, bool reportAsDataBoundary) { - stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, - DataPriorityType.Default, powershellInstanceId)); + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, + DataPriorityType.Default, _powershellInstanceId)); } internal override void Prepare() { - if (isDataAckSendPending) + if (_isDataAckSendPending) { - isDataAckSendPending = false; + _isDataAckSendPending = false; // let the base class prepare itself. base.Prepare(); // Send ACK back to the client as we have processed data. - stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(powershellInstanceId)); + _stdOutWriter.WriteLine(OutOfProcessUtils.CreateDataAckPacket(_powershellInstanceId)); } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index 128a7b776..8e0487191 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -32,9 +32,9 @@ namespace System.Management.Automation.Remoting { #region Private Data - private PSPrincipal userPrinicpal; - private string connectionString; - private PSPrimitiveDictionary applicationArguments; + private PSPrincipal _userPrinicpal; + private string _connectionString; + private PSPrimitiveDictionary _applicationArguments; #endregion @@ -58,7 +58,7 @@ namespace System.Management.Automation.Remoting /// private PSSenderInfo(SerializationInfo info, StreamingContext context) { - if(info == null) + if (info == null) { return; } @@ -85,9 +85,9 @@ namespace System.Management.Automation.Remoting PSObject result = PSObject.AsPSObject(PSSerializer.Deserialize(serializedData)); PSSenderInfo senderInfo = DeserializingTypeConverter.RehydratePSSenderInfo(result); - this.userPrinicpal = senderInfo.userPrinicpal; - this.connectionString = senderInfo.connectionString; - this.applicationArguments = senderInfo.applicationArguments; + _userPrinicpal = senderInfo._userPrinicpal; + _connectionString = senderInfo._connectionString; + _applicationArguments = senderInfo._applicationArguments; #if !CORECLR // TimeZone Not In CoreCLR this.clientTimeZone = senderInfo.ClientTimeZone; @@ -116,8 +116,8 @@ namespace System.Management.Automation.Remoting [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] public PSSenderInfo(PSPrincipal userPrincipal, string httpUrl) { - this.userPrinicpal = userPrincipal; - this.connectionString = httpUrl; + _userPrinicpal = userPrincipal; + _connectionString = httpUrl; } #endregion @@ -129,7 +129,7 @@ namespace System.Management.Automation.Remoting /// public PSPrincipal UserInfo { - get { return userPrinicpal; } + get { return _userPrinicpal; } // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -142,7 +142,7 @@ namespace System.Management.Automation.Remoting public TimeZone ClientTimeZone { get { return clientTimeZone; } - internal set { clientTimeZone = value; } + internal set { clientTimeZone = value; } } private TimeZone clientTimeZone; #endif @@ -151,9 +151,9 @@ namespace System.Management.Automation.Remoting /// Connection string used by the client to connect to the server. This is /// directly taken from WSMAN_SENDER_DETAILS struct (from wsman.h) /// - public string ConnectionString - { - get { return connectionString; } + public string ConnectionString + { + get { return _connectionString; } // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -164,8 +164,8 @@ namespace System.Management.Automation.Remoting /// public PSPrimitiveDictionary ApplicationArguments { - get { return applicationArguments; } - internal set { applicationArguments = value; } + get { return _applicationArguments; } + internal set { _applicationArguments = value; } } #endregion @@ -178,31 +178,31 @@ namespace System.Management.Automation.Remoting { #region Private Data - private PSIdentity psIdentity; - private WindowsIdentity windowsIdentity; + private PSIdentity _psIdentity; + private WindowsIdentity _windowsIdentity; #endregion /// /// Gets the identity of the current user principal. /// - public PSIdentity Identity - { - get { return psIdentity; } + public PSIdentity Identity + { + get { return _psIdentity; } // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. } - + /// /// Gets the WindowsIdentity (if possible) representation of the current Identity. /// PSPrincipal can represent any user for example a LiveID user, network user within /// a domain etc. This property tries to convert the Identity to WindowsIdentity /// using the user token supplied. /// - public WindowsIdentity WindowsIdentity - { - get { return windowsIdentity; } + public WindowsIdentity WindowsIdentity + { + get { return _windowsIdentity; } // No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's // and usually they dont cache this data internally..so did not want to give // cmdlets/scripts a chance to modify these. @@ -228,10 +228,10 @@ namespace System.Management.Automation.Remoting /// public bool IsInRole(string role) { - if (null != windowsIdentity) + if (null != _windowsIdentity) { // Get Windows Principal for this identity - WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity); + WindowsPrincipal windowsPrincipal = new WindowsPrincipal(_windowsIdentity); return windowsPrincipal.IsInRole(role); } else @@ -245,10 +245,10 @@ namespace System.Management.Automation.Remoting /// internal bool IsInRole(WindowsBuiltInRole role) { - if (null != windowsIdentity) + if (null != _windowsIdentity) { // Get Windows Principal for this identity - WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity); + WindowsPrincipal windowsPrincipal = new WindowsPrincipal(_windowsIdentity); return windowsPrincipal.IsInRole(role); } else @@ -271,8 +271,8 @@ namespace System.Management.Automation.Remoting /// public PSPrincipal(PSIdentity identity, WindowsIdentity windowsIdentity) { - this.psIdentity = identity; - this.windowsIdentity = windowsIdentity; + _psIdentity = identity; + _windowsIdentity = windowsIdentity; } #endregion @@ -285,10 +285,10 @@ namespace System.Management.Automation.Remoting { #region Private Data - private string authenticationType; - private bool isAuthenticated; - private string userName; - private PSCertificateDetails certDetails; + private string _authenticationType; + private bool _isAuthenticated; + private string _userName; + private PSCertificateDetails _certDetails; #endregion @@ -304,19 +304,19 @@ namespace System.Management.Automation.Remoting /// WSMAN_AUTH_CLIENT_CERTIFICATE /// WSMAN_AUTH_LIVEID /// - public string AuthenticationType { get { return authenticationType; } } + public string AuthenticationType { get { return _authenticationType; } } /// /// Gets a value that indicates whether the user has been authenticated. /// - public bool IsAuthenticated { get { return isAuthenticated; } } + public bool IsAuthenticated { get { return _isAuthenticated; } } /// /// Gets the name of the user. /// - public string Name { get { return userName; } } + public string Name { get { return _userName; } } /// /// Gets the certificate details of the user if supported, null otherwise. /// - public PSCertificateDetails CertificateDetails { get { return certDetails; } } + public PSCertificateDetails CertificateDetails { get { return _certDetails; } } #region Public Constructor @@ -346,10 +346,10 @@ namespace System.Management.Automation.Remoting /// public PSIdentity(string authType, bool isAuthenticated, string userName, PSCertificateDetails cert) { - this.authenticationType = authType; - this.isAuthenticated = isAuthenticated; - this.userName = userName; - this.certDetails = cert; + _authenticationType = authType; + _isAuthenticated = isAuthenticated; + _userName = userName; + _certDetails = cert; } #endregion @@ -361,25 +361,25 @@ namespace System.Management.Automation.Remoting public sealed class PSCertificateDetails { #region Private Data - - private string subject; - private string issuerName; - private string issuerThumbprint; + + private string _subject; + private string _issuerName; + private string _issuerThumbprint; #endregion /// /// Gets Subject of the certificate. /// - public string Subject { get { return subject; } } + public string Subject { get { return _subject; } } /// /// Gets the issuer name of the certificate. /// - public string IssuerName { get { return issuerName; } } + public string IssuerName { get { return _issuerName; } } /// /// Gets the issuer thumb print. /// - public string IssuerThumbprint { get { return issuerThumbprint;} } + public string IssuerThumbprint { get { return _issuerThumbprint; } } #region Constructor @@ -397,9 +397,9 @@ namespace System.Management.Automation.Remoting /// public PSCertificateDetails(string subject, string issuerName, string issuerThumbprint) { - this.subject = subject; - this.issuerName = issuerName; - this.issuerThumbprint = issuerThumbprint; + _subject = subject; + _issuerName = issuerName; + _issuerThumbprint = issuerThumbprint; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 9b414c199..99faa9886 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -52,7 +52,7 @@ namespace System.Management.Automation.Remoting } internal set { - _privateData = value; + _privateData = value; } } @@ -62,7 +62,6 @@ namespace System.Management.Automation.Remoting private PSSessionConfigurationData() { - } internal static string Unescape(string s) @@ -85,16 +84,16 @@ namespace System.Management.Automation.Remoting configurationData = Unescape(configurationData); XmlReaderSettings readerSettings = new XmlReaderSettings - { - CheckCharacters = false, - IgnoreComments = true, - IgnoreProcessingInstructions = true, - MaxCharactersInDocument = 10000, + { + CheckCharacters = false, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + MaxCharactersInDocument = 10000, #if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR - XmlResolver = null, + XmlResolver = null, #endif - ConformanceLevel = ConformanceLevel.Fragment - }; + ConformanceLevel = ConformanceLevel.Fragment + }; using (XmlReader reader = XmlReader.Create(new StringReader(configurationData), readerSettings)) { @@ -237,6 +236,5 @@ namespace System.Management.Automation.Remoting private const string ValueToken = "Value"; #endregion Private Members - } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 77382cbed..bc766df7c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -36,7 +36,7 @@ namespace System.Management.Automation.Remoting } #region Sending Data - + /// /// DataStructure used by different remoting protocol / /// DataStructures to pass data to transport manager. @@ -51,18 +51,18 @@ namespace System.Management.Automation.Remoting // actual data store(s) to store priority based data and its // corresponding sync objects to provide thread safety. - private SerializedDataStream[] dataToBeSent; + private SerializedDataStream[] _dataToBeSent; // fragmentor used to serialize & fragment objects added to this collection. - private Fragmentor fragmentor; - private object[] syncObjects; - + private Fragmentor _fragmentor; + private object[] _syncObjects; + // callbacks used if no data is available at any time. // these callbacks are used to notify when data becomes available under // suc circumstances. - private OnDataAvailableCallback onDataAvailableCallback; - private SerializedDataStream.OnDataAvailableCallback onSendCollectionDataAvailable; - private bool isHandlingCallback; - private object readSyncObject = new object(); + private OnDataAvailableCallback _onDataAvailableCallback; + private SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable; + private bool _isHandlingCallback; + private object _readSyncObject = new object(); /// /// Callback that is called once a fragmented data is available to send. @@ -73,7 +73,7 @@ namespace System.Management.Automation.Remoting /// /// Priority stream to which belongs to. /// - internal delegate void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType); + internal delegate void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType); #endregion @@ -84,7 +84,7 @@ namespace System.Management.Automation.Remoting /// internal PrioritySendDataCollection() { - onSendCollectionDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); + _onSendCollectionDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); } #endregion @@ -93,19 +93,19 @@ namespace System.Management.Automation.Remoting internal Fragmentor Fragmentor { - get { return fragmentor; } - set + get { return _fragmentor; } + set { Dbg.Assert(null != value, "Fragmentor cannot be null."); - fragmentor = value; + _fragmentor = value; // create serialized streams using fragment size. string[] names = Enum.GetNames(typeof(DataPriorityType)); - dataToBeSent = new SerializedDataStream[names.Length]; - syncObjects = new object[names.Length]; + _dataToBeSent = new SerializedDataStream[names.Length]; + _syncObjects = new object[names.Length]; for (int i = 0; i < names.Length; i++) { - dataToBeSent[i] = new SerializedDataStream(fragmentor.FragmentSize); - syncObjects[i] = new object(); + _dataToBeSent[i] = new SerializedDataStream(_fragmentor.FragmentSize); + _syncObjects[i] = new object(); } } } @@ -126,15 +126,15 @@ namespace System.Management.Automation.Remoting internal void Add(RemoteDataObject data, DataPriorityType priority) { Dbg.Assert(null != data, "Cannot send null data object"); - Dbg.Assert(null != fragmentor, "Fragmentor cannot be null while adding objects"); - Dbg.Assert(null != dataToBeSent, "Serialized streams are not initialized"); + Dbg.Assert(null != _fragmentor, "Fragmentor cannot be null while adding objects"); + Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized"); // make sure the only one object is fragmented and added to the collection // at any give time. This way the order of fragmenets is maintained // in the SendDataCollection(s). - lock(syncObjects[(int)priority]) + lock (_syncObjects[(int)priority]) { - fragmentor.Fragment(data, dataToBeSent[(int)priority]); + _fragmentor.Fragment(data, _dataToBeSent[(int)priority]); } } @@ -160,15 +160,15 @@ namespace System.Management.Automation.Remoting /// internal void Clear() { - Dbg.Assert(null != dataToBeSent, "Serialized streams are not initialized"); - lock(syncObjects[(int)DataPriorityType.PromptResponse]) + Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized"); + lock (_syncObjects[(int)DataPriorityType.PromptResponse]) { - dataToBeSent[(int)DataPriorityType.PromptResponse].Dispose(); + _dataToBeSent[(int)DataPriorityType.PromptResponse].Dispose(); } - lock (syncObjects[(int)DataPriorityType.Default]) + lock (_syncObjects[(int)DataPriorityType.Default]) { - dataToBeSent[(int)DataPriorityType.Default].Dispose(); + _dataToBeSent[(int)DataPriorityType.Default].Dispose(); } } @@ -197,28 +197,28 @@ namespace System.Management.Automation.Remoting /// /// A FragementRemoteObject if available, otherwise null. /// - internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback, + internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback, out DataPriorityType priorityType) { - lock (readSyncObject) - { + lock (_readSyncObject) + { priorityType = DataPriorityType.Default; // send data from which ever stream that has data directly. byte[] result = null; - result = dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(onSendCollectionDataAvailable); + result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.PromptResponse; if (null == result) { - result = dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(onSendCollectionDataAvailable); + result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.Default; } // no data to return..so register the callback. if (null == result) { // register callback. - onDataAvailableCallback = callback; + _onDataAvailableCallback = callback; } return result; @@ -227,23 +227,23 @@ namespace System.Management.Automation.Remoting private void OnDataAvailable(byte[] data, bool isEndFragment) { - lock(readSyncObject) + lock (_readSyncObject) { // PromptResponse and Default priority collection can both raise at the // same time. This will take care of the situation. - if (isHandlingCallback) + if (_isHandlingCallback) { return; } - isHandlingCallback = true; + _isHandlingCallback = true; } - if (null != onDataAvailableCallback) + if (null != _onDataAvailableCallback) { DataPriorityType prType; // now get the fragment and call the callback.. - byte[] result = ReadOrRegisterCallback(onDataAvailableCallback, out prType); + byte[] result = ReadOrRegisterCallback(_onDataAvailableCallback, out prType); if (null != result) { @@ -251,18 +251,18 @@ namespace System.Management.Automation.Remoting // multiple times. we are resetting before actually calling // the callback to make sure the caller calls ReadOrRegisterCallback // at a later point and we dont loose the callback handle. - OnDataAvailableCallback realCallback = onDataAvailableCallback; - onDataAvailableCallback = null; + OnDataAvailableCallback realCallback = _onDataAvailableCallback; + _onDataAvailableCallback = null; realCallback(result, prType); } } - isHandlingCallback = false; + _isHandlingCallback = false; } #endregion } - + #endregion #region Receiving Data @@ -277,44 +277,44 @@ namespace System.Management.Automation.Remoting #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] - static private PSTraceSource baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); + static private PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion #region Private Data // fragmentor used to defragment objects added to this collection. - private Fragmentor defragmentor; - + private Fragmentor _defragmentor; + // this stream holds incoming data..this stream doesn't know anything // about fragment boundaries. - private MemoryStream pendingDataStream; + private MemoryStream _pendingDataStream; // the idea is to maintain 1 whole object. // 1 whole object may contain any number of fragments. blob from // each fragement is written to this stream. - private MemoryStream dataToProcessStream; - private long currentObjectId; - private long currentFrgId; + private MemoryStream _dataToProcessStream; + private long _currentObjectId; + private long _currentFrgId; // max deseriazlied object size in bytes - private Nullable maxReceivedObjectSize; - private int totalReceivedObjectSizeSoFar; - private bool isCreateByClientTM; + private Nullable _maxReceivedObjectSize; + private int _totalReceivedObjectSizeSoFar; + private bool _isCreateByClientTM; // this indicates if any off sync fragments canbe ignored // this gets reset (to false) upon receiving the next "start" fragment along the stream - private bool canIgnoreOffSyncFragments = false; + private bool _canIgnoreOffSyncFragments = false; // objects need to cleanly release resources without // locking entire processing logic. - private object syncObject; - private bool isDisposed; + private object _syncObject; + private bool _isDisposed; // holds the number of threads that are currently in // ProcessRawData method. This might happen only for // ServerCommandTransportManager case where the command // is run in the same thread that runs ProcessRawData (to avoid // thread context switch). - private int numberOfThreadsProcessing; + private int _numberOfThreadsProcessing; // limits the numberOfThreadsProcessing variable. - private int maxNumberOfThreadsToAllowForProcessing = 1; + private int _maxNumberOfThreadsToAllowForProcessing = 1; #endregion @@ -326,7 +326,7 @@ namespace System.Management.Automation.Remoting /// /// Deserialized object that can be processed. /// - internal delegate void OnDataAvailableCallback(RemoteDataObject data); + internal delegate void OnDataAvailableCallback(RemoteDataObject data); #endregion @@ -350,22 +350,22 @@ namespace System.Management.Automation.Remoting // to nor shrink the stream, although you might be able to modify the existing contents // depending on the parameters passed into the constructor. Empty memory streams are // resizable, and can be written to and read from. - pendingDataStream = new MemoryStream(); - syncObject = new object(); - this.defragmentor = defragmentor; - isCreateByClientTM = createdByClientTM; + _pendingDataStream = new MemoryStream(); + _syncObject = new object(); + _defragmentor = defragmentor; + _isCreateByClientTM = createdByClientTM; } #endregion #region Internal Methods / Properties - + /// /// Limits the deserialized object size received from a remote machine. /// internal Nullable MaximumReceivedObjectSize { - set { maxReceivedObjectSize = value; } + set { _maxReceivedObjectSize = value; } } /// @@ -376,7 +376,7 @@ namespace System.Management.Automation.Remoting /// internal void AllowTwoThreadsToProcessRawData() { - maxNumberOfThreadsToAllowForProcessing = 2; + _maxNumberOfThreadsToAllowForProcessing = 2; } /// @@ -387,7 +387,7 @@ namespace System.Management.Automation.Remoting /// internal void PrepareForStreamConnect() { - canIgnoreOffSyncFragments = true; + _canIgnoreOffSyncFragments = true; } /// @@ -420,16 +420,16 @@ namespace System.Management.Automation.Remoting { Dbg.Assert(null != data, "Cannot process null data"); Dbg.Assert(null != callback, "Callback cannot be null"); - - lock (syncObject) + + lock (_syncObject) { - if (isDisposed) + if (_isDisposed) { return; } - numberOfThreadsProcessing++; - if (numberOfThreadsProcessing > maxNumberOfThreadsToAllowForProcessing) + _numberOfThreadsProcessing++; + if (_numberOfThreadsProcessing > _maxNumberOfThreadsToAllowForProcessing) { Dbg.Assert(false, "Multiple threads are not allowed in ProcessRawData."); } @@ -437,22 +437,22 @@ namespace System.Management.Automation.Remoting try { - pendingDataStream.Write(data, 0, data.Length); + _pendingDataStream.Write(data, 0, data.Length); // this do loop will process one deserialized object. // using a loop allows to process multiple objects within // the same packet do { - if (pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength) + if (_pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength) { // there is not enough data to be processed. - baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.", - pendingDataStream.Length, FragmentedRemoteObject.HeaderLength); + s_baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.", + _pendingDataStream.Length, FragmentedRemoteObject.HeaderLength); return; } - byte[] dataRead = pendingDataStream.ToArray(); + byte[] dataRead = _pendingDataStream.ToArray(); // there is enough data to process here. get the fragment header long objectId = FragmentedRemoteObject.GetObjectId(dataRead, 0); @@ -466,13 +466,13 @@ namespace System.Management.Automation.Remoting bool eFlag = FragmentedRemoteObject.GetIsEndFragment(dataRead, 0); int blobLength = FragmentedRemoteObject.GetBlobLength(dataRead, 0); - if ((baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((s_baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { - baseTracer.WriteLine("Object Id: {0}", objectId); - baseTracer.WriteLine("Fragment Id: {0}", fragmentId); - baseTracer.WriteLine("Start Flag: {0}", sFlag); - baseTracer.WriteLine("End Flag: {0}", eFlag); - baseTracer.WriteLine("Blob Length: {0}", blobLength); + s_baseTracer.WriteLine("Object Id: {0}", objectId); + s_baseTracer.WriteLine("Fragment Id: {0}", fragmentId); + s_baseTracer.WriteLine("Start Flag: {0}", sFlag); + s_baseTracer.WriteLine("End Flag: {0}", eFlag); + s_baseTracer.WriteLine("Blob Length: {0}", blobLength); } int totalLengthOfFragment = 0; @@ -483,40 +483,40 @@ namespace System.Management.Automation.Remoting } catch (System.OverflowException) { - baseTracer.WriteLine("Fragement too big."); + s_baseTracer.WriteLine("Fragement too big."); ResetRecieveData(); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig); throw e; } - if (pendingDataStream.Length < totalLengthOfFragment) + if (_pendingDataStream.Length < totalLengthOfFragment) { - baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.", - pendingDataStream.Length, totalLengthOfFragment); + s_baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.", + _pendingDataStream.Length, totalLengthOfFragment); return; } // ensure object size limit is not reached - if (maxReceivedObjectSize.HasValue) + if (_maxReceivedObjectSize.HasValue) { - totalReceivedObjectSizeSoFar = unchecked(totalReceivedObjectSizeSoFar + totalLengthOfFragment); - if ((totalReceivedObjectSizeSoFar < 0) || (totalReceivedObjectSizeSoFar > maxReceivedObjectSize.Value)) + _totalReceivedObjectSizeSoFar = unchecked(_totalReceivedObjectSizeSoFar + totalLengthOfFragment); + if ((_totalReceivedObjectSizeSoFar < 0) || (_totalReceivedObjectSizeSoFar > _maxReceivedObjectSize.Value)) { - baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}", - totalReceivedObjectSizeSoFar, maxReceivedObjectSize); + s_baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}", + _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); PSRemotingTransportException e = null; - if (isCreateByClientTM) + if (_isCreateByClientTM) { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient, - totalReceivedObjectSizeSoFar, maxReceivedObjectSize); + _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); } else { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer, - totalReceivedObjectSizeSoFar, maxReceivedObjectSize); + _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); } ResetRecieveData(); @@ -526,14 +526,14 @@ namespace System.Management.Automation.Remoting // appears like stream doesn't have individual postion marker for read and write // since we are going to read from now... - pendingDataStream.Seek(0, SeekOrigin.Begin); + _pendingDataStream.Seek(0, SeekOrigin.Begin); // we have enough data to process..so read the data from the stream and process. byte[] oneFragment = new byte[totalLengthOfFragment]; // this will change position back to totalLengthOfFragment - int dataCount = pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment); + int dataCount = _pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment); Dbg.Assert(dataCount == totalLengthOfFragment, "Unable to read enough data from the stream. Read failed"); - + PSEtwLog.LogAnalyticVerbose( PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, @@ -545,74 +545,74 @@ namespace System.Management.Automation.Remoting new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength)); byte[] extraData = null; - if (totalLengthOfFragment < pendingDataStream.Length) + if (totalLengthOfFragment < _pendingDataStream.Length) { // there is more data in the stream than fragment size..so save that data - extraData = new byte[pendingDataStream.Length - totalLengthOfFragment]; - pendingDataStream.Read(extraData, 0, (int)(pendingDataStream.Length - totalLengthOfFragment)); + extraData = new byte[_pendingDataStream.Length - totalLengthOfFragment]; + _pendingDataStream.Read(extraData, 0, (int)(_pendingDataStream.Length - totalLengthOfFragment)); } // reset incoming stream. - pendingDataStream.Dispose(); - pendingDataStream = new MemoryStream(); + _pendingDataStream.Dispose(); + _pendingDataStream = new MemoryStream(); if (null != extraData) { - pendingDataStream.Write(extraData, 0, extraData.Length); + _pendingDataStream.Write(extraData, 0, extraData.Length); } if (sFlag) { - canIgnoreOffSyncFragments = false; //reset this upon receiving a start fragment of a fresh object - currentObjectId = objectId; + _canIgnoreOffSyncFragments = false; //reset this upon receiving a start fragment of a fresh object + _currentObjectId = objectId; // Memory streams created with an unsigned byte array provide a non-resizable stream view // of the data, and can only be written to. When using a byte array, you can neither append // to nor shrink the stream, although you might be able to modify the existing contents // depending on the parameters passed into the constructor. Empty memory streams are // resizable, and can be written to and read from. - dataToProcessStream = new MemoryStream(); + _dataToProcessStream = new MemoryStream(); } else { // check if the data belongs to the same object as the start fragment - if (objectId != currentObjectId) + if (objectId != _currentObjectId) { - baseTracer.WriteLine("ObjectId != CurrentObjectId"); + s_baseTracer.WriteLine("ObjectId != CurrentObjectId"); //TODO - drop an ETW event ResetRecieveData(); - if (!canIgnoreOffSyncFragments) + if (!_canIgnoreOffSyncFragments) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching); throw e; } else { - baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId"); + s_baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId"); continue; } } - if (fragmentId != (currentFrgId + 1)) + if (fragmentId != (_currentFrgId + 1)) { - baseTracer.WriteLine("Fragment Id is not in sequence."); + s_baseTracer.WriteLine("Fragment Id is not in sequence."); //TODO - drop an ETW event ResetRecieveData(); - if (!canIgnoreOffSyncFragments) + if (!_canIgnoreOffSyncFragments) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.FragmetIdsNotInSequence); throw e; } else { - baseTracer.WriteLine("Ignoring Fragment Id is not in sequence."); + s_baseTracer.WriteLine("Ignoring Fragment Id is not in sequence."); continue; } } } // make fragment id from this packet as the current fragment id - currentFrgId = fragmentId; + _currentFrgId = fragmentId; // store the blob in a separate stream - dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength); + _dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength); if (eFlag) { @@ -620,10 +620,10 @@ namespace System.Management.Automation.Remoting { // appears like stream doesn't individual postion marker for read and write // since we are going to read from now..i am resetting position to 0. - dataToProcessStream.Seek(0, SeekOrigin.Begin); - RemoteDataObject remoteObject = RemoteDataObject.CreateFrom(dataToProcessStream, defragmentor); - baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId); - baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId); + _dataToProcessStream.Seek(0, SeekOrigin.Begin); + RemoteDataObject remoteObject = RemoteDataObject.CreateFrom(_dataToProcessStream, _defragmentor); + s_baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId); + s_baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId); // notify the caller that a deserialized object is available. callback(remoteObject); } @@ -633,7 +633,7 @@ namespace System.Management.Automation.Remoting ResetRecieveData(); } - if (isDisposed) + if (_isDisposed) { break; } @@ -642,13 +642,13 @@ namespace System.Management.Automation.Remoting } finally { - lock (syncObject) + lock (_syncObject) { - if (isDisposed && (numberOfThreadsProcessing == 1)) + if (_isDisposed && (_numberOfThreadsProcessing == 1)) { ReleaseResources(); } - numberOfThreadsProcessing--; + _numberOfThreadsProcessing--; } } } @@ -659,27 +659,27 @@ namespace System.Management.Automation.Remoting private void ResetRecieveData() { // reset resources used to store incoming data (for a single object) - if (null != dataToProcessStream) + if (null != _dataToProcessStream) { - dataToProcessStream.Dispose(); + _dataToProcessStream.Dispose(); } - currentObjectId = 0; - currentFrgId = 0; - totalReceivedObjectSizeSoFar = 0; + _currentObjectId = 0; + _currentFrgId = 0; + _totalReceivedObjectSizeSoFar = 0; } private void ReleaseResources() { - if (null != pendingDataStream) + if (null != _pendingDataStream) { - pendingDataStream.Dispose(); - pendingDataStream = null; + _pendingDataStream.Dispose(); + _pendingDataStream = null; } - if (null != dataToProcessStream) + if (null != _dataToProcessStream) { - dataToProcessStream.Dispose(); - dataToProcessStream = null; + _dataToProcessStream.Dispose(); + _dataToProcessStream = null; } } #endregion @@ -700,10 +700,10 @@ namespace System.Management.Automation.Remoting internal virtual void Dispose(bool isDisposing) { - lock (syncObject) + lock (_syncObject) { - isDisposed = true; - if (numberOfThreadsProcessing == 0) + _isDisposed = true; + if (_numberOfThreadsProcessing == 0) { ReleaseResources(); } @@ -723,14 +723,14 @@ namespace System.Management.Automation.Remoting { #region Private Data - private Fragmentor defragmentor; - private ReceiveDataCollection[] recvdData; - private bool isCreateByClientTM; + private Fragmentor _defragmentor; + private ReceiveDataCollection[] _recvdData; + private bool _isCreateByClientTM; #endregion #region Constructor - + /// /// Construct a priority recieve data collection /// @@ -741,27 +741,27 @@ namespace System.Management.Automation.Remoting /// internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { - this.defragmentor = defragmentor; + _defragmentor = defragmentor; string[] names = Enum.GetNames(typeof(DataPriorityType)); - recvdData = new ReceiveDataCollection[names.Length]; + _recvdData = new ReceiveDataCollection[names.Length]; for (int index = 0; index < names.Length; index++) { - recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM); + _recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM); } - isCreateByClientTM = createdByClientTM; + _isCreateByClientTM = createdByClientTM; } #endregion #region Internal Methods / Properties - + /// /// Limits the total data received from a remote machine. /// internal Nullable MaximumReceivedDataSize { - set + set { - defragmentor.DeserializationContext.MaximumAllowedMemory = value; + _defragmentor.DeserializationContext.MaximumAllowedMemory = value; } } @@ -772,7 +772,7 @@ namespace System.Management.Automation.Remoting { set { - foreach (ReceiveDataCollection recvdDataBuffer in recvdData) + foreach (ReceiveDataCollection recvdDataBuffer in _recvdData) { recvdDataBuffer.MaximumReceivedObjectSize = value; } @@ -785,9 +785,9 @@ namespace System.Management.Automation.Remoting /// internal void PrepareForStreamConnect() { - for (int index = 0; index < recvdData.Length; index++) + for (int index = 0; index < _recvdData.Length; index++) { - recvdData[index].PrepareForStreamConnect(); + _recvdData[index].PrepareForStreamConnect(); } } @@ -800,9 +800,9 @@ namespace System.Management.Automation.Remoting /// internal void AllowTwoThreadsToProcessRawData() { - for (int index = 0; index < recvdData.Length; index++) + for (int index = 0; index < _recvdData.Length; index++) { - recvdData[index].AllowTwoThreadsToProcessRawData(); + _recvdData[index].AllowTwoThreadsToProcessRawData(); } } @@ -837,7 +837,7 @@ namespace System.Management.Automation.Remoting /// /// Might throw other exceptions as the deserialized object is handled here. /// - internal void ProcessRawData(byte[] data, + internal void ProcessRawData(byte[] data, DataPriorityType priorityType, ReceiveDataCollection.OnDataAvailableCallback callback) { @@ -845,29 +845,29 @@ namespace System.Management.Automation.Remoting try { - defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length); + _defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length); } - catch(System.Xml.XmlException) + catch (System.Xml.XmlException) { PSRemotingTransportException e = null; - if (isCreateByClientTM) + if (_isCreateByClientTM) { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient, - defragmentor.DeserializationContext.MaximumAllowedMemory.Value); + _defragmentor.DeserializationContext.MaximumAllowedMemory.Value); } else { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer, - defragmentor.DeserializationContext.MaximumAllowedMemory.Value); + _defragmentor.DeserializationContext.MaximumAllowedMemory.Value); } throw e; } - recvdData[(int)priorityType].ProcessRawData(data, callback); + _recvdData[(int)priorityType].ProcessRawData(data, callback); } #endregion @@ -888,11 +888,11 @@ namespace System.Management.Automation.Remoting internal virtual void Dispose(bool isDisposing) { - if (null != recvdData) + if (null != _recvdData) { - for (int index = 0; index < recvdData.Length; index++) + for (int index = 0; index < _recvdData.Length; index++) { - recvdData[index].Dispose(); + _recvdData[index].Dispose(); } } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 1d6686cee..6869f44ae 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -149,7 +149,7 @@ namespace System.Management.Automation.Remoting.Client /// internal struct MarshalledObject : IDisposable { - private IntPtr dataPtr; + private IntPtr _dataPtr; /// /// Constructs a MarshalledObject with the supplied @@ -158,13 +158,13 @@ namespace System.Management.Automation.Remoting.Client /// internal MarshalledObject(IntPtr dataPtr) { - this.dataPtr = dataPtr; + _dataPtr = dataPtr; } /// /// Gets the unmanaged ptr. /// - internal IntPtr DataPtr { get { return dataPtr; } } + internal IntPtr DataPtr { get { return _dataPtr; } } /// /// Creates a MarshalledObject for the specified object. @@ -181,7 +181,7 @@ namespace System.Management.Automation.Remoting.Client // Now create the MarshalledObject and return. MarshalledObject result = new MarshalledObject(); - result.dataPtr = ptr; + result._dataPtr = ptr; return result; } @@ -191,10 +191,10 @@ namespace System.Management.Automation.Remoting.Client /// public void Dispose() { - if (IntPtr.Zero != dataPtr) + if (IntPtr.Zero != _dataPtr) { - Marshal.FreeHGlobal(dataPtr); - dataPtr = IntPtr.Zero; + Marshal.FreeHGlobal(_dataPtr); + _dataPtr = IntPtr.Zero; } } @@ -205,7 +205,7 @@ namespace System.Management.Automation.Remoting.Client /// public static implicit operator IntPtr(MarshalledObject obj) { - return obj.dataPtr; + return obj._dataPtr; } } @@ -310,16 +310,16 @@ namespace System.Management.Automation.Remoting.Client internal IntPtr password; } - private WSManUserNameCredentialStruct cred; - private MarshalledObject data; + private WSManUserNameCredentialStruct _cred; + private MarshalledObject _data; /// /// Default constructor /// internal WSManUserNameAuthenticationCredentials() { - cred = new WSManUserNameCredentialStruct(); - data = MarshalledObject.Create(cred); + _cred = new WSManUserNameCredentialStruct(); + _data = MarshalledObject.Create(_cred); } /// @@ -343,15 +343,15 @@ namespace System.Management.Automation.Remoting.Client internal WSManUserNameAuthenticationCredentials(string name, System.Security.SecureString pwd, WSManAuthenticationMechanism authMechanism) { - cred = new WSManUserNameCredentialStruct(); - cred.authenticationMechanism = authMechanism; - cred.userName = name; + _cred = new WSManUserNameCredentialStruct(); + _cred.authenticationMechanism = authMechanism; + _cred.userName = name; if (null != pwd) { - cred.password = ClrFacade.SecureStringToCoTaskMemUnicode(pwd); + _cred.password = ClrFacade.SecureStringToCoTaskMemUnicode(pwd); } - data = MarshalledObject.Create(cred); + _data = MarshalledObject.Create(_cred); } /// @@ -359,7 +359,7 @@ namespace System.Management.Automation.Remoting.Client /// internal WSManUserNameCredentialStruct CredentialStruct { - get { return cred; } + get { return _cred; } } /// @@ -368,7 +368,7 @@ namespace System.Management.Automation.Remoting.Client /// public override MarshalledObject GetMarshalledObject() { - return data; + return _data; } /// @@ -377,13 +377,13 @@ namespace System.Management.Automation.Remoting.Client /// protected override void Dispose(bool isDisposing) { - if (cred.password != IntPtr.Zero) + if (_cred.password != IntPtr.Zero) { - Marshal.ZeroFreeCoTaskMemUnicode(cred.password); - cred.password = IntPtr.Zero; + Marshal.ZeroFreeCoTaskMemUnicode(_cred.password); + _cred.password = IntPtr.Zero; } - data.Dispose(); + _data.Dispose(); } } @@ -396,7 +396,7 @@ namespace System.Management.Automation.Remoting.Client /// /// [StructLayout(LayoutKind.Sequential)] - struct WSManThumbprintStruct + private struct WSManThumbprintStruct { /// /// @@ -413,7 +413,7 @@ namespace System.Management.Automation.Remoting.Client /// internal IntPtr reserved; } - private MarshalledObject data; + private MarshalledObject _data; /// /// Constructs an WSManCertificateThumbprintCredentials object. @@ -428,7 +428,7 @@ namespace System.Management.Automation.Remoting.Client cred.certificateThumbprint = thumbPrint; cred.reserved = IntPtr.Zero; - data = MarshalledObject.Create(cred); + _data = MarshalledObject.Create(cred); } /// @@ -437,7 +437,7 @@ namespace System.Management.Automation.Remoting.Client /// public override MarshalledObject GetMarshalledObject() { - return data; + return _data; } /// @@ -447,7 +447,7 @@ namespace System.Management.Automation.Remoting.Client protected override void Dispose(bool isDisposing) { // data is of struct type..so there is no need to set it to null.. - data.Dispose(); + _data.Dispose(); } } @@ -556,7 +556,7 @@ namespace System.Management.Automation.Remoting.Client /// encoding which is specific to WSManSendShellInput API; this option can be used /// with WSManGetSessionOptionAsDword API; it cannot be used with WSManSetSessionOption API. /// - WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB = 29, + WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB = 29, /// /// string - /// @@ -573,7 +573,7 @@ namespace System.Management.Automation.Remoting.Client /// DWORD - When using just a machine name in the connection string use an SSL connection. /// 0 means HTTP, 1 means HTTPS. Default is 0. /// - WSMAN_OPTION_USE_SSL = 33 + WSMAN_OPTION_USE_SSL = 33 #endregion } @@ -640,11 +640,11 @@ namespace System.Management.Automation.Remoting.Client /// internal class WSManData_ManToUn : IDisposable { - private WSManDataStruct internalData; + private WSManDataStruct _internalData; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr marshalledObject = IntPtr.Zero; + private IntPtr _marshalledObject = IntPtr.Zero; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr marshalledBuffer = IntPtr.Zero; + private IntPtr _marshalledBuffer = IntPtr.Zero; /// /// Constructs a WSMAN_DATA_BINARY object. This is used to send @@ -655,18 +655,18 @@ namespace System.Management.Automation.Remoting.Client { Dbg.Assert(null != data, "Data cannot be null"); - internalData = new WSManDataStruct(); - internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); - internalData.binaryOrTextData.bufferLength = data.Length; - internalData.type = (uint)WSManDataType.WSMAN_DATA_TYPE_BINARY; + _internalData = new WSManDataStruct(); + _internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); + _internalData.binaryOrTextData.bufferLength = data.Length; + _internalData.type = (uint)WSManDataType.WSMAN_DATA_TYPE_BINARY; - IntPtr dataToSendPtr = Marshal.AllocHGlobal(internalData.binaryOrTextData.bufferLength); - internalData.binaryOrTextData.data = dataToSendPtr; - marshalledBuffer = dataToSendPtr; // Stored directly to enable graceful clean up during finalizer scenarios + IntPtr dataToSendPtr = Marshal.AllocHGlobal(_internalData.binaryOrTextData.bufferLength); + _internalData.binaryOrTextData.data = dataToSendPtr; + _marshalledBuffer = dataToSendPtr; // Stored directly to enable graceful clean up during finalizer scenarios - Marshal.Copy(data, 0, internalData.binaryOrTextData.data, internalData.binaryOrTextData.bufferLength); - marshalledObject = Marshal.AllocHGlobal(ClrFacade.SizeOf()); - Marshal.StructureToPtr(internalData, marshalledObject, false); + Marshal.Copy(data, 0, _internalData.binaryOrTextData.data, _internalData.binaryOrTextData.bufferLength); + _marshalledObject = Marshal.AllocHGlobal(ClrFacade.SizeOf()); + Marshal.StructureToPtr(_internalData, _marshalledObject, false); } /// @@ -678,16 +678,16 @@ namespace System.Management.Automation.Remoting.Client { Dbg.Assert(null != data, "Data cannot be null"); - internalData = new WSManDataStruct(); - internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); - internalData.binaryOrTextData.bufferLength = data.Length; - internalData.type = (uint)WSManDataType.WSMAN_DATA_TYPE_TEXT; + _internalData = new WSManDataStruct(); + _internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); + _internalData.binaryOrTextData.bufferLength = data.Length; + _internalData.type = (uint)WSManDataType.WSMAN_DATA_TYPE_TEXT; // marshal text data - internalData.binaryOrTextData.data = Marshal.StringToHGlobalUni(data); - marshalledBuffer = internalData.binaryOrTextData.data; // Stored directly to enable graceful clean up during finalizer scenarios - marshalledObject = Marshal.AllocHGlobal(ClrFacade.SizeOf()); - Marshal.StructureToPtr(internalData, marshalledObject, false); + _internalData.binaryOrTextData.data = Marshal.StringToHGlobalUni(data); + _marshalledBuffer = _internalData.binaryOrTextData.data; // Stored directly to enable graceful clean up during finalizer scenarios + _marshalledObject = Marshal.AllocHGlobal(ClrFacade.SizeOf()); + Marshal.StructureToPtr(_internalData, _marshalledObject, false); } /// @@ -702,13 +702,13 @@ namespace System.Management.Automation.Remoting.Client Dispose(false); } - /// + /// /// Gets the type of data. /// internal uint Type { - get { return internalData.type; } - set { internalData.type = value; } + get { return _internalData.type; } + set { _internalData.type = value; } } /// @@ -716,8 +716,8 @@ namespace System.Management.Automation.Remoting.Client /// internal int BufferLength { - get { return internalData.binaryOrTextData.bufferLength; } - set { internalData.binaryOrTextData.bufferLength = value; } + get { return _internalData.binaryOrTextData.bufferLength; } + set { _internalData.binaryOrTextData.bufferLength = value; } } /// @@ -735,15 +735,15 @@ namespace System.Management.Automation.Remoting.Client // Managed objects should not be deleted when this is called via the finalizer // because they may have been collected already. To prevent leaking the marshalledBuffer // pointer, we are storing its value as a private member of the class, just like marshalledObject. - if (marshalledBuffer != IntPtr.Zero) + if (_marshalledBuffer != IntPtr.Zero) { - Marshal.FreeHGlobal(marshalledBuffer); - marshalledBuffer = IntPtr.Zero; + Marshal.FreeHGlobal(_marshalledBuffer); + _marshalledBuffer = IntPtr.Zero; } - if (marshalledObject != IntPtr.Zero) + if (_marshalledObject != IntPtr.Zero) { - Marshal.FreeHGlobal(marshalledObject); - marshalledObject = IntPtr.Zero; + Marshal.FreeHGlobal(_marshalledObject); + _marshalledObject = IntPtr.Zero; } } @@ -756,7 +756,7 @@ namespace System.Management.Automation.Remoting.Client { if (null != data) { - return data.marshalledObject; + return data._marshalledObject; } else { @@ -780,7 +780,7 @@ namespace System.Management.Automation.Remoting.Client /// /// Gets the buffer length of data. /// - private int _bufferLength; + private int _bufferLength; internal int BufferLength { get { return _bufferLength; } @@ -864,7 +864,7 @@ namespace System.Management.Automation.Remoting.Client if (IntPtr.Zero != unmanagedData) { WSManDataStruct resultInternal = ClrFacade.PtrToStructure(unmanagedData); - result = WSManData_UnToMan.UnMarshal(resultInternal); + result = WSManData_UnToMan.UnMarshal(resultInternal); } return result; @@ -877,8 +877,8 @@ namespace System.Management.Automation.Remoting.Client [StructLayout(LayoutKind.Sequential)] internal struct WSManDataDWord { - private WSManDataType type; - private WSManDWordDataInternal dwordData; + private WSManDataType _type; + private WSManDWordDataInternal _dwordData; /// /// Constructs a WSMAN_DATA_DWORD object. @@ -886,9 +886,9 @@ namespace System.Management.Automation.Remoting.Client /// internal WSManDataDWord(int data) { - dwordData = new WSManDWordDataInternal(); - dwordData.number = data; - type = WSManDataType.WSMAN_DATA_TYPE_DWORD; + _dwordData = new WSManDWordDataInternal(); + _dwordData.number = data; + _type = WSManDataType.WSMAN_DATA_TYPE_DWORD; } /// @@ -908,7 +908,7 @@ namespace System.Management.Automation.Remoting.Client /// [StructLayout(LayoutKind.Sequential)] private struct WSManDWordDataInternal - { + { internal int number; internal IntPtr reserved; } @@ -931,11 +931,11 @@ namespace System.Management.Automation.Remoting.Client [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr streamIDs; } - + internal struct WSManStreamIDSet_ManToUn { - private WSManStreamIDSetStruct streamSetInfo; - private MarshalledObject data; + private WSManStreamIDSetStruct _streamSetInfo; + private MarshalledObject _data; /// /// Constructor @@ -946,16 +946,16 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(streamIds != null, "stream ids cannot be null or empty"); int sizeOfIntPtr = ClrFacade.SizeOf(); - streamSetInfo = new WSManStreamIDSetStruct(); - streamSetInfo.streamIDsCount = streamIds.Length; - streamSetInfo.streamIDs = Marshal.AllocHGlobal(sizeOfIntPtr * streamIds.Length); + _streamSetInfo = new WSManStreamIDSetStruct(); + _streamSetInfo.streamIDsCount = streamIds.Length; + _streamSetInfo.streamIDs = Marshal.AllocHGlobal(sizeOfIntPtr * streamIds.Length); for (int index = 0; index < streamIds.Length; index++) { IntPtr streamAddress = Marshal.StringToHGlobalUni(streamIds[index]); - Marshal.WriteIntPtr(streamSetInfo.streamIDs, index * sizeOfIntPtr, streamAddress); + Marshal.WriteIntPtr(_streamSetInfo.streamIDs, index * sizeOfIntPtr, streamAddress); } - data = MarshalledObject.Create(streamSetInfo); + _data = MarshalledObject.Create(_streamSetInfo); } /// @@ -963,13 +963,13 @@ namespace System.Management.Automation.Remoting.Client /// internal void Dispose() { - if (IntPtr.Zero != streamSetInfo.streamIDs) + if (IntPtr.Zero != _streamSetInfo.streamIDs) { int sizeOfIntPtr = ClrFacade.SizeOf(); - for (int index = 0; index < streamSetInfo.streamIDsCount; index++) + for (int index = 0; index < _streamSetInfo.streamIDsCount; index++) { IntPtr streamAddress = IntPtr.Zero; - streamAddress = Marshal.ReadIntPtr(streamSetInfo.streamIDs, index * sizeOfIntPtr); + streamAddress = Marshal.ReadIntPtr(_streamSetInfo.streamIDs, index * sizeOfIntPtr); if (IntPtr.Zero != streamAddress) { @@ -977,12 +977,12 @@ namespace System.Management.Automation.Remoting.Client streamAddress = IntPtr.Zero; } } - - Marshal.FreeHGlobal(streamSetInfo.streamIDs); - streamSetInfo.streamIDs = IntPtr.Zero; + + Marshal.FreeHGlobal(_streamSetInfo.streamIDs); + _streamSetInfo.streamIDs = IntPtr.Zero; } - data.Dispose(); + _data.Dispose(); } /// @@ -992,13 +992,12 @@ namespace System.Management.Automation.Remoting.Client /// public static implicit operator IntPtr(WSManStreamIDSet_ManToUn obj) { - return obj.data.DataPtr; + return obj._data.DataPtr; } } internal class WSManStreamIDSet_UnToMan { - internal string[] streamIDs; internal int streamIDsCount; @@ -1093,8 +1092,8 @@ namespace System.Management.Automation.Remoting.Client { #region Managed to Unmanaged - private WSManOptionSetStruct optionSet; - private MarshalledObject data; + private WSManOptionSetStruct _optionSet; + private MarshalledObject _data; /// /// Options to construct this OptionSet with. @@ -1105,20 +1104,20 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(null != options, "options cannot be null"); int sizeOfOption = ClrFacade.SizeOf(); - optionSet = new WSManOptionSetStruct(); - optionSet.optionsCount = options.Length; - optionSet.optionsMustUnderstand = true; - optionSet.options = Marshal.AllocHGlobal(sizeOfOption * options.Length); + _optionSet = new WSManOptionSetStruct(); + _optionSet.optionsCount = options.Length; + _optionSet.optionsMustUnderstand = true; + _optionSet.options = Marshal.AllocHGlobal(sizeOfOption * options.Length); - for(int index = 0; index < options.Length; index++) + for (int index = 0; index < options.Length; index++) { // Look at the structure of native WSManOptionSet.. Options is a pointer.. // In C-Style array individual elements are continuous..so I am building // continuous array elements here. - Marshal.StructureToPtr(options[index], (IntPtr)(optionSet.options.ToInt64() + (sizeOfOption * index)), false); + Marshal.StructureToPtr(options[index], (IntPtr)(_optionSet.options.ToInt64() + (sizeOfOption * index)), false); } - data = MarshalledObject.Create(optionSet); + _data = MarshalledObject.Create(_optionSet); // For conformity: this.optionsCount = 0; @@ -1131,13 +1130,13 @@ namespace System.Management.Automation.Remoting.Client /// public void Dispose() { - if (IntPtr.Zero != optionSet.options) + if (IntPtr.Zero != _optionSet.options) { - Marshal.FreeHGlobal(optionSet.options); - optionSet.options = IntPtr.Zero; + Marshal.FreeHGlobal(_optionSet.options); + _optionSet.options = IntPtr.Zero; } // dispose option set - data.Dispose(); + _data.Dispose(); } /// @@ -1147,7 +1146,7 @@ namespace System.Management.Automation.Remoting.Client /// public static implicit operator IntPtr(WSManOptionSet optionSet) { - return optionSet.data.DataPtr; + return optionSet._data.DataPtr; } #endregion @@ -1221,26 +1220,26 @@ namespace System.Management.Automation.Remoting.Client [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr args; } - WSManCommandArgSetInternal internalData; + private WSManCommandArgSetInternal _internalData; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - MarshalledObject data; + private MarshalledObject _data; #region Managed to Unmanaged internal WSManCommandArgSet(byte[] firstArgument) { - internalData = new WSManCommandArgSetInternal(); - internalData.argsCount = 1; - internalData.args = Marshal.AllocHGlobal(ClrFacade.SizeOf()); + _internalData = new WSManCommandArgSetInternal(); + _internalData.argsCount = 1; + _internalData.args = Marshal.AllocHGlobal(ClrFacade.SizeOf()); // argument set takes only strings..but powershell's serialized pipeline might contain // \0 (null characters) which are unacceptable in WSMan. So we are converting to Base64 // here. The server will convert this back to original string. string base64EncodedArgument = Convert.ToBase64String(firstArgument); IntPtr firstArgAddress = Marshal.StringToHGlobalUni(base64EncodedArgument); - Marshal.WriteIntPtr(internalData.args, firstArgAddress); + Marshal.WriteIntPtr(_internalData.args, firstArgAddress); - data = MarshalledObject.Create(internalData); + _data = MarshalledObject.Create(_internalData); // For conformity: this.args = null; @@ -1253,15 +1252,15 @@ namespace System.Management.Automation.Remoting.Client /// public void Dispose() { - IntPtr firstArgAddress = Marshal.ReadIntPtr(internalData.args); + IntPtr firstArgAddress = Marshal.ReadIntPtr(_internalData.args); if (IntPtr.Zero != firstArgAddress) { Marshal.FreeHGlobal(firstArgAddress); } - Marshal.FreeHGlobal(internalData.args); + Marshal.FreeHGlobal(_internalData.args); - data.Dispose(); + _data.Dispose(); } /// @@ -1271,7 +1270,7 @@ namespace System.Management.Automation.Remoting.Client /// public static implicit operator IntPtr(WSManCommandArgSet obj) { - return obj.data.DataPtr; + return obj._data.DataPtr; } #endregion @@ -1328,15 +1327,15 @@ namespace System.Management.Automation.Remoting.Client internal uint idleTimeoutMs; } - private WSManShellDisconnectInfoInternal internalInfo; + private WSManShellDisconnectInfoInternal _internalInfo; internal MarshalledObject data; #region Constructor / Other methods internal WSManShellDisconnectInfo(uint serverIdleTimeOut) { - internalInfo = new WSManShellDisconnectInfoInternal(); - internalInfo.idleTimeoutMs = serverIdleTimeOut; - data = MarshalledObject.Create(internalInfo); + _internalInfo = new WSManShellDisconnectInfoInternal(); + _internalInfo.idleTimeoutMs = serverIdleTimeOut; + data = MarshalledObject.Create(_internalInfo); } /// @@ -1392,7 +1391,7 @@ namespace System.Management.Automation.Remoting.Client /// [MarshalAs(UnmanagedType.LPWStr)] internal string name; - } + } /// /// Managed to unmanaged representation of WSMAN_SHELL_STARTUP_INFO. @@ -1401,7 +1400,7 @@ namespace System.Management.Automation.Remoting.Client /// internal struct WSManShellStartupInfo_ManToUn : IDisposable { - private WSManShellStartupInfoStruct internalInfo; + private WSManShellStartupInfoStruct _internalInfo; internal MarshalledObject data; #region Constructor / Other methods @@ -1420,16 +1419,16 @@ namespace System.Management.Automation.Remoting.Client /// internal WSManShellStartupInfo_ManToUn(WSManStreamIDSet_ManToUn inputStreamSet, WSManStreamIDSet_ManToUn outputStreamSet, uint serverIdleTimeOut, string name) { - internalInfo = new WSManShellStartupInfoStruct(); - internalInfo.inputStreamSet = inputStreamSet; - internalInfo.outputStreamSet = outputStreamSet; - internalInfo.idleTimeoutMs = serverIdleTimeOut; + _internalInfo = new WSManShellStartupInfoStruct(); + _internalInfo.inputStreamSet = inputStreamSet; + _internalInfo.outputStreamSet = outputStreamSet; + _internalInfo.idleTimeoutMs = serverIdleTimeOut; // WSMan uses %USER_PROFILE% as the default working directory. - internalInfo.workingDirectory = null; - internalInfo.environmentVariableSet = IntPtr.Zero; - internalInfo.name = name; + _internalInfo.workingDirectory = null; + _internalInfo.environmentVariableSet = IntPtr.Zero; + _internalInfo.name = name; - data = MarshalledObject.Create(internalInfo); + data = MarshalledObject.Create(_internalInfo); } /// @@ -1563,7 +1562,7 @@ namespace System.Management.Automation.Remoting.Client public int proxyAccessType; public WSManUserNameAuthenticationCredentials.WSManUserNameCredentialStruct proxyAuthCredentialsStruct; } - private MarshalledObject data; + private MarshalledObject _data; /// /// @@ -1583,13 +1582,13 @@ namespace System.Management.Automation.Remoting.Client internalInfo.proxyAuthCredentialsStruct = authCredentials.CredentialStruct; } - data = MarshalledObject.Create(internalInfo); + _data = MarshalledObject.Create(internalInfo); } public void Dispose() { // data is of struct type..so no need to set it to null. - data.Dispose(); + _data.Dispose(); GC.SuppressFinalize(this); } @@ -1600,7 +1599,7 @@ namespace System.Management.Automation.Remoting.Client /// public static implicit operator IntPtr(WSManProxyInfo proxyInfo) { - return proxyInfo.data.DataPtr; + return proxyInfo._data.DataPtr; } } @@ -1721,9 +1720,9 @@ namespace System.Management.Automation.Remoting.Client internal struct WSManShellAsyncCallback { // GC handle which prevents garbage collector from collecting this delegate. - private GCHandle gcHandle; + private GCHandle _gcHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr asyncCallback; + private IntPtr _asyncCallback; internal WSManShellAsyncCallback(WSManShellCompletionFunction callback) { @@ -1732,13 +1731,13 @@ namespace System.Management.Automation.Remoting.Client // to the delegate, allowing relocation of the delegate, but preventing // disposal. Using GCHandle without pinning reduces fragmentation potential // of the managed heap. - gcHandle = GCHandle.Alloc(callback); - asyncCallback = Marshal.GetFunctionPointerForDelegate(callback); + _gcHandle = GCHandle.Alloc(callback); + _asyncCallback = Marshal.GetFunctionPointerForDelegate(callback); } public static implicit operator IntPtr(WSManShellAsyncCallback callback) { - return callback.asyncCallback; + return callback._asyncCallback; } } @@ -1753,33 +1752,33 @@ namespace System.Management.Automation.Remoting.Client internal IntPtr operationContext; internal IntPtr asyncCallback; } - private MarshalledObject data; - private WSManShellAsyncInternal internalData; + private MarshalledObject _data; + private WSManShellAsyncInternal _internalData; internal WSManShellAsync(IntPtr context, WSManShellAsyncCallback callback) { - internalData = new WSManShellAsyncInternal(); - internalData.operationContext = context; + _internalData = new WSManShellAsyncInternal(); + _internalData.operationContext = context; - internalData.asyncCallback = callback; - data = MarshalledObject.Create(internalData); + _internalData.asyncCallback = callback; + _data = MarshalledObject.Create(_internalData); } public void Dispose() { - data.Dispose(); + _data.Dispose(); } public static implicit operator IntPtr(WSManShellAsync async) { - return async.data; + return async._data; } } /// /// Used in the shell completion function delegate to refer to error. /// - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct WSManError { internal int errorCode; @@ -1807,9 +1806,8 @@ namespace System.Management.Automation.Remoting.Client /// internal static WSManError UnMarshal(IntPtr unmanagedData) { - return ClrFacade.PtrToStructure(unmanagedData); + return ClrFacade.PtrToStructure(unmanagedData); } - } internal class WSManCreateShellDataResult @@ -1856,7 +1854,6 @@ namespace System.Management.Automation.Remoting.Client internal int textLength; internal IntPtr text; } - } internal class WSManConnectDataResult @@ -1864,7 +1861,7 @@ namespace System.Management.Automation.Remoting.Client [StructLayout(LayoutKind.Sequential)] private struct WSManConnectDataResultInternal { - internal WSManDataStruct data; + internal WSManDataStruct data; } internal string data; @@ -1876,7 +1873,7 @@ namespace System.Management.Automation.Remoting.Client string connectData = null; if (resultInternal.data.textData.textLength > 0) { - connectData = Marshal.PtrToStringUni(resultInternal.data.textData.text, resultInternal.data.textData.textLength); + connectData = Marshal.PtrToStringUni(resultInternal.data.textData.text, resultInternal.data.textData.textLength); } WSManConnectDataResult result = new WSManConnectDataResult(); @@ -1900,7 +1897,6 @@ namespace System.Management.Automation.Remoting.Client internal int textLength; internal IntPtr text; } - } /// /// Used in the shell compeletion function delegate to refer to the data. @@ -1931,7 +1927,7 @@ namespace System.Management.Automation.Remoting.Client { WSManReceiveDataResultInternal result1 = ClrFacade.PtrToStructure(unmanagedData); - + //copy data from unmanaged heap to managed heap. byte[] dataRecvd = null; if (result1.data.binaryData.bufferLength > 0) @@ -1948,7 +1944,7 @@ namespace System.Management.Automation.Remoting.Client WSManReceiveDataResult result = new WSManReceiveDataResult(); result.data = dataRecvd; result.stream = result1.streamId; - + return result; } @@ -2003,7 +1999,7 @@ namespace System.Management.Automation.Remoting.Client /// /// Kept around to allow direct access to shutdownNotification and its handle. /// - private WSManPluginRequestInternal internalDetails; + private WSManPluginRequestInternal _internalDetails; /// /// Volatile value that should be read directly from its unmanaged location. @@ -2011,7 +2007,7 @@ namespace System.Management.Automation.Remoting.Client /// internal bool shutdownNotification { - get { return internalDetails.shutdownNotification; } + get { return _internalDetails.shutdownNotification; } } /// @@ -2020,7 +2016,7 @@ namespace System.Management.Automation.Remoting.Client /// internal IntPtr shutdownNotificationHandle { - get { return internalDetails.shutdownNotificationHandle; } + get { return _internalDetails.shutdownNotificationHandle; } } /// @@ -2047,7 +2043,7 @@ namespace System.Management.Automation.Remoting.Client result.locale = resultInternal.locale; result.resourceUri = resultInternal.resourceUri; result.operationInfo = WSManOperationInfo.UnMarshal(resultInternal.operationInfo); - result.internalDetails = resultInternal; + result._internalDetails = resultInternal; result.unmanagedHandle = unmanagedData; } return result; @@ -2065,7 +2061,7 @@ namespace System.Management.Automation.Remoting.Client internal IntPtr senderDetails; [MarshalAs(UnmanagedType.LPWStr)] internal string locale; - [MarshalAs(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] internal string resourceUri; /// /// WSManOperationInfo @@ -2296,7 +2292,6 @@ namespace System.Management.Automation.Remoting.Client [MarshalAs(UnmanagedType.LPWStr)] internal string value; } - } #endregion @@ -2457,11 +2452,11 @@ namespace System.Management.Automation.Remoting.Client } catch (ArgumentNullException) { - } + } catch (System.Text.DecoderFallbackException) { } - + return returnval; } @@ -2515,7 +2510,7 @@ namespace System.Management.Automation.Remoting.Client openContent, asyncCallback, ref shellOperationHandle); } - [DllImport(WSManNativeApi.WSManApiDll, EntryPoint="WSManCreateShellEx", SetLastError = false, CharSet = CharSet.Unicode)] + [DllImport(WSManNativeApi.WSManApiDll, EntryPoint = "WSManCreateShellEx", SetLastError = false, CharSet = CharSet.Unicode)] private static extern void WSManCreateShellExInternal(IntPtr wsManSessionHandle, int flags, [MarshalAs(UnmanagedType.LPWStr)]string resourceUri, @@ -2748,7 +2743,7 @@ namespace System.Management.Automation.Remoting.Client /// /// [DllImport(WSManNativeApi.WSManApiDll, EntryPoint = "WSManSignalShell", SetLastError = false, CharSet = CharSet.Unicode)] - internal static extern void WSManSignalShellEx(IntPtr shellOperationHandle, + internal static extern void WSManSignalShellEx(IntPtr shellOperationHandle, IntPtr cmdOperationHandle, int flags, string code, @@ -2789,7 +2784,7 @@ namespace System.Management.Automation.Remoting.Client string returnval = ""; int bufferSize = 0; // calculate buffer size required - if (ERROR_INSUFFICIENT_BUFFER != WSManGetErrorMessage(wsManAPIHandle, + if (ERROR_INSUFFICIENT_BUFFER != WSManGetErrorMessage(wsManAPIHandle, 0, langCode, errorCode, 0, null, out bufferSize)) { return returnval; @@ -2889,7 +2884,7 @@ namespace System.Management.Automation.Remoting.Client IntPtr requestDetails, int flags, [In, Out, MarshalAs(UnmanagedType.LPStruct)] WSManDataStruct data); - //[In, Out] ref IntPtr data); + //[In, Out] ref IntPtr data); /// /// Reports the completion of an operation by all operation entry points except for the @@ -2913,14 +2908,14 @@ namespace System.Management.Automation.Remoting.Client /// /// No more data on this stream. Only valid when a stream is specified. /// - WSMAN_FLAG_RECEIVE_RESULT_NO_MORE_DATA = 1, + WSMAN_FLAG_RECEIVE_RESULT_NO_MORE_DATA = 1, /// /// Send the data as soon as possible. Normally data is held onto in /// order to maximise the size of the response packet. This should /// only be used if a request/response style of data is needed between /// the send and receive data streams. /// - WSMAN_FLAG_RECEIVE_FLUSH = 2, + WSMAN_FLAG_RECEIVE_FLUSH = 2, /// /// Data reported is at a boundary. Plugins usually serialize and fragment /// output data objects and push them along the receive byte stream. @@ -2993,7 +2988,7 @@ namespace System.Management.Automation.Remoting.Client /// unit testing. /// Note: It is implemented as a class to avoid exposing it outside the module /// - interface IWSManNativeApiFacade + internal interface IWSManNativeApiFacade { // TODO: Expand this to cover the rest of the API once I prove that it works! @@ -3074,7 +3069,7 @@ namespace System.Management.Automation.Remoting.Client IntPtr shutdownContext) { #if UNIX - WSManNativeApi.WSManPluginRegisterShutdownCallback(requestDetails, shutdownCallback, shutdownContext); + WSManNativeApi.WSManPluginRegisterShutdownCallback(requestDetails, shutdownCallback, shutdownContext); #endif } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index a5d9e3ed2..137ae4bce 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -31,7 +31,7 @@ namespace System.Management.Automation.Remoting /// /// Consolidation of constants for uniformity. /// - static class WSManPluginConstants + internal static class WSManPluginConstants { internal const int ExitCodeSuccess = 0x00000000; internal const int ExitCodeFailure = 0x00000001; @@ -48,7 +48,7 @@ namespace System.Management.Automation.Remoting internal const string PowerShellStartupProtocolVersionValue = "2.0"; internal const string PowerShellOptionPrefix = "PS_"; - internal const int WSManPluginParamsGetRequestedLocale = 5; + internal const int WSManPluginParamsGetRequestedLocale = 5; internal const int WSManPluginParamsGetRequestedDataLocale = 6; } @@ -59,33 +59,33 @@ namespace System.Management.Automation.Remoting /// internal enum WSManPluginErrorCodes : int { - NullPluginContext = -2141976624, // 0x805407D0 - PluginContextNotFound = -2141976623, // 0x805407D1 + NullPluginContext = -2141976624, // 0x805407D0 + PluginContextNotFound = -2141976623, // 0x805407D1 - NullInvalidInput = -2141975624, // 0x80540BB8 - NullInvalidStreamSets = -2141975623, // 0x80540BB9 - SessionCreationFailed = -2141975622, // 0x80540BBA - NullShellContext = -2141975621, // 0x80540BBB - InvalidShellContext = -2141975620, // 0x80540BBC - InvalidCommandContext = -2141975619, // 0x80540BBD - InvalidInputStream = -2141975618, // 0x80540BBE - InvalidInputDatatype = -2141975617, // 0x80540BBF - InvalidOutputStream = -2141975616, // 0x80540BC0 - InvalidSenderDetails = -2141975615, // 0x80540BC1 - ShutdownRegistrationFailed = -2141975614, // 0x80540BC2 - ReportContextFailed = -2141975613, // 0x80540BC3 - InvalidArgSet = -2141975612, // 0x80540BC4 - ProtocolVersionNotMatch = -2141975611, // 0x80540BC5 - OptionNotUnderstood = -2141975610, // 0x80540BC6 - ProtocolVersionNotFound = -2141975609, // 0x80540BC7 + NullInvalidInput = -2141975624, // 0x80540BB8 + NullInvalidStreamSets = -2141975623, // 0x80540BB9 + SessionCreationFailed = -2141975622, // 0x80540BBA + NullShellContext = -2141975621, // 0x80540BBB + InvalidShellContext = -2141975620, // 0x80540BBC + InvalidCommandContext = -2141975619, // 0x80540BBD + InvalidInputStream = -2141975618, // 0x80540BBE + InvalidInputDatatype = -2141975617, // 0x80540BBF + InvalidOutputStream = -2141975616, // 0x80540BC0 + InvalidSenderDetails = -2141975615, // 0x80540BC1 + ShutdownRegistrationFailed = -2141975614, // 0x80540BC2 + ReportContextFailed = -2141975613, // 0x80540BC3 + InvalidArgSet = -2141975612, // 0x80540BC4 + ProtocolVersionNotMatch = -2141975611, // 0x80540BC5 + OptionNotUnderstood = -2141975610, // 0x80540BC6 + ProtocolVersionNotFound = -2141975609, // 0x80540BC7 - ManagedException = -2141974624, // 0x80540FA0 - PluginOperationClose = -2141974623, // 0x80540FA1 - PluginConnectNoNegotiationData = -2141974622, // 0x80540FA2 - PluginConnectOperationFailed = -2141974621, // 0x80540FA3 + ManagedException = -2141974624, // 0x80540FA0 + PluginOperationClose = -2141974623, // 0x80540FA1 + PluginConnectNoNegotiationData = -2141974622, // 0x80540FA2 + PluginConnectOperationFailed = -2141974621, // 0x80540FA3 - NoError = 0, - OutOfMemory = -2147024882 // 0x8007000E + NoError = 0, + OutOfMemory = -2147024882 // 0x8007000E } /// @@ -96,7 +96,7 @@ namespace System.Management.Automation.Remoting /// their lifetime is managed by WinRM. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - class WSManPluginOperationShutdownContext // TODO: Rename to OperationShutdownContext when removing the MC++ module. + internal class WSManPluginOperationShutdownContext // TODO: Rename to OperationShutdownContext when removing the MC++ module. { #region Internal Members @@ -111,9 +111,9 @@ namespace System.Management.Automation.Remoting #region Constructors internal WSManPluginOperationShutdownContext( - IntPtr plgContext, - IntPtr shContext, - IntPtr cmdContext, + IntPtr plgContext, + IntPtr shContext, + IntPtr cmdContext, bool isRcvOp) { pluginContext = plgContext; @@ -130,13 +130,13 @@ namespace System.Management.Automation.Remoting /// Represents the logical grouping of all actions required to handle the /// lifecycle of shell sessions through the WinRM plugin. /// - class WSManPluginInstance + internal class WSManPluginInstance { #region Private Members - private Dictionary activeShellSessions; - private object syncObject; - private static Dictionary activePlugins = new Dictionary(); + private Dictionary _activeShellSessions; + private object _syncObject; + private static Dictionary s_activePlugins = new Dictionary(); /// /// Enables dependency injection after the static constructor is called. @@ -152,8 +152,8 @@ namespace System.Management.Automation.Remoting internal WSManPluginInstance() { - activeShellSessions = new Dictionary(); - syncObject = new System.Object(); + _activeShellSessions = new Dictionary(); + _syncObject = new System.Object(); } /// @@ -324,12 +324,12 @@ namespace System.Management.Automation.Remoting if (null != inboundShellInformation) { - if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type) + if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type) { // only text data is supported ReportOperationComplete( requestDetails, - WSManPluginErrorCodes.InvalidInputDatatype, + WSManPluginErrorCodes.InvalidInputDatatype, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidInputDataType, "WSMAN_DATA_TYPE_TEXT")); @@ -354,15 +354,15 @@ namespace System.Management.Automation.Remoting if (WSManPluginConstants.ExitCodeSuccess != result) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.ReportContextFailed, StringUtil.Format( RemotingErrorIdStrings.WSManPluginReportContextFailed)); DeleteFromActiveShellSessions(requestDetails.unmanagedHandle); return; - } + } } - catch(System.Exception e) + catch (System.Exception e) { CommandProcessorBase.CheckForSevereException(e); @@ -373,7 +373,7 @@ namespace System.Management.Automation.Remoting DeleteFromActiveShellSessions(requestDetails.unmanagedHandle); ReportOperationComplete( requestDetails, - WSManPluginErrorCodes.ManagedException, + WSManPluginErrorCodes.ManagedException, StringUtil.Format( RemotingErrorIdStrings.WSManPluginManagedException, e.Message)); @@ -382,9 +382,9 @@ namespace System.Management.Automation.Remoting bool isRegisterWaitForSingleObjectSucceeded = true; - //always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen - lock (mgdShellSession.shellSyncObject) - { + //always synchronize calls to OperationComplete once notification handle is registered.. else duplicate OperationComplete calls are bound to happen + lock (mgdShellSession.shellSyncObject) + { mgdShellSession.registeredShutdownNotification = 1; // Wrap the provided handle so it can be passed to the registration function @@ -400,13 +400,13 @@ namespace System.Management.Automation.Remoting //On non-windows platforms the shutdown notification is done through a callback instead of a windows event handle. //Register the callback and this will then signal the event. Note, the gch object is deleted in the shell shutdown //notification that will always come in to shut down the operation. - + GCHandle gch = GCHandle.Alloc(eventWaitHandle); IntPtr p = GCHandle.ToIntPtr(gch); wsmanPinvokeStatic.WSManPluginRegisterShutdownCallback( requestDetails.unmanagedHandle, - WSManPluginManagedEntryWrapper.workerPtrs.UnmanagedStruct.wsManPluginShutdownCallbackNative, + WSManPluginManagedEntryWrapper.workerPtrs.UnmanagedStruct.wsManPluginShutdownCallbackNative, p); } @@ -439,9 +439,8 @@ namespace System.Management.Automation.Remoting { mgdShellSession.SendOneItemToSessionHelper(convertedBase64, WSManPluginConstants.SupportedInputStream); } - } - catch(System.Exception e) + catch (System.Exception e) { CommandProcessorBase.CheckForSevereException(e); @@ -500,12 +499,12 @@ namespace System.Management.Automation.Remoting internal void CloseCommandOperation( WSManPluginOperationShutdownContext context) - { + { PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation, PSOpcode.Disconnect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - context.shellContext.ToString(), - context.commandContext.ToString(), + context.shellContext.ToString(), + context.commandContext.ToString(), context.isReceiveOperation.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext); @@ -517,7 +516,6 @@ namespace System.Management.Automation.Remoting } SetThreadProperties(mgdShellSession.creationRequestDetails); mgdShellSession.CloseCommandOperation(context); - } /// @@ -529,17 +527,17 @@ namespace System.Management.Automation.Remoting WSManPluginShellSession newShellSession) { int count = -1; - lock (syncObject) + lock (_syncObject) { IntPtr key = newShellSession.creationRequestDetails.unmanagedHandle; Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); - if (!activeShellSessions.ContainsKey(key)) + if (!_activeShellSessions.ContainsKey(key)) { - activeShellSessions.Add(key, newShellSession); + _activeShellSessions.Add(key, newShellSession); // trigger an event outside the lock - count = activeShellSessions.Count; + count = _activeShellSessions.Count; } } @@ -558,10 +556,10 @@ namespace System.Management.Automation.Remoting private WSManPluginShellSession GetFromActiveShellSessions( IntPtr key) { - lock (syncObject) + lock (_syncObject) { WSManPluginShellSession result; - activeShellSessions.TryGetValue(key, out result); + _activeShellSessions.TryGetValue(key, out result); return result; } } @@ -574,12 +572,12 @@ namespace System.Management.Automation.Remoting IntPtr keyToDelete) { int count = -1; - lock (syncObject) + lock (_syncObject) { - if (activeShellSessions.Remove(keyToDelete)) + if (_activeShellSessions.Remove(keyToDelete)) { // trigger an event outside the lock - count = activeShellSessions.Count; + count = _activeShellSessions.Count; } } if (-1 != count) @@ -588,14 +586,14 @@ namespace System.Management.Automation.Remoting WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count)); } } - + /// /// Triggers a shell close from an event handler. /// /// Shell context /// private void HandleShellSessionClosed( - Object source, + Object source, EventArgs e) { DeleteFromActiveShellSessions((IntPtr)source); @@ -676,19 +674,19 @@ namespace System.Management.Automation.Remoting if (null == mgdShellSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidShellContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidShellContext)); return; } - mgdShellSession.CreateCommand(pluginContext, requestDetails, flags, commandLine, arguments); + mgdShellSession.CreateCommand(pluginContext, requestDetails, flags, commandLine, arguments); } internal void StopCommand( - WSManNativeApi.WSManPluginRequest requestDetails, - IntPtr shellContext, + WSManNativeApi.WSManPluginRequest requestDetails, + IntPtr shellContext, IntPtr commandContext) { if (null == requestDetails) @@ -706,21 +704,21 @@ namespace System.Management.Automation.Remoting String.Empty); return; } - + SetThreadProperties(requestDetails); - + PSEtwLog.LogAnalyticInformational(PSEventId.ServerStopCommand, PSOpcode.Disconnect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)shellContext).ToString(), - ((IntPtr)commandContext).ToString(), + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (null == mgdShellSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidShellContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidShellContext)); @@ -748,7 +746,7 @@ namespace System.Management.Automation.Remoting PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic); // all active shells should be closed at this point - Dbg.Assert(activeShellSessions.Count == 0, "All active shells should be closed"); + Dbg.Assert(_activeShellSessions.Count == 0, "All active shells should be closed"); // raise shutting down notification WSManServerChannelEvents.RaiseShuttingDownEvent(); @@ -785,7 +783,7 @@ namespace System.Management.Automation.Remoting if (null == mgdShellSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidShellContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidShellContext)); @@ -794,7 +792,7 @@ namespace System.Management.Automation.Remoting if (IntPtr.Zero == commandContext) { - mgdShellSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation); + mgdShellSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation); return; } @@ -803,7 +801,7 @@ namespace System.Management.Automation.Remoting if (null == mgdCmdSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidCommandContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidCommandContext)); @@ -836,7 +834,7 @@ namespace System.Management.Automation.Remoting } SetThreadProperties(requestDetails); - + PSEtwLog.LogAnalyticInformational(PSEventId.ServerReceivedData, PSOpcode.Open, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, @@ -846,7 +844,7 @@ namespace System.Management.Automation.Remoting if (null == mgdShellSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidShellContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidShellContext) @@ -857,7 +855,7 @@ namespace System.Management.Automation.Remoting if (IntPtr.Zero == commandContext) { // the data is destined for shell (runspace) session. so let shell handle it - mgdShellSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); + mgdShellSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); return; } @@ -866,14 +864,14 @@ namespace System.Management.Automation.Remoting if (null == mgdCmdSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidCommandContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidCommandContext)); return; } - mgdCmdSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); + mgdCmdSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); } /// @@ -900,19 +898,19 @@ namespace System.Management.Automation.Remoting } SetThreadProperties(requestDetails); - + PSEtwLog.LogAnalyticInformational(PSEventId.ServerClientReceiveRequest, PSOpcode.Open, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)shellContext).ToString(), - ((IntPtr)commandContext).ToString(), + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (null == mgdShellSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidShellContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginInvalidShellContext) @@ -944,10 +942,10 @@ namespace System.Management.Automation.Remoting if (null == mgdCmdSession) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.InvalidCommandContext, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidCommandContext)); + RemotingErrorIdStrings.WSManPluginInvalidCommandContext)); return; } @@ -1102,7 +1100,7 @@ namespace System.Management.Automation.Remoting /// /// protected internal bool EnsureProtocolVersionComplies( - WSManNativeApi.WSManPluginRequest requestDetails, + WSManNativeApi.WSManPluginRequest requestDetails, string clientVersionString) { if (String.Equals(clientVersionString, WSManPluginConstants.PowerShellStartupProtocolVersionValue, StringComparison.Ordinal)) @@ -1117,7 +1115,7 @@ namespace System.Management.Automation.Remoting System.Version serverVersion = Utils.StringToVersion(WSManPluginConstants.PowerShellStartupProtocolVersionValue); if ((null != clientVersion) && (null != serverVersion) && - (clientVersion.Major == serverVersion.Major) && + (clientVersion.Major == serverVersion.Major) && (clientVersion.Minor >= serverVersion.Minor)) { return true; @@ -1155,7 +1153,7 @@ namespace System.Management.Automation.Remoting if (null == pluginToUse) { - lock (activePlugins) + lock (s_activePlugins) { pluginToUse = GetFromActivePlugins(pluginContext); if (null == pluginToUse) @@ -1183,9 +1181,9 @@ namespace System.Management.Automation.Remoting IntPtr shellContext, // PVOID [MarshalAs(UnmanagedType.LPWStr)] string commandLine, IntPtr arguments) // WSMAN_COMMAND_ARG_SET* - { + { WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - + if (null == pluginToUse) { ReportOperationComplete( @@ -1199,7 +1197,7 @@ namespace System.Management.Automation.Remoting // Marshal the incoming pointers into managed types prior to the call WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); WSManNativeApi.WSManCommandArgSet argSet = WSManNativeApi.WSManCommandArgSet.UnMarshal(arguments); - + pluginToUse.CreateCommand(pluginContext, request, flags, shellContext, commandLine, argSet); } @@ -1210,13 +1208,13 @@ namespace System.Management.Automation.Remoting IntPtr shellContext, IntPtr commandContext, IntPtr inboundConnectInformation) - { + { WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - + if (null == pluginToUse) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.PluginContextNotFound, StringUtil.Format( RemotingErrorIdStrings.WSManPluginContextNotFound)); @@ -1227,7 +1225,7 @@ namespace System.Management.Automation.Remoting WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); WSManNativeApi.WSManData_UnToMan connectInformation = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundConnectInformation); - pluginToUse.ConnectShellOrCommand(request, flags, shellContext, commandContext, connectInformation); + pluginToUse.ConnectShellOrCommand(request, flags, shellContext, commandContext, connectInformation); } internal static void PerformWSManPluginSend( @@ -1240,11 +1238,11 @@ namespace System.Management.Automation.Remoting IntPtr inboundData) // WSMAN_DATA* { WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - + if (null == pluginToUse) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.PluginContextNotFound, StringUtil.Format( RemotingErrorIdStrings.WSManPluginContextNotFound)); @@ -1271,7 +1269,7 @@ namespace System.Management.Automation.Remoting if (null == pluginToUse) { ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.PluginContextNotFound, StringUtil.Format( RemotingErrorIdStrings.WSManPluginContextNotFound)); @@ -1320,7 +1318,7 @@ namespace System.Management.Automation.Remoting if (null == pluginToUse) { ReportOperationComplete( - request, + request, WSManPluginErrorCodes.PluginContextNotFound, StringUtil.Format( RemotingErrorIdStrings.WSManPluginContextNotFound)); @@ -1382,21 +1380,21 @@ namespace System.Management.Automation.Remoting private static WSManPluginInstance GetFromActivePlugins(IntPtr pluginContext) { - lock (activePlugins) + lock (s_activePlugins) { WSManPluginInstance result = null; - activePlugins.TryGetValue(pluginContext, out result); + s_activePlugins.TryGetValue(pluginContext, out result); return result; } } private static void AddToActivePlugins(IntPtr pluginContext, WSManPluginInstance plugin) { - lock (activePlugins) + lock (s_activePlugins) { - if (!activePlugins.ContainsKey(pluginContext)) + if (!s_activePlugins.ContainsKey(pluginContext)) { - activePlugins.Add(pluginContext, plugin); + s_activePlugins.Add(pluginContext, plugin); return; } } @@ -1410,7 +1408,7 @@ namespace System.Management.Automation.Remoting /// /// internal static void ReportWSManOperationComplete( - WSManNativeApi.WSManPluginRequest requestDetails, + WSManNativeApi.WSManPluginRequest requestDetails, WSManPluginErrorCodes errorCode) { Dbg.Assert(null != requestDetails, "requestDetails cannot be null in operation complete."); @@ -1432,7 +1430,7 @@ namespace System.Management.Automation.Remoting /// /// internal static void ReportWSManOperationComplete( - WSManNativeApi.WSManPluginRequest requestDetails, + WSManNativeApi.WSManPluginRequest requestDetails, Exception reasonForClose) { Dbg.Assert(null != requestDetails, "requestDetails cannot be null in operation complete."); @@ -1451,11 +1449,11 @@ namespace System.Management.Automation.Remoting PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - requestDetails.ToString(), + requestDetails.ToString(), Convert.ToString(error, CultureInfo.InvariantCulture), errorMessage, stackTrace); - + if (null != reasonForClose) { // report operation complete to wsman with the error message (if any). @@ -1469,7 +1467,7 @@ namespace System.Management.Automation.Remoting else { ReportOperationComplete( - requestDetails.unmanagedHandle, + requestDetails.unmanagedHandle, WSManPluginErrorCodes.NoError); } } @@ -1486,14 +1484,14 @@ namespace System.Management.Automation.Remoting { // requestDetails cannot not be null. Dbg.Assert(null != requestDetails, "requestDetails cannot be null"); - + //IntPtr nativeLocaleData = IntPtr.Zero; WSManNativeApi.WSManDataStruct outputStruct = new WSManNativeApi.WSManDataStruct(); int hResult = wsmanPinvokeStatic.WSManPluginGetOperationParameters( requestDetails.unmanagedHandle, WSManPluginConstants.WSManPluginParamsGetRequestedLocale, outputStruct); - //ref nativeLocaleData); + //ref nativeLocaleData); bool retreivingLocaleSucceeded = (0 == hResult); WSManNativeApi.WSManData_UnToMan localeData = WSManNativeApi.WSManData_UnToMan.UnMarshal(outputStruct); // nativeLocaleData @@ -1502,7 +1500,7 @@ namespace System.Management.Automation.Remoting requestDetails.unmanagedHandle, WSManPluginConstants.WSManPluginParamsGetRequestedDataLocale, outputStruct); - //ref nativeDataLocaleData); + //ref nativeDataLocaleData); bool retreivingDataLocaleSucceeded = ((int)WSManPluginErrorCodes.NoError == hResult); WSManNativeApi.WSManData_UnToMan dataLocaleData = WSManNativeApi.WSManData_UnToMan.UnMarshal(outputStruct); // nativeDataLocaleData @@ -1511,7 +1509,7 @@ namespace System.Management.Automation.Remoting { if (retreivingLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == localeData.Type)) { - CultureInfo uiCultureToUse = new CultureInfo(localeData.Text); + CultureInfo uiCultureToUse = new CultureInfo(localeData.Text); ClrFacade.SetCurrentThreadUiCulture(uiCultureToUse); } } @@ -1525,13 +1523,13 @@ namespace System.Management.Automation.Remoting { if (retreivingDataLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == dataLocaleData.Type)) { - CultureInfo cultureToUse = new CultureInfo(dataLocaleData.Text); + CultureInfo cultureToUse = new CultureInfo(dataLocaleData.Text); ClrFacade.SetCurrentThreadCulture(cultureToUse); } } // ignore if there is any exception constructing the culture.. catch (ArgumentException) - { + { } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 56fef4394..fb02e1fce 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -46,7 +46,7 @@ namespace System.Management.Automation.Remoting /// PCWSTR /// WSMAN_SHELL_STARTUP_INFO* /// WSMAN_DATA* - delegate void WSMPluginShellDelegate( // TODO: Rename to WSManPluginShellDelegate once I remove the MC++ module. + internal delegate void WSMPluginShellDelegate( // TODO: Rename to WSManPluginShellDelegate once I remove the MC++ module. IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -59,7 +59,7 @@ namespace System.Management.Automation.Remoting /// /// PVOID /// PVOID - delegate void WSMPluginReleaseShellContextDelegate( + internal delegate void WSMPluginReleaseShellContextDelegate( IntPtr pluginContext, IntPtr shellContext); @@ -72,7 +72,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PVOID optional /// WSMAN_DATA* optional - delegate void WSMPluginConnectDelegate( + internal delegate void WSMPluginConnectDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -89,7 +89,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PCWSTR /// WSMAN_COMMAND_ARG_SET* - delegate void WSMPluginCommandDelegate( + internal delegate void WSMPluginCommandDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -101,8 +101,8 @@ namespace System.Management.Automation.Remoting /// Delegate that is passed to native layer for callback on operation shutdown notifications /// /// IntPtr - delegate void WSMPluginOperationShutdownDelegate( - IntPtr shutdownContext); + internal delegate void WSMPluginOperationShutdownDelegate( + IntPtr shutdownContext); /// /// @@ -110,7 +110,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PVOID /// PVOID - delegate void WSMPluginReleaseCommandContextDelegate( + internal delegate void WSMPluginReleaseCommandContextDelegate( IntPtr pluginContext, IntPtr shellContext, IntPtr commandContext); @@ -125,7 +125,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PCWSTR /// WSMAN_DATA* - delegate void WSMPluginSendDelegate( + internal delegate void WSMPluginSendDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -143,7 +143,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PVOID optional /// WSMAN_STREAM_ID_SET* optional - delegate void WSMPluginReceiveDelegate( + internal delegate void WSMPluginReceiveDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -160,7 +160,7 @@ namespace System.Management.Automation.Remoting /// PVOID /// PVOID optional /// PCWSTR - delegate void WSMPluginSignalDelegate( + internal delegate void WSMPluginSignalDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -181,7 +181,7 @@ namespace System.Management.Automation.Remoting /// /// /// PVOID - delegate void WSMShutdownPluginDelegate( + internal delegate void WSMShutdownPluginDelegate( IntPtr pluginContext); /// @@ -192,28 +192,28 @@ namespace System.Management.Automation.Remoting #region Private Members // Holds the delegate pointers in a structure that has identical layout to the native structure. - private WSManPluginEntryDelegatesInternal unmanagedStruct = new WSManPluginEntryDelegatesInternal(); + private WSManPluginEntryDelegatesInternal _unmanagedStruct = new WSManPluginEntryDelegatesInternal(); internal WSManPluginEntryDelegatesInternal UnmanagedStruct { - get { return unmanagedStruct; } + get { return _unmanagedStruct; } } // Flag: Has Dispose already been called? - private bool disposed = false; + private bool _disposed = false; /// /// GC handle which prevents garbage collector from collecting this delegate. /// - private GCHandle pluginShellGCHandle; - private GCHandle pluginReleaseShellContextGCHandle; - private GCHandle pluginCommandGCHandle; - private GCHandle pluginReleaseCommandContextGCHandle; - private GCHandle pluginSendGCHandle; - private GCHandle pluginReceiveGCHandle; - private GCHandle pluginSignalGCHandle; - private GCHandle pluginConnectGCHandle; - private GCHandle shutdownPluginGCHandle; - private GCHandle WSMPluginOperationShutdownGCHandle; + private GCHandle _pluginShellGCHandle; + private GCHandle _pluginReleaseShellContextGCHandle; + private GCHandle _pluginCommandGCHandle; + private GCHandle _pluginReleaseCommandContextGCHandle; + private GCHandle _pluginSendGCHandle; + private GCHandle _pluginReceiveGCHandle; + private GCHandle _pluginSignalGCHandle; + private GCHandle _pluginConnectGCHandle; + private GCHandle _shutdownPluginGCHandle; + private GCHandle _WSMPluginOperationShutdownGCHandle; #endregion @@ -234,9 +234,9 @@ namespace System.Management.Automation.Remoting /// Internal implementation of Dispose pattern callable by consumers. /// public void Dispose() - { + { Dispose(true); - GC.SuppressFinalize(this); + GC.SuppressFinalize(this); } /// @@ -245,13 +245,13 @@ namespace System.Management.Automation.Remoting /// private void Dispose(bool disposing) { - if (disposed) - return; + if (_disposed) + return; // Free any unmanaged objects here. this.CleanUpDelegates(); - disposed = true; + _disposed = true; } /// @@ -281,56 +281,56 @@ namespace System.Management.Automation.Remoting // of the managed heap. { WSMPluginShellDelegate pluginShell = new WSMPluginShellDelegate(WSManPluginManagedEntryWrapper.WSManPluginShell); - this.pluginShellGCHandle = GCHandle.Alloc(pluginShell); + _pluginShellGCHandle = GCHandle.Alloc(pluginShell); // marshal the delegate to a unmanaged function pointer so that AppDomain reference is stored correctly. // Populate the outgoing structure so the caller has access to the entry points - unmanagedStruct.wsManPluginShellCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShell); + _unmanagedStruct.wsManPluginShellCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShell); } { WSMPluginReleaseShellContextDelegate pluginReleaseShellContext = new WSMPluginReleaseShellContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseShellContext); - this.pluginReleaseShellContextGCHandle = GCHandle.Alloc(pluginReleaseShellContext); - unmanagedStruct.wsManPluginReleaseShellContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseShellContext); + _pluginReleaseShellContextGCHandle = GCHandle.Alloc(pluginReleaseShellContext); + _unmanagedStruct.wsManPluginReleaseShellContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseShellContext); } - { + { WSMPluginCommandDelegate pluginCommand = new WSMPluginCommandDelegate(WSManPluginManagedEntryWrapper.WSManPluginCommand); - this.pluginCommandGCHandle = GCHandle.Alloc(pluginCommand); - unmanagedStruct.wsManPluginCommandCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginCommand); + _pluginCommandGCHandle = GCHandle.Alloc(pluginCommand); + _unmanagedStruct.wsManPluginCommandCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginCommand); } { WSMPluginReleaseCommandContextDelegate pluginReleaseCommandContext = new WSMPluginReleaseCommandContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseCommandContext); - this.pluginReleaseCommandContextGCHandle = GCHandle.Alloc(pluginReleaseCommandContext); - unmanagedStruct.wsManPluginReleaseCommandContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseCommandContext); + _pluginReleaseCommandContextGCHandle = GCHandle.Alloc(pluginReleaseCommandContext); + _unmanagedStruct.wsManPluginReleaseCommandContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseCommandContext); } - { + { WSMPluginSendDelegate pluginSend = new WSMPluginSendDelegate(WSManPluginManagedEntryWrapper.WSManPluginSend); - this.pluginSendGCHandle = GCHandle.Alloc(pluginSend); - unmanagedStruct.wsManPluginSendCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSend); + _pluginSendGCHandle = GCHandle.Alloc(pluginSend); + _unmanagedStruct.wsManPluginSendCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSend); } - { + { WSMPluginReceiveDelegate pluginReceive = new WSMPluginReceiveDelegate(WSManPluginManagedEntryWrapper.WSManPluginReceive); - this.pluginReceiveGCHandle = GCHandle.Alloc(pluginReceive); - unmanagedStruct.wsManPluginReceiveCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReceive); + _pluginReceiveGCHandle = GCHandle.Alloc(pluginReceive); + _unmanagedStruct.wsManPluginReceiveCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReceive); } - { + { WSMPluginSignalDelegate pluginSignal = new WSMPluginSignalDelegate(WSManPluginManagedEntryWrapper.WSManPluginSignal); - this.pluginSignalGCHandle = GCHandle.Alloc(pluginSignal); - unmanagedStruct.wsManPluginSignalCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSignal); + _pluginSignalGCHandle = GCHandle.Alloc(pluginSignal); + _unmanagedStruct.wsManPluginSignalCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSignal); } - { + { WSMPluginConnectDelegate pluginConnect = new WSMPluginConnectDelegate(WSManPluginManagedEntryWrapper.WSManPluginConnect); - this.pluginConnectGCHandle = GCHandle.Alloc(pluginConnect); - unmanagedStruct.wsManPluginConnectCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginConnect); + _pluginConnectGCHandle = GCHandle.Alloc(pluginConnect); + _unmanagedStruct.wsManPluginConnectCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginConnect); } { WSMShutdownPluginDelegate shutdownPlugin = new WSMShutdownPluginDelegate(WSManPluginManagedEntryWrapper.ShutdownPlugin); - this.shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin); - unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin); + _shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin); + _unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin); } - if(!Platform.IsWindows) + if (!Platform.IsWindows) { WSMPluginOperationShutdownDelegate pluginShutDownDelegate = new WSMPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown); - this.WSMPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate); - unmanagedStruct.wsManPluginShutdownCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShutDownDelegate); + _WSMPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate); + _unmanagedStruct.wsManPluginShutdownCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShutDownDelegate); } } @@ -340,20 +340,20 @@ namespace System.Management.Automation.Remoting private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (null != this.pluginShellGCHandle) + if (null != _pluginShellGCHandle) { - this.pluginShellGCHandle.Free(); - this.pluginReleaseShellContextGCHandle.Free(); - this.pluginCommandGCHandle.Free(); - this.pluginReleaseCommandContextGCHandle.Free(); - this.pluginSendGCHandle.Free(); - this.pluginReceiveGCHandle.Free(); - this.pluginSignalGCHandle.Free(); - this.pluginConnectGCHandle.Free(); - this.shutdownPluginGCHandle.Free(); - if(!Platform.IsWindows) + _pluginShellGCHandle.Free(); + _pluginReleaseShellContextGCHandle.Free(); + _pluginCommandGCHandle.Free(); + _pluginReleaseCommandContextGCHandle.Free(); + _pluginSendGCHandle.Free(); + _pluginReceiveGCHandle.Free(); + _pluginSignalGCHandle.Free(); + _pluginConnectGCHandle.Free(); + _shutdownPluginGCHandle.Free(); + if (!Platform.IsWindows) { - this.WSMPluginOperationShutdownGCHandle.Free(); + _WSMPluginOperationShutdownGCHandle.Free(); } } } @@ -424,8 +424,7 @@ namespace System.Management.Automation.Remoting /// [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginShutdownCallbackNative; - - } + } } /// @@ -523,12 +522,12 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginNullPluginContext, - "pluginContext", + RemotingErrorIdStrings.WSManPluginNullPluginContext, + "pluginContext", "WSManPluginConnect") ); return; - } + } WSManPluginInstance.PerformWSManPluginConnect(pluginContext, requestDetails, flags, shellContext, commandContext, inboundConnectInformation); } @@ -549,7 +548,7 @@ namespace System.Management.Automation.Remoting [MarshalAs(UnmanagedType.LPWStr)] string extraInfo, IntPtr startupInfo, IntPtr inboundShellInformation) - { + { if (IntPtr.Zero == pluginContext) { WSManPluginInstance.ReportOperationComplete( @@ -557,7 +556,7 @@ namespace System.Management.Automation.Remoting WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullPluginContext, - "pluginContext", + "pluginContext", "WSManPluginShell") ); return; @@ -615,7 +614,7 @@ namespace System.Management.Automation.Remoting WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullPluginContext, - "Plugin Context", + "Plugin Context", "WSManPluginCommand") ); return; @@ -624,15 +623,15 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformWSManPluginCommand(pluginContext, requestDetails, flags, shellContext, commandLine, arguments); } - /// + /// /// Operation shutdown notification that was registered with the native layer for each of the shellCreate operations. /// /// IntPtr - public static void WSManPSShutdown( + public static void WSManPSShutdown( IntPtr shutdownContext) - { + { GCHandle gch = GCHandle.FromIntPtr(shutdownContext); - EventWaitHandle eventHandle = (EventWaitHandle) gch.Target; + EventWaitHandle eventHandle = (EventWaitHandle)gch.Target; eventHandle.Set(); gch.Free(); } @@ -674,19 +673,19 @@ namespace System.Management.Automation.Remoting if (IntPtr.Zero == pluginContext) { WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullPluginContext, - "Plugin Context", + "Plugin Context", "WSManPluginSend") ); return; } - + WSManPluginInstance.PerformWSManPluginSend(pluginContext, requestDetails, flags, shellContext, commandContext, stream, inboundData); } - + /// /// /// @@ -707,11 +706,11 @@ namespace System.Management.Automation.Remoting if (IntPtr.Zero == pluginContext) { WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullPluginContext, - "Plugin Context", + "Plugin Context", "WSManPluginReceive") ); return; @@ -740,11 +739,11 @@ namespace System.Management.Automation.Remoting if ((IntPtr.Zero == pluginContext) || (IntPtr.Zero == shellContext)) { WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NullPluginContext, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullPluginContext, - "Plugin Context", + "Plugin Context", "WSManPluginSignal") ); return; @@ -752,7 +751,7 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformWSManPluginSignal(pluginContext, requestDetails, flags, shellContext, commandContext, code); } - + /// /// Callback used to register with thread pool to notify when a plugin operation shuts down. /// Conforms to: @@ -775,9 +774,8 @@ namespace System.Management.Automation.Remoting WSManPluginInstance.PerformCloseOperation(context); } - - #endregion + #endregion } /// @@ -791,15 +789,15 @@ namespace System.Management.Automation.Remoting #region IDisposable // Flag: Has Dispose already been called? - private bool disposed = false; + private bool _disposed = false; /// /// Internal implementation of Dispose pattern callable by consumers. /// public void Dispose() - { + { Dispose(true); - GC.SuppressFinalize(this); + GC.SuppressFinalize(this); } /// @@ -808,13 +806,13 @@ namespace System.Management.Automation.Remoting /// private void Dispose(bool disposing) { - if (disposed) - return; + if (_disposed) + return; // Free any unmanaged objects here. - this.initDelegateHandle.Free(); + _initDelegateHandle.Free(); - disposed = true; + _disposed = true; } /// @@ -844,7 +842,7 @@ namespace System.Management.Automation.Remoting /// /// Prevents the delegate object from being garbage collected so it can be passed to the native code. /// - private GCHandle initDelegateHandle; + private GCHandle _initDelegateHandle; /// /// Entry point for native code that cannot call static methods. @@ -853,7 +851,7 @@ namespace System.Management.Automation.Remoting public IntPtr GetEntryDelegate() { InitPluginDelegate initDelegate = new InitPluginDelegate(WSManPluginManagedEntryWrapper.InitPlugin); - this.initDelegateHandle = GCHandle.Alloc(initDelegate); + _initDelegateHandle = GCHandle.Alloc(initDelegate); return Marshal.GetFunctionPointerForDelegate(initDelegate); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 41913739b..38066ee2a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -32,10 +32,10 @@ namespace System.Management.Automation.Remoting /// internal abstract class WSManPluginServerSession : IDisposable { - private object syncObject; + private object _syncObject; protected bool isClosed; - protected bool isContextReported; + protected bool isContextReported; // used to keep track of last error..this will be used // for reporting operation complete to WSMan. protected Exception lastErrorReported; @@ -57,13 +57,13 @@ namespace System.Management.Automation.Remoting internal event EventHandler SessionClosed; // Track whether Dispose has been called. - private bool disposed = false; + private bool _disposed = false; protected WSManPluginServerSession( WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr) { - syncObject = new Object(); + _syncObject = new Object(); this.creationRequestDetails = creationRequestDetails; this.transportMgr = trnsprtMgr; @@ -96,13 +96,13 @@ namespace System.Management.Automation.Remoting /// /// True when called from Dispose(), False when called from Finalize(). protected virtual void Dispose(bool disposing) - { + { // Check to see if Dispose has already been called. - if(!this.disposed) + if (!_disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. - if(disposing) + if (disposing) { // Dispose managed resources. //Close(false); @@ -115,7 +115,7 @@ namespace System.Management.Automation.Remoting Close(false); // Note disposing has been done. - disposed = true; + _disposed = true; } } @@ -139,7 +139,7 @@ namespace System.Management.Automation.Remoting int flags, string stream, WSManNativeApi.WSManData_UnToMan inboundData) - { + { if ((!String.Equals(stream, WSManPluginConstants.SupportedInputStream, StringComparison.Ordinal)) && (!String.Equals(stream, WSManPluginConstants.SupportedPromptResponseStream, StringComparison.Ordinal))) { @@ -147,7 +147,7 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.InvalidInputStream, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidInputStream, + RemotingErrorIdStrings.WSManPluginInvalidInputStream, WSManPluginConstants.SupportedInputStream)); return; } @@ -156,7 +156,7 @@ namespace System.Management.Automation.Remoting { // no data is supplied..just ignore. WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NoError); return; } @@ -168,12 +168,12 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.InvalidInputDatatype, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidInputStream, + RemotingErrorIdStrings.WSManPluginInvalidInputStream, "WSMAN_DATA_TYPE_BINARY")); return; } - lock (syncObject) + lock (_syncObject) { if (true == isClosed) { @@ -192,7 +192,7 @@ namespace System.Management.Automation.Remoting } internal void SendOneItemToSessionHelper( - System.Byte[] data, + System.Byte[] data, string stream) { transportMgr.ProcessRawData(data, stream); @@ -218,7 +218,7 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidOutputStream, + RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } @@ -230,12 +230,12 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.InvalidOutputStream, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidOutputStream, + RemotingErrorIdStrings.WSManPluginInvalidOutputStream, WSManPluginConstants.SupportedOutputStream)); return false; } - return transportMgr.EnableTransportManagerSendDataToClient(requestDetails, ctxtToReport); + return transportMgr.EnableTransportManagerSendDataToClient(requestDetails, ctxtToReport); } /// @@ -247,7 +247,7 @@ namespace System.Management.Automation.Remoting int result = 0; bool isRegisterWaitForSingleObjectFailed = false; - lock (syncObject) + lock (_syncObject) { if (true == isClosed) { @@ -379,7 +379,7 @@ namespace System.Management.Automation.Remoting // Report Operation Complete using the send request details. internal void ReportSendOperationComplete() { - lock (syncObject) + lock (_syncObject) { if (null != sendRequestDetails) { @@ -404,34 +404,34 @@ namespace System.Management.Automation.Remoting /// /// /// - class WSManPluginShellSession : WSManPluginServerSession + internal class WSManPluginShellSession : WSManPluginServerSession { #region Private Members - private Dictionary activeCommandSessions; - private ServerRemoteSession remoteSession; - + private Dictionary _activeCommandSessions; + private ServerRemoteSession _remoteSession; + #endregion #region Internally Visible Members - + internal object shellSyncObject; - + #endregion #region Constructor internal WSManPluginShellSession( - WSManNativeApi.WSManPluginRequest creationRequestDetails, + WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr, ServerRemoteSession remoteSession, WSManPluginOperationShutdownContext shutDownContext) : base(creationRequestDetails, trnsprtMgr) { - this.remoteSession = remoteSession; - this.remoteSession.Closed += + _remoteSession = remoteSession; + _remoteSession.Closed += new EventHandler(this.HandleServerRemoteSessionClosed); - this.activeCommandSessions = new Dictionary(); + _activeCommandSessions = new Dictionary(); this.shellSyncObject = new System.Object(); this.shutDownContext = shutDownContext; } @@ -453,7 +453,7 @@ namespace System.Management.Automation.Remoting if (null == inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NullInvalidInput, StringUtil.Format( RemotingErrorIdStrings.WSManPluginNullInvalidInput, @@ -463,7 +463,7 @@ namespace System.Management.Automation.Remoting } //not registering shutdown event as this is a synchronous operation. - + IntPtr responseXml = IntPtr.Zero; try { @@ -474,14 +474,14 @@ namespace System.Management.Automation.Remoting inputData = ServerOperationHelpers.ExtractEncodedXmlElement( inboundConnectInformation.Text, WSManNativeApi.PS_CONNECT_XML_TAG); - + //this will raise exceptions on failure try { - remoteSession.ExecuteConnect(inputData, out outputData); + _remoteSession.ExecuteConnect(inputData, out outputData); //construct Xml to send back - string responseData = String.Format(System.Globalization.CultureInfo.InvariantCulture, + string responseData = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}", WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, @@ -494,7 +494,7 @@ namespace System.Management.Automation.Remoting catch (PSRemotingDataStructureException ex) { WSManPluginInstance.ReportOperationComplete(requestDetails, WSManPluginErrorCodes.PluginConnectOperationFailed, ex.Message); - } + } } catch (OutOfMemoryException) { @@ -507,7 +507,7 @@ namespace System.Management.Automation.Remoting Marshal.FreeHGlobal(responseXml); } } - + return; } @@ -522,20 +522,20 @@ namespace System.Management.Automation.Remoting try { // inbound cmd information is already verified.. so no need to verify here. - WSManPluginCommandTransportManager serverCmdTransportMgr = new WSManPluginCommandTransportManager(transportMgr); + WSManPluginCommandTransportManager serverCmdTransportMgr = new WSManPluginCommandTransportManager(transportMgr); serverCmdTransportMgr.Initialize(); // Apply quota limits on the command transport manager - remoteSession.ApplyQuotaOnCommandTransportManager(serverCmdTransportMgr); + _remoteSession.ApplyQuotaOnCommandTransportManager(serverCmdTransportMgr); - WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, this.remoteSession); + WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, _remoteSession); AddToActiveCmdSessions(mgdCmdSession); mgdCmdSession.SessionClosed += new EventHandler(this.HandleCommandSessionClosed); mgdCmdSession.shutDownContext = new WSManPluginOperationShutdownContext( pluginContext, - creationRequestDetails.unmanagedHandle, - mgdCmdSession.creationRequestDetails.unmanagedHandle, + creationRequestDetails.unmanagedHandle, + mgdCmdSession.creationRequestDetails.unmanagedHandle, false); do @@ -546,25 +546,25 @@ namespace System.Management.Automation.Remoting requestDetails, WSManPluginErrorCodes.InvalidArgSet, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginInvalidArgSet, + RemotingErrorIdStrings.WSManPluginInvalidArgSet, "WSManPluginCommand")); break; } // Report plugin context to WSMan mgdCmdSession.ReportContext(); - }while(false); + } while (false); } - catch(System.Exception e) + catch (System.Exception e) { CommandProcessorBase.CheckForSevereException(e); // if there is an exception creating remote session send the message to client. WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.ManagedException, StringUtil.Format( - RemotingErrorIdStrings.WSManPluginManagedException, + RemotingErrorIdStrings.WSManPluginManagedException, e.Message)); } } @@ -597,16 +597,16 @@ namespace System.Management.Automation.Remoting lock (shellSyncObject) { if (isClosed) - { + { return; } IntPtr key = newCmdSession.creationRequestDetails.unmanagedHandle; Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); - if (!activeCommandSessions.ContainsKey(key)) + if (!_activeCommandSessions.ContainsKey(key)) { - activeCommandSessions.Add(key, newCmdSession); + _activeCommandSessions.Add(key, newCmdSession); return; } } @@ -622,29 +622,29 @@ namespace System.Management.Automation.Remoting return; } - activeCommandSessions.Remove(keyToDelete); + _activeCommandSessions.Remove(keyToDelete); } } // closes all the active command sessions. private void CloseAndClearCommandSessions( - Exception reasonForClose) + Exception reasonForClose) { Collection copyCmdSessions = new Collection(); lock (shellSyncObject) { - Dictionary.Enumerator cmdEnumerator = activeCommandSessions.GetEnumerator(); - while(cmdEnumerator.MoveNext()) + Dictionary.Enumerator cmdEnumerator = _activeCommandSessions.GetEnumerator(); + while (cmdEnumerator.MoveNext()) { copyCmdSessions.Add(cmdEnumerator.Current.Value); } - activeCommandSessions.Clear(); + _activeCommandSessions.Clear(); } // close the command sessions outside of the lock IEnumerator cmdSessionEnumerator = copyCmdSessions.GetEnumerator(); - while(cmdSessionEnumerator.MoveNext()) + while (cmdSessionEnumerator.MoveNext()) { WSManPluginCommandSession cmdSession = cmdSessionEnumerator.Current; // we are not interested in session closed events anymore as we are intiating the close @@ -663,13 +663,13 @@ namespace System.Management.Automation.Remoting lock (shellSyncObject) { WSManPluginCommandSession result = null; - activeCommandSessions.TryGetValue(cmdContext, out result); + _activeCommandSessions.TryGetValue(cmdContext, out result); return result; } } private void HandleServerRemoteSessionClosed( - Object sender, + Object sender, RemoteSessionStateMachineEventArgs eventArgs) { Exception reasonForClose = null; @@ -681,7 +681,7 @@ namespace System.Management.Automation.Remoting } private void HandleCommandSessionClosed( - Object source, + Object source, EventArgs e) { // command context is passed as "source" parameter @@ -689,12 +689,12 @@ namespace System.Management.Automation.Remoting } internal override void CloseOperation( - WSManPluginOperationShutdownContext context, + WSManPluginOperationShutdownContext context, Exception reasonForClose) - { + { // let command sessions to close. lock (shellSyncObject) - { + { if (true == isClosed) { return; @@ -714,7 +714,7 @@ namespace System.Management.Automation.Remoting ReportSendOperationComplete(); // close the shell's transport manager after commands handled the operation transportMgr.DoClose(isRcvOpShuttingDown, reasonForClose); - + if (!isRcvOp) { // Initiate close on the active command sessions and then clear the internal @@ -732,32 +732,32 @@ namespace System.Management.Automation.Remoting } } - class WSManPluginCommandSession : WSManPluginServerSession + internal class WSManPluginCommandSession : WSManPluginServerSession { #region Private Members - private ServerRemoteSession remoteSession; - + private ServerRemoteSession _remoteSession; + #endregion #region Internally Visible Members - + internal object cmdSyncObject; - + #endregion #region Constructor - + internal WSManPluginCommandSession( - WSManNativeApi.WSManPluginRequest creationRequestDetails, + WSManNativeApi.WSManPluginRequest creationRequestDetails, WSManPluginServerTransportManager trnsprtMgr, ServerRemoteSession remoteSession) : base(creationRequestDetails, trnsprtMgr) { - this.remoteSession = remoteSession; + _remoteSession = remoteSession; cmdSyncObject = new System.Object(); } - + #endregion internal bool ProcessArguments( @@ -768,7 +768,7 @@ namespace System.Management.Automation.Remoting return false; } - System.Byte[] convertedBase64 = Convert.FromBase64String(arguments.args[0]); + System.Byte[] convertedBase64 = Convert.FromBase64String(arguments.args[0]); transportMgr.ProcessRawData(convertedBase64, WSManPluginConstants.SupportedInputStream); return true; @@ -784,11 +784,11 @@ namespace System.Management.Automation.Remoting // stop the command..command will be stoped if we raise ClosingEvent on // transport manager. transportMgr.PerformStop(); - WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); + WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); } internal override void CloseOperation( - WSManPluginOperationShutdownContext context, + WSManPluginOperationShutdownContext context, Exception reasonForClose) { // let command sessions to close. @@ -804,14 +804,14 @@ namespace System.Management.Automation.Remoting isClosed = true; } } - + bool isRcvOp = context.isReceiveOperation; // only one thread will be here. - bool isRcvOpShuttingDown = (context.isShuttingDown) && + bool isRcvOpShuttingDown = (context.isShuttingDown) && (context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); - bool isCmdShuttingDown = (context.isShuttingDown) && + bool isCmdShuttingDown = (context.isShuttingDown) && (!context.isReceiveOperation) && (context.commandContext == creationRequestDetails.unmanagedHandle); @@ -826,10 +826,10 @@ namespace System.Management.Automation.Remoting // null check is not performed here because Managed C++ will take care of this. base.SafeInvokeSessionClosed(creationRequestDetails.unmanagedHandle, EventArgs.Empty); // Send Operation Complete to WSMan service - WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); + WSManPluginInstance.ReportWSManOperationComplete(creationRequestDetails, reasonForClose); // let base class release its resources this.Close(isCmdShuttingDown); - } + } } /// @@ -840,13 +840,13 @@ namespace System.Management.Automation.Remoting /// /// /// - internal override void ExecuteConnect( + internal override void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, int flags, WSManNativeApi.WSManData_UnToMan inboundConnectInformation) { WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NoError); return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 7c49a68bd..6b48c7d47 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -19,45 +19,45 @@ namespace System.Management.Automation.Remoting { internal class WSManPluginServerTransportManager : AbstractServerSessionTransportManager { - private WSManNativeApi.WSManPluginRequest requestDetails; + private WSManNativeApi.WSManPluginRequest _requestDetails; - // the following variables are used to block thread from sending + // the following variables are used to block thread from sending // data to the client until the client sends a receive request. - private bool isRequestPending; - private object syncObject; - private ManualResetEvent waitHandle; - private Dictionary activeCmdTransportManagers; - private bool isClosed; + private bool _isRequestPending; + private object _syncObject; + private ManualResetEvent _waitHandle; + private Dictionary _activeCmdTransportManagers; + private bool _isClosed; // used to keep track of last error..this will be used // for reporting operation complete to WSMan. - private Exception lastErrorReported; + private Exception _lastErrorReported; // used with RegisterWaitForSingleObject. This object needs to be freed // upon close - private WSManPluginOperationShutdownContext shutDownContext; + private WSManPluginOperationShutdownContext _shutDownContext; // tracker used in conjunction with WSMan API to identify a particular // shell context. - RegisteredWaitHandle registeredShutDownWaitHandle; + private RegisteredWaitHandle _registeredShutDownWaitHandle; // event that gets raised when Prepare is called. Respective Session // object can use this callback to ReportContext to client. public event EventHandler PrepareCalled; - + #region Constructor internal WSManPluginServerTransportManager( - int fragmentSize, + int fragmentSize, PSRemotingCryptoHelper cryptoHelper) : base(fragmentSize, cryptoHelper) { - syncObject = new Object(); - activeCmdTransportManagers = new Dictionary(); - waitHandle = new ManualResetEvent(false); + _syncObject = new Object(); + _activeCmdTransportManagers = new Dictionary(); + _waitHandle = new ManualResetEvent(false); } - + #endregion - #region Inherited_from_AbstractServerSessionTransportManager + #region Inherited_from_AbstractServerSessionTransportManager internal override void Close( Exception reasonForClose) { @@ -73,28 +73,28 @@ namespace System.Management.Automation.Remoting /// [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Justification = "The WSManPluginReceiveResult return value is not documented and is not needed in this case.")] internal void DoClose( - bool isShuttingDown, + bool isShuttingDown, Exception reasonForClose) { - if (isClosed) + if (_isClosed) { return; } - lock (syncObject) + lock (_syncObject) { - if (isClosed) + if (_isClosed) { return; } - isClosed = true; - lastErrorReported = reasonForClose; + _isClosed = true; + _lastErrorReported = reasonForClose; - if (!isRequestPending) + if (!_isRequestPending) { // release threads blocked on the sending data to client if any - waitHandle.Set(); + _waitHandle.Set(); } } @@ -105,51 +105,51 @@ namespace System.Management.Automation.Remoting { RaiseClosingEvent(); - foreach (var cmdTrsprtKvp in activeCmdTransportManagers) + foreach (var cmdTrsprtKvp in _activeCmdTransportManagers) { cmdTrsprtKvp.Value.Close(reasonForClose); } - activeCmdTransportManagers.Clear(); + _activeCmdTransportManagers.Clear(); - if (null != registeredShutDownWaitHandle) + if (null != _registeredShutDownWaitHandle) { // This will not wait for the callback to complete. - registeredShutDownWaitHandle.Unregister(null); - registeredShutDownWaitHandle = null; + _registeredShutDownWaitHandle.Unregister(null); + _registeredShutDownWaitHandle = null; } // Delete the context only if isShuttingDown != true. isShuttingDown will // be true only when the method is called from RegisterWaitForSingleObject // handler..in which case the context will be freed from the callback. - if (null != shutDownContext) + if (null != _shutDownContext) { - shutDownContext = null; + _shutDownContext = null; } // This might happen when client did not send a receive request // but the server is closing - if (null != requestDetails) + if (null != _requestDetails) { // Notify that no more data is being sent on this transport. WSManNativeApi.WSManPluginReceiveResult( - requestDetails.unmanagedHandle, + _requestDetails.unmanagedHandle, (int)WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_RESULT_NO_MORE_DATA, WSManPluginConstants.SupportedOutputStream, IntPtr.Zero, WSManNativeApi.WSMAN_COMMAND_STATE_DONE, 0); - - WSManPluginInstance.ReportWSManOperationComplete(requestDetails, reasonForClose); + + WSManPluginInstance.ReportWSManOperationComplete(_requestDetails, reasonForClose); // We should not use request details again after reporting operation complete // so releasing the resource. Remember not to free this memory as this memory // is allocated and owned by WSMan. - requestDetails = null; + _requestDetails = null; } } finally { // dispose resources - waitHandle.Dispose(); + _waitHandle.Dispose(); } } @@ -159,7 +159,7 @@ namespace System.Management.Automation.Remoting /// internal override void ReportExecutionStatusAsRunning() { - if (true == isClosed) + if (true == _isClosed) { return; } @@ -168,12 +168,12 @@ namespace System.Management.Automation.Remoting //there should have been a receive request in place already - lock (syncObject) + lock (_syncObject) { - if (!isClosed) + if (!_isClosed) { result = WSManNativeApi.WSManPluginReceiveResult( - requestDetails.unmanagedHandle, + _requestDetails.unmanagedHandle, 0, null, IntPtr.Zero, @@ -186,7 +186,7 @@ namespace System.Management.Automation.Remoting { ReportError(result, "WSManPluginReceiveResult"); } - } + } /// /// if flush is true, data will be sent immediately to the client. This is accomplished @@ -197,27 +197,27 @@ namespace System.Management.Automation.Remoting /// /// protected override void SendDataToClient( - byte[] data, - bool flush, - bool reportAsPending, + byte[] data, + bool flush, + bool reportAsPending, bool reportAsDataBoundary) { - if (true == isClosed) + if (true == _isClosed) { return; } // double-check locking mechanism is used here to avoid entering into lock // every time data is sent..entering/exiting from lock is costly. - if (!isRequestPending) - { + if (!_isRequestPending) + { // Dont send data until we have received request from client. // The following blocks the calling thread. The thread is // unblocked once a request from client arrives. - waitHandle.WaitOne(); - isRequestPending = true; + _waitHandle.WaitOne(); + _isRequestPending = true; // at this point request must be pending..so dispose waitHandle - waitHandle.Dispose(); + _waitHandle.Dispose(); } int result = (int)WSManPluginErrorCodes.NoError; @@ -225,20 +225,20 @@ namespace System.Management.Automation.Remoting // to send data to client using WSMan API. using (WSManNativeApi.WSManData_ManToUn dataToBeSent = new WSManNativeApi.WSManData_ManToUn(data)) { - lock (syncObject) + lock (_syncObject) { - if (!isClosed) + if (!_isClosed) { int flags = 0; if (flush) - flags |= (int) WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_FLUSH; + flags |= (int)WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_FLUSH; if (reportAsDataBoundary) //currently assigning hardcoded value for this flag, this is a new change in wsman.h and needs to be replaced with the actual definition once // modified wsman.h is in public headers - flags |= (int) WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_RESULT_DATA_BOUNDARY; + flags |= (int)WSManNativeApi.WSManFlagReceive.WSMAN_FLAG_RECEIVE_RESULT_DATA_BOUNDARY; result = WSManNativeApi.WSManPluginReceiveResult( - requestDetails.unmanagedHandle, + _requestDetails.unmanagedHandle, flags, WSManPluginConstants.SupportedOutputStream, dataToBeSent, @@ -270,24 +270,24 @@ namespace System.Management.Automation.Remoting internal override AbstractServerTransportManager GetCommandTransportManager( Guid powerShellCmdId) { - return activeCmdTransportManagers[powerShellCmdId]; + return _activeCmdTransportManagers[powerShellCmdId]; } // Used by command transport manager to manage cmd transport manager instances by session. internal void ReportTransportMgrForCmd( - Guid cmdId, + Guid cmdId, WSManPluginServerTransportManager transportManager) { - lock (syncObject) + lock (_syncObject) { - if (isClosed) + if (_isClosed) { return; } - if (!activeCmdTransportManagers.ContainsKey(cmdId)) + if (!_activeCmdTransportManagers.ContainsKey(cmdId)) { - activeCmdTransportManagers.Add(cmdId, transportManager); + _activeCmdTransportManagers.Add(cmdId, transportManager); } } } @@ -295,70 +295,70 @@ namespace System.Management.Automation.Remoting internal override void RemoveCommandTransportManager( Guid cmdId) { - lock (syncObject) + lock (_syncObject) { - if (isClosed) + if (_isClosed) { return; } - activeCmdTransportManagers.Remove(cmdId); + _activeCmdTransportManagers.Remove(cmdId); } } -#endregion + #endregion internal bool EnableTransportManagerSendDataToClient( WSManNativeApi.WSManPluginRequest requestDetails, WSManPluginOperationShutdownContext ctxtToReport) { - shutDownContext = ctxtToReport; + _shutDownContext = ctxtToReport; bool isRegisterWaitForSingleObjectSucceeded = true; - lock (syncObject) + lock (_syncObject) { - if (isRequestPending) + if (_isRequestPending) { // if a request is already pending..ignore this. WSManPluginInstance.ReportWSManOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.NoError); return false; } - if (isClosed) + if (_isClosed) { - WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); + WSManPluginInstance.ReportWSManOperationComplete(requestDetails, _lastErrorReported); return false; } - isRequestPending = true; - this.requestDetails = requestDetails; + _isRequestPending = true; + _requestDetails = requestDetails; if (Platform.IsWindows) { - // Wrap the provided handle so it can be passed to the registration function - SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM - EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); - ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); + // Wrap the provided handle so it can be passed to the registration function + SafeWaitHandle safeWaitHandle = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM + EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); + ClrFacade.SetSafeWaitHandle(eventWaitHandle, safeWaitHandle); - this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( - eventWaitHandle, - new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), - shutDownContext, - -1, // INFINITE - true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? - if (null == this.registeredShutDownWaitHandle) - { - isRegisterWaitForSingleObjectSucceeded = false; - } + _registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject( + eventWaitHandle, + new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback), + _shutDownContext, + -1, // INFINITE + true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? + if (null == _registeredShutDownWaitHandle) + { + isRegisterWaitForSingleObjectSucceeded = false; + } } // release thread waiting to send data to the client. - waitHandle.Set(); + _waitHandle.Set(); } if (!isRegisterWaitForSingleObjectSucceeded) { WSManPluginInstance.PerformCloseOperation(ctxtToReport); WSManPluginInstance.ReportOperationComplete( - requestDetails, + requestDetails, WSManPluginErrorCodes.ShutdownRegistrationFailed, StringUtil.Format( RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed)); @@ -375,7 +375,7 @@ namespace System.Management.Automation.Remoting // a command like StateChangedInfo etc. internal void PerformStop() { - if (isRequestPending) + if (_isRequestPending) { RaiseClosingEvent(); } @@ -386,30 +386,30 @@ namespace System.Management.Automation.Remoting } } - class WSManPluginCommandTransportManager : WSManPluginServerTransportManager + internal class WSManPluginCommandTransportManager : WSManPluginServerTransportManager { - private WSManPluginServerTransportManager serverTransportMgr; - private System.Guid cmdId; - + private WSManPluginServerTransportManager _serverTransportMgr; + private System.Guid _cmdId; + // Create Cmd Transport Manager for this sessn trnsprt manager internal WSManPluginCommandTransportManager(WSManPluginServerTransportManager srvrTransportMgr) : base(srvrTransportMgr.Fragmentor.FragmentSize, srvrTransportMgr.CryptoHelper) { - this.serverTransportMgr = srvrTransportMgr; + _serverTransportMgr = srvrTransportMgr; this.TypeTable = srvrTransportMgr.TypeTable; } internal void Initialize() { - this.PowerShellGuidObserver += new System.EventHandler(OnPowershellGuidReported); - this.MigrateDataReadyEventHandlers(serverTransportMgr); + this.PowerShellGuidObserver += new System.EventHandler(OnPowershellGuidReported); + this.MigrateDataReadyEventHandlers(_serverTransportMgr); } private void OnPowershellGuidReported(object src, System.EventArgs args) - { - cmdId = (System.Guid) src; - serverTransportMgr.ReportTransportMgrForCmd(cmdId, this); - this.PowerShellGuidObserver -= new System.EventHandler(this.OnPowershellGuidReported); + { + _cmdId = (System.Guid)src; + _serverTransportMgr.ReportTransportMgrForCmd(_cmdId, this); + this.PowerShellGuidObserver -= new System.EventHandler(this.OnPowershellGuidReported); } } } // namespace System.Management.Automation.Remoting \ No newline at end of file diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index baabca2fb..1b5f27c9e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -43,7 +43,7 @@ using TypeTable = System.Management.Automation.Runspaces.TypeTable; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting.Client -{ +{ /// /// WSMan TransportManager related utils /// @@ -52,7 +52,7 @@ namespace System.Management.Automation.Remoting.Client #region Static Data // Fully qualified error Id modifiers based on transport (WinRM) error codes. - private static Dictionary _transportErrorCodeToFQEID = new Dictionary() + private static Dictionary s_transportErrorCodeToFQEID = new Dictionary() { {WSManNativeApi.ERROR_WSMAN_ACCESS_DENIED, "AccessDenied"}, {WSManNativeApi.ERROR_WSMAN_OUTOF_MEMORY, "ServerOutOfMemory"}, @@ -129,11 +129,11 @@ namespace System.Management.Automation.Remoting.Client params object[] resourceArgs) { PSRemotingTransportException e; - + //For the first two special error conditions, it is remotely possible that the wsmanSessionTM is null when the failures are returned //as part of command TM operations (could be returned becuase of RC retries under the hood) //Not worth to handle these cases seperately as there are very corner scenarios, but need to make sure wsmanSessionTM is not referenced - + // Destination server is reporting that URI redirect is required for this user. if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM != null)) @@ -273,7 +273,7 @@ namespace System.Management.Automation.Remoting.Client string defaultFQEID) { string specificErrorId; - if (_transportErrorCodeToFQEID.TryGetValue(transportErrorCode, out specificErrorId)) + if (s_transportErrorCodeToFQEID.TryGetValue(transportErrorCode, out specificErrorId)) { return specificErrorId + "," + defaultFQEID; } @@ -296,7 +296,7 @@ namespace System.Management.Automation.Remoting.Client internal sealed class WSManClientSessionTransportManager : BaseClientSessionTransportManager { #region Consts - + /// /// Max uri redirection count session variable. /// @@ -339,55 +339,55 @@ namespace System.Management.Automation.Remoting.Client #region Private Data // operation handles are owned by WSMan [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManSessionHandle; + private IntPtr _wsManSessionHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManShellOperationHandle; + private IntPtr _wsManShellOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManRecieveOperationHandle; + private IntPtr _wsManRecieveOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManSendOperationHandle; + private IntPtr _wsManSendOperationHandle; // this is used with WSMan callbacks to represent a session transport manager. - private long sessionContextID; + private long _sessionContextID; - private WSManTransportManagerUtils.tmStartModes startMode = WSManTransportManagerUtils.tmStartModes.None; + private WSManTransportManagerUtils.tmStartModes _startMode = WSManTransportManagerUtils.tmStartModes.None; - private string sessionName; + private string _sessionName; - private bool supportsDisconnect; + private bool _supportsDisconnect; // callbacks - private PrioritySendDataCollection.OnDataAvailableCallback onDataAvailableToSendCallback; + private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; // instance callback handlers - private WSManNativeApi.WSManShellAsync createSessionCallback; - private WSManNativeApi.WSManShellAsync receivedFromRemote; - private WSManNativeApi.WSManShellAsync sendToRemoteCompleted; - private WSManNativeApi.WSManShellAsync disconnectSessionCompleted; - private WSManNativeApi.WSManShellAsync reconnectSessionCompleted; - private WSManNativeApi.WSManShellAsync connectSessionCallback; + private WSManNativeApi.WSManShellAsync _createSessionCallback; + private WSManNativeApi.WSManShellAsync _receivedFromRemote; + private WSManNativeApi.WSManShellAsync _sendToRemoteCompleted; + private WSManNativeApi.WSManShellAsync _disconnectSessionCompleted; + private WSManNativeApi.WSManShellAsync _reconnectSessionCompleted; + private WSManNativeApi.WSManShellAsync _connectSessionCallback; // TODO: This GCHandle is required as it seems WSMan is calling create callback // after we call Close. This seems wrong. Opened bug on WSMan to track this. - private GCHandle createSessionCallbackGCHandle; - private WSManNativeApi.WSManShellAsync closeSessionCompleted; - + private GCHandle _createSessionCallbackGCHandle; + private WSManNativeApi.WSManShellAsync _closeSessionCompleted; + // used by WSManCreateShell call to send additional data (like negotiation) // during shell creation. This is an instance variable to allow for redirection. - private WSManNativeApi.WSManData_ManToUn openContent; + private WSManNativeApi.WSManData_ManToUn _openContent; // By default WSMan compresses data sent on the network..use this flag to not do // this. - private bool noCompression; - private bool noMachineProfile; + private bool _noCompression; + private bool _noMachineProfile; private WSManConnectionInfo _connectionInfo; private int _connectionRetryCount; - + private const string resBaseName = "remotingerroridstrings"; // Robust connections maximum retry time value in milliseconds. - private int maxRetryTime; + private int _maxRetryTime; - private WSManAPIDataCommon wsManApiData; + private WSManAPIDataCommon _wsManApiData; private void ProcessShellData(string data) { @@ -404,15 +404,14 @@ namespace System.Management.Automation.Remoting.Client { if (reader.NodeType == XmlNodeType.Element) { - if (reader.LocalName.Equals("IdleTimeOut", StringComparison.OrdinalIgnoreCase) || + if (reader.LocalName.Equals("IdleTimeOut", StringComparison.OrdinalIgnoreCase) || reader.LocalName.Equals("MaxIdleTimeOut", StringComparison.OrdinalIgnoreCase)) { - bool settingIdleTimeout = !reader.LocalName.Equals("MaxIdleTimeOut", StringComparison.OrdinalIgnoreCase); string timeoutString = reader.ReadElementContentAsString(); - Dbg.Assert(timeoutString.Substring(0, 2).Equals("PT", StringComparison.OrdinalIgnoreCase), + Dbg.Assert(timeoutString.Substring(0, 2).Equals("PT", StringComparison.OrdinalIgnoreCase), "IdleTimeout is not in expected format"); int decimalIndex = timeoutString.IndexOf('.'); @@ -463,25 +462,25 @@ namespace System.Management.Automation.Remoting.Client #endregion #region Static Data - + // static callback delegate - private static WSManNativeApi.WSManShellAsyncCallback sessionCreateCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionCloseCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionReceiveCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionSendCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionDisconnectCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionReconnectCallback; - private static WSManNativeApi.WSManShellAsyncCallback sessionConnectCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionCreateCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionCloseCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionReceiveCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionSendCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionDisconnectCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionReconnectCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_sessionConnectCallback; // This dictionary maintains active session transport managers to be used from various // callbacks. - private static Dictionary SessionTMHandles = - new Dictionary(); - private static long SessionTMSeed; + private static Dictionary s_sessionTMHandles = + new Dictionary(); + private static long s_sessionTMSeed; //generate unique session id private static long GetNextSessionTMHandleId() { - return System.Threading.Interlocked.Increment(ref SessionTMSeed); + return System.Threading.Interlocked.Increment(ref s_sessionTMSeed); } // we need a synchronized add and remove so that multiple threads @@ -489,17 +488,17 @@ namespace System.Management.Automation.Remoting.Client private static void AddSessionTransportManager(long sessnTMId, WSManClientSessionTransportManager sessnTransportManager) { - lock (SessionTMHandles) + lock (s_sessionTMHandles) { - SessionTMHandles.Add(sessnTMId, sessnTransportManager); + s_sessionTMHandles.Add(sessnTMId, sessnTransportManager); } } private static void RemoveSessionTransportManager(long sessnTMId) { - lock (SessionTMHandles) + lock (s_sessionTMHandles) { - SessionTMHandles.Remove(sessnTMId); + s_sessionTMHandles.Remove(sessnTMId); } } @@ -511,9 +510,9 @@ namespace System.Management.Automation.Remoting.Client { sessnTMId = operationContext.ToInt64(); sessnTransportManager = null; - lock (SessionTMHandles) + lock (s_sessionTMHandles) { - return SessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager); + return s_sessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager); } } @@ -521,8 +520,8 @@ namespace System.Management.Automation.Remoting.Client #region SHIM: Redirection delegates for test purposes - private static Delegate sessionSendRedirect = null; - private static Delegate protocolVersionRedirect = null; + private static Delegate s_sessionSendRedirect = null; + private static Delegate s_protocolVersionRedirect = null; #endregion @@ -536,31 +535,31 @@ namespace System.Management.Automation.Remoting.Client // Initialize callback delegates WSManNativeApi.WSManShellCompletionFunction createDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnCreateSessionCallback); - sessionCreateCallback = new WSManNativeApi.WSManShellAsyncCallback(createDelegate); + s_sessionCreateCallback = new WSManNativeApi.WSManShellAsyncCallback(createDelegate); WSManNativeApi.WSManShellCompletionFunction closeDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnCloseSessionCompleted); - sessionCloseCallback = new WSManNativeApi.WSManShellAsyncCallback(closeDelegate); + s_sessionCloseCallback = new WSManNativeApi.WSManShellAsyncCallback(closeDelegate); WSManNativeApi.WSManShellCompletionFunction receiveDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionDataReceived); - sessionReceiveCallback = new WSManNativeApi.WSManShellAsyncCallback(receiveDelegate); + s_sessionReceiveCallback = new WSManNativeApi.WSManShellAsyncCallback(receiveDelegate); WSManNativeApi.WSManShellCompletionFunction sendDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionSendCompleted); - sessionSendCallback = new WSManNativeApi.WSManShellAsyncCallback(sendDelegate); + s_sessionSendCallback = new WSManNativeApi.WSManShellAsyncCallback(sendDelegate); WSManNativeApi.WSManShellCompletionFunction disconnectDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionDisconnectCompleted); - sessionDisconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(disconnectDelegate); + s_sessionDisconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(disconnectDelegate); WSManNativeApi.WSManShellCompletionFunction reconnectDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionReconnectCompleted); - sessionReconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(reconnectDelegate); + s_sessionReconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(reconnectDelegate); WSManNativeApi.WSManShellCompletionFunction connectDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionConnectCallback); - sessionConnectCallback = new WSManNativeApi.WSManShellAsyncCallback(connectDelegate); + s_sessionConnectCallback = new WSManNativeApi.WSManShellAsyncCallback(connectDelegate); } /// @@ -584,18 +583,18 @@ namespace System.Management.Automation.Remoting.Client PSRemotingCryptoHelper cryptoHelper, string sessionName) : base(runspacePoolInstanceId, cryptoHelper) { // Initialize WSMan instance - wsManApiData = new WSManAPIDataCommon(); - if (wsManApiData.WSManAPIHandle == IntPtr.Zero) + _wsManApiData = new WSManAPIDataCommon(); + if (_wsManApiData.WSManAPIHandle == IntPtr.Zero) { throw new PSRemotingTransportException( - StringUtil.Format(RemotingErrorIdStrings.WSManInitFailed, wsManApiData.ErrorCode)); + StringUtil.Format(RemotingErrorIdStrings.WSManInitFailed, _wsManApiData.ErrorCode)); } Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null"); CryptoHelper = cryptoHelper; dataToBeSent.Fragmentor = base.Fragmentor; - this.sessionName = sessionName; - + _sessionName = sessionName; + // session transport manager can recieve unlimited data..however each object is limited // by maxRecvdObjectSize. this is to allow clients to use a session for an unlimited time.. // also the messages that can be sent to a session are limited and very controlled. @@ -605,7 +604,7 @@ namespace System.Management.Automation.Remoting.Client ReceivedDataCollection.MaximumReceivedDataSize = null; ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize; - onDataAvailableToSendCallback = + _onDataAvailableToSendCallback = new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); Initialize(connectionInfo.ConnectionUri, connectionInfo); @@ -627,21 +626,21 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetDefaultTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting Default timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_DEFAULT_OPERATION_TIMEOUTMS, new WSManNativeApi.WSManDataDWord(milliseconds)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; - } + } } } @@ -655,17 +654,17 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetConnectTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting CreateShell timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_CREATE_SHELL, new WSManNativeApi.WSManDataDWord(milliseconds)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -683,17 +682,17 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetCloseTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting CloseShell timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_CLOSE_SHELL_OPERATION, new WSManNativeApi.WSManDataDWord(milliseconds)); - + if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -711,17 +710,17 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetSendTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting SendShellInput timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SEND_SHELL_INPUT, new WSManNativeApi.WSManDataDWord(milliseconds)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -739,17 +738,17 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetReceiveTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting ReceiveShellOutput timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_RECEIVE_SHELL_OUTPUT, new WSManNativeApi.WSManDataDWord(milliseconds)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -767,17 +766,17 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetSignalTimeOut(int milliseconds) { - Dbg.Assert(wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); + Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null"); using (tracer.TraceMethod("Setting SignalShell timeout: {0} milliseconds", milliseconds)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SIGNAL_SHELL, new WSManNativeApi.WSManDataDWord(milliseconds)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -795,13 +794,13 @@ namespace System.Management.Automation.Remoting.Client /// internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, int dwordData) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, option, new WSManNativeApi.WSManDataDWord(dwordData)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -820,13 +819,13 @@ namespace System.Management.Automation.Remoting.Client { using (WSManNativeApi.WSManData_ManToUn data = new WSManNativeApi.WSManData_ManToUn(stringData)) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, option, data); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -840,12 +839,12 @@ namespace System.Management.Automation.Remoting.Client internal WSManAPIDataCommon WSManAPIData { - get { return wsManApiData; } + get { return _wsManApiData; } } internal bool SupportsDisconnect { - get { return supportsDisconnect; } + get { return _supportsDisconnect; } } @@ -865,7 +864,7 @@ namespace System.Management.Automation.Remoting.Client //Add ETW traces // disconnect Callback - disconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionDisconnectCallback); + _disconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionDisconnectCallback); try { lock (syncObject) @@ -883,10 +882,10 @@ namespace System.Management.Automation.Remoting.Client flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0; - WSManNativeApi.WSManDisconnectShellEx(wsManShellOperationHandle, + WSManNativeApi.WSManDisconnectShellEx(_wsManShellOperationHandle, flags, disconnectInfo, - disconnectSessionCompleted); + _disconnectSessionCompleted); } } finally @@ -903,7 +902,7 @@ namespace System.Management.Automation.Remoting.Client //Add ETW traces // reconnect Callback - reconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionReconnectCallback); + _reconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionReconnectCallback); lock (syncObject) { if (isClosed) @@ -919,11 +918,10 @@ namespace System.Management.Automation.Remoting.Client flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0; - WSManNativeApi.WSManReconnectShellEx(wsManShellOperationHandle, + WSManNativeApi.WSManReconnectShellEx(_wsManShellOperationHandle, flags, - reconnectSessionCompleted); + _reconnectSessionCompleted); } - } /// @@ -942,7 +940,7 @@ namespace System.Management.Automation.Remoting.Client ReceivedDataCollection.PrepareForStreamConnect(); // additional content with connect shell call. Negotiation and connect related messages // should be included in payload - if (null == openContent) + if (null == _openContent) { DataPriorityType additionalDataType; byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); @@ -955,7 +953,7 @@ namespace System.Management.Automation.Remoting.Client WSManNativeApi.PS_CONNECT_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(additionalData)); - openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); + _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } //THERE SHOULD BE NO ADDITIONAL DATA. If there is, it means we are not able to push all initial negotaion related data @@ -968,18 +966,17 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(false, "Negotiation payload does not fit in ConnectShell"); return; } - } // Create and store context for this shell operation. This context is used from various callbacks - sessionContextID = GetNextSessionTMHandleId(); - AddSessionTransportManager(sessionContextID, this); + _sessionContextID = GetNextSessionTMHandleId(); + AddSessionTransportManager(_sessionContextID, this); //session is implicitly assumed to support disconnect - supportsDisconnect = true; + _supportsDisconnect = true; // Create Callback - connectSessionCallback = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionConnectCallback); + _connectSessionCallback = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionConnectCallback); lock (syncObject) { if (isClosed) @@ -989,8 +986,8 @@ namespace System.Management.Automation.Remoting.Client return; } - Dbg.Assert(startMode == WSManTransportManagerUtils.tmStartModes.None, "startMode is not in expected state"); - startMode = WSManTransportManagerUtils.tmStartModes.Connect; + Dbg.Assert(_startMode == WSManTransportManagerUtils.tmStartModes.None, "startMode is not in expected state"); + _startMode = WSManTransportManagerUtils.tmStartModes.Connect; int flags = 0; flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Block) ? @@ -998,19 +995,19 @@ namespace System.Management.Automation.Remoting.Client flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0; - WSManNativeApi.WSManConnectShellEx(wsManSessionHandle, + WSManNativeApi.WSManConnectShellEx(_wsManSessionHandle, flags, _connectionInfo.ShellUri, RunspacePoolInstanceId.ToString().ToUpperInvariant(), //wsman is case sensetive wrt shellId. so consistently using upper case IntPtr.Zero, - openContent, - connectSessionCallback, - ref wsManShellOperationHandle); + _openContent, + _connectSessionCallback, + ref _wsManShellOperationHandle); } - if (wsManShellOperationHandle == IntPtr.Zero) + if (_wsManShellOperationHandle == IntPtr.Zero) { - TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(wsManApiData.WSManAPIHandle, + TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(_wsManApiData.WSManAPIHandle, this, new WSManNativeApi.WSManError(), TransportMethodEnum.ConnectShellEx, @@ -1043,13 +1040,13 @@ namespace System.Management.Automation.Remoting.Client PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), Guid.Empty.ToString()); - receivedFromRemote = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionReceiveCallback); - WSManNativeApi.WSManReceiveShellOutputEx(wsManShellOperationHandle, - IntPtr.Zero, 0, wsManApiData.OutputStreamSet, receivedFromRemote, - ref wsManRecieveOperationHandle); + _receivedFromRemote = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionReceiveCallback); + WSManNativeApi.WSManReceiveShellOutputEx(_wsManShellOperationHandle, + IntPtr.Zero, 0, _wsManApiData.OutputStreamSet, _receivedFromRemote, + ref _wsManRecieveOperationHandle); } } - + /// /// Starts connecting to remote end asynchronously. This will result in a WSManCreateShellEx WSMan /// async call. By the time this call returns, we will have a valid handle, if the operation @@ -1063,15 +1060,15 @@ namespace System.Management.Automation.Remoting.Client { Dbg.Assert(!isClosed, "object already disposed"); Dbg.Assert(!String.IsNullOrEmpty(_connectionInfo.ShellUri), "shell uri cannot be null or empty."); - Dbg.Assert(wsManApiData != null, "WSManApiData should always be created before session creation."); + Dbg.Assert(_wsManApiData != null, "WSManApiData should always be created before session creation."); - List shellOptions = new List(wsManApiData.CommonOptionSet); + List shellOptions = new List(_wsManApiData.CommonOptionSet); #region SHIM: Redirection code for protocol version - - if (protocolVersionRedirect != null) + + if (s_protocolVersionRedirect != null) { - string newProtocolVersion = (string)protocolVersionRedirect.DynamicInvoke(); + string newProtocolVersion = (string)s_protocolVersionRedirect.DynamicInvoke(); shellOptions.Clear(); WSManNativeApi.WSManOption newPrtVOption = new WSManNativeApi.WSManOption(); newPrtVOption.name = RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME; @@ -1090,15 +1087,15 @@ namespace System.Management.Automation.Remoting.Client // startup info WSManNativeApi.WSManShellStartupInfo_ManToUn startupInfo = - new WSManNativeApi.WSManShellStartupInfo_ManToUn(wsManApiData.InputStreamSet, - wsManApiData.OutputStreamSet, + new WSManNativeApi.WSManShellStartupInfo_ManToUn(_wsManApiData.InputStreamSet, + _wsManApiData.OutputStreamSet, uIdleTimeout, - sessionName); + _sessionName); // additional content with create shell call. Piggy back first fragement from // the dataToBeSent buffer. - if (null == openContent) - { + if (null == _openContent) + { DataPriorityType additionalDataType; byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); @@ -1106,10 +1103,10 @@ namespace System.Management.Automation.Remoting.Client bool sendContinue = true; - if (sessionSendRedirect != null) + if (s_sessionSendRedirect != null) { object[] arguments = new object[2] { null, additionalData }; - sendContinue = (bool)sessionSendRedirect.DynamicInvoke(arguments); + sendContinue = (bool)s_sessionSendRedirect.DynamicInvoke(arguments); additionalData = (byte[])arguments[0]; } @@ -1126,21 +1123,21 @@ namespace System.Management.Automation.Remoting.Client WSManNativeApi.PS_CREATION_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(additionalData)); - openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); + _openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml); } } // Create the session context information only once. CreateAsync() can be called multiple // times by RetrySessionCreation for flaky networks. - if (sessionContextID == 0) + if (_sessionContextID == 0) { // Create and store context for this shell operation. This context is used from various callbacks - sessionContextID = GetNextSessionTMHandleId(); - AddSessionTransportManager(sessionContextID, this); + _sessionContextID = GetNextSessionTMHandleId(); + AddSessionTransportManager(_sessionContextID, this); // Create Callback - createSessionCallback = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionCreateCallback); - createSessionCallbackGCHandle = GCHandle.Alloc(createSessionCallback); + _createSessionCallback = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionCreateCallback); + _createSessionCallbackGCHandle = GCHandle.Alloc(_createSessionCallback); } PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, @@ -1158,10 +1155,10 @@ namespace System.Management.Automation.Remoting.Client return; } - Dbg.Assert(startMode == WSManTransportManagerUtils.tmStartModes.None, "startMode is not in expected state"); - startMode = WSManTransportManagerUtils.tmStartModes.Create; + Dbg.Assert(_startMode == WSManTransportManagerUtils.tmStartModes.None, "startMode is not in expected state"); + _startMode = WSManTransportManagerUtils.tmStartModes.Create; - if (noMachineProfile) + if (_noMachineProfile) { WSManNativeApi.WSManOption noProfile = new WSManNativeApi.WSManOption(); noProfile.name = WSManNativeApi.NoProfile; @@ -1170,29 +1167,29 @@ namespace System.Management.Automation.Remoting.Client shellOptions.Add(noProfile); } - int flags = noCompression ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_NO_COMPRESSION : 0; + int flags = _noCompression ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_NO_COMPRESSION : 0; flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Block) ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_BLOCK : 0; - flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ? + flags |= (_connectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0; using (WSManNativeApi.WSManOptionSet optionSet = new WSManNativeApi.WSManOptionSet(shellOptions.ToArray())) { - WSManNativeApi.WSManCreateShellEx(wsManSessionHandle, + WSManNativeApi.WSManCreateShellEx(_wsManSessionHandle, flags, _connectionInfo.ShellUri, RunspacePoolInstanceId.ToString().ToUpperInvariant(), startupInfo, optionSet, - openContent, - createSessionCallback, - ref wsManShellOperationHandle); + _openContent, + _createSessionCallback, + ref _wsManShellOperationHandle); } } - if (wsManShellOperationHandle == IntPtr.Zero) + if (_wsManShellOperationHandle == IntPtr.Zero) { - TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(wsManApiData.WSManAPIHandle, + TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(_wsManApiData.WSManAPIHandle, this, new WSManNativeApi.WSManError(), TransportMethodEnum.CreateShellEx, @@ -1206,7 +1203,6 @@ namespace System.Management.Automation.Remoting.Client { startupInfo.Dispose(); } - } /// @@ -1223,15 +1219,15 @@ namespace System.Management.Automation.Remoting.Client { return; } - - if (startMode == WSManTransportManagerUtils.tmStartModes.None) + + if (_startMode == WSManTransportManagerUtils.tmStartModes.None) { shouldRaiseCloseCompleted = true; } - else if (startMode == WSManTransportManagerUtils.tmStartModes.Create || - startMode == WSManTransportManagerUtils.tmStartModes.Connect) + else if (_startMode == WSManTransportManagerUtils.tmStartModes.Create || + _startMode == WSManTransportManagerUtils.tmStartModes.Connect) { - if (IntPtr.Zero == wsManShellOperationHandle) + if (IntPtr.Zero == _wsManShellOperationHandle) { shouldRaiseCloseCompleted = true; } @@ -1249,23 +1245,23 @@ namespace System.Management.Automation.Remoting.Client if (shouldRaiseCloseCompleted) { - try + try { RaiseCloseCompleted(); } finally { - RemoveSessionTransportManager(sessionContextID); + RemoveSessionTransportManager(_sessionContextID); } return; } //TODO - On unexpected failures on a reconstructed session... we dont want to close server session PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseShell, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); - closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionCloseCallback); - WSManNativeApi.WSManCloseShell(wsManShellOperationHandle, 0, closeSessionCompleted); + _closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionCloseCallback); + WSManNativeApi.WSManCloseShell(_wsManShellOperationHandle, 0, _closeSessionCompleted); } /// @@ -1280,20 +1276,20 @@ namespace System.Management.Automation.Remoting.Client if (serverProtocolVersion <= RemotingConstants.ProtocolVersionWin7RTM) { int maxEnvSize; - WSManNativeApi.WSManGetSessionOptionAsDword(wsManSessionHandle, + WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB, out maxEnvSize); if (maxEnvSize == WSManNativeApi.WSMAN_DEFAULT_MAX_ENVELOPE_SIZE_KB_V3) { - int result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB, new WSManNativeApi.WSManDataDWord(WSManNativeApi.WSMAN_DEFAULT_MAX_ENVELOPE_SIZE_KB_V2)); if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -1301,7 +1297,7 @@ namespace System.Management.Automation.Remoting.Client //retrieve the packet size again int packetSize; - WSManNativeApi.WSManGetSessionOptionAsDword(wsManSessionHandle, + WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out packetSize); // packet size returned is in KB. Convert this into bytes @@ -1320,8 +1316,8 @@ namespace System.Management.Automation.Remoting.Client { Dbg.Assert(!isClosed, "Transport manager must not be closed while preparing for redirection."); - closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionCloseCallback); - WSManNativeApi.WSManCloseShell(wsManShellOperationHandle, 0, closeSessionCompleted); + _closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionCloseCallback); + WSManNativeApi.WSManCloseShell(_wsManShellOperationHandle, 0, _closeSessionCompleted); } /// @@ -1345,10 +1341,10 @@ namespace System.Management.Automation.Remoting.Client RunspacePoolInstanceId.ToString(), newUri.ToString()); Initialize(newUri, (WSManConnectionInfo)connectionInfo); //reset startmode - startMode = WSManTransportManagerUtils.tmStartModes.None; + _startMode = WSManTransportManagerUtils.tmStartModes.None; CreateAsync(); } - + /// /// Creates a command transport manager. This will create a new PrioritySendDataCollection which should be used to /// send data to the server. @@ -1372,7 +1368,7 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(null != wsmanConnectionInfo, "ConnectionInfo must be WSManConnectionInfo"); WSManClientCommandTransportManager result = new - WSManClientCommandTransportManager(wsmanConnectionInfo, wsManShellOperationHandle, cmd, noInput, this); + WSManClientCommandTransportManager(wsmanConnectionInfo, _wsManShellOperationHandle, cmd, noInput, this); return result; } @@ -1392,8 +1388,8 @@ namespace System.Management.Automation.Remoting.Client { Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null."); - this._connectionInfo = connectionInfo; - + _connectionInfo = connectionInfo; + // this will generate: http://ComputerName:port/appname?PSVersion= // PSVersion= pattern is needed to make Exchange compatible with PS V2 CTP3 // release. Using the PSVersion= logic, Exchange R4 server will redirect @@ -1427,7 +1423,7 @@ namespace System.Management.Automation.Remoting.Client PSVersionInfo.PSVersion, additionalUriSuffixString); } - else + else { // if there is already a query string, append using & .. see RFC 3986 connectionStr = string.Format(CultureInfo.InvariantCulture, @@ -1470,7 +1466,7 @@ namespace System.Management.Automation.Remoting.Client string userName = null; System.Security.SecureString password = null; - switch(connectionInfo.ProxyAuthentication) + switch (connectionInfo.ProxyAuthentication) { case AuthenticationMechanism.Negotiate: authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE; @@ -1498,13 +1494,13 @@ namespace System.Management.Automation.Remoting.Client new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, proxyAuthCredentials); int result = 0; - + try { - result = WSManNativeApi.WSManCreateSession(wsManApiData.WSManAPIHandle, connectionStr, 0, + result = WSManNativeApi.WSManCreateSession(_wsManApiData.WSManAPIHandle, connectionStr, 0, authCredentials.GetMarshalledObject(), - (null == proxyInfo) ? IntPtr.Zero : (IntPtr) proxyInfo, - ref wsManSessionHandle); + (null == proxyInfo) ? IntPtr.Zero : (IntPtr)proxyInfo, + ref _wsManSessionHandle); } finally { @@ -1528,7 +1524,7 @@ namespace System.Management.Automation.Remoting.Client if (result != 0) { // Get the error message from WSMan - string errorMessage = WSManNativeApi.WSManGetErrorMessage(wsManApiData.WSManAPIHandle, result); + string errorMessage = WSManNativeApi.WSManGetErrorMessage(_wsManApiData.WSManAPIHandle, result); PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage); throw exception; @@ -1536,21 +1532,21 @@ namespace System.Management.Automation.Remoting.Client // set the packet size for this session int packetSize; - WSManNativeApi.WSManGetSessionOptionAsDword(wsManSessionHandle, + WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out packetSize); // packet size returned is in KB. Convert this into bytes.. Fragmentor.FragmentSize = packetSize << 10; // Get robust connections maximum retries time. - WSManNativeApi.WSManGetSessionOptionAsDword(wsManSessionHandle, + WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_RETRY_TIME, - out this.maxRetryTime); + out _maxRetryTime); this.dataToBeSent.Fragmentor = base.Fragmentor; - noCompression = !connectionInfo.UseCompression; - noMachineProfile = connectionInfo.NoMachineProfile; - + _noCompression = !connectionInfo.UseCompression; + _noMachineProfile = connectionInfo.NoMachineProfile; + // set other WSMan session related defaults if (isSSLSpecified) { @@ -1567,7 +1563,7 @@ namespace System.Management.Automation.Remoting.Client // check if implicit credentials can be used for Negotiate if (connectionInfo.AllowImplicitCredentialForNegotiate) { - result = WSManNativeApi.WSManSetSessionOption(wsManSessionHandle, + result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS, new WSManNativeApi.WSManDataDWord(1)); } @@ -1631,7 +1627,7 @@ namespace System.Management.Automation.Remoting.Client { EnqueueAndStartProcessingThread(null, eventArgs, null); } - + /// /// Log the error message in the Crimson logger and raise error handler. /// @@ -1686,17 +1682,17 @@ namespace System.Management.Automation.Remoting.Client { if (shouldClearSend) { - if (null != sendToRemoteCompleted) + if (null != _sendToRemoteCompleted) { - sendToRemoteCompleted.Dispose(); - sendToRemoteCompleted = null; + _sendToRemoteCompleted.Dispose(); + _sendToRemoteCompleted = null; } // For send..clear always - if (IntPtr.Zero != wsManSendOperationHandle) + if (IntPtr.Zero != _wsManSendOperationHandle) { - WSManNativeApi.WSManCloseOperation(wsManSendOperationHandle, 0); - wsManSendOperationHandle = IntPtr.Zero; + WSManNativeApi.WSManCloseOperation(_wsManSendOperationHandle, 0); + _wsManSendOperationHandle = IntPtr.Zero; } } else @@ -1704,16 +1700,16 @@ namespace System.Management.Automation.Remoting.Client // clearing for receive..Clear only when the end of operation is reached. if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_END_OF_OPERATION) { - if (IntPtr.Zero != wsManRecieveOperationHandle) + if (IntPtr.Zero != _wsManRecieveOperationHandle) { - WSManNativeApi.WSManCloseOperation(wsManRecieveOperationHandle, 0); - wsManRecieveOperationHandle = IntPtr.Zero; + WSManNativeApi.WSManCloseOperation(_wsManRecieveOperationHandle, 0); + _wsManRecieveOperationHandle = IntPtr.Zero; } - if (null != receivedFromRemote) + if (null != _receivedFromRemote) { - receivedFromRemote.Dispose(); - receivedFromRemote = null; + _receivedFromRemote.Dispose(); + _receivedFromRemote = null; } } } @@ -1758,7 +1754,7 @@ namespace System.Management.Automation.Remoting.Client /// internal int MaxRetryConnectionTime { - get { return this.maxRetryTime; } + get { return _maxRetryTime; } } /// @@ -1767,7 +1763,7 @@ namespace System.Management.Automation.Remoting.Client /// internal IntPtr SessionHandle { - get { return this.wsManSessionHandle; } + get { return _wsManSessionHandle; } } /// @@ -1775,7 +1771,7 @@ namespace System.Management.Automation.Remoting.Client /// internal WSManConnectionInfo ConnectionInfo { - get { return this._connectionInfo; } + get { return _connectionInfo; } } /// @@ -1837,7 +1833,7 @@ namespace System.Management.Automation.Remoting.Client private void StartCreateRetry(object state) { // Begin new session create attempt. - startMode = WSManTransportManagerUtils.tmStartModes.None; + _startMode = WSManTransportManagerUtils.tmStartModes.None; CreateAsync(); } @@ -1860,7 +1856,7 @@ namespace System.Management.Automation.Remoting.Client WSManClientSessionTransportManager sessionTM = null; if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle)) { - // We dont have the session TM handle..just return. + // We dont have the session TM handle..just return. tracer.WriteLine("Unable to find a transport manager for context {0}.", sessionTMHandle); return; } @@ -1881,7 +1877,7 @@ namespace System.Management.Automation.Remoting.Client // be called before WSManCreateShellEx returns. since we already validated the // shell context exists, safely assigning the shellOperationHandle to shell transport manager. // Remove this once WSMan fixes its code. - sessionTM.wsManShellOperationHandle = shellOperationHandle; + sessionTM._wsManShellOperationHandle = shellOperationHandle; lock (sessionTM.syncObject) { @@ -1895,7 +1891,7 @@ namespace System.Management.Automation.Remoting.Client if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); - + if (errorStruct.errorCode != 0) { tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); @@ -1909,7 +1905,7 @@ namespace System.Management.Automation.Remoting.Client } TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.CreateShellEx, @@ -1922,15 +1918,15 @@ namespace System.Management.Automation.Remoting.Client } //check if the session supports disconnect - sessionTM.supportsDisconnect = ((flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0) ? true : false; + sessionTM._supportsDisconnect = ((flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0) ? true : false; // openContent is used by redirection ie., while redirecting to // a new machine.. this is not needed anymore as the connection // is successfully established. - if (null != sessionTM.openContent) + if (null != sessionTM._openContent) { - sessionTM.openContent.Dispose(); - sessionTM.openContent = null; + sessionTM._openContent.Dispose(); + sessionTM._openContent = null; } if (data != IntPtr.Zero) @@ -1998,7 +1994,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.CloseShellOperationEx, @@ -2035,10 +2031,10 @@ namespace System.Management.Automation.Remoting.Client //LOG ETW EVENTS // Dispose the OnDisconnect callback as it is not needed anymore - if (null != sessionTM.disconnectSessionCompleted) + if (null != sessionTM._disconnectSessionCompleted) { - sessionTM.disconnectSessionCompleted.Dispose(); - sessionTM.disconnectSessionCompleted = null; + sessionTM._disconnectSessionCompleted.Dispose(); + sessionTM._disconnectSessionCompleted = null; } if (IntPtr.Zero != error) @@ -2050,7 +2046,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.DisconnectShellEx, @@ -2077,7 +2073,7 @@ namespace System.Management.Automation.Remoting.Client //Log ETW traces } - + return; } @@ -2103,10 +2099,10 @@ namespace System.Management.Automation.Remoting.Client //Add ETW events // Dispose the OnCreate callback as it is not needed anymore - if (null != sessionTM.reconnectSessionCompleted) + if (null != sessionTM._reconnectSessionCompleted) { - sessionTM.reconnectSessionCompleted.Dispose(); - sessionTM.reconnectSessionCompleted = null; + sessionTM._reconnectSessionCompleted.Dispose(); + sessionTM._reconnectSessionCompleted = null; } if (IntPtr.Zero != error) @@ -2118,7 +2114,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.ReconnectShellEx, @@ -2221,7 +2217,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.ConnectShellEx, @@ -2234,10 +2230,10 @@ namespace System.Management.Automation.Remoting.Client } //dispose openContent - if (null != sessionTM.openContent) + if (null != sessionTM._openContent) { - sessionTM.openContent.Dispose(); - sessionTM.openContent = null; + sessionTM._openContent.Dispose(); + sessionTM._openContent = null; } lock (sessionTM.syncObject) @@ -2247,7 +2243,7 @@ namespace System.Management.Automation.Remoting.Client { tracer.WriteLine("Client Session TM: Transport manager is closed. So returning"); return; - } + } } //process returned Xml @@ -2261,7 +2257,7 @@ namespace System.Management.Automation.Remoting.Client // Set up the data-to-send callback. sessionTM.SendOneItem(); - + // successfully made a connection. Now report this by raising the ConnectCompleted event. // Microsoft's PS 3.0 Server will return all negotiation related data in one shot in connect Data // Note that we are not starting to receive data yet. the DSHandlers above will do that when the session @@ -2293,7 +2289,7 @@ namespace System.Management.Automation.Remoting.Client PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, sessionTM.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString()); - if (!shellOperationHandle.Equals(sessionTM.wsManShellOperationHandle)) + if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle)) { // WSMan returned data from a wrong shell..notify the caller // about the same. @@ -2327,7 +2323,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.SendShellInputEx, @@ -2341,7 +2337,7 @@ namespace System.Management.Automation.Remoting.Client // Send the next item, if available sessionTM.SendOneItem(); - } + } // WSMan will make sure this callback is synchronously called ie., if 1 callback // is active, the callback will not be called from a different thread. @@ -2372,7 +2368,7 @@ namespace System.Management.Automation.Remoting.Client return; } - if (!shellOperationHandle.Equals(sessionTM.wsManShellOperationHandle)) + if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle)) { // WSMan returned data from a wrong shell..notify the caller // about the same. @@ -2394,7 +2390,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( - sessionTM.wsManApiData.WSManAPIHandle, + sessionTM._wsManApiData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.ReceiveShellOutputEx, @@ -2411,10 +2407,10 @@ namespace System.Management.Automation.Remoting.Client { tracer.WriteLine("Session Received Data : {0}", dataReceived.data.Length); PSEtwLog.LogAnalyticInformational( - PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, + PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - sessionTM.RunspacePoolInstanceId.ToString(), - Guid.Empty.ToString(), + sessionTM.RunspacePoolInstanceId.ToString(), + Guid.Empty.ToString(), dataReceived.data.Length.ToString(CultureInfo.InvariantCulture)); sessionTM.ProcessRawData(dataReceived.data, dataReceived.stream); } @@ -2428,7 +2424,7 @@ namespace System.Management.Automation.Remoting.Client { DataPriorityType priorityType; // This will either return data or register callback but doesn't do both. - byte[] data = dataToBeSent.ReadOrRegisterCallback(onDataAvailableToSendCallback, + byte[] data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); if (null != data) { @@ -2453,10 +2449,10 @@ namespace System.Management.Automation.Remoting.Client bool sendContinue = true; - if (sessionSendRedirect != null) + if (s_sessionSendRedirect != null) { object[] arguments = new object[2] { null, package }; - sendContinue = (bool)sessionSendRedirect.DynamicInvoke(arguments); + sendContinue = (bool)s_sessionSendRedirect.DynamicInvoke(arguments); package = (byte[])arguments[0]; } @@ -2471,8 +2467,8 @@ namespace System.Management.Automation.Remoting.Client PSEtwLog.LogAnalyticInformational( PSEventId.WSManSendShellInputEx, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), - Guid.Empty.ToString(), + RunspacePoolInstanceId.ToString(), + Guid.Empty.ToString(), serializedContent.BufferLength.ToString(CultureInfo.InvariantCulture)); lock (syncObject) @@ -2485,13 +2481,13 @@ namespace System.Management.Automation.Remoting.Client } // send callback - sendToRemoteCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(sessionContextID), sessionSendCallback); - WSManNativeApi.WSManSendShellInputEx(wsManShellOperationHandle, IntPtr.Zero, 0, - priorityType == DataPriorityType.Default ? - WSManNativeApi.WSMAN_STREAM_ID_STDIN : WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE, - serializedContent, - sendToRemoteCompleted, - ref wsManSendOperationHandle); + _sendToRemoteCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionSendCallback); + WSManNativeApi.WSManSendShellInputEx(_wsManShellOperationHandle, IntPtr.Zero, 0, + priorityType == DataPriorityType.Default ? + WSManNativeApi.WSMAN_STREAM_ID_STDIN : WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE, + serializedContent, + _sendToRemoteCompleted, + ref _wsManSendOperationHandle); } } } @@ -2503,7 +2499,7 @@ namespace System.Management.Automation.Remoting.Client [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] internal override void Dispose(bool isDisposing) { - tracer.WriteLine("Disposing session with session context: {0} Operation Context: {1}", sessionContextID, wsManShellOperationHandle); + tracer.WriteLine("Disposing session with session context: {0} Operation Context: {1}", _sessionContextID, _wsManShellOperationHandle); CloseSessionAndClearResources(); @@ -2512,10 +2508,10 @@ namespace System.Management.Automation.Remoting.Client // openContent is used by redirection ie., while redirecting to // a new machine and hence this is cleared only when the session // is disposing. - if (isDisposing && (null != openContent)) + if (isDisposing && (null != _openContent)) { - openContent.Dispose(); - openContent = null; + _openContent.Dispose(); + _openContent = null; } base.Dispose(isDisposing); @@ -2527,18 +2523,18 @@ namespace System.Management.Automation.Remoting.Client /// private void CloseSessionAndClearResources() { - tracer.WriteLine("Clearing session with session context: {0} Operation Context: {1}", sessionContextID, wsManShellOperationHandle); + tracer.WriteLine("Clearing session with session context: {0} Operation Context: {1}", _sessionContextID, _wsManShellOperationHandle); // Taking a copy of session handle as we should call WSManCloseSession only once and // clear the original value. This will protect us if Dispose() is called twice. - IntPtr tempWSManSessionHandle = wsManSessionHandle; - wsManSessionHandle = IntPtr.Zero; + IntPtr tempWSManSessionHandle = _wsManSessionHandle; + _wsManSessionHandle = IntPtr.Zero; // Call WSManCloseSession on a different thread as Dispose can be called from one of // the WSMan callback threads. WSMan does not support closing a session in the callbacks. ThreadPool.QueueUserWorkItem(new WaitCallback( // wsManSessionHandle is passed as parameter to allow the thread to be independent // of the rest of the parent object. - delegate(object state) + delegate (object state) { IntPtr sessionHandle = (IntPtr)state; if (sessionHandle != IntPtr.Zero) @@ -2548,41 +2544,41 @@ namespace System.Management.Automation.Remoting.Client }), tempWSManSessionHandle); // remove session context from session handles dictionary - RemoveSessionTransportManager(sessionContextID); + RemoveSessionTransportManager(_sessionContextID); - if (null != closeSessionCompleted) + if (null != _closeSessionCompleted) { - closeSessionCompleted.Dispose(); - closeSessionCompleted = null; + _closeSessionCompleted.Dispose(); + _closeSessionCompleted = null; } // Dispose the create session completed callback here, since it is // used for periodic robust connection retry/auto-disconnect // notifications while the shell is active. - if (null != createSessionCallback) + if (null != _createSessionCallback) { - createSessionCallbackGCHandle.Free(); - createSessionCallback.Dispose(); - createSessionCallback = null; + _createSessionCallbackGCHandle.Free(); + _createSessionCallback.Dispose(); + _createSessionCallback = null; } // Dispose the OnConnect callback if one present - if (null != connectSessionCallback) + if (null != _connectSessionCallback) { - connectSessionCallback.Dispose(); - connectSessionCallback = null; + _connectSessionCallback.Dispose(); + _connectSessionCallback = null; } // Reset the session context Id to zero so that a new one will be generated for // any following redirected session. - sessionContextID = 0; + _sessionContextID = 0; } private void DisposeWSManAPIDataAsync() { - WSManAPIDataCommon tempWSManApiData = wsManApiData; + WSManAPIDataCommon tempWSManApiData = _wsManApiData; if (tempWSManApiData == null) { return; } - wsManApiData = null; + _wsManApiData = null; // Dispose and de-initialize the WSManAPIData instance object on separate worker thread to ensure // it is not run on a WinRM thread (which will fail). @@ -2605,15 +2601,15 @@ namespace System.Management.Automation.Remoting.Client internal class WSManAPIDataCommon : IDisposable { [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr handle; + private IntPtr _handle; // if any - private int errorCode; - private WSManNativeApi.WSManStreamIDSet_ManToUn inputStreamSet; - private WSManNativeApi.WSManStreamIDSet_ManToUn outputStreamSet; - private List commonOptionSet; + private int _errorCode; + private WSManNativeApi.WSManStreamIDSet_ManToUn _inputStreamSet; + private WSManNativeApi.WSManStreamIDSet_ManToUn _outputStreamSet; + private List _commonOptionSet; // Dispose - private bool isDisposed; - private object syncObject = new object(); + private bool _isDisposed; + private object _syncObject = new object(); #if !CORECLR private WindowsIdentity _identityToImpersonate; #endif @@ -2630,17 +2626,17 @@ namespace System.Management.Automation.Remoting.Client _identityToImpersonate : null; #endif - handle = IntPtr.Zero; - errorCode = WSManNativeApi.WSManInitialize(WSManNativeApi.WSMAN_FLAG_REQUESTED_API_VERSION_1_1, ref handle); + _handle = IntPtr.Zero; + _errorCode = WSManNativeApi.WSManInitialize(WSManNativeApi.WSMAN_FLAG_REQUESTED_API_VERSION_1_1, ref _handle); // input / output streams common to all connections - inputStreamSet = new WSManNativeApi.WSManStreamIDSet_ManToUn( - new string[] { - WSManNativeApi.WSMAN_STREAM_ID_STDIN, - WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE + _inputStreamSet = new WSManNativeApi.WSManStreamIDSet_ManToUn( + new string[] { + WSManNativeApi.WSMAN_STREAM_ID_STDIN, + WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE }); - outputStreamSet = new WSManNativeApi.WSManStreamIDSet_ManToUn( - new string[] { WSManNativeApi.WSMAN_STREAM_ID_STDOUT} ); + _outputStreamSet = new WSManNativeApi.WSManStreamIDSet_ManToUn( + new string[] { WSManNativeApi.WSMAN_STREAM_ID_STDOUT }); // startup options common to all connections @@ -2649,15 +2645,15 @@ namespace System.Management.Automation.Remoting.Client protocolStartupOption.value = RemotingConstants.ProtocolVersion.ToString(); protocolStartupOption.mustComply = true; - commonOptionSet = new List(); - commonOptionSet.Add(protocolStartupOption); + _commonOptionSet = new List(); + _commonOptionSet.Add(protocolStartupOption); } - internal int ErrorCode { get { return errorCode; } } - internal WSManNativeApi.WSManStreamIDSet_ManToUn InputStreamSet { get { return inputStreamSet; } } - internal WSManNativeApi.WSManStreamIDSet_ManToUn OutputStreamSet { get { return outputStreamSet; } } - internal List CommonOptionSet { get { return commonOptionSet; } } - internal IntPtr WSManAPIHandle { get { return handle; } } + internal int ErrorCode { get { return _errorCode; } } + internal WSManNativeApi.WSManStreamIDSet_ManToUn InputStreamSet { get { return _inputStreamSet; } } + internal WSManNativeApi.WSManStreamIDSet_ManToUn OutputStreamSet { get { return _outputStreamSet; } } + internal List CommonOptionSet { get { return _commonOptionSet; } } + internal IntPtr WSManAPIHandle { get { return _handle; } } /// /// Dispose @@ -2668,16 +2664,16 @@ namespace System.Management.Automation.Remoting.Client [SuppressMessage("Microsoft.Usage", "CA2216:Disposabletypesshoulddeclarefinalizer")] public void Dispose() { - lock (syncObject) + lock (_syncObject) { - if (isDisposed) { return; } - isDisposed = true; + if (_isDisposed) { return; } + _isDisposed = true; } - inputStreamSet.Dispose(); - outputStreamSet.Dispose(); + _inputStreamSet.Dispose(); + _outputStreamSet.Dispose(); - if (IntPtr.Zero != handle) + if (IntPtr.Zero != _handle) { #if !CORECLR // If we initialized with thread impersonation make sure de-initialize is run with same. @@ -2686,11 +2682,11 @@ namespace System.Management.Automation.Remoting.Client { try { - _identityToImpersonate.Impersonate() ; + _identityToImpersonate.Impersonate(); } catch (ObjectDisposedException) { - handle = IntPtr.Zero; + _handle = IntPtr.Zero; return; } } @@ -2698,8 +2694,8 @@ namespace System.Management.Automation.Remoting.Client try { #endif - int result = WSManNativeApi.WSManDeinitialize(handle, 0); - Dbg.Assert(result == 0, "WSManDeinitialize returned non-zero value"); + int result = WSManNativeApi.WSManDeinitialize(_handle, 0); + Dbg.Assert(result == 0, "WSManDeinitialize returned non-zero value"); #if !CORECLR } finally @@ -2715,7 +2711,7 @@ namespace System.Management.Automation.Remoting.Client } } #endif - handle = IntPtr.Zero; + _handle = IntPtr.Zero; } } } @@ -2747,62 +2743,61 @@ namespace System.Management.Automation.Remoting.Client #region Private Data // operation handles - private IntPtr wsManShellOperationHandle; + private IntPtr _wsManShellOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManCmdOperationHandle; + private IntPtr _wsManCmdOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr cmdSignalOperationHandle; + private IntPtr _cmdSignalOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManRecieveOperationHandle; + private IntPtr _wsManRecieveOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr wsManSendOperationHandle; + private IntPtr _wsManSendOperationHandle; // this is used with WSMan callbacks to represent a command transport manager. - private long cmdContextId; - - private PrioritySendDataCollection.OnDataAvailableCallback onDataAvailableToSendCallback; + private long _cmdContextId; + + private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; // should be integrated with receiveDataInitiated - private bool shouldStartReceivingData; + private bool _shouldStartReceivingData; // bools used to track and send stop signal only after Create is completed. - private bool isCreateCallbackReceived; - private bool isStopSignalPending; - private bool isDisconnectPending; - private bool isSendingInput; - private bool isDisconnectedOnInvoke; + private bool _isCreateCallbackReceived; + private bool _isStopSignalPending; + private bool _isDisconnectPending; + private bool _isSendingInput; + private bool _isDisconnectedOnInvoke; // callbacks - private WSManNativeApi.WSManShellAsync createCmdCompleted; - private WSManNativeApi.WSManShellAsync receivedFromRemote; - private WSManNativeApi.WSManShellAsync sendToRemoteCompleted; - private WSManNativeApi.WSManShellAsync reconnectCmdCompleted; - private WSManNativeApi.WSManShellAsync connectCmdCompleted; + private WSManNativeApi.WSManShellAsync _createCmdCompleted; + private WSManNativeApi.WSManShellAsync _receivedFromRemote; + private WSManNativeApi.WSManShellAsync _sendToRemoteCompleted; + private WSManNativeApi.WSManShellAsync _reconnectCmdCompleted; + private WSManNativeApi.WSManShellAsync _connectCmdCompleted; // TODO: This GCHandle is required as it seems WSMan is calling create callback // after we call Close. This seems wrong. Opened bug on WSMan to track this. - private GCHandle createCmdCompletedGCHandle; - private WSManNativeApi.WSManShellAsync closeCmdCompleted; - private WSManNativeApi.WSManShellAsync signalCmdCompleted; + private GCHandle _createCmdCompletedGCHandle; + private WSManNativeApi.WSManShellAsync _closeCmdCompleted; + private WSManNativeApi.WSManShellAsync _signalCmdCompleted; // this is the chunk that got delivered on onDataAvailableToSendCallback // will be sent during subsequent SendOneItem() - private SendDataChunk chunkToSend; + private SendDataChunk _chunkToSend; - private string cmdLine; + private string _cmdLine; private readonly WSManClientSessionTransportManager _sessnTm; private class SendDataChunk { - public SendDataChunk(byte[] data, DataPriorityType type) { - this.data = data; - this.type = type; + _data = data; + _type = type; } public byte[] Data { get { - return data; + return _data; } } @@ -2810,12 +2805,12 @@ namespace System.Management.Automation.Remoting.Client { get { - return type; + return _type; } } - - private byte[] data; - private DataPriorityType type; + + private byte[] _data; + private DataPriorityType _type; } #endregion @@ -2823,44 +2818,44 @@ namespace System.Management.Automation.Remoting.Client #region Static Data // static callback delegate - private static WSManNativeApi.WSManShellAsyncCallback cmdCreateCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdCloseCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdReceiveCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdSendCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdSignalCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdReconnectCallback; - private static WSManNativeApi.WSManShellAsyncCallback cmdConnectCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdCreateCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdCloseCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdReceiveCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdSendCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdSignalCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdReconnectCallback; + private static WSManNativeApi.WSManShellAsyncCallback s_cmdConnectCallback; static WSManClientCommandTransportManager() { // Initialize callback delegates WSManNativeApi.WSManShellCompletionFunction createDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnCreateCmdCompleted); - cmdCreateCallback = new WSManNativeApi.WSManShellAsyncCallback(createDelegate); + s_cmdCreateCallback = new WSManNativeApi.WSManShellAsyncCallback(createDelegate); WSManNativeApi.WSManShellCompletionFunction closeDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnCloseCmdCompleted); - cmdCloseCallback = new WSManNativeApi.WSManShellAsyncCallback(closeDelegate); + s_cmdCloseCallback = new WSManNativeApi.WSManShellAsyncCallback(closeDelegate); WSManNativeApi.WSManShellCompletionFunction receiveDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteCmdDataReceived); - cmdReceiveCallback = new WSManNativeApi.WSManShellAsyncCallback(receiveDelegate); + s_cmdReceiveCallback = new WSManNativeApi.WSManShellAsyncCallback(receiveDelegate); WSManNativeApi.WSManShellCompletionFunction sendDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteCmdSendCompleted); - cmdSendCallback = new WSManNativeApi.WSManShellAsyncCallback(sendDelegate); + s_cmdSendCallback = new WSManNativeApi.WSManShellAsyncCallback(sendDelegate); WSManNativeApi.WSManShellCompletionFunction signalDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnRemoteCmdSignalCompleted); - cmdSignalCallback = new WSManNativeApi.WSManShellAsyncCallback(signalDelegate); + s_cmdSignalCallback = new WSManNativeApi.WSManShellAsyncCallback(signalDelegate); WSManNativeApi.WSManShellCompletionFunction reconnectDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnReconnectCmdCompleted); - cmdReconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(reconnectDelegate); + s_cmdReconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(reconnectDelegate); WSManNativeApi.WSManShellCompletionFunction connectDelegate = new WSManNativeApi.WSManShellCompletionFunction(OnConnectCmdCompleted); - cmdConnectCallback = new WSManNativeApi.WSManShellAsyncCallback(connectDelegate); + s_cmdConnectCallback = new WSManNativeApi.WSManShellAsyncCallback(connectDelegate); } #endregion @@ -2897,17 +2892,17 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(IntPtr.Zero != wsManShellOperationHandle, "Shell operation handle cannot be IntPtr.Zero."); Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null"); - this.wsManShellOperationHandle = wsManShellOperationHandle; - + _wsManShellOperationHandle = wsManShellOperationHandle; + // Apply quota limits.. allow for data to be unlimited.. ReceivedDataCollection.MaximumReceivedDataSize = connectionInfo.MaximumReceivedDataSizePerCommand; ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize; - cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory(); - onDataAvailableToSendCallback = + _cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory(); + _onDataAvailableToSendCallback = new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback); _sessnTm = sessnTM; // Suspend queue on robust connections initiated event. - sessnTM.RobustConnectionsInitiated += HandleRobustConnectionsIntiated; + sessnTM.RobustConnectionsInitiated += HandleRobustConnectionsIntiated; // Resume queue on robust connections completed event. sessnTM.RobustConnectionsCompleted += HandleRobusConnectionsCompleted; @@ -2917,7 +2912,7 @@ namespace System.Management.Automation.Remoting.Client #region SHIM: Redirection delegate for command code send. - private static Delegate commandCodeSendRedirect = null; + private static Delegate s_commandCodeSendRedirect = null; #endregion @@ -2949,12 +2944,12 @@ namespace System.Management.Automation.Remoting.Client serializedPipeline.Read(); // create cmdContextId - cmdContextId = GetNextCmdTMHandleId(); - AddCmdTransportManager(cmdContextId, this); + _cmdContextId = GetNextCmdTMHandleId(); + AddCmdTransportManager(_cmdContextId, this); // Create Callback - connectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdConnectCallback); - reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdReconnectCallback); + _connectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdConnectCallback); + _reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdReconnectCallback); lock (syncObject) { if (isClosed) @@ -2964,16 +2959,16 @@ namespace System.Management.Automation.Remoting.Client return; } - WSManNativeApi.WSManConnectShellCommandEx(wsManShellOperationHandle, + WSManNativeApi.WSManConnectShellCommandEx(_wsManShellOperationHandle, 0, PowershellInstanceId.ToString().ToUpperInvariant(), IntPtr.Zero, IntPtr.Zero, - connectCmdCompleted, - ref wsManCmdOperationHandle); + _connectCmdCompleted, + ref _wsManCmdOperationHandle); } - if (wsManCmdOperationHandle == IntPtr.Zero) + if (_wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventargs = @@ -2998,10 +2993,10 @@ namespace System.Management.Automation.Remoting.Client bool sendContinue = true; - if (commandCodeSendRedirect != null) + if (s_commandCodeSendRedirect != null) { object[] arguments = new object[2] { null, cmdPart1 }; - sendContinue = (bool)commandCodeSendRedirect.DynamicInvoke(arguments); + sendContinue = (bool)s_commandCodeSendRedirect.DynamicInvoke(arguments); cmdPart1 = (byte[])arguments[0]; } @@ -3013,16 +3008,16 @@ namespace System.Management.Automation.Remoting.Client WSManNativeApi.WSManCommandArgSet argSet = new WSManNativeApi.WSManCommandArgSet(cmdPart1); // create cmdContextId - cmdContextId = GetNextCmdTMHandleId(); - AddCmdTransportManager(cmdContextId, this); - + _cmdContextId = GetNextCmdTMHandleId(); + AddCmdTransportManager(_cmdContextId, this); + PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); - - createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdCreateCallback); - createCmdCompletedGCHandle = GCHandle.Alloc(createCmdCompleted); - reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdReconnectCallback); + + _createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdCreateCallback); + _createCmdCompletedGCHandle = GCHandle.Alloc(_createCmdCompleted); + _reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdReconnectCallback); using (argSet) { @@ -3030,23 +3025,23 @@ namespace System.Management.Automation.Remoting.Client { if (!isClosed) { - WSManNativeApi.WSManRunShellCommandEx(wsManShellOperationHandle, + WSManNativeApi.WSManRunShellCommandEx(_wsManShellOperationHandle, 0, PowershellInstanceId.ToString().ToUpperInvariant(), // WSManRunsShellCommand doesn't accept empty string "". - (cmdLine == null || cmdLine.Length==0)? " ": (cmdLine.Length <= 256? cmdLine : cmdLine.Substring(0, 255)), + (_cmdLine == null || _cmdLine.Length == 0) ? " " : (_cmdLine.Length <= 256 ? _cmdLine : _cmdLine.Substring(0, 255)), argSet, IntPtr.Zero, - createCmdCompleted, - ref wsManCmdOperationHandle); + _createCmdCompleted, + ref _wsManCmdOperationHandle); - tracer.WriteLine("Started cmd with command context : {0} Operation context: {1}", cmdContextId, wsManCmdOperationHandle); + tracer.WriteLine("Started cmd with command context : {0} Operation context: {1}", _cmdContextId, _wsManCmdOperationHandle); } } } } - if (wsManCmdOperationHandle == IntPtr.Zero) + if (_wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventargs = @@ -3069,7 +3064,7 @@ namespace System.Management.Automation.Remoting.Client return; } - WSManNativeApi.WSManReconnectShellCommandEx(wsManCmdOperationHandle, 0, reconnectCmdCompleted); + WSManNativeApi.WSManReconnectShellCommandEx(_wsManCmdOperationHandle, 0, _reconnectCmdCompleted); } } /// @@ -3087,22 +3082,22 @@ namespace System.Management.Automation.Remoting.Client // WSMan API do not allow a signal/input/receive be sent until RunShellCommand is // successfull (ie., callback is received)..so note that a signal is to be sent // here and return. - if (!isCreateCallbackReceived) + if (!_isCreateCallbackReceived) { - isStopSignalPending = true; + _isStopSignalPending = true; return; } // we are about to send a signal..so clear pending bit. - isStopSignalPending = false; + _isStopSignalPending = false; - tracer.WriteLine("Sending stop signal with command context: {0} Operation Context {1}", cmdContextId, wsManCmdOperationHandle); + tracer.WriteLine("Sending stop signal with command context: {0} Operation Context {1}", _cmdContextId, _wsManCmdOperationHandle); PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignal, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString(), StopSignal); - signalCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdSignalCallback); - WSManNativeApi.WSManSignalShellEx(wsManShellOperationHandle, wsManCmdOperationHandle, 0, - StopSignal, signalCmdCompleted, ref cmdSignalOperationHandle); + _signalCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdSignalCallback); + WSManNativeApi.WSManSignalShellEx(_wsManShellOperationHandle, _wsManCmdOperationHandle, 0, + StopSignal, _signalCmdCompleted, ref _cmdSignalOperationHandle); } } @@ -3111,7 +3106,7 @@ namespace System.Management.Automation.Remoting.Client /// internal override void CloseAsync() { - tracer.WriteLine("Closing command with command context: {0} Operation Context {1}", cmdContextId, wsManCmdOperationHandle); + tracer.WriteLine("Closing command with command context: {0} Operation Context {1}", _cmdContextId, _wsManCmdOperationHandle); bool shouldRaiseCloseCompleted = false; // then let other threads release the lock before we cleaning up the resources. @@ -3128,23 +3123,23 @@ namespace System.Management.Automation.Remoting.Client // There is no valid cmd operation handle..so just // raise close completed. - if (IntPtr.Zero == wsManCmdOperationHandle) + if (IntPtr.Zero == _wsManCmdOperationHandle) { shouldRaiseCloseCompleted = true; - } + } } base.CloseAsync(); if (shouldRaiseCloseCompleted) { - try + try { RaiseCloseCompleted(); } finally { - RemoveCmdTransportManager(cmdContextId); + RemoveCmdTransportManager(_cmdContextId); } return; } @@ -3152,11 +3147,11 @@ namespace System.Management.Automation.Remoting.Client PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommand, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); - closeCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdCloseCallback); - Dbg.Assert((IntPtr)closeCmdCompleted != IntPtr.Zero, "closeCmdCompleted callback is null in cmdTM.CloseAsync()"); - WSManNativeApi.WSManCloseCommand(wsManCmdOperationHandle, 0, closeCmdCompleted); + _closeCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdCloseCallback); + Dbg.Assert((IntPtr)_closeCmdCompleted != IntPtr.Zero, "closeCmdCompleted callback is null in cmdTM.CloseAsync()"); + WSManNativeApi.WSManCloseCommand(_wsManCmdOperationHandle, 0, _closeCmdCompleted); } - + /// /// Handle transport error - calls EnqueueAndStartProcessingThread to process transport exception /// in a different thread @@ -3190,11 +3185,11 @@ namespace System.Management.Automation.Remoting.Client } PSEtwLog.LogOperationalError( - PSEventId.TransportError, PSOpcode.Open, PSTask.None, + PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, - RunspacePoolInstanceId.ToString(), + RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString(), - eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture), + eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture), eventArgs.Exception.Message, stackTrace); @@ -3242,17 +3237,17 @@ namespace System.Management.Automation.Remoting.Client { if (shouldClearSend) { - if (null != sendToRemoteCompleted) + if (null != _sendToRemoteCompleted) { - sendToRemoteCompleted.Dispose(); - sendToRemoteCompleted = null; + _sendToRemoteCompleted.Dispose(); + _sendToRemoteCompleted = null; } // For send..clear always - if (IntPtr.Zero != wsManSendOperationHandle) + if (IntPtr.Zero != _wsManSendOperationHandle) { - WSManNativeApi.WSManCloseOperation(wsManSendOperationHandle, 0); - wsManSendOperationHandle = IntPtr.Zero; + WSManNativeApi.WSManCloseOperation(_wsManSendOperationHandle, 0); + _wsManSendOperationHandle = IntPtr.Zero; } } else @@ -3260,16 +3255,16 @@ namespace System.Management.Automation.Remoting.Client // clearing for receive..Clear only when the end of operation is reached. if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_END_OF_OPERATION) { - if (IntPtr.Zero != wsManRecieveOperationHandle) + if (IntPtr.Zero != _wsManRecieveOperationHandle) { - WSManNativeApi.WSManCloseOperation(wsManRecieveOperationHandle, 0); - wsManRecieveOperationHandle = IntPtr.Zero; + WSManNativeApi.WSManCloseOperation(_wsManRecieveOperationHandle, 0); + _wsManRecieveOperationHandle = IntPtr.Zero; } - if (null != receivedFromRemote) + if (null != _receivedFromRemote) { - receivedFromRemote.Dispose(); - receivedFromRemote = null; + _receivedFromRemote.Dispose(); + _receivedFromRemote = null; } } } @@ -3280,15 +3275,15 @@ namespace System.Management.Automation.Remoting.Client /// internal override void PrepareForDisconnect() { - this.isDisconnectPending = true; + _isDisconnectPending = true; // If there is not input processing and the command has already been created // on the server then this object is ready for Disconnect now. // Otherwise let the sending input data call back handle it. - if (this.isClosed || this.isDisconnectedOnInvoke || - (this.isCreateCallbackReceived && + if (this.isClosed || _isDisconnectedOnInvoke || + (_isCreateCallbackReceived && this.serializedPipeline.Length == 0 && - !this.isSendingInput)) + !_isSendingInput)) { RaiseReadyForDisconnect(); } @@ -3299,7 +3294,7 @@ namespace System.Management.Automation.Remoting.Client /// internal override void PrepareForConnect() { - this.isDisconnectPending = false; + _isDisconnectPending = false; } #endregion @@ -3331,11 +3326,11 @@ namespace System.Management.Automation.Remoting.Client cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); // dispose the cmdCompleted callback as it is not needed any more - if (null != cmdTM.createCmdCompleted) + if (null != cmdTM._createCmdCompleted) { - cmdTM.createCmdCompletedGCHandle.Free(); - cmdTM.createCmdCompleted.Dispose(); - cmdTM.createCmdCompleted = null; + cmdTM._createCmdCompletedGCHandle.Free(); + cmdTM._createCmdCompleted.Dispose(); + cmdTM._createCmdCompleted = null; } // TODO: 188098 wsManCmdOperationHandle should be populated by WSManRunShellCommandEx, @@ -3343,7 +3338,7 @@ namespace System.Management.Automation.Remoting.Client // be called before WSManRunShellCommandEx returns. since we already validated the // cmd context exists, safely assigning the commandOperationHandle to cmd transport manager. // Remove this once WSMan fixes its code. - cmdTM.wsManCmdOperationHandle = commandOperationHandle; + cmdTM._wsManCmdOperationHandle = commandOperationHandle; if (IntPtr.Zero != error) { @@ -3351,7 +3346,7 @@ namespace System.Management.Automation.Remoting.Client if (errorStruct.errorCode != 0) { tracer.WriteLine("OnCreateCmdCompleted callback: WSMan reported an error: {0}", errorStruct.errorDetail); - + TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, @@ -3368,14 +3363,14 @@ namespace System.Management.Automation.Remoting.Client // Send remaing cmd / parameter fragments. lock (cmdTM.syncObject) { - cmdTM.isCreateCallbackReceived = true; + cmdTM._isCreateCallbackReceived = true; // make sure the transport is not closed yet. if (cmdTM.isClosed) { tracer.WriteLine("Client Session TM: Transport manager is closed. So returning"); - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); } @@ -3385,7 +3380,7 @@ namespace System.Management.Automation.Remoting.Client // If a disconnect is pending at this point then we should not start // receiving data or sending input and let the disconnect take place. - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); return; @@ -3393,7 +3388,7 @@ namespace System.Management.Automation.Remoting.Client if (cmdTM.serializedPipeline.Length == 0) { - cmdTM.shouldStartReceivingData = true; + cmdTM._shouldStartReceivingData = true; } // Start sending data if any..and see if we can initiate a receive. @@ -3401,7 +3396,7 @@ namespace System.Management.Automation.Remoting.Client // WSMan API does not allow a signal/input/receive be sent until RunShellCommand is // successfull (ie., callback is received) - if (cmdTM.isStopSignalPending) + if (cmdTM._isStopSignalPending) { cmdTM.SendStopSignal(); } @@ -3428,13 +3423,13 @@ namespace System.Management.Automation.Remoting.Client } // dispose the cmdCompleted callback as it is not needed any more - if (null != cmdTM.connectCmdCompleted) + if (null != cmdTM._connectCmdCompleted) { - cmdTM.connectCmdCompleted.Dispose(); - cmdTM.connectCmdCompleted = null; + cmdTM._connectCmdCompleted.Dispose(); + cmdTM._connectCmdCompleted = null; } - cmdTM.wsManCmdOperationHandle = commandOperationHandle; + cmdTM._wsManCmdOperationHandle = commandOperationHandle; if (IntPtr.Zero != error) { @@ -3464,7 +3459,7 @@ namespace System.Management.Automation.Remoting.Client tracer.WriteLine("Client Session TM: Transport manager is closed. So returning"); // Release disconnect pending, if any. - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); } @@ -3474,17 +3469,17 @@ namespace System.Management.Automation.Remoting.Client // If a disconnect is pending at this point then we should not start // receiving data or sending input and let the disconnect take place. - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); return; } // Allow SendStopSignal. - cmdTM.isCreateCallbackReceived = true; + cmdTM._isCreateCallbackReceived = true; // Send stop signal if it is pending. - if (cmdTM.isStopSignalPending) + if (cmdTM._isStopSignalPending) { cmdTM.SendStopSignal(); } @@ -3516,12 +3511,12 @@ namespace System.Management.Automation.Remoting.Client return; } - tracer.WriteLine("Close completed callback received for command: {0}", cmdTM.cmdContextId); + tracer.WriteLine("Close completed callback received for command: {0}", cmdTM._cmdContextId); PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommandCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); } @@ -3548,15 +3543,15 @@ namespace System.Management.Automation.Remoting.Client return; } - cmdTM.isSendingInput = false; + cmdTM._isSendingInput = false; // do the logging for this send PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); - if ((!shellOperationHandle.Equals(cmdTM.wsManShellOperationHandle)) || - (!commandOperationHandle.Equals(cmdTM.wsManCmdOperationHandle))) + if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || + (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { tracer.WriteLine("SendShellInputEx callback: ShellOperationHandles are not the same as the Send is initiated with"); // WSMan returned data from a wrong shell..notify the caller @@ -3568,7 +3563,7 @@ namespace System.Management.Automation.Remoting.Client return; } - + // release the resources related to send cmdTM.ClearReceiveOrSendResources(flags, true); @@ -3577,7 +3572,7 @@ namespace System.Management.Automation.Remoting.Client { tracer.WriteLine("Client Command TM: Transport manager is closed. So returning"); - if (cmdTM.isDisconnectPending) + if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); } @@ -3594,7 +3589,7 @@ namespace System.Management.Automation.Remoting.Client if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 995)) { tracer.WriteLine("CmdSend callback: WSMan reported an error: {0}", errorStruct.errorDetail); - + TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, @@ -3631,8 +3626,8 @@ namespace System.Management.Automation.Remoting.Client return; } - if ((!shellOperationHandle.Equals(cmdTM.wsManShellOperationHandle)) || - (!commandOperationHandle.Equals(cmdTM.wsManCmdOperationHandle))) + if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || + (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. @@ -3675,9 +3670,9 @@ namespace System.Management.Automation.Remoting.Client } } - if (flags == (int) WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_RECEIVE_DELAY_STREAM_REQUEST_PROCESSED) + if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_RECEIVE_DELAY_STREAM_REQUEST_PROCESSED) { - cmdTM.isDisconnectedOnInvoke = true; + cmdTM._isDisconnectedOnInvoke = true; cmdTM.RaiseDelayStreamProcessedEvent(); return; } @@ -3689,8 +3684,8 @@ namespace System.Management.Automation.Remoting.Client PSEtwLog.LogAnalyticInformational( PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - cmdTM.RunspacePoolInstanceId.ToString(), - cmdTM.powershellInstanceId.ToString(), + cmdTM.RunspacePoolInstanceId.ToString(), + cmdTM.powershellInstanceId.ToString(), dataReceived.data.Length.ToString(CultureInfo.InvariantCulture)); cmdTM.ProcessRawData(dataReceived.data, dataReceived.stream); } @@ -3713,8 +3708,8 @@ namespace System.Management.Automation.Remoting.Client return; } - if ((!shellOperationHandle.Equals(cmdTM.wsManShellOperationHandle)) || - (!commandOperationHandle.Equals(cmdTM.wsManCmdOperationHandle))) + if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || + (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. @@ -3749,7 +3744,7 @@ namespace System.Management.Automation.Remoting.Client // The command may have been disconnected before all input was read or // the returned command data started to be received. - cmdTM.shouldStartReceivingData = true; + cmdTM._shouldStartReceivingData = true; cmdTM.SendOneItem(); cmdTM.RaiseReconnectCompleted(); @@ -3779,8 +3774,8 @@ namespace System.Management.Automation.Remoting.Client PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); - if ((!shellOperationHandle.Equals(cmdTM.wsManShellOperationHandle)) || - (!commandOperationHandle.Equals(cmdTM.wsManCmdOperationHandle))) + if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || + (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. @@ -3792,20 +3787,20 @@ namespace System.Management.Automation.Remoting.Client return; } - + // release the resources related to signal - if (IntPtr.Zero != cmdTM.cmdSignalOperationHandle) + if (IntPtr.Zero != cmdTM._cmdSignalOperationHandle) { - WSManNativeApi.WSManCloseOperation(cmdTM.cmdSignalOperationHandle, 0); - cmdTM.cmdSignalOperationHandle = IntPtr.Zero; + WSManNativeApi.WSManCloseOperation(cmdTM._cmdSignalOperationHandle, 0); + cmdTM._cmdSignalOperationHandle = IntPtr.Zero; } - if (null != cmdTM.signalCmdCompleted) + if (null != cmdTM._signalCmdCompleted) { - cmdTM.signalCmdCompleted.Dispose(); - cmdTM.signalCmdCompleted = null; + cmdTM._signalCmdCompleted.Dispose(); + cmdTM._signalCmdCompleted = null; } - + // if the transport manager is already closed..ignore the errors and return if (cmdTM.isClosed) { @@ -3839,7 +3834,7 @@ namespace System.Management.Automation.Remoting.Client { // If a disconnect is completing then do not send any more data. // Also raise the readyfordisconnect event. - if (this.isDisconnectPending) + if (_isDisconnectPending) { RaiseReadyForDisconnect(); return; @@ -3857,28 +3852,28 @@ namespace System.Management.Automation.Remoting.Client // once command string + parameters are sent. if (serializedPipeline.Length == 0) { - shouldStartReceivingData = true; + _shouldStartReceivingData = true; } } - else if (chunkToSend != null) // there is a pending chunk to be sent + else if (_chunkToSend != null) // there is a pending chunk to be sent { - data = chunkToSend.Data; - priorityType = chunkToSend.Type; - chunkToSend = null; + data = _chunkToSend.Data; + priorityType = _chunkToSend.Type; + _chunkToSend = null; } else { // This will either return data or register callback but doesn't do both. - data = dataToBeSent.ReadOrRegisterCallback(onDataAvailableToSendCallback, out priorityType); + data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); } if (null != data) { - this.isSendingInput = true; + _isSendingInput = true; SendData(data, priorityType); } - if (shouldStartReceivingData) + if (_shouldStartReceivingData) { StartReceivingData(); } @@ -3889,14 +3884,14 @@ namespace System.Management.Automation.Remoting.Client Dbg.Assert(null != data, "data cannot be null in the data available callback"); tracer.WriteLine("Received data from dataToBeSent store."); - Dbg.Assert(chunkToSend == null, "data callback received while a chunk is pending to be sent"); - chunkToSend = new SendDataChunk(data, priorityType); + Dbg.Assert(_chunkToSend == null, "data callback received while a chunk is pending to be sent"); + _chunkToSend = new SendDataChunk(data, priorityType); SendOneItem(); } #region SHIM: Redirection delegate for command data send. - private static Delegate commandSendRedirect = null; + private static Delegate s_commandSendRedirect = null; #endregion @@ -3909,10 +3904,10 @@ namespace System.Management.Automation.Remoting.Client bool sendContinue = true; - if (commandSendRedirect != null) + if (s_commandSendRedirect != null) { object[] arguments = new object[2] { null, package }; - sendContinue = (bool)commandSendRedirect.DynamicInvoke(arguments); + sendContinue = (bool)s_commandSendRedirect.DynamicInvoke(arguments); package = (byte[])arguments[0]; } @@ -3925,9 +3920,9 @@ namespace System.Management.Automation.Remoting.Client new WSManNativeApi.WSManData_ManToUn(package)) { PSEtwLog.LogAnalyticInformational( - PSEventId.WSManSendShellInputEx, PSOpcode.Send, PSTask.None, + PSEventId.WSManSendShellInputEx, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), + RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString(), serializedContent.BufferLength.ToString(CultureInfo.InvariantCulture)); @@ -3941,13 +3936,13 @@ namespace System.Management.Automation.Remoting.Client } // send callback - sendToRemoteCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdSendCallback); - WSManNativeApi.WSManSendShellInputEx(wsManShellOperationHandle, wsManCmdOperationHandle, 0, - priorityType == DataPriorityType.Default ? - WSManNativeApi.WSMAN_STREAM_ID_STDIN : WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE, - serializedContent, - sendToRemoteCompleted, - ref wsManSendOperationHandle); + _sendToRemoteCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdSendCallback); + WSManNativeApi.WSManSendShellInputEx(_wsManShellOperationHandle, _wsManCmdOperationHandle, 0, + priorityType == DataPriorityType.Default ? + WSManNativeApi.WSMAN_STREAM_ID_STDIN : WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE, + serializedContent, + _sendToRemoteCompleted, + ref _wsManSendOperationHandle); } } } @@ -3958,7 +3953,7 @@ namespace System.Management.Automation.Remoting.Client PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); // We should call Receive only once.. WSMan will call the callback multiple times. - shouldStartReceivingData = false; + _shouldStartReceivingData = false; lock (syncObject) { // make sure the transport is not closed. @@ -3976,11 +3971,11 @@ namespace System.Management.Automation.Remoting.Client receiveDataInitiated = true; // recive callback - receivedFromRemote = new WSManNativeApi.WSManShellAsync(new IntPtr(cmdContextId), cmdReceiveCallback); - WSManNativeApi.WSManReceiveShellOutputEx(wsManShellOperationHandle, - wsManCmdOperationHandle, startInDisconnectedMode ? (int) WSManNativeApi.WSManShellFlag.WSMAN_FLAG_RECEIVE_DELAY_OUTPUT_STREAM : 0, + _receivedFromRemote = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdReceiveCallback); + WSManNativeApi.WSManReceiveShellOutputEx(_wsManShellOperationHandle, + _wsManCmdOperationHandle, startInDisconnectedMode ? (int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_RECEIVE_DELAY_OUTPUT_STREAM : 0, _sessnTm.WSManAPIData.OutputStreamSet, - receivedFromRemote, ref wsManRecieveOperationHandle); + _receivedFromRemote, ref _wsManRecieveOperationHandle); } } @@ -3990,12 +3985,12 @@ namespace System.Management.Automation.Remoting.Client internal override void Dispose(bool isDisposing) { - tracer.WriteLine("Disposing command with command context: {0} Operation Context: {1}", cmdContextId, wsManCmdOperationHandle); + tracer.WriteLine("Disposing command with command context: {0} Operation Context: {1}", _cmdContextId, _wsManCmdOperationHandle); base.Dispose(isDisposing); // remove command context from cmd handles dictionary - RemoveCmdTransportManager(cmdContextId); - + RemoveCmdTransportManager(_cmdContextId); + // unregister event handlers if (null != _sessnTm) { @@ -4003,19 +3998,19 @@ namespace System.Management.Automation.Remoting.Client _sessnTm.RobustConnectionsCompleted -= HandleRobusConnectionsCompleted; } - if (null != closeCmdCompleted) + if (null != _closeCmdCompleted) { - closeCmdCompleted.Dispose(); - closeCmdCompleted = null; + _closeCmdCompleted.Dispose(); + _closeCmdCompleted = null; } - if (null != reconnectCmdCompleted) + if (null != _reconnectCmdCompleted) { - reconnectCmdCompleted.Dispose(); - reconnectCmdCompleted = null; + _reconnectCmdCompleted.Dispose(); + _reconnectCmdCompleted = null; } - wsManCmdOperationHandle = IntPtr.Zero; + _wsManCmdOperationHandle = IntPtr.Zero; } #endregion @@ -4024,14 +4019,14 @@ namespace System.Management.Automation.Remoting.Client // This dictionary maintains active command transport managers to be used from various // callbacks. - private static Dictionary CmdTMHandles = + private static Dictionary s_cmdTMHandles = new Dictionary(); - private static long CmdTMSeed; + private static long s_cmdTMSeed; //Generate command transport manager unique id private static long GetNextCmdTMHandleId() { - return System.Threading.Interlocked.Increment(ref CmdTMSeed); + return System.Threading.Interlocked.Increment(ref s_cmdTMSeed); } // we need a synchronized add and remove so that multiple threads @@ -4039,17 +4034,17 @@ namespace System.Management.Automation.Remoting.Client private static void AddCmdTransportManager(long cmdTMId, WSManClientCommandTransportManager cmdTransportManager) { - lock (CmdTMHandles) + lock (s_cmdTMHandles) { - CmdTMHandles.Add(cmdTMId, cmdTransportManager); + s_cmdTMHandles.Add(cmdTMId, cmdTransportManager); } } private static void RemoveCmdTransportManager(long cmdTMId) { - lock (CmdTMHandles) + lock (s_cmdTMHandles) { - CmdTMHandles.Remove(cmdTMId); + s_cmdTMHandles.Remove(cmdTMId); } } @@ -4061,9 +4056,9 @@ namespace System.Management.Automation.Remoting.Client { cmdTMId = operationContext.ToInt64(); cmdTransportManager = null; - lock (CmdTMHandles) + lock (s_cmdTMHandles) { - return CmdTMHandles.TryGetValue(cmdTMId, out cmdTransportManager); + return s_cmdTMHandles.TryGetValue(cmdTMId, out cmdTransportManager); } } diff --git a/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs b/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs index 92847078f..6149b6457 100644 --- a/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs +++ b/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -23,75 +24,75 @@ namespace System.Management.Automation.Remoting internal enum RemoteHostMethodId { // Host read-only properties. - GetName = 1, - GetVersion = 2, - GetInstanceId = 3, - GetCurrentCulture = 4, - GetCurrentUICulture = 5, + GetName = 1, + GetVersion = 2, + GetInstanceId = 3, + GetCurrentCulture = 4, + GetCurrentUICulture = 5, // Host methods. - SetShouldExit = 6, - EnterNestedPrompt = 7, - ExitNestedPrompt = 8, - NotifyBeginApplication = 9, - NotifyEndApplication = 10, + SetShouldExit = 6, + EnterNestedPrompt = 7, + ExitNestedPrompt = 8, + NotifyBeginApplication = 9, + NotifyEndApplication = 10, // Host UI methods. - ReadLine = 11, - ReadLineAsSecureString = 12, - Write1 = 13, - Write2 = 14, - WriteLine1 = 15, - WriteLine2 = 16, - WriteLine3 = 17, - WriteErrorLine = 18, - WriteDebugLine = 19, - WriteProgress = 20, - WriteVerboseLine = 21, - WriteWarningLine = 22, - Prompt = 23, - PromptForCredential1 = 24, - PromptForCredential2 = 25, - PromptForChoice = 26, + ReadLine = 11, + ReadLineAsSecureString = 12, + Write1 = 13, + Write2 = 14, + WriteLine1 = 15, + WriteLine2 = 16, + WriteLine3 = 17, + WriteErrorLine = 18, + WriteDebugLine = 19, + WriteProgress = 20, + WriteVerboseLine = 21, + WriteWarningLine = 22, + Prompt = 23, + PromptForCredential1 = 24, + PromptForCredential2 = 25, + PromptForChoice = 26, // Host Raw UI read-write properties. - GetForegroundColor = 27, - SetForegroundColor = 28, - GetBackgroundColor = 29, - SetBackgroundColor = 30, - GetCursorPosition = 31, - SetCursorPosition = 32, - GetWindowPosition = 33, - SetWindowPosition = 34, - GetCursorSize = 35, - SetCursorSize = 36, - GetBufferSize = 37, - SetBufferSize = 38, - GetWindowSize = 39, - SetWindowSize = 40, - GetWindowTitle = 41, - SetWindowTitle = 42, + GetForegroundColor = 27, + SetForegroundColor = 28, + GetBackgroundColor = 29, + SetBackgroundColor = 30, + GetCursorPosition = 31, + SetCursorPosition = 32, + GetWindowPosition = 33, + SetWindowPosition = 34, + GetCursorSize = 35, + SetCursorSize = 36, + GetBufferSize = 37, + SetBufferSize = 38, + GetWindowSize = 39, + SetWindowSize = 40, + GetWindowTitle = 41, + SetWindowTitle = 42, // Host Raw UI read-only properties. - GetMaxWindowSize = 43, - GetMaxPhysicalWindowSize = 44, - GetKeyAvailable = 45, + GetMaxWindowSize = 43, + GetMaxPhysicalWindowSize = 44, + GetKeyAvailable = 45, // Host Raw UI methods. - ReadKey = 46, - FlushInputBuffer = 47, - SetBufferContents1 = 48, - SetBufferContents2 = 49, - GetBufferContents = 50, - ScrollBufferContents = 51, + ReadKey = 46, + FlushInputBuffer = 47, + SetBufferContents1 = 48, + SetBufferContents2 = 49, + GetBufferContents = 50, + ScrollBufferContents = 51, // IHostSupportsInteractiveSession methods. - PushRunspace = 52, - PopRunspace = 53, + PushRunspace = 52, + PopRunspace = 53, // IHostSupportsInteractiveSession read-only properties. - GetIsRunspacePushed = 54, - GetRunspace = 55, + GetIsRunspacePushed = 54, + GetRunspace = 55, // IHostSupportsMultipleChoiceSelection PromptForChoiceMultipleSelection = 56, @@ -171,15 +172,15 @@ namespace System.Management.Automation.Remoting /// Create a new instance of RemoteHostMethodInfo. /// internal RemoteHostMethodInfo( - Type interfaceType, - string name, - Type returnType, - Type[] parameterTypes) + Type interfaceType, + string name, + Type returnType, + Type[] parameterTypes) { - this._interfaceType = interfaceType; - this._name = name; - this._returnType = returnType; - this._parameterTypes = parameterTypes; + _interfaceType = interfaceType; + _name = name; + _returnType = returnType; + _parameterTypes = parameterTypes; } /// diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index cddb2a768..7596d7a1f 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -25,7 +25,7 @@ namespace System.Management.Automation.Remoting.Server protected object _syncObject = new object(); protected string _initialCommand; protected ManualResetEvent allcmdsClosedEvent; - + // Thread impersonation. protected WindowsIdentity _windowsIdentityToImpersonate; @@ -415,7 +415,7 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private static OutOfProcessMediator SingletonInstance; + private static OutOfProcessMediator s_singletonInstance; #endregion @@ -461,20 +461,20 @@ namespace System.Management.Automation.Remoting.Server { lock (SyncObject) { - if (null != SingletonInstance) + if (null != s_singletonInstance) { Dbg.Assert(false, "Run should not be called multiple times"); return; } - SingletonInstance = new OutOfProcessMediator(); + s_singletonInstance = new OutOfProcessMediator(); } #if !CORECLR // AppDomain is not available in CoreCLR // Setup unhandled exception to log events AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); #endif - SingletonInstance.Start(initialCommand); + s_singletonInstance.Start(initialCommand); } #endregion @@ -484,7 +484,7 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private static NamedPipeProcessMediator SingletonInstance; + private static NamedPipeProcessMediator s_singletonInstance; private readonly RemoteSessionNamedPipeServer _namedPipeServer; @@ -517,7 +517,7 @@ namespace System.Management.Automation.Remoting.Server originalStdIn = namedPipeServer.TextReader; originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter); originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter); - + // Flow impersonation if requested. WindowsIdentity currentIdentity = null; try @@ -539,20 +539,20 @@ namespace System.Management.Automation.Remoting.Server { lock (SyncObject) { - if (SingletonInstance != null && !SingletonInstance.IsDisposed) + if (s_singletonInstance != null && !s_singletonInstance.IsDisposed) { Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed."); return; } - SingletonInstance = new NamedPipeProcessMediator(namedPipeServer); + s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer); } - -#if !CORECLR + +#if !CORECLR // AppDomain is not available in CoreCLR AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); #endif - SingletonInstance.Start(initialCommand, namedPipeServer.ConfigurationName); + s_singletonInstance.Start(initialCommand, namedPipeServer.ConfigurationName); } #endregion @@ -578,7 +578,7 @@ namespace System.Management.Automation.Remoting.Server #region Constructors internal NamedPipeErrorTextWriter( - TextWriter textWriter) : base (textWriter) + TextWriter textWriter) : base(textWriter) { } #endregion @@ -598,7 +598,7 @@ namespace System.Management.Automation.Remoting.Server { #region Private Data - private static HyperVSocketMediator Instance; + private static HyperVSocketMediator s_instance; private readonly RemoteSessionHyperVSocketServer _hypervSocketServer; @@ -635,7 +635,7 @@ namespace System.Management.Automation.Remoting.Server { lock (SyncObject) { - Instance = new HyperVSocketMediator(); + s_instance = new HyperVSocketMediator(); } #if !CORECLR @@ -643,7 +643,7 @@ namespace System.Management.Automation.Remoting.Server AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); #endif - Instance.Start(initialCommand, configurationName); + s_instance.Start(initialCommand, configurationName); } #endregion diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index 42e320ef9..a5be9a2f5 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -155,7 +156,7 @@ namespace System.Management.Automation.Remoting // Process the response. object returnValue = remoteHostResponse.SimulateExecution(); Dbg.Assert(returnValue is T, "Expected returnValue is T"); - return (T) remoteHostResponse.SimulateExecution(); + return (T)remoteHostResponse.SimulateExecution(); } } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 0f1e57ede..90aaa3e34 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -20,35 +20,35 @@ namespace System.Management.Automation { #region Private Members - private bool extraPowerShellAlreadyScheduled; - private PowerShell extraPowerShell; // extra PowerShell at the server to be run after localPowerShell - private PowerShell localPowerShell; // local PowerShell at the server - private PSDataCollection localPowerShellOutput; // output buffer for the local PowerShell - private Guid clientPowerShellId; // the client PowerShell's guid - // that is associated with this - // powershell driver - private Guid clientRunspacePoolId; // the id of the client runspace pool - // associated with this powershell - private ServerPowerShellDataStructureHandler dsHandler; - // data structure handler object to handle all - // communications with the client - private PSDataCollection input; // input for local powershell invocation - private bool[] datasent = new bool[2]; // if the remaining data has been sent - // to the client before sending state - // information - private object syncObject = new object(); // sync object for synchronizing sending - // data to client - private bool noInput; // there is no input when this driver - // was created - private bool addToHistory; - private ServerRemoteHost remoteHost; // the server remote host instance + private bool _extraPowerShellAlreadyScheduled; + private PowerShell _extraPowerShell; // extra PowerShell at the server to be run after localPowerShell + private PowerShell _localPowerShell; // local PowerShell at the server + private PSDataCollection _localPowerShellOutput; // output buffer for the local PowerShell + private Guid _clientPowerShellId; // the client PowerShell's guid + // that is associated with this + // powershell driver + private Guid _clientRunspacePoolId; // the id of the client runspace pool + // associated with this powershell + private ServerPowerShellDataStructureHandler _dsHandler; + // data structure handler object to handle all + // communications with the client + private PSDataCollection _input; // input for local powershell invocation + private bool[] _datasent = new bool[2]; // if the remaining data has been sent + // to the client before sending state + // information + private object _syncObject = new object(); // sync object for synchronizing sending + // data to client + private bool _noInput; // there is no input when this driver + // was created + private bool _addToHistory; + private ServerRemoteHost _remoteHost; // the server remote host instance // associated with this powershell #if !CORECLR // No ApartmentState In CoreCLR private ApartmentState apartmentState; // apartment state for this powershell #endif - private RemoteStreamOptions remoteStreamOptions; // serialization options for the streams in this powershell + private RemoteStreamOptions _remoteStreamOptions; // serialization options for the streams in this powershell - private IRSPDriverInvoke psDriverInvoker; // Handles nested invocation of PS drivers. + private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers. #endregion Private Members @@ -139,7 +139,7 @@ namespace System.Management.Automation /// /// If not null, this is used as another source of output sent to the client. /// - internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, + internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, PSDataCollection output) @@ -168,55 +168,55 @@ namespace System.Management.Automation /// /// If not null, this is used as another source of output sent to the client. /// - internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, + internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, PSDataCollection output) #endif { - this.clientPowerShellId = clientPowerShellId; - this.clientRunspacePoolId = clientRunspacePoolId; - this.remoteStreamOptions = streamOptions; + _clientPowerShellId = clientPowerShellId; + _clientRunspacePoolId = clientRunspacePoolId; + _remoteStreamOptions = streamOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = apartmentState; #endif - this.localPowerShell = powershell; - this.extraPowerShell = extraPowerShell; - this.localPowerShellOutput = new PSDataCollection(); - this.noInput = noInput; - this.addToHistory = addToHistory; - this.psDriverInvoker = runspacePoolDriver; + _localPowerShell = powershell; + _extraPowerShell = extraPowerShell; + _localPowerShellOutput = new PSDataCollection(); + _noInput = noInput; + _addToHistory = addToHistory; + _psDriverInvoker = runspacePoolDriver; - this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, remoteStreamOptions, localPowerShell); - this.remoteHost = dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); + _dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, _remoteStreamOptions, _localPowerShell); + _remoteHost = _dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); if (!noInput) { - input = new PSDataCollection(); - input.ReleaseOnEnumeration = true; - input.IdleEvent += new EventHandler(HandleIdleEvent); + _input = new PSDataCollection(); + _input.ReleaseOnEnumeration = true; + _input.IdleEvent += new EventHandler(HandleIdleEvent); } - RegisterPipelineOutputEventHandlers(localPowerShellOutput); + RegisterPipelineOutputEventHandlers(_localPowerShellOutput); - if (localPowerShell != null) + if (_localPowerShell != null) { - RegisterPowerShellEventHandlers(localPowerShell); - datasent[0] = false; + RegisterPowerShellEventHandlers(_localPowerShell); + _datasent[0] = false; } if (extraPowerShell != null) { RegisterPowerShellEventHandlers(extraPowerShell); - datasent[1] = false; + _datasent[1] = false; } - RegisterDataStructureHandlerEventHandlers(dsHandler); + RegisterDataStructureHandlerEventHandlers(_dsHandler); // set the runspace pool and invoke this powershell if (null != rsToUse) { - localPowerShell.Runspace = rsToUse; + _localPowerShell.Runspace = rsToUse; if (extraPowerShell != null) { extraPowerShell.Runspace = rsToUse; @@ -224,7 +224,7 @@ namespace System.Management.Automation } else { - localPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; + _localPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; if (extraPowerShell != null) { extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; @@ -235,12 +235,12 @@ namespace System.Management.Automation { output.DataAdded += (sender, args) => { - if (localPowerShellOutput.IsOpen) + if (_localPowerShellOutput.IsOpen) { var items = output.ReadAll(); foreach (var item in items) { - localPowerShellOutput.Add(item); + _localPowerShellOutput.Add(item); } } }; @@ -256,7 +256,7 @@ namespace System.Management.Automation /// internal PSDataCollection InputCollection { - get { return input; } + get { return _input; } } /// @@ -264,7 +264,7 @@ namespace System.Management.Automation /// internal PowerShell LocalPowerShell { - get { return localPowerShell; } + get { return _localPowerShell; } } /// @@ -276,7 +276,7 @@ namespace System.Management.Automation { get { - return clientPowerShellId; + return _clientPowerShellId; } } @@ -287,7 +287,7 @@ namespace System.Management.Automation { get { - return this.remoteStreamOptions; + return _remoteStreamOptions; } } @@ -302,9 +302,8 @@ namespace System.Management.Automation { get { - return clientRunspacePoolId; + return _clientRunspacePoolId; } - } /// @@ -315,7 +314,7 @@ namespace System.Management.Automation { get { - return dsHandler; + return _dsHandler; } } @@ -324,39 +323,38 @@ namespace System.Management.Automation if (startMainPowerShell) { // prepare transport manager for sending and receiving data. - dsHandler.Prepare(); + _dsHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings(); #if !CORECLR // No ApartmentState In CoreCLR settings.ApartmentState = apartmentState; #endif - settings.Host = remoteHost; + settings.Host = _remoteHost; // Flow the impersonation policy to pipeline execution thread // only if the current thread is impersonated (Delegation is // also a kind of impersonation). if (Platform.IsWindows) { - WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); - switch (currentThreadIdentity.ImpersonationLevel) - { - - case TokenImpersonationLevel.Impersonation: - case TokenImpersonationLevel.Delegation: - settings.FlowImpersonationPolicy = true; - break; - default: - settings.FlowImpersonationPolicy = false; - break; - } + WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); + switch (currentThreadIdentity.ImpersonationLevel) + { + case TokenImpersonationLevel.Impersonation: + case TokenImpersonationLevel.Delegation: + settings.FlowImpersonationPolicy = true; + break; + default: + settings.FlowImpersonationPolicy = false; + break; + } } else { - settings.FlowImpersonationPolicy = false; + settings.FlowImpersonationPolicy = false; } - settings.AddToHistory = addToHistory; + settings.AddToHistory = _addToHistory; return settings; } @@ -366,11 +364,11 @@ namespace System.Management.Automation if (startMainPowerShell) { - return localPowerShell.BeginInvoke(input, localPowerShellOutput, settings, null, null); + return _localPowerShell.BeginInvoke(_input, _localPowerShellOutput, settings, null, null); } else { - return extraPowerShell.BeginInvoke(input, localPowerShellOutput, settings, null, null); + return _extraPowerShell.BeginInvoke(_input, _localPowerShellOutput, settings, null, null); } } @@ -390,19 +388,18 @@ namespace System.Management.Automation /// internal void RunNoOpCommand() { - if (this.localPowerShell != null) + if (_localPowerShell != null) { System.Threading.ThreadPool.QueueUserWorkItem( - (state) => + (state) => { - this.localPowerShell.SetStateChanged( + _localPowerShell.SetStateChanged( new PSInvocationStateInfo( PSInvocationState.Running, null)); - this.localPowerShell.SetStateChanged( + _localPowerShell.SetStateChanged( new PSInvocationStateInfo( PSInvocationState.Completed, null)); - }); } } @@ -417,7 +414,7 @@ namespace System.Management.Automation Exception ex = null; try { - localPowerShell.InvokeWithDebugger(input, localPowerShellOutput, settings, true); + _localPowerShell.InvokeWithDebugger(_input, _localPowerShellOutput, settings, true); } catch (Exception e) { @@ -430,15 +427,15 @@ namespace System.Management.Automation // Since this is being invoked asynchronously on a single pipeline thread // any invoke failures (such as possible debugger failures) need to be // passed back to client or the original client invoke request will hang. - string failedCommand = localPowerShell.Commands.Commands[0].CommandText; - localPowerShell.Commands.Clear(); + string failedCommand = _localPowerShell.Commands.Commands[0].CommandText; + _localPowerShell.Commands.Clear(); string msg = StringUtil.Format( RemotingErrorIdStrings.ServerSideNestedCommandInvokeFailed, failedCommand ?? string.Empty, ex.Message ?? string.Empty); - localPowerShell.AddCommand("Write-Error").AddArgument(msg); - localPowerShell.Invoke(); + _localPowerShell.AddCommand("Write-Error").AddArgument(msg); + _localPowerShell.Invoke(); } } @@ -515,11 +512,11 @@ namespace System.Management.Automation case PSInvocationState.Failed: case PSInvocationState.Stopped: { - if (localPowerShell.RunningExtraCommands) + if (_localPowerShell.RunningExtraCommands) { // If completed successfully then allow extra commands to run. if (state == PSInvocationState.Completed) { return; } - + // For failed or stopped state, extra commands cannot run and // we allow this command invocation to finish. } @@ -534,28 +531,28 @@ namespace System.Management.Automation // the runspace pool data structure handler on the client side SendRemainingData(); - if (state == PSInvocationState.Completed && - (extraPowerShell != null) && - !extraPowerShellAlreadyScheduled) + if (state == PSInvocationState.Completed && + (_extraPowerShell != null) && + !_extraPowerShellAlreadyScheduled) { - extraPowerShellAlreadyScheduled = true; + _extraPowerShellAlreadyScheduled = true; Start(false); } else { - dsHandler.RaiseRemoveAssociationEvent(); + _dsHandler.RaiseRemoveAssociationEvent(); // send the state change notification to the client - dsHandler.SendStateChangedInformationToClient( + _dsHandler.SendStateChangedInformationToClient( eventArgs.InvocationStateInfo); - UnregisterPowerShellEventHandlers(localPowerShell); - if (extraPowerShell != null) + UnregisterPowerShellEventHandlers(_localPowerShell); + if (_extraPowerShell != null) { - UnregisterPowerShellEventHandlers(extraPowerShell); + UnregisterPowerShellEventHandlers(_extraPowerShell); } - UnregisterDataStructureHandlerEventHandlers(dsHandler); - UnregisterPipelineOutputEventHandlers(localPowerShellOutput); + UnregisterDataStructureHandlerEventHandlers(_dsHandler); + UnregisterPipelineOutputEventHandlers(_localPowerShellOutput); // BUGBUG: currently the local powershell cannot // be disposed as raising the events is @@ -569,7 +566,7 @@ namespace System.Management.Automation case PSInvocationState.Stopping: { // abort all pending host calls - remoteHost.ServerMethodExecutor.AbortAllCalls(); + _remoteHost.ServerMethodExecutor.AbortAllCalls(); } break; } @@ -584,18 +581,18 @@ namespace System.Management.Automation { int index = e.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if (!datasent[indexIntoDataSent]) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if (!_datasent[indexIntoDataSent]) { - PSObject data = localPowerShellOutput[index]; + PSObject data = _localPowerShellOutput[index]; // once send the output is removed so that the same // is not sent again by SendRemainingData() method - localPowerShellOutput.RemoveAt(index); + _localPowerShellOutput.RemoveAt(index); // send the output data to the client - dsHandler.SendOutputDataToClient(data); + _dsHandler.SendOutputDataToClient(data); } } // lock .. } @@ -609,18 +606,18 @@ namespace System.Management.Automation { int index = e.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - ErrorRecord errorRecord = localPowerShell.Streams.Error[index]; + ErrorRecord errorRecord = _localPowerShell.Streams.Error[index]; // once send the error record is removed so that the same // is not sent again by SendRemainingData() method - localPowerShell.Streams.Error.RemoveAt(index); + _localPowerShell.Streams.Error.RemoveAt(index); // send the error record to the client - dsHandler.SendErrorRecordToClient(errorRecord); + _dsHandler.SendErrorRecordToClient(errorRecord); } } // lock ... } @@ -634,18 +631,18 @@ namespace System.Management.Automation { int index = eventArgs.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - ProgressRecord data = localPowerShell.Streams.Progress[index]; + ProgressRecord data = _localPowerShell.Streams.Progress[index]; // once the debug message is sent, it is removed so that // the same is not sent again by SendRemainingData() method - localPowerShell.Streams.Progress.RemoveAt(index); + _localPowerShell.Streams.Progress.RemoveAt(index); // send the output data to the client - dsHandler.SendProgressRecordToClient(data); + _dsHandler.SendProgressRecordToClient(data); } } // lock .. } @@ -659,18 +656,18 @@ namespace System.Management.Automation { int index = eventArgs.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - WarningRecord data = localPowerShell.Streams.Warning[index]; + WarningRecord data = _localPowerShell.Streams.Warning[index]; // once the debug message is sent, it is removed so that // the same is not sent again by SendRemainingData() method - localPowerShell.Streams.Warning.RemoveAt(index); - + _localPowerShell.Streams.Warning.RemoveAt(index); + // send the output data to the client - dsHandler.SendWarningRecordToClient(data); + _dsHandler.SendWarningRecordToClient(data); } } // lock .. } @@ -684,18 +681,18 @@ namespace System.Management.Automation { int index = eventArgs.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - VerboseRecord data = localPowerShell.Streams.Verbose[index]; + VerboseRecord data = _localPowerShell.Streams.Verbose[index]; // once the debug message is sent, it is removed so that // the same is not sent again by SendRemainingData() method - localPowerShell.Streams.Verbose.RemoveAt(index); + _localPowerShell.Streams.Verbose.RemoveAt(index); // send the output data to the client - dsHandler.SendVerboseRecordToClient(data); + _dsHandler.SendVerboseRecordToClient(data); } } // lock .. } @@ -709,18 +706,18 @@ namespace System.Management.Automation { int index = eventArgs.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - DebugRecord data = localPowerShell.Streams.Debug[index]; + DebugRecord data = _localPowerShell.Streams.Debug[index]; // once the debug message is sent, it is removed so that // the same is not sent again by SendRemainingData() method - localPowerShell.Streams.Debug.RemoveAt(index); + _localPowerShell.Streams.Debug.RemoveAt(index); // send the output data to the client - dsHandler.SendDebugRecordToClient(data); + _dsHandler.SendDebugRecordToClient(data); } } // lock .. } @@ -734,18 +731,18 @@ namespace System.Management.Automation { int index = eventArgs.Index; - lock (syncObject) + lock (_syncObject) { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - if ((indexIntoDataSent == 0) && (!datasent[indexIntoDataSent])) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent])) { - InformationRecord data = localPowerShell.Streams.Information[index]; + InformationRecord data = _localPowerShell.Streams.Information[index]; // once the Information message is sent, it is removed so that // the same is not sent again by SendRemainingData() method - localPowerShell.Streams.Information.RemoveAt(index); + _localPowerShell.Streams.Information.RemoveAt(index); // send the output data to the client - dsHandler.SendInformationRecordToClient(data); + _dsHandler.SendInformationRecordToClient(data); } } // lock .. } @@ -763,37 +760,37 @@ namespace System.Management.Automation /// discarded private void SendRemainingData() { - int indexIntoDataSent = (!extraPowerShellAlreadyScheduled) ? 0 : 1; - lock (syncObject) + int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1; + lock (_syncObject) { - datasent[indexIntoDataSent] = true; + _datasent[indexIntoDataSent] = true; } try { // BUGBUG: change this code to use enumerator // blocked on bug #108824, to be fixed by Kriscv - for (int i = 0; i < localPowerShellOutput.Count; i++) + for (int i = 0; i < _localPowerShellOutput.Count; i++) { - PSObject data = localPowerShellOutput[i]; - dsHandler.SendOutputDataToClient(data); + PSObject data = _localPowerShellOutput[i]; + _dsHandler.SendOutputDataToClient(data); } - localPowerShellOutput.Clear(); + _localPowerShellOutput.Clear(); //foreach (ErrorRecord errorRecord in localPowerShell.Error) - for (int i = 0; i < localPowerShell.Streams.Error.Count; i++) + for (int i = 0; i < _localPowerShell.Streams.Error.Count; i++) { - ErrorRecord errorRecord = localPowerShell.Streams.Error[i]; - dsHandler.SendErrorRecordToClient(errorRecord); + ErrorRecord errorRecord = _localPowerShell.Streams.Error[i]; + _dsHandler.SendErrorRecordToClient(errorRecord); } - localPowerShell.Streams.Error.Clear(); + _localPowerShell.Streams.Error.Clear(); } finally { - lock (syncObject) + lock (_syncObject) { // reset to original state so other pipelines can stream. - datasent[indexIntoDataSent] = true; + _datasent[indexIntoDataSent] = true; } } } @@ -807,10 +804,10 @@ namespace System.Management.Automation { do // false loop { - if (localPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped || - localPowerShell.InvocationStateInfo.State == PSInvocationState.Completed || - localPowerShell.InvocationStateInfo.State == PSInvocationState.Failed || - localPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping) + if (_localPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped || + _localPowerShell.InvocationStateInfo.State == PSInvocationState.Completed || + _localPowerShell.InvocationStateInfo.State == PSInvocationState.Failed || + _localPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping) { break; } @@ -818,33 +815,33 @@ namespace System.Management.Automation { // Ensure that the local PowerShell command is not stopped in debug mode. bool handledByDebugger = false; - if (!localPowerShell.IsNested && - this.psDriverInvoker != null) + if (!_localPowerShell.IsNested && + _psDriverInvoker != null) { - handledByDebugger = this.psDriverInvoker.HandleStopSignal(); + handledByDebugger = _psDriverInvoker.HandleStopSignal(); } - + if (!handledByDebugger) { - localPowerShell.Stop(); + _localPowerShell.Stop(); } } } while (false); - if (extraPowerShell != null) + if (_extraPowerShell != null) { do // false loop { - if (extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped || - extraPowerShell.InvocationStateInfo.State == PSInvocationState.Completed || - extraPowerShell.InvocationStateInfo.State == PSInvocationState.Failed || - extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping) + if (_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped || + _extraPowerShell.InvocationStateInfo.State == PSInvocationState.Completed || + _extraPowerShell.InvocationStateInfo.State == PSInvocationState.Failed || + _extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping) { break; } else { - extraPowerShell.Stop(); + _extraPowerShell.Stop(); } } while (false); } @@ -859,9 +856,9 @@ namespace System.Management.Automation { // This can be called in pushed runspace scenarios for error reporting (pipeline stopped). // Ignore for noInput. - if (!noInput && (input != null)) + if (!_noInput && (_input != null)) { - input.Add(eventArgs.Data); + _input.Add(eventArgs.Data); } } @@ -874,9 +871,9 @@ namespace System.Management.Automation { // This can be called in pushed runspace scenarios for error reporting (pipeline stopped). // Ignore for noInput. - if (!noInput && (input != null)) + if (!_noInput && (_input != null)) { - input.Complete(); + _input.Complete(); } } @@ -884,10 +881,10 @@ namespace System.Management.Automation { //Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (input != null) + if (_input != null) { //TODO: Post an ETW event - input.Complete(); + _input.Complete(); } } @@ -898,7 +895,7 @@ namespace System.Management.Automation /// arguments describing this event private void HandleHostResponseReceived(object sender, RemoteDataEventArgs eventArgs) { - remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data); + _remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data); } /// @@ -908,7 +905,7 @@ namespace System.Management.Automation /// private void HandleIdleEvent(object sender, EventArgs args) { - Runspace rs = dsHandler.RunspaceUsedToInvokePowerShell; + Runspace rs = _dsHandler.RunspaceUsedToInvokePowerShell; if (rs != null) { PSLocalEventManager events = (object)rs.Events as PSLocalEventManager; diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 251db9086..64b26f9d3 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -219,7 +220,7 @@ namespace System.Management.Automation.Remoting internal virtual bool AllowPushRunspace { get { return (_serverDriverRemoteHost != null) ? _serverDriverRemoteHost.AllowPushRunspace : false; } - set { if (_serverDriverRemoteHost != null) {_serverDriverRemoteHost.AllowPushRunspace = value; } } + set { if (_serverDriverRemoteHost != null) { _serverDriverRemoteHost.AllowPushRunspace = value; } } } #endregion diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 252c83c65..16fb00dfe 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -66,7 +67,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.ForegroundColor)) { - return (ConsoleColor) this.HostDefaultData.GetValue(HostDefaultDataId.ForegroundColor); + return (ConsoleColor)this.HostDefaultData.GetValue(HostDefaultDataId.ForegroundColor); } else { @@ -90,7 +91,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.BackgroundColor)) { - return (ConsoleColor) this.HostDefaultData.GetValue(HostDefaultDataId.BackgroundColor); + return (ConsoleColor)this.HostDefaultData.GetValue(HostDefaultDataId.BackgroundColor); } else { @@ -114,7 +115,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.CursorPosition)) { - return (Coordinates) this.HostDefaultData.GetValue(HostDefaultDataId.CursorPosition); + return (Coordinates)this.HostDefaultData.GetValue(HostDefaultDataId.CursorPosition); } else { @@ -138,7 +139,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowPosition)) { - return (Coordinates) this.HostDefaultData.GetValue(HostDefaultDataId.WindowPosition); + return (Coordinates)this.HostDefaultData.GetValue(HostDefaultDataId.WindowPosition); } else { @@ -162,7 +163,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.CursorSize)) { - return (int) this.HostDefaultData.GetValue(HostDefaultDataId.CursorSize); + return (int)this.HostDefaultData.GetValue(HostDefaultDataId.CursorSize); } else { @@ -186,7 +187,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.BufferSize)) { - return (Size) this.HostDefaultData.GetValue(HostDefaultDataId.BufferSize); + return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.BufferSize); } else { @@ -210,7 +211,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowSize)) { - return (Size) this.HostDefaultData.GetValue(HostDefaultDataId.WindowSize); + return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.WindowSize); } else { @@ -234,7 +235,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowTitle)) { - return (string) this.HostDefaultData.GetValue(HostDefaultDataId.WindowTitle); + return (string)this.HostDefaultData.GetValue(HostDefaultDataId.WindowTitle); } else { @@ -258,7 +259,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.MaxWindowSize)) { - return (Size) this.HostDefaultData.GetValue(HostDefaultDataId.MaxWindowSize); + return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.MaxWindowSize); } else { @@ -276,7 +277,7 @@ namespace System.Management.Automation.Remoting { if (this.HostDefaultData.HasValue(HostDefaultDataId.MaxPhysicalWindowSize)) { - return (Size) this.HostDefaultData.GetValue(HostDefaultDataId.MaxPhysicalWindowSize); + return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.MaxPhysicalWindowSize); } else { diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 281e41e9a..a448ae128 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -240,7 +241,7 @@ namespace System.Management.Automation.Remoting /// public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName) { - return _serverMethodExecutor.ExecuteMethod(RemoteHostMethodId.PromptForCredential1, + return _serverMethodExecutor.ExecuteMethod(RemoteHostMethodId.PromptForCredential1, new object[] { caption, message, userName, targetName }); } @@ -250,7 +251,7 @@ namespace System.Management.Automation.Remoting public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) { return _serverMethodExecutor.ExecuteMethod(RemoteHostMethodId.PromptForCredential2, - new object[] { caption, message, userName, targetName, allowedCredentialTypes, options } ); + new object[] { caption, message, userName, targetName, allowedCredentialTypes, options }); } } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index 873963209..b386c8ad4 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -33,12 +33,12 @@ namespace System.Management.Automation internal ServerRunspacePoolDataStructureHandler(ServerRunspacePoolDriver driver, AbstractServerSessionTransportManager transportManager) { - this.clientRunspacePoolId = driver.InstanceId; - this.transportManager = transportManager; + _clientRunspacePoolId = driver.InstanceId; + _transportManager = transportManager; } #endregion Constructors - + #region Data Structure Handler Methods /// @@ -61,7 +61,7 @@ namespace System.Management.Automation versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData( - clientRunspacePoolId, applicationPrivateDataWithVersionTable); + _clientRunspacePoolId, applicationPrivateDataWithVersionTable); SendDataAsync(data); } @@ -73,7 +73,7 @@ namespace System.Management.Automation internal void SendStateInfoToClient(RunspacePoolStateInfo stateInfo) { RemoteDataObject data = RemotingEncoder.GenerateRunspacePoolStateInfo( - clientRunspacePoolId, stateInfo); + _clientRunspacePoolId, stateInfo); SendDataAsync(data); } @@ -84,7 +84,7 @@ namespace System.Management.Automation /// event to send internal void SendPSEventArgsToClient(PSEventArgs e) { - RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(clientRunspacePoolId, e); + RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(_clientRunspacePoolId, e); SendDataAsync(data); } @@ -96,9 +96,9 @@ namespace System.Management.Automation internal void ProcessConnect() { List dsHandlers; - lock (associationSyncObject) + lock (_associationSyncObject) { - dsHandlers = new List(associatedShells.Values); + dsHandlers = new List(_associatedShells.Values); } foreach (var dsHandler in dsHandlers) { @@ -150,8 +150,8 @@ namespace System.Management.Automation //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running - transportManager.ReportExecutionStatusAsRunning(); - + _transportManager.ReportExecutionStatusAsRunning(); + HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostResponse)); } break; @@ -191,7 +191,6 @@ namespace System.Management.Automation ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } break; - } // switch... } @@ -207,20 +206,20 @@ namespace System.Management.Automation Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, PowerShell localPowerShell) { // start with pool's transport manager. - AbstractServerTransportManager cmdTransportManager = transportManager; + AbstractServerTransportManager cmdTransportManager = _transportManager; if (instanceId != Guid.Empty) { - cmdTransportManager = transportManager.GetCommandTransportManager(instanceId); + cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId); Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code"); } ServerPowerShellDataStructureHandler dsHandler = new ServerPowerShellDataStructureHandler(instanceId, runspacePoolId, remoteStreamOptions, cmdTransportManager, localPowerShell); - lock (associationSyncObject) + lock (_associationSyncObject) { - associatedShells.Add(dsHandler.PowerShellId, dsHandler); + _associatedShells.Add(dsHandler.PowerShellId, dsHandler); } dsHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); @@ -236,11 +235,11 @@ namespace System.Management.Automation /// internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler() { - lock (associationSyncObject) + lock (_associationSyncObject) { - if (associatedShells.Count > 0) + if (_associatedShells.Count > 0) { - foreach(object o in associatedShells.Values) + foreach (object o in _associatedShells.Values) { ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler; if (result != null) @@ -278,8 +277,8 @@ namespace System.Management.Automation /// response to send internal void SendResponseToClient(long callId, object response) { - RemoteDataObject message = - RemotingEncoder.GenerateRunspacePoolOperationResponse(clientRunspacePoolId, response, callId); + RemoteDataObject message = + RemotingEncoder.GenerateRunspacePoolOperationResponse(_clientRunspacePoolId, response, callId); SendDataAsync(message); } @@ -289,8 +288,8 @@ namespace System.Management.Automation /// internal TypeTable TypeTable { - get { return transportManager.TypeTable; } - set { transportManager.TypeTable = value; } + get { return _transportManager.TypeTable; } + set { _transportManager.TypeTable = value; } } #endregion Data Structure Handler Methods @@ -353,7 +352,7 @@ namespace System.Management.Automation private void SendDataAsync(RemoteDataObject data) { Dbg.Assert(null != data, "Cannot send null object."); - transportManager.SendDataToClient(data, true); + _transportManager.SendDataToClient(data, true); } /// @@ -368,9 +367,9 @@ namespace System.Management.Automation { ServerPowerShellDataStructureHandler dsHandler = null; - lock (associationSyncObject) + lock (_associationSyncObject) { - bool success = associatedShells.TryGetValue(clientPowerShellId, out dsHandler); + bool success = _associatedShells.TryGetValue(clientPowerShellId, out dsHandler); if (!success) { @@ -392,30 +391,30 @@ namespace System.Management.Automation ServerPowerShellDataStructureHandler dsHandler = sender as ServerPowerShellDataStructureHandler; - lock (associationSyncObject) + lock (_associationSyncObject) { - associatedShells.Remove(dsHandler.PowerShellId); + _associatedShells.Remove(dsHandler.PowerShellId); } // let session transport manager remove its association of command transport manager. - transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); + _transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId); } #endregion Private Methods #region Private Members - private Guid clientRunspacePoolId; + private Guid _clientRunspacePoolId; // transport manager using which this // runspace pool driver handles all client // communication - private AbstractServerSessionTransportManager transportManager; - private Dictionary associatedShells + private AbstractServerSessionTransportManager _transportManager; + private Dictionary _associatedShells = new Dictionary(); - // powershell data structure handlers associated with this - // runspace pool data structure handler - object associationSyncObject = new object(); - // object to synchronize operations to above + // powershell data structure handlers associated with this + // runspace pool data structure handler + private object _associationSyncObject = new object(); + // object to synchronize operations to above #endregion Private Members } @@ -430,11 +429,11 @@ namespace System.Management.Automation // transport manager using which this // powershell driver handles all client // communication - private AbstractServerTransportManager transportManager; - private Guid clientRunspacePoolId; - private Guid clientPowerShellId; - private RemoteStreamOptions streamSerializationOptions; - private Runspace rsUsedToInvokePowerShell; + private AbstractServerTransportManager _transportManager; + private Guid _clientRunspacePoolId; + private Guid _clientPowerShellId; + private RemoteStreamOptions _streamSerializationOptions; + private Runspace _rsUsedToInvokePowerShell; #endregion Private Members @@ -452,10 +451,10 @@ namespace System.Management.Automation internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, AbstractServerTransportManager transportManager, PowerShell localPowerShell) { - this.clientPowerShellId = instanceId; - this.clientRunspacePoolId = runspacePoolId; - this.transportManager = transportManager; - this.streamSerializationOptions = remoteStreamOptions; + _clientPowerShellId = instanceId; + _clientRunspacePoolId = runspacePoolId; + _transportManager = transportManager; + _streamSerializationOptions = remoteStreamOptions; transportManager.Closing += HandleTransportClosing; if (localPowerShell != null) @@ -465,9 +464,9 @@ namespace System.Management.Automation } } - void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs e) + private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs e) { - rsUsedToInvokePowerShell = e.Args; + _rsUsedToInvokePowerShell = e.Args; } #endregion Constructors @@ -481,9 +480,9 @@ namespace System.Management.Automation { // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. so we dont need to prepare command transport manager - if (clientPowerShellId != Guid.Empty) + if (_clientPowerShellId != Guid.Empty) { - transportManager.Prepare(); + _transportManager.Prepare(); } } @@ -500,18 +499,18 @@ namespace System.Management.Automation (stateInfo.State == PSInvocationState.Stopped), "SendStateChangedInformationToClient should be called to notify a termination state"); SendDataAsync(RemotingEncoder.GeneratePowerShellStateInfo( - stateInfo, clientPowerShellId, clientRunspacePoolId)); + stateInfo, _clientPowerShellId, _clientRunspacePoolId)); // Close the transport manager only if the PowerShell Guid != Guid.Empty. // When Guid.Empty is used, PowerShell must be using pool's transport manager // to send data to client. - if (clientPowerShellId != Guid.Empty) + if (_clientPowerShellId != Guid.Empty) { // no need to listen for closing events as we are initiating the close - transportManager.Closing -= HandleTransportClosing; + _transportManager.Closing -= HandleTransportClosing; // if terminal state is reached close the transport manager instead of letting // the client intiate the close. - transportManager.Close(null); + _transportManager.Close(null); } } @@ -522,7 +521,7 @@ namespace System.Management.Automation internal void SendOutputDataToClient(PSObject data) { SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data, - clientPowerShellId, clientRunspacePoolId)); + _clientPowerShellId, _clientRunspacePoolId)); } /// @@ -531,10 +530,10 @@ namespace System.Management.Automation /// error record to send internal void SendErrorRecordToClient(ErrorRecord errorRecord) { - errorRecord.SerializeExtendedInfo = (this.streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0; + errorRecord.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellError( - errorRecord, clientRunspacePoolId, clientPowerShellId)); + errorRecord, _clientRunspacePoolId, _clientPowerShellId)); } /// @@ -543,10 +542,10 @@ namespace System.Management.Automation /// warning record internal void SendWarningRecordToClient(WarningRecord record) { - record.SerializeExtendedInfo = (this.streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0; + record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( - record, clientRunspacePoolId, clientPowerShellId, RemotingDataType.PowerShellWarning)); + record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellWarning)); } /// @@ -555,10 +554,10 @@ namespace System.Management.Automation /// debug record internal void SendDebugRecordToClient(DebugRecord record) { - record.SerializeExtendedInfo = (this.streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0; + record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( - record, clientRunspacePoolId, clientPowerShellId, RemotingDataType.PowerShellDebug)); + record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellDebug)); } /// @@ -567,10 +566,10 @@ namespace System.Management.Automation /// warning record internal void SendVerboseRecordToClient(VerboseRecord record) { - record.SerializeExtendedInfo = (this.streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0; + record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0; SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( - record, clientRunspacePoolId, clientPowerShellId, RemotingDataType.PowerShellVerbose)); + record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellVerbose)); } /// @@ -580,7 +579,7 @@ namespace System.Management.Automation internal void SendProgressRecordToClient(ProgressRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( - record, clientRunspacePoolId, clientPowerShellId)); + record, _clientRunspacePoolId, _clientPowerShellId)); } /// @@ -590,7 +589,7 @@ namespace System.Management.Automation internal void SendInformationRecordToClient(InformationRecord record) { SendDataAsync(RemotingEncoder.GeneratePowerShellInformational( - record, clientRunspacePoolId, clientPowerShellId)); + record, _clientRunspacePoolId, _clientPowerShellId)); } /// @@ -636,7 +635,7 @@ namespace System.Management.Automation InputReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } break; - + case RemotingDataType.PowerShellInputEnd: { Dbg.Assert(InputEndReceived != null, @@ -654,7 +653,7 @@ namespace System.Management.Automation //part of host message robustness algo. Now the host response is back, report to transport that // execution status is back to running - transportManager.ReportExecutionStatusAsRunning(); + _transportManager.ReportExecutionStatusAsRunning(); HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(remoteHostResponse)); } @@ -662,7 +661,7 @@ namespace System.Management.Automation } // switch ... } - /// + /// /// Raise a remove association event. This is raised /// when the powershell has gone into a terminal state /// and the runspace pool need not maintain any further @@ -702,8 +701,8 @@ namespace System.Management.Automation // If the host was not null on the client, then the PowerShell object should // get a brand spanking new host. - return new ServerRemoteHost(clientRunspacePoolId, clientPowerShellId, hostInfo, - transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost); + return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo, + _transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost); } #endregion Data Structure Handler Methods @@ -756,7 +755,7 @@ namespace System.Management.Automation { get { - return clientPowerShellId; + return _clientPowerShellId; } } @@ -766,7 +765,7 @@ namespace System.Management.Automation /// internal Runspace RunspaceUsedToInvokePowerShell { - get { return rsUsedToInvokePowerShell; } + get { return _rsUsedToInvokePowerShell; } } #endregion Internal Methods @@ -786,7 +785,7 @@ namespace System.Management.Automation Dbg.Assert(null != data, "Cannot send null object."); // this is from a command execution..let transport manager collect // as much data as possible and send bigger buffer to client. - transportManager.SendDataToClient(data, false); + _transportManager.SendDataToClient(data, false); } /// @@ -801,5 +800,4 @@ namespace System.Management.Automation #endregion Private Methods } - } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 9ced86889..c6c7397fc 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -42,52 +42,52 @@ namespace System.Management.Automation #region Private Members // local runspace pool at the server - private RunspacePool localRunspacePool; + private RunspacePool _localRunspacePool; // Script to run after a RunspacePool/Runspace is created in this session. - private ConfigurationDataFromXML configData; + private ConfigurationDataFromXML _configData; // application private data to send back to the client in when we get into "opened" state - private PSPrimitiveDictionary applicationPrivateData; + private PSPrimitiveDictionary _applicationPrivateData; // the client runspacepool's guid that is // associated with this runspace pool driver - private Guid clientRunspacePoolId; + private Guid _clientRunspacePoolId; // data structure handler object to handle all communications // with the client - private ServerRunspacePoolDataStructureHandler dsHandler; + private ServerRunspacePoolDataStructureHandler _dsHandler; // powershell's associated with this runspace pool - private Dictionary associatedShells + private Dictionary _associatedShells = new Dictionary(); // remote host associated with this runspacepool - private ServerDriverRemoteHost remoteHost; + private ServerDriverRemoteHost _remoteHost; - private bool isClosed; + private bool _isClosed; // server capability reported to the client during negotiation (not the actual capability) - private RemoteSessionCapability serverCapability; - private Runspace rsToUseForSteppablePipeline; + private RemoteSessionCapability _serverCapability; + private Runspace _rsToUseForSteppablePipeline; // steppable pipeline event subscribers exist per-session - private ServerSteppablePipelineSubscriber eventSubscriber = new ServerSteppablePipelineSubscriber(); - private PSDataCollection inputCollection; // PowerShell driver input collection + private ServerSteppablePipelineSubscriber _eventSubscriber = new ServerSteppablePipelineSubscriber(); + private PSDataCollection _inputCollection; // PowerShell driver input collection // Object to invoke nested PowerShell drivers on single pipeline worker thread. - private PowerShellDriverInvoker driverNestedInvoker; + private PowerShellDriverInvoker _driverNestedInvoker; // Remote wrapper for script debugger. - private ServerRemoteDebugger serverRemoteDebugger; + private ServerRemoteDebugger _serverRemoteDebugger; // Version of PowerShell client. - private Version clientPSVersion; + private Version _clientPSVersion; // Optional endpoint configuration name. // Used in OutOfProc scenarios that do not support PSSession endpoint configuration. // Results in a configured remote runspace pushed onto driver host. - private string configurationName; + private string _configurationName; /// /// Event that get raised when the RunspacePool is closed. @@ -97,7 +97,7 @@ namespace System.Management.Automation #endregion Private Members #region Constructors - + #if CORECLR // No ApartmentState In CoreCLR /// @@ -125,15 +125,15 @@ namespace System.Management.Automation /// Client PowerShell version. /// Optional endpoint configuration name to create a pushed configured runspace. internal ServerRunspacePoolDriver( - Guid clientRunspacePoolId, + Guid clientRunspacePoolId, int minRunspaces, - int maxRunspaces, + int maxRunspaces, PSThreadOptions threadOptions, - HostInfo hostInfo, + HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, - AbstractServerSessionTransportManager transportManager, + AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Version psClientVersion, @@ -165,16 +165,16 @@ namespace System.Management.Automation /// Client PowerShell version. /// Optional endpoint configuration name to create a pushed configured runspace. internal ServerRunspacePoolDriver( - Guid clientRunspacePoolId, + Guid clientRunspacePoolId, int minRunspaces, - int maxRunspaces, - PSThreadOptions threadOptions, - ApartmentState apartmentState, - HostInfo hostInfo, + int maxRunspaces, + PSThreadOptions threadOptions, + ApartmentState apartmentState, + HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, - AbstractServerSessionTransportManager transportManager, + AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Version psClientVersion, @@ -183,20 +183,20 @@ namespace System.Management.Automation { Dbg.Assert(null != configData, "ConfigurationData cannot be null"); - this.serverCapability = serverCapability; - this.clientPSVersion = psClientVersion; + _serverCapability = serverCapability; + _clientPSVersion = psClientVersion; - this.configurationName = configurationName; + _configurationName = configurationName; // Create a new server host and associate for host call // integration - this.remoteHost = new ServerDriverRemoteHost(clientRunspacePoolId, + _remoteHost = new ServerDriverRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager, null); - this.configData = configData; - this.applicationPrivateData = applicationPrivateData; - localRunspacePool = RunspaceFactory.CreateRunspacePool( - minRunspaces, maxRunspaces, initialSessionState, this.remoteHost); + _configData = configData; + _applicationPrivateData = applicationPrivateData; + _localRunspacePool = RunspaceFactory.CreateRunspacePool( + minRunspaces, maxRunspaces, initialSessionState, _remoteHost); // Set ThreadOptions for this RunspacePool // The default server settings is to make new commands execute in the calling thread...this saves @@ -205,7 +205,7 @@ namespace System.Management.Automation PSThreadOptions serverThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if (threadOptions == PSThreadOptions.Default || threadOptions == serverThreadOptions) { - localRunspacePool.ThreadOptions = serverThreadOptions; + _localRunspacePool.ThreadOptions = serverThreadOptions; } else { @@ -214,7 +214,7 @@ namespace System.Management.Automation throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions)); } - localRunspacePool.ThreadOptions = threadOptions; + _localRunspacePool.ThreadOptions = threadOptions; } #if !CORECLR // No ApartmentState In CoreCLR @@ -223,50 +223,50 @@ namespace System.Management.Automation if (apartmentState == ApartmentState.Unknown || apartmentState == serverApartmentState) { - localRunspacePool.ApartmentState = serverApartmentState; + _localRunspacePool.ApartmentState = serverApartmentState; } else { - localRunspacePool.ApartmentState = apartmentState; + _localRunspacePool.ApartmentState = apartmentState; } #endif // If we have a runspace pool with a single runspace then we can run nested pipelines on // on it in a single pipeline invoke thread. if (maxRunspaces == 1 && - (localRunspacePool.ThreadOptions == PSThreadOptions.Default || - localRunspacePool.ThreadOptions == PSThreadOptions.UseCurrentThread)) + (_localRunspacePool.ThreadOptions == PSThreadOptions.Default || + _localRunspacePool.ThreadOptions == PSThreadOptions.UseCurrentThread)) { - driverNestedInvoker = new PowerShellDriverInvoker(); + _driverNestedInvoker = new PowerShellDriverInvoker(); } - this.clientRunspacePoolId = clientRunspacePoolId; - this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); + _clientRunspacePoolId = clientRunspacePoolId; + _dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); // handle the StateChanged event of the runspace pool - localRunspacePool.StateChanged += + _localRunspacePool.StateChanged += new EventHandler(HandleRunspacePoolStateChanged); // listen for events on the runspace pool - localRunspacePool.ForwardEvent += + _localRunspacePool.ForwardEvent += new EventHandler(HandleRunspacePoolForwardEvent); - localRunspacePool.RunspaceCreated += HandleRunspaceCreated; + _localRunspacePool.RunspaceCreated += HandleRunspaceCreated; // register for all the events from the data structure handler - dsHandler.CreateAndInvokePowerShell += + _dsHandler.CreateAndInvokePowerShell += new EventHandler>>(HandleCreateAndInvokePowerShell); - dsHandler.GetCommandMetadata += + _dsHandler.GetCommandMetadata += new EventHandler>>(HandleGetCommandMetadata); - dsHandler.HostResponseReceived += + _dsHandler.HostResponseReceived += new EventHandler>(HandleHostResponseReceived); - dsHandler.SetMaxRunspacesReceived += + _dsHandler.SetMaxRunspacesReceived += new EventHandler>(HandleSetMaxRunspacesReceived); - dsHandler.SetMinRunspacesReceived += + _dsHandler.SetMinRunspacesReceived += new EventHandler>(HandleSetMinRunspacesReceived); - dsHandler.GetAvailableRunspacesReceived += + _dsHandler.GetAvailableRunspacesReceived += new EventHandler>(HandleGetAvailalbeRunspacesReceived); - dsHandler.ResetRunspaceState += + _dsHandler.ResetRunspaceState += new EventHandler>(HandleResetRunspaceState); } @@ -281,7 +281,7 @@ namespace System.Management.Automation { get { - return dsHandler; + return _dsHandler; } } @@ -290,7 +290,7 @@ namespace System.Management.Automation /// internal ServerRemoteHost ServerRemoteHost { - get { return remoteHost; } + get { return _remoteHost; } } /// @@ -300,7 +300,7 @@ namespace System.Management.Automation { get { - return clientRunspacePoolId; + return _clientRunspacePoolId; } } @@ -312,7 +312,7 @@ namespace System.Management.Automation { get { - return localRunspacePool; + return _localRunspacePool; } } @@ -323,7 +323,7 @@ namespace System.Management.Automation internal void Start() { // open the runspace pool - localRunspacePool.Open(); + _localRunspacePool.Open(); } /// @@ -334,70 +334,70 @@ namespace System.Management.Automation internal void SendApplicationPrivateDataToClient() { // Include Debug mode information. - if (this.applicationPrivateData == null) + if (_applicationPrivateData == null) { - this.applicationPrivateData = new PSPrimitiveDictionary(); + _applicationPrivateData = new PSPrimitiveDictionary(); } - if (serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { // Current debug mode. - DebugModes debugMode = serverRemoteDebugger.DebugMode; - if (this.applicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting)) + DebugModes debugMode = _serverRemoteDebugger.DebugMode; + if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting)) { - this.applicationPrivateData[RemoteDebugger.DebugModeSetting] = (int)debugMode; + _applicationPrivateData[RemoteDebugger.DebugModeSetting] = (int)debugMode; } else { - this.applicationPrivateData.Add(RemoteDebugger.DebugModeSetting, (int)debugMode); + _applicationPrivateData.Add(RemoteDebugger.DebugModeSetting, (int)debugMode); } // Current debug state. - bool inBreakpoint = serverRemoteDebugger.InBreakpoint; - if (this.applicationPrivateData.ContainsKey(RemoteDebugger.DebugStopState)) + bool inBreakpoint = _serverRemoteDebugger.InBreakpoint; + if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugStopState)) { - this.applicationPrivateData[RemoteDebugger.DebugStopState] = inBreakpoint; + _applicationPrivateData[RemoteDebugger.DebugStopState] = inBreakpoint; } else { - this.applicationPrivateData.Add(RemoteDebugger.DebugStopState, inBreakpoint); + _applicationPrivateData.Add(RemoteDebugger.DebugStopState, inBreakpoint); } // Current debug breakpoint count. - int breakpointCount = serverRemoteDebugger.GetBreakpointCount(); - if (this.applicationPrivateData.ContainsKey(RemoteDebugger.DebugBreakpointCount)) + int breakpointCount = _serverRemoteDebugger.GetBreakpointCount(); + if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugBreakpointCount)) { - this.applicationPrivateData[RemoteDebugger.DebugBreakpointCount] = breakpointCount; + _applicationPrivateData[RemoteDebugger.DebugBreakpointCount] = breakpointCount; } else { - this.applicationPrivateData.Add(RemoteDebugger.DebugBreakpointCount, breakpointCount); + _applicationPrivateData.Add(RemoteDebugger.DebugBreakpointCount, breakpointCount); } // Current debugger BreakAll option setting. - bool breakAll = serverRemoteDebugger.IsDebuggerSteppingEnabled; - if (this.applicationPrivateData.ContainsKey(RemoteDebugger.BreakAllSetting)) + bool breakAll = _serverRemoteDebugger.IsDebuggerSteppingEnabled; + if (_applicationPrivateData.ContainsKey(RemoteDebugger.BreakAllSetting)) { - this.applicationPrivateData[RemoteDebugger.BreakAllSetting] = breakAll; + _applicationPrivateData[RemoteDebugger.BreakAllSetting] = breakAll; } else { - this.applicationPrivateData.Add(RemoteDebugger.BreakAllSetting, breakAll); + _applicationPrivateData.Add(RemoteDebugger.BreakAllSetting, breakAll); } // Current debugger PreserveUnhandledBreakpoints setting. - UnhandledBreakpointProcessingMode bpMode = serverRemoteDebugger.UnhandledBreakpointMode; - if (this.applicationPrivateData.ContainsKey(RemoteDebugger.UnhandledBreakpointModeSetting)) + UnhandledBreakpointProcessingMode bpMode = _serverRemoteDebugger.UnhandledBreakpointMode; + if (_applicationPrivateData.ContainsKey(RemoteDebugger.UnhandledBreakpointModeSetting)) { - this.applicationPrivateData[RemoteDebugger.UnhandledBreakpointModeSetting] = (int)bpMode; + _applicationPrivateData[RemoteDebugger.UnhandledBreakpointModeSetting] = (int)bpMode; } else { - this.applicationPrivateData.Add(RemoteDebugger.UnhandledBreakpointModeSetting, (int)bpMode); + _applicationPrivateData.Add(RemoteDebugger.UnhandledBreakpointModeSetting, (int)bpMode); } } - dsHandler.SendApplicationPrivateDataToClient(this.applicationPrivateData, this.serverCapability); + _dsHandler.SendApplicationPrivateDataToClient(_applicationPrivateData, _serverCapability); } /// @@ -405,14 +405,14 @@ namespace System.Management.Automation /// internal void Close() { - if (!isClosed) + if (!_isClosed) { - isClosed = true; + _isClosed = true; - if ((this.remoteHost != null) && (this.remoteHost.IsRunspacePushed)) + if ((_remoteHost != null) && (_remoteHost.IsRunspacePushed)) { - Runspace runspaceToDispose = this.remoteHost.PushedRunspace; - this.remoteHost.PopRunspace(); + Runspace runspaceToDispose = _remoteHost.PushedRunspace; + _remoteHost.PopRunspace(); if (runspaceToDispose != null) { runspaceToDispose.Dispose(); @@ -421,19 +421,19 @@ namespace System.Management.Automation DisposeRemoteDebugger(); - localRunspacePool.Close(); - localRunspacePool.StateChanged -= + _localRunspacePool.Close(); + _localRunspacePool.StateChanged -= new EventHandler(HandleRunspacePoolStateChanged); - localRunspacePool.ForwardEvent -= + _localRunspacePool.ForwardEvent -= new EventHandler(HandleRunspacePoolForwardEvent); - localRunspacePool.Dispose(); - localRunspacePool = null; + _localRunspacePool.Dispose(); + _localRunspacePool = null; - if (rsToUseForSteppablePipeline != null) + if (_rsToUseForSteppablePipeline != null) { - rsToUseForSteppablePipeline.Close(); - rsToUseForSteppablePipeline.Dispose(); - rsToUseForSteppablePipeline = null; + _rsToUseForSteppablePipeline.Close(); + _rsToUseForSteppablePipeline.Dispose(); + _rsToUseForSteppablePipeline = null; } Closed.SafeInvoke(this, EventArgs.Empty); } @@ -450,12 +450,12 @@ namespace System.Management.Automation /// public void EnterNestedPipeline() { - if (driverNestedInvoker == null) + if (_driverNestedInvoker == null) { throw new PSNotSupportedException(RemotingErrorIdStrings.NestedPipelineNotSupported); } - driverNestedInvoker.PushInvoker(); + _driverNestedInvoker.PushInvoker(); } /// @@ -464,12 +464,12 @@ namespace System.Management.Automation /// public void ExitNestedPipeline() { - if (driverNestedInvoker == null) + if (_driverNestedInvoker == null) { throw new PSNotSupportedException(RemotingErrorIdStrings.NestedPipelineNotSupported); } - driverNestedInvoker.PopInvoker(); + _driverNestedInvoker.PopInvoker(); } /// @@ -481,9 +481,9 @@ namespace System.Management.Automation /// public bool HandleStopSignal() { - if (this.serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { - return this.serverRemoteDebugger.HandleStopSignal(); + return _serverRemoteDebugger.HandleStopSignal(); } return false; @@ -501,24 +501,24 @@ namespace System.Management.Automation /// private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEventArgs args) { - this.dsHandler.TypeTable = args.Runspace.ExecutionContext.TypeTable; - this.rsToUseForSteppablePipeline = args.Runspace; + _dsHandler.TypeTable = args.Runspace.ExecutionContext.TypeTable; + _rsToUseForSteppablePipeline = args.Runspace; - SetupRemoteDebugger(this.rsToUseForSteppablePipeline); + SetupRemoteDebugger(_rsToUseForSteppablePipeline); - if (!string.IsNullOrEmpty(this.configurationName)) + if (!string.IsNullOrEmpty(_configurationName)) { // Client is requesting a configured session. // Create a configured remote runspace and push onto host stack. - if ((this.remoteHost != null) && !(this.remoteHost.IsRunspacePushed)) + if ((_remoteHost != null) && !(_remoteHost.IsRunspacePushed)) { // Let exceptions propagate. - RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(this.configurationName, this.remoteHost); + RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(_configurationName, _remoteHost); - this.remoteHost.AllowPushRunspace = true; - this.remoteHost.PropagatePop = true; + _remoteHost.AllowPushRunspace = true; + _remoteHost.PropagatePop = true; - this.remoteHost.PushRunspace(remoteRunspace); + _remoteHost.PushRunspace(remoteRunspace); } } } @@ -528,15 +528,15 @@ namespace System.Management.Automation CmdletInfo cmdletInfo = runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(ServerRemoteDebugger.SetPSBreakCommandText); if (cmdletInfo == null) { - if((runspace.ExecutionContext.LanguageMode != PSLanguageMode.FullLanguage) && - (! runspace.ExecutionContext.UseFullLanguageModeInDebugger)) + if ((runspace.ExecutionContext.LanguageMode != PSLanguageMode.FullLanguage) && + (!runspace.ExecutionContext.UseFullLanguageModeInDebugger)) { return; } } else { - if(cmdletInfo.Visibility != SessionStateEntryVisibility.Public) + if (cmdletInfo.Visibility != SessionStateEntryVisibility.Public) { return; } @@ -544,20 +544,20 @@ namespace System.Management.Automation // Remote debugger is created only when client version is PSVersion (4.0) // or greater, and remote session supports debugging. - if ((driverNestedInvoker != null) && - (clientPSVersion != null && clientPSVersion >= PSVersionInfo.PSV4Version) && + if ((_driverNestedInvoker != null) && + (_clientPSVersion != null && _clientPSVersion >= PSVersionInfo.PSV4Version) && (runspace != null && runspace.Debugger != null)) { - this.serverRemoteDebugger = new ServerRemoteDebugger(this, runspace, runspace.Debugger); - this.remoteHost.ServerDebugger = this.serverRemoteDebugger; + _serverRemoteDebugger = new ServerRemoteDebugger(this, runspace, runspace.Debugger); + _remoteHost.ServerDebugger = _serverRemoteDebugger; } } private void DisposeRemoteDebugger() { - if (serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { - serverRemoteDebugger.Dispose(); + _serverRemoteDebugger.Dispose(); } } @@ -590,20 +590,20 @@ namespace System.Management.Automation Debug.Assert(powershell != null, "powershell shouldn't be null"); // run the startup script on the runspace's host - HostInfo hostInfo = this.remoteHost.HostInfo; + HostInfo hostInfo = _remoteHost.HostInfo; ServerPowerShellDriver driver = new ServerPowerShellDriver( - powershell, + powershell, null, - true, - Guid.Empty, - this.InstanceId, + true, + Guid.Empty, + this.InstanceId, this, #if !CORECLR // No ApartmentState In CoreCLR args.Runspace.ApartmentState, #endif - hostInfo, - RemoteStreamOptions.AddInvocationInfo, - false, + hostInfo, + RemoteStreamOptions.AddInvocationInfo, + false, args.Runspace); IAsyncResult asyncResult = driver.Start(); @@ -694,14 +694,14 @@ namespace System.Management.Automation private void InvokeStartupScripts(RunspaceCreatedEventArgs args) { Command cmdToRun = null; - if (!string.IsNullOrEmpty(configData.StartupScript)) + if (!string.IsNullOrEmpty(_configData.StartupScript)) { // build the startup script..merge output / error. - cmdToRun = new Command(configData.StartupScript, false, false); + cmdToRun = new Command(_configData.StartupScript, false, false); } - else if (!string.IsNullOrEmpty(configData.InitializationScriptForOutOfProcessRunspace)) + else if (!string.IsNullOrEmpty(_configData.InitializationScriptForOutOfProcessRunspace)) { - cmdToRun = new Command(configData.InitializationScriptForOutOfProcessRunspace, true, false); + cmdToRun = new Command(_configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (null != cmdToRun) @@ -710,12 +710,12 @@ namespace System.Management.Automation // if startup script set $PSApplicationPrivateData, then use that value as ApplicationPrivateData // instead of using results from PSSessionConfiguration.GetApplicationPrivateData() - if (localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) + if (_localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object privateDataVariable = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (privateDataVariable != null) { - this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo( + _applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo( privateDataVariable, typeof(PSPrimitiveDictionary), true, @@ -738,23 +738,23 @@ namespace System.Management.Automation RunspacePoolState state = eventArgs.RunspacePoolStateInfo.State; Exception reason = eventArgs.RunspacePoolStateInfo.Reason; - switch(state) + switch (state) { case RunspacePoolState.Broken: case RunspacePoolState.Closing: case RunspacePoolState.Closed: { - dsHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); + _dsHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); } break; case RunspacePoolState.Opened: { SendApplicationPrivateDataToClient(); - dsHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); + _dsHandler.SendStateInfoToClient(new RunspacePoolStateInfo(state, reason)); } break; - } + } } /// @@ -764,7 +764,7 @@ namespace System.Management.Automation { if (e.ForwardEvent) { - dsHandler.SendPSEventArgsToClient(e); + _dsHandler.SendPSEventArgsToClient(e); } } @@ -793,40 +793,40 @@ namespace System.Management.Automation bool isNested = false; // The server would've dropped the protocol version of an older client was connecting - if (this.serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) + if (_serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM) { isNested = RemotingDecoder.GetIsNested(data.Data); } // Perform pre-processing of command for over the wire debugging commands. - if (serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { DebuggerCommandArgument commandArgument; bool terminateImmediate = false; - var result = PreProcessDebuggerCommand(powershell.Commands, serverRemoteDebugger.IsActive, serverRemoteDebugger.IsRemote, out commandArgument); + var result = PreProcessDebuggerCommand(powershell.Commands, _serverRemoteDebugger.IsActive, _serverRemoteDebugger.IsRemote, out commandArgument); switch (result) { case PreProcessCommandResult.SetDebuggerAction: // Run this directly on the debugger and terminate the remote command. - serverRemoteDebugger.SetDebuggerAction(commandArgument.ResumeAction.Value); + _serverRemoteDebugger.SetDebuggerAction(commandArgument.ResumeAction.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetDebugMode: // Set debug mode directly and terminate remote command. - serverRemoteDebugger.SetDebugMode(commandArgument.Mode.Value); + _serverRemoteDebugger.SetDebugMode(commandArgument.Mode.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetDebuggerStepMode: // Enable debugger and set to step action, then terminate remote command. - serverRemoteDebugger.SetDebuggerStepMode(commandArgument.DebuggerStepEnabled.Value); + _serverRemoteDebugger.SetDebuggerStepMode(commandArgument.DebuggerStepEnabled.Value); terminateImmediate = true; break; case PreProcessCommandResult.SetPreserveUnhandledBreakpointMode: - serverRemoteDebugger.UnhandledBreakpointMode = commandArgument.UnhandledBreakpointMode.Value; + _serverRemoteDebugger.UnhandledBreakpointMode = commandArgument.UnhandledBreakpointMode.Value; terminateImmediate = true; break; @@ -840,18 +840,18 @@ namespace System.Management.Automation if (terminateImmediate) { ServerPowerShellDriver noOpDriver = new ServerPowerShellDriver( - powershell, + powershell, null, - noInput, - data.PowerShellId, - data.RunspacePoolId, - this, + noInput, + data.PowerShellId, + data.RunspacePoolId, + this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif - hostInfo, - streamOptions, - addToHistory, + hostInfo, + streamOptions, + addToHistory, null); noOpDriver.RunNoOpCommand(); @@ -859,13 +859,13 @@ namespace System.Management.Automation } } - if (remoteHost.IsRunspacePushed) + if (_remoteHost.IsRunspacePushed) { // If we have a pushed runspace then execute there. // Ensure debugger is enabled to the original mode it was set to. - if (serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { - serverRemoteDebugger.CheckDebuggerState(); + _serverRemoteDebugger.CheckDebuggerState(); } StartPowerShellCommandOnPushedRunspace( @@ -882,11 +882,11 @@ namespace System.Management.Automation } else if (isNested) { - if (localRunspacePool.GetMaxRunspaces() == 1) + if (_localRunspacePool.GetMaxRunspaces() == 1) { - if (driverNestedInvoker != null && driverNestedInvoker.IsActive) + if (_driverNestedInvoker != null && _driverNestedInvoker.IsActive) { - if (driverNestedInvoker.IsAvailable == false) + if (_driverNestedInvoker.IsAvailable == false) { // A nested command is already running. throw new PSInvalidOperationException( @@ -899,30 +899,29 @@ namespace System.Management.Automation // Always invoke PowerShell commands on pipeline worker thread // for single runspace case, to support nested invocation requests (debugging scenario). ServerPowerShellDriver srdriver = new ServerPowerShellDriver( - powershell, + powershell, null, - noInput, - data.PowerShellId, - data.RunspacePoolId, - this, + noInput, + data.PowerShellId, + data.RunspacePoolId, + this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif - hostInfo, - streamOptions, - addToHistory, - rsToUseForSteppablePipeline); + hostInfo, + streamOptions, + addToHistory, + _rsToUseForSteppablePipeline); - inputCollection = srdriver.InputCollection; - driverNestedInvoker.InvokeDriverAsync(srdriver); + _inputCollection = srdriver.InputCollection; + _driverNestedInvoker.InvokeDriverAsync(srdriver); return; } - else if (this.serverRemoteDebugger != null && - this.serverRemoteDebugger.InBreakpoint && - this.serverRemoteDebugger.IsPushed) + else if (_serverRemoteDebugger != null && + _serverRemoteDebugger.InBreakpoint && + _serverRemoteDebugger.IsPushed) { - - this.serverRemoteDebugger.StartPowerShellCommand( + _serverRemoteDebugger.StartPowerShellCommand( powershell, data.PowerShellId, data.RunspacePoolId, @@ -930,7 +929,7 @@ namespace System.Management.Automation #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif - remoteHost, + _remoteHost, hostInfo, streamOptions, addToHistory); @@ -948,27 +947,27 @@ namespace System.Management.Automation throw new PSInvalidOperationException(); } - ServerPowerShellDataStructureHandler psHandler = this.dsHandler.GetPowerShellDataStructureHandler(); + ServerPowerShellDataStructureHandler psHandler = _dsHandler.GetPowerShellDataStructureHandler(); if (psHandler != null) - { + { // Have steppable invocation request. powershell.SetIsNested(false); // Execute command concurrently ServerSteppablePipelineDriver spDriver = new ServerSteppablePipelineDriver( - powershell, + powershell, noInput, - data.PowerShellId, - data.RunspacePoolId, - this, + data.PowerShellId, + data.RunspacePoolId, + this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif hostInfo, - streamOptions, - addToHistory, - rsToUseForSteppablePipeline, - eventSubscriber, - inputCollection); + streamOptions, + addToHistory, + _rsToUseForSteppablePipeline, + _eventSubscriber, + _inputCollection); spDriver.Start(); return; @@ -981,28 +980,28 @@ namespace System.Management.Automation // Invoke command normally. Ensure debugger is enabled to the // original mode it was set to. - if (serverRemoteDebugger != null) + if (_serverRemoteDebugger != null) { - serverRemoteDebugger.CheckDebuggerState(); + _serverRemoteDebugger.CheckDebuggerState(); } // Invoke PowerShell on driver runspace pool. ServerPowerShellDriver driver = new ServerPowerShellDriver( - powershell, + powershell, null, - noInput, - data.PowerShellId, - data.RunspacePoolId, - this, + noInput, + data.PowerShellId, + data.RunspacePoolId, + this, #if !CORECLR // No ApartmentState In CoreCLR apartmentState, #endif - hostInfo, - streamOptions, - addToHistory, + hostInfo, + streamOptions, + addToHistory, null); - inputCollection = driver.InputCollection; + _inputCollection = driver.InputCollection; driver.Start(); } @@ -1083,7 +1082,7 @@ namespace System.Management.Automation HostInfo useRunspaceHost = new HostInfo(null); useRunspaceHost.UseRunspaceHost = true; - if (remoteHost.IsRunspacePushed) + if (_remoteHost.IsRunspacePushed) { // If we have a pushed runspace then execute there. StartPowerShellCommandOnPushedRunspace( @@ -1117,16 +1116,16 @@ namespace System.Management.Automation driver.Start(); } } - + /// /// Handles host responses /// /// sender of this event, unused /// arguments describing this event - private void HandleHostResponseReceived(object sender, + private void HandleHostResponseReceived(object sender, RemoteDataEventArgs eventArgs) { - remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient((eventArgs.Data)); + _remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient((eventArgs.Data)); } /// @@ -1141,8 +1140,8 @@ namespace System.Management.Automation int maxRunspaces = (int)((PSNoteProperty)data.Properties[RemoteDataNameStrings.MaxRunspaces]).Value; long callId = (long)((PSNoteProperty)data.Properties[RemoteDataNameStrings.CallId]).Value; - bool response = localRunspacePool.SetMaxRunspaces(maxRunspaces); - dsHandler.SendResponseToClient(callId, response); + bool response = _localRunspacePool.SetMaxRunspaces(maxRunspaces); + _dsHandler.SendResponseToClient(callId, response); } /// @@ -1157,8 +1156,8 @@ namespace System.Management.Automation int minRunspaces = (int)((PSNoteProperty)data.Properties[RemoteDataNameStrings.MinRunspaces]).Value; long callId = (long)((PSNoteProperty)data.Properties[RemoteDataNameStrings.CallId]).Value; - bool response = localRunspacePool.SetMinRunspaces(minRunspaces); - dsHandler.SendResponseToClient(callId, response); + bool response = _localRunspacePool.SetMinRunspaces(minRunspaces); + _dsHandler.SendResponseToClient(callId, response); } /// @@ -1172,9 +1171,9 @@ namespace System.Management.Automation PSObject data = eventArgs.Data; long callId = (long)((PSNoteProperty)data.Properties[RemoteDataNameStrings.CallId]).Value; - int availableRunspaces = localRunspacePool.GetAvailableRunspaces(); + int availableRunspaces = _localRunspacePool.GetAvailableRunspaces(); - dsHandler.SendResponseToClient(callId, availableRunspaces); + _dsHandler.SendResponseToClient(callId, availableRunspaces); } /// @@ -1187,7 +1186,7 @@ namespace System.Management.Automation long callId = (long)((PSNoteProperty)(eventArgs.Data).Properties[RemoteDataNameStrings.CallId]).Value; bool response = ResetRunspaceState(); - dsHandler.SendResponseToClient(callId, response); + _dsHandler.SendResponseToClient(callId, response); } /// @@ -1196,8 +1195,8 @@ namespace System.Management.Automation /// private bool ResetRunspaceState() { - LocalRunspace runspaceToReset = this.rsToUseForSteppablePipeline as LocalRunspace; - if ((runspaceToReset == null) || (localRunspacePool.GetMaxRunspaces() > 1)) + LocalRunspace runspaceToReset = _rsToUseForSteppablePipeline as LocalRunspace; + if ((runspaceToReset == null) || (_localRunspacePool.GetMaxRunspaces() > 1)) { return false; } @@ -1237,7 +1236,7 @@ namespace System.Management.Automation bool noInput, bool addToHistory) { - Runspace runspace = this.remoteHost.PushedRunspace; + Runspace runspace = _remoteHost.PushedRunspace; ServerPowerShellDriver driver = new ServerPowerShellDriver( powershell, @@ -1263,7 +1262,7 @@ namespace System.Management.Automation CommandProcessorBase.CheckForSevereException(e); // Pop runspace on error. - this.remoteHost.PopRunspace(); + _remoteHost.PopRunspace(); throw; } @@ -2002,7 +2001,7 @@ namespace System.Management.Automation { _wrappedDebugger.Value.UnhandledBreakpointMode = value; if (value == UnhandledBreakpointProcessingMode.Ignore && - this._inDebugMode) + _inDebugMode) { // Release debugger stop hold. ExitDebugMode(DebuggerResumeAction.Continue); @@ -2097,7 +2096,7 @@ namespace System.Management.Automation // Get impersonation information to flow if any. WindowsIdentity currentIdentity = null; try - { + { currentIdentity = WindowsIdentity.GetCurrent(); } catch (System.Security.SecurityException) { } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs index ded069b35..68fd7e953 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs @@ -1,6 +1,7 @@ /********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ + using System; using System.Threading; using System.Collections.Generic; @@ -19,14 +20,14 @@ namespace System.Management.Automation /// internal class ExecutionContextForStepping : IDisposable { - private ExecutionContext executionContext; - private PSInformationalBuffers originalInformationalBuffers; - private PSHost originalHost; + private ExecutionContext _executionContext; + private PSInformationalBuffers _originalInformationalBuffers; + private PSHost _originalHost; private ExecutionContextForStepping(ExecutionContext ctxt) { Dbg.Assert(ctxt != null, "ExecutionContext cannot be null."); - executionContext = ctxt; + _executionContext = ctxt; } internal static ExecutionContextForStepping PrepareExecutionContext( @@ -36,9 +37,9 @@ namespace System.Management.Automation { ExecutionContextForStepping result = new ExecutionContextForStepping(ctxt); - result.originalInformationalBuffers + result._originalInformationalBuffers = ctxt.InternalHost.InternalUI.GetInformationalMessageBuffers(); - result.originalHost = ctxt.InternalHost.ExternalHost; + result._originalHost = ctxt.InternalHost.ExternalHost; ctxt.InternalHost. InternalUI.SetInformationalMessageBuffers(newBuffers); @@ -52,11 +53,11 @@ namespace System.Management.Automation // resetting unmanaged resources. void IDisposable.Dispose() { - executionContext.InternalHost. - InternalUI.SetInformationalMessageBuffers(originalInformationalBuffers); - executionContext.InternalHost.SetHostRef(originalHost); + _executionContext.InternalHost. + InternalUI.SetInformationalMessageBuffers(_originalInformationalBuffers); + _executionContext.InternalHost.SetHostRef(_originalHost); GC.SuppressFinalize(this); - } + } } /// @@ -67,40 +68,40 @@ namespace System.Management.Automation { #region Private Data - private PowerShell localPowerShell; - private Guid clientPowerShellId; // the client PowerShell's guid + private PowerShell _localPowerShell; + private Guid _clientPowerShellId; // the client PowerShell's guid // that is associated with this // powershell driver - private Guid clientRunspacePoolId; // the id of the client runspace pool + private Guid _clientRunspacePoolId; // the id of the client runspace pool // associated with this powershell - private ServerPowerShellDataStructureHandler dsHandler; + private ServerPowerShellDataStructureHandler _dsHandler; // data structure handler object to handle all // communications with the client - private PSDataCollection input; // input for local powershell invocation - private IEnumerator inputEnumerator; + private PSDataCollection _input; // input for local powershell invocation + private IEnumerator _inputEnumerator; //private bool datasent = false; // if the remaining data has been sent // to the client before sending state // information - private object syncObject = new object(); // sync object for synchronizing sending + private object _syncObject = new object(); // sync object for synchronizing sending // data to client - private bool noInput; // there is no input when this driver + private bool _noInput; // there is no input when this driver // was created - private bool addToHistory; - private ServerRemoteHost remoteHost; // the server remote host instance - // associated with this powershell - #if !CORECLR // No ApartmentState In CoreCLR + private bool _addToHistory; + private ServerRemoteHost _remoteHost; // the server remote host instance + // associated with this powershell +#if !CORECLR // No ApartmentState In CoreCLR private ApartmentState apartmentState; // apartment state for this powershell #endif - private RemoteStreamOptions remoteStreamOptions; // serialization options for the streams in this powershell + private RemoteStreamOptions _remoteStreamOptions; // serialization options for the streams in this powershell - private int totalObjectsProcessedSoFar; + private int _totalObjectsProcessedSoFar; // pipeline that runs the actual command. - private SteppablePipeline steppablePipeline; - private bool isProcessingInput; - private bool isPulsed; - private PSInvocationState stateOfSteppablePipeline; - private ServerSteppablePipelineSubscriber eventSubscriber; - private PSDataCollection powershellInput; // input collection of the PowerShell pipeline + private SteppablePipeline _steppablePipeline; + private bool _isProcessingInput; + private bool _isPulsed; + private PSInvocationState _stateOfSteppablePipeline; + private ServerSteppablePipelineSubscriber _eventSubscriber; + private PSDataCollection _powershellInput; // input collection of the PowerShell pipeline #endregion @@ -129,7 +130,7 @@ namespace System.Management.Automation /// Steppable pipeline event subscriber /// /// input collection of the PowerShell pipeline - internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, + internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection powershellInput) @@ -165,32 +166,32 @@ namespace System.Management.Automation bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection powershellInput) #endif { - this.localPowerShell = powershell; - this.clientPowerShellId = clientPowerShellId; - this.clientRunspacePoolId = clientRunspacePoolId; - this.remoteStreamOptions = streamOptions; + _localPowerShell = powershell; + _clientPowerShellId = clientPowerShellId; + _clientRunspacePoolId = clientRunspacePoolId; + _remoteStreamOptions = streamOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = apartmentState; #endif - this.noInput = noInput; - this.addToHistory = addToHistory; - this.eventSubscriber = eventSubscriber; - this.powershellInput = powershellInput; + _noInput = noInput; + _addToHistory = addToHistory; + _eventSubscriber = eventSubscriber; + _powershellInput = powershellInput; - input = new PSDataCollection(); - inputEnumerator = input.GetEnumerator(); - input.ReleaseOnEnumeration = true; + _input = new PSDataCollection(); + _inputEnumerator = _input.GetEnumerator(); + _input.ReleaseOnEnumeration = true; - this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, remoteStreamOptions, null); - this.remoteHost = dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); + _dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, _remoteStreamOptions, null); + _remoteHost = _dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); // subscribe to various data structure handler events - dsHandler.InputEndReceived += new EventHandler(HandleInputEndReceived); - dsHandler.InputReceived += new EventHandler>(HandleInputReceived); - dsHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived); - dsHandler.HostResponseReceived += + _dsHandler.InputEndReceived += new EventHandler(HandleInputEndReceived); + _dsHandler.InputReceived += new EventHandler>(HandleInputReceived); + _dsHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived); + _dsHandler.HostResponseReceived += new EventHandler>(HandleHostResponseReceived); - dsHandler.OnSessionConnected +=new EventHandler(HandleSessionConnected); + _dsHandler.OnSessionConnected += new EventHandler(HandleSessionConnected); if (rsToUse == null) { @@ -198,10 +199,10 @@ namespace System.Management.Automation } // else, set the runspace pool and invoke this powershell - localPowerShell.Runspace = rsToUse; + _localPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); - stateOfSteppablePipeline = PSInvocationState.NotStarted; + _stateOfSteppablePipeline = PSInvocationState.NotStarted; } #region Internal Methods @@ -211,7 +212,7 @@ namespace System.Management.Automation /// internal PowerShell LocalPowerShell { - get { return localPowerShell; } + get { return _localPowerShell; } } /// @@ -221,7 +222,7 @@ namespace System.Management.Automation /// internal Guid InstanceId { - get { return clientPowerShellId; } + get { return _clientPowerShellId; } } /// @@ -229,7 +230,7 @@ namespace System.Management.Automation /// internal ServerRemoteHost RemoteHost { - get { return remoteHost; } + get { return _remoteHost; } } /// @@ -237,7 +238,7 @@ namespace System.Management.Automation /// internal RemoteStreamOptions RemoteStreamOptions { - get { return this.remoteStreamOptions; } + get { return _remoteStreamOptions; } } /// @@ -249,7 +250,7 @@ namespace System.Management.Automation /// internal Guid RunspacePoolId { - get { return clientRunspacePoolId; } + get { return _clientRunspacePoolId; } } /// @@ -258,7 +259,7 @@ namespace System.Management.Automation /// internal ServerPowerShellDataStructureHandler DataStructureHandler { - get { return dsHandler; } + get { return _dsHandler; } } /// @@ -266,7 +267,7 @@ namespace System.Management.Automation /// internal PSInvocationState PipelineState { - get { return stateOfSteppablePipeline; } + get { return _stateOfSteppablePipeline; } } /// @@ -274,7 +275,7 @@ namespace System.Management.Automation /// internal bool NoInput { - get { return noInput; } + get { return _noInput; } } /// @@ -282,8 +283,8 @@ namespace System.Management.Automation /// internal SteppablePipeline SteppablePipeline { - get { return steppablePipeline; } - set { steppablePipeline = value; } + get { return _steppablePipeline; } + set { _steppablePipeline = value; } } /// @@ -291,7 +292,7 @@ namespace System.Management.Automation /// internal object SyncObject { - get { return syncObject; } + get { return _syncObject; } } /// @@ -299,8 +300,8 @@ namespace System.Management.Automation /// internal bool ProcessingInput { - get { return isProcessingInput; } - set { isProcessingInput = value; } + get { return _isProcessingInput; } + set { _isProcessingInput = value; } } /// @@ -308,7 +309,7 @@ namespace System.Management.Automation /// internal IEnumerator InputEnumerator { - get { return inputEnumerator; } + get { return _inputEnumerator; } } /// @@ -316,7 +317,7 @@ namespace System.Management.Automation /// internal PSDataCollection Input { - get { return input; } + get { return _input; } } /// @@ -324,8 +325,8 @@ namespace System.Management.Automation /// internal bool Pulsed { - get { return isPulsed; } - set { isPulsed = value; } + get { return _isPulsed; } + set { _isPulsed = value; } } /// @@ -333,8 +334,8 @@ namespace System.Management.Automation /// internal int TotalObjectsProcessed { - get { return totalObjectsProcessedSoFar; } - set { totalObjectsProcessedSoFar = value; } + get { return _totalObjectsProcessedSoFar; } + set { _totalObjectsProcessedSoFar = value; } } /// @@ -342,13 +343,13 @@ namespace System.Management.Automation /// internal void Start() { - stateOfSteppablePipeline = PSInvocationState.Running; + _stateOfSteppablePipeline = PSInvocationState.Running; - eventSubscriber.FireStartSteppablePipeline(this); + _eventSubscriber.FireStartSteppablePipeline(this); - if (powershellInput != null) + if (_powershellInput != null) { - powershellInput.Pulse(); + _powershellInput.Pulse(); } } @@ -363,13 +364,13 @@ namespace System.Management.Automation /// arguments describing this event internal void HandleInputEndReceived(object sender, EventArgs eventArgs) { - input.Complete(); + _input.Complete(); CheckAndPulseForProcessing(true); - if (powershellInput != null) + if (_powershellInput != null) { - powershellInput.Pulse(); + _powershellInput.Pulse(); } } @@ -377,9 +378,9 @@ namespace System.Management.Automation { //Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (input != null) + if (_input != null) { - input.Complete(); + _input.Complete(); } } @@ -390,7 +391,7 @@ namespace System.Management.Automation /// arguments describing this event internal void HandleHostResponseReceived(object sender, RemoteDataEventArgs eventArgs) { - remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data); + _remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data); } /// @@ -400,16 +401,16 @@ namespace System.Management.Automation /// unused private void HandleStopReceived(object sender, EventArgs eventArgs) { - lock (syncObject) + lock (_syncObject) { - stateOfSteppablePipeline = PSInvocationState.Stopping; + _stateOfSteppablePipeline = PSInvocationState.Stopping; } PerformStop(); - if (powershellInput != null) + if (_powershellInput != null) { - powershellInput.Pulse(); + _powershellInput.Pulse(); } } @@ -420,19 +421,19 @@ namespace System.Management.Automation /// arguments describing this event private void HandleInputReceived(object sender, RemoteDataEventArgs eventArgs) { - Dbg.Assert(!noInput, "Input data should not be received for powershells created with no input"); + Dbg.Assert(!_noInput, "Input data should not be received for powershells created with no input"); - if (input != null) + if (_input != null) { - lock (syncObject) + lock (_syncObject) { - input.Add(eventArgs.Data); + _input.Add(eventArgs.Data); } CheckAndPulseForProcessing(false); - if (powershellInput != null) + if (_powershellInput != null) { - powershellInput.Pulse(); + _powershellInput.Pulse(); } } } @@ -447,28 +448,28 @@ namespace System.Management.Automation { if (complete) { - eventSubscriber.FireHandleProcessRecord(this); + _eventSubscriber.FireHandleProcessRecord(this); } - else if (!isPulsed) + else if (!_isPulsed) { bool shouldPulse = false; - lock (syncObject) + lock (_syncObject) { - if (isPulsed) + if (_isPulsed) { return; } - if (!isProcessingInput && ((input.Count > totalObjectsProcessedSoFar))) + if (!_isProcessingInput && ((_input.Count > _totalObjectsProcessedSoFar))) { shouldPulse = true; - isPulsed = true; + _isPulsed = true; } } - if (shouldPulse && (stateOfSteppablePipeline == PSInvocationState.Running)) + if (shouldPulse && (_stateOfSteppablePipeline == PSInvocationState.Running)) { - eventSubscriber.FireHandleProcessRecord(this); + _eventSubscriber.FireHandleProcessRecord(this); } } } @@ -479,12 +480,12 @@ namespace System.Management.Automation internal void PerformStop() { bool shouldPerformStop = false; - lock (syncObject) + lock (_syncObject) { - if (!isProcessingInput && (stateOfSteppablePipeline == PSInvocationState.Stopping)) + if (!_isProcessingInput && (_stateOfSteppablePipeline == PSInvocationState.Stopping)) { shouldPerformStop = true; - } + } } if (shouldPerformStop) @@ -502,9 +503,9 @@ namespace System.Management.Automation { PSInvocationState copyState = PSInvocationState.NotStarted; bool shoulRaiseEvents = false; - lock (syncObject) + lock (_syncObject) { - switch (stateOfSteppablePipeline) + switch (_stateOfSteppablePipeline) { case PSInvocationState.NotStarted: { @@ -569,22 +570,22 @@ namespace System.Management.Automation break; } - stateOfSteppablePipeline = copyState; + _stateOfSteppablePipeline = copyState; } if (shoulRaiseEvents) { // send the state change notification to the client - dsHandler.SendStateChangedInformationToClient( + _dsHandler.SendStateChangedInformationToClient( new PSInvocationStateInfo(copyState, reason)); } - if (stateOfSteppablePipeline == PSInvocationState.Completed - || stateOfSteppablePipeline == PSInvocationState.Stopped - || stateOfSteppablePipeline == PSInvocationState.Failed) + if (_stateOfSteppablePipeline == PSInvocationState.Completed + || _stateOfSteppablePipeline == PSInvocationState.Stopped + || _stateOfSteppablePipeline == PSInvocationState.Failed) { // Remove itself from the runspace pool - dsHandler.RaiseRemoveAssociationEvent(); + _dsHandler.RaiseRemoveAssociationEvent(); } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 923e659e1..4adbd64f2 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -1,6 +1,7 @@ /********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ + using System; using System.Threading; using System.Collections.Generic; @@ -39,31 +40,31 @@ namespace System.Management.Automation { #region Private data - private object syncObject = new object(); - private bool initialized = false; - private PSLocalEventManager eventManager; - private PSEventSubscriber startSubscriber; - private PSEventSubscriber processSubscriber; + private object _syncObject = new object(); + private bool _initialized = false; + private PSLocalEventManager _eventManager; + private PSEventSubscriber _startSubscriber; + private PSEventSubscriber _processSubscriber; #endregion internal void SubscribeEvents(ServerSteppablePipelineDriver driver) { - lock (syncObject) + lock (_syncObject) { - if (!initialized) + if (!_initialized) { - eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager; + _eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager; - if (eventManager != null) + if (_eventManager != null) { - startSubscriber = eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null, + _startSubscriber = _eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true); - processSubscriber = eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null, + _processSubscriber = _eventManager.SubscribeEvent(this, "RunProcessRecord", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleProcessRecord), true, false, true); } - initialized = true; + _initialized = true; } } } @@ -280,12 +281,12 @@ namespace System.Management.Automation /// steppable pipeline driver internal void FireStartSteppablePipeline(ServerSteppablePipelineDriver driver) { - lock (syncObject) + lock (_syncObject) { - if (eventManager != null) + if (_eventManager != null) { - eventManager.GenerateEvent(startSubscriber.SourceIdentifier, this, - new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); + _eventManager.GenerateEvent(_startSubscriber.SourceIdentifier, this, + new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); } } } @@ -296,11 +297,11 @@ namespace System.Management.Automation /// steppable pipeline driver internal void FireHandleProcessRecord(ServerSteppablePipelineDriver driver) { - lock (syncObject) + lock (_syncObject) { - if (eventManager != null) + if (_eventManager != null) { - eventManager.GenerateEvent(processSubscriber.SourceIdentifier, this, + _eventManager.GenerateEvent(_processSubscriber.SourceIdentifier, this, new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); } } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 7fd08b9ec..307d333c4 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -39,7 +39,7 @@ namespace System.Management.Automation.Remoting { private RemoteSessionCapability _clientCapability; private RemoteSessionCapability _serverCapability; - private bool isNegotiationSucceeded; + private bool _isNegotiationSucceeded; #region Constructors @@ -90,8 +90,8 @@ namespace System.Management.Automation.Remoting /// internal bool IsNegotiationSucceeded { - get { return isNegotiationSucceeded; } - set { isNegotiationSucceeded = value; } + get { return _isNegotiationSucceeded; } + set { _isNegotiationSucceeded = value; } } } @@ -109,7 +109,7 @@ namespace System.Management.Automation.Remoting internal class ServerRemoteSession : RemoteSession { [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); private ServerRemoteSessionContext _context; private ServerRemoteSessionDataStructureHandler _sessionDSHandler; @@ -120,8 +120,8 @@ namespace System.Management.Automation.Remoting private PSSessionConfiguration _sessionConfigProvider; // used to apply quotas on command and session transportmanagers. - private Nullable maxRecvdObjectSize; - private Nullable maxRecvdDataSizeCommand; + private Nullable _maxRecvdObjectSize; + private Nullable _maxRecvdDataSizeCommand; private ServerRunspacePoolDriver _runspacePoolDriver; private PSRemotingCryptoHelperServer _cryptoHelper; @@ -172,8 +172,8 @@ namespace System.Management.Automation.Remoting _initParameters = initializationParameters; if (Platform.IsWindows) { - _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; - _cryptoHelper.Session = this; + _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; + _cryptoHelper.Session = this; } _context = new ServerRemoteSessionContext(); @@ -182,13 +182,13 @@ namespace System.Management.Automation.Remoting _sessionDSHandler.CreateRunspacePoolReceived += HandleCreateRunspacePool; _sessionDSHandler.NegotiationReceived += HandleNegotiationReceived; _sessionDSHandler.SessionClosing += HandleSessionDSHandlerClosing; - _sessionDSHandler.PublicKeyReceived += - new EventHandler>(HandlePublicKeyReceived); + _sessionDSHandler.PublicKeyReceived += + new EventHandler>(HandlePublicKeyReceived); transportManager.Closing += HandleResourceClosing; // update the quotas from sessionState..start with default size..and // when Custom Session Configuration is loaded (during runsapce creation) update this. - transportManager.ReceivedDataCollection.MaximumReceivedObjectSize = + transportManager.ReceivedDataCollection.MaximumReceivedObjectSize = BaseTransportManager.MaximumReceivedObjectSize; // session transport manager can recieve unlimited data..however each object is limited @@ -234,10 +234,10 @@ namespace System.Management.Automation.Remoting AbstractServerSessionTransportManager transportManager, string configurationName = null) { - Dbg.Assert((senderInfo != null) & (senderInfo.UserInfo != null), + Dbg.Assert((senderInfo != null) & (senderInfo.UserInfo != null), "senderInfo and userInfo cannot be null."); - - _trace.WriteLine("Finding InitialSessionState provider for id : {0}", configurationProviderId); + + s_trace.WriteLine("Finding InitialSessionState provider for id : {0}", configurationProviderId); if (string.IsNullOrEmpty(configurationProviderId)) { @@ -251,7 +251,7 @@ namespace System.Management.Automation.Remoting { _configurationName = configurationName }; - + // start state machine. RemoteSessionStateMachineEventArgs startEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession); result._sessionDSHandler.StateMachine.RaiseEvent(startEventArg); @@ -272,7 +272,7 @@ namespace System.Management.Automation.Remoting AbstractServerSessionTransportManager transportManager, string configurationName) { - ServerRemoteSession result = CreateServerRemoteSession(senderInfo, + ServerRemoteSession result = CreateServerRemoteSession(senderInfo, "Microsoft.PowerShell", "", transportManager, configurationName); result._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace; return result; @@ -378,7 +378,7 @@ namespace System.Management.Automation.Remoting case RemotingDataType.SessionCapability: _sessionDSHandler.RaiseDataReceivedEvent(dataEventArg); break; - + case RemotingDataType.PublicKey: _sessionDSHandler.RaiseDataReceivedEvent(dataEventArg); break; @@ -387,7 +387,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(false, "Should never reach here"); break; } - } + } break; // TODO: Directly calling an event handler in StateMachine bypassing the StateMachine's @@ -453,7 +453,7 @@ namespace System.Management.Automation.Remoting // send using data structure handler SessionDataStructureHandler.SendRequestForPublicKey(); - RemoteSessionStateMachineEventArgs eventArgs = + RemoteSessionStateMachineEventArgs eventArgs = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyRequested); SessionDataStructureHandler.StateMachine.RaiseEvent(eventArgs); } @@ -573,7 +573,7 @@ namespace System.Management.Automation.Remoting long fragmentId = FragmentedRemoteObject.GetFragmentId(connectData, 0); bool sFlag = FragmentedRemoteObject.GetIsStartFragment(connectData, 0); bool eFlag = FragmentedRemoteObject.GetIsEndFragment(connectData, 0); - int blobLength = FragmentedRemoteObject.GetBlobLength(connectData, 0); + int blobLength = FragmentedRemoteObject.GetBlobLength(connectData, 0); if (blobLength > totalDataLen - FragmentedRemoteObject.HeaderLength) { @@ -684,7 +684,7 @@ namespace System.Management.Automation.Remoting try { clientRequestedMinRunspaces = RemotingDecoder.GetMinRunspaces(connectRunspacePoolObject.Data); - clientRequestedMaxRunspaces = RemotingDecoder.GetMaxRunspaces(connectRunspacePoolObject.Data); + clientRequestedMaxRunspaces = RemotingDecoder.GetMaxRunspaces(connectRunspacePoolObject.Data); clientRequestedRunspaceCount = true; } catch (PSRemotingDataStructureException) @@ -716,7 +716,7 @@ namespace System.Management.Automation.Remoting //setMax or setMinrunspacees request. //TODO: resolve this race.. probably by letting the runspace pool consume all messages before we execute this. if (clientRequestedRunspaceCount - && (_runspacePoolDriver.RunspacePool.GetMaxRunspaces() != clientRequestedMaxRunspaces) + && (_runspacePoolDriver.RunspacePool.GetMaxRunspaces() != clientRequestedMaxRunspaces) && (_runspacePoolDriver.RunspacePool.GetMinRunspaces() != clientRequestedMinRunspaces)) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnMismatchedRunspacePoolProperties); @@ -728,12 +728,12 @@ namespace System.Management.Automation.Remoting RemoteDataObject runspacepoolInitData = RemotingEncoder.GenerateRunspacePoolInitData(_runspacePoolDriver.InstanceId, _runspacePoolDriver.RunspacePool.GetMaxRunspaces(), _runspacePoolDriver.RunspacePool.GetMinRunspaces()); - + //having this stream operating separately will result in out of sync fragment Ids. but this is still OK //as this is executed only when connecting from a new client that does not have any previous fragments context. //no problem even if fragment Ids in this respose and the sessiontransport stream clash (interfere) and its guaranteed // that the fragments in connect response are always complete (enclose a complete object). - SerializedDataStream stream = new SerializedDataStream(4*1024);//Each message with fragment headers cannot cross 4k + SerializedDataStream stream = new SerializedDataStream(4 * 1024);//Each message with fragment headers cannot cross 4k stream.Enter(); capability.Serialize(stream, fragmentor); stream.Exit(); @@ -749,7 +749,7 @@ namespace System.Management.Automation.Remoting //enque a connect event in state machine to let session do any other post-connect operation // Do this outside of the sychronous connect operation, as otherwise connect can easily get deadlocked ThreadPool.QueueUserWorkItem(new WaitCallback( - delegate(object state) + delegate (object state) { RemoteSessionStateMachineEventArgs startEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ConnectSession); _sessionDSHandler.StateMachine.RaiseEvent(startEventArg); @@ -765,7 +765,7 @@ namespace System.Management.Automation.Remoting if (_runspacePoolDriver != null) { _runspacePoolDriver.SendApplicationPrivateDataToClient(); - } + } } /// @@ -806,8 +806,8 @@ namespace System.Management.Automation.Remoting configurationData.InitializationScriptForOutOfProcessRunspace = _initScriptForOutOfProcRS; // start with data from configuration XML and then override with data // from EndPointConfiguration type. - maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB; - maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB; + _maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB; + _maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB; DISCPowerShellConfiguration discProvider = null; @@ -860,7 +860,7 @@ namespace System.Management.Automation.Remoting new SessionStateVariableEntry(RemoteDataNameStrings.SenderInfoPreferenceVariable, _senderInfo, Remoting.PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.PSSenderInfoDescription), + RemotingErrorIdStrings.PSSenderInfoDescription), ScopedItemOptions.ReadOnly)); // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion @@ -894,10 +894,10 @@ namespace System.Management.Automation.Remoting if (!string.IsNullOrEmpty(configurationData.EndPointConfigurationTypeName)) { // user specified a type to load for configuration..use the values from this type. - maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo); - maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo); + _maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo); + _maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo); } - _sessionDSHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = maxRecvdObjectSize; + _sessionDSHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; // MaximumReceivedDataSize is not set for session transport manager...see the constructor // for more info. @@ -915,19 +915,19 @@ namespace System.Management.Automation.Remoting throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists, _runspacePoolDriver.InstanceId); } - + bool isAdministrator = _senderInfo.UserInfo.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); ServerRunspacePoolDriver tmpDriver = new ServerRunspacePoolDriver( clientRunspacePoolId, - minRunspaces, - maxRunspaces, - threadOptions, + minRunspaces, + maxRunspaces, + threadOptions, #if !CORECLR // No ApartmentState In CoreCLR - apartmentState, + apartmentState, #endif - hostInfo, - rsSessionStateToUse, + hostInfo, + rsSessionStateToUse, applicationPrivateData, configurationData, this.SessionDataStructureHandler.TransportManager, @@ -970,13 +970,13 @@ namespace System.Management.Automation.Remoting // Send server's capability to client. RemoteSessionStateMachineEventArgs sendingNegotiationArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); _sessionDSHandler.StateMachine.RaiseEvent(sendingNegotiationArg); - + // if negotiation succeeded change the state to neg. completed. RemoteSessionStateMachineEventArgs negotiationCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationCompleted); _sessionDSHandler.StateMachine.RaiseEvent(negotiationCompletedArg); } - catch(PSRemotingDataStructureException dse) + catch (PSRemotingDataStructureException dse) { // Before setting to negotiation failed..send servers capability...that // way client can communicate differently if it wants to. @@ -984,8 +984,8 @@ namespace System.Management.Automation.Remoting new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); _sessionDSHandler.StateMachine.RaiseEvent(sendingNegotiationArg); - RemoteSessionStateMachineEventArgs negotiationFailedArg = - new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationFailed, + RemoteSessionStateMachineEventArgs negotiationFailedArg = + new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationFailed, dse); _sessionDSHandler.StateMachine.RaiseEvent(negotiationFailedArg); } @@ -1204,8 +1204,8 @@ namespace System.Management.Automation.Remoting internal void ApplyQuotaOnCommandTransportManager(AbstractServerTransportManager cmdTransportManager) { Dbg.Assert(null != cmdTransportManager, "cmdTransportManager cannot be null"); - cmdTransportManager.ReceivedDataCollection.MaximumReceivedDataSize = maxRecvdDataSizeCommand; - cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = maxRecvdObjectSize; + cmdTransportManager.ReceivedDataCollection.MaximumReceivedDataSize = _maxRecvdDataSizeCommand; + cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index e64a1cfab..2c625d2e7 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -35,11 +35,11 @@ namespace System.Management.Automation.Remoting internal class ServerRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")] - static private PSTraceSource _trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); + static private PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); private ServerRemoteSession _session; private object _syncObject; - private Queue processPendingEventsQueue + private Queue _processPendingEventsQueue = new Queue(); // whether some thread is actively processing events // in a loop. If this is set then other threads @@ -47,8 +47,8 @@ namespace System.Management.Automation.Remoting // at processing the events in the queue. This will // guarantee that events will always be serialized // and processed - private bool eventsInProcess = false; - + private bool _eventsInProcess = false; + private EventHandler[,] _stateMachineHandle; private RemoteSessionState _state; @@ -82,7 +82,7 @@ namespace System.Management.Automation.Remoting _syncObject = new object(); _stateMachineHandle = new EventHandler[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; - + for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { _stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatalError; @@ -90,34 +90,34 @@ namespace System.Management.Automation.Remoting _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += DoCloseFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += DoCloseCompleted; - + _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += DoNegotiationTimeout; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += DoSendFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += DoReceiveFailed; - _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect; + _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect; } _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[(int)RemoteSessionState.NegotiationPending, (int)RemoteSessionEvent.NegotiationReceived] += DoNegotiationReceived; - _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; + _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += DoNegotiationCompleted; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationCompleted] += DoEstablished; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationPending] += DoNegotiationPending; - + _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.MessageReceived] += DoMessageReceived; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += DoNegotiationFailed; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += DoConnectFailed; - _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange ; // + _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // @@ -130,7 +130,7 @@ namespace System.Management.Automation.Remoting _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // - + for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) @@ -201,14 +201,14 @@ namespace System.Management.Automation.Remoting // make sure only one thread is processing events. lock (_syncObject) { - _trace.WriteLine("Event received : {0}", fsmEventArg.StateEvent); - processPendingEventsQueue.Enqueue(fsmEventArg); + s_trace.WriteLine("Event received : {0}", fsmEventArg.StateEvent); + _processPendingEventsQueue.Enqueue(fsmEventArg); - if (eventsInProcess) + if (_eventsInProcess) { - return; + return; } - eventsInProcess = true; + _eventsInProcess = true; } ProcessEvents(); @@ -233,17 +233,16 @@ namespace System.Management.Automation.Remoting { lock (_syncObject) { - if (processPendingEventsQueue.Count == 0) + if (_processPendingEventsQueue.Count == 0) { - eventsInProcess = false; + _eventsInProcess = false; break; } - eventArgs = processPendingEventsQueue.Dequeue(); + eventArgs = _processPendingEventsQueue.Dequeue(); } RaiseEventPrivate(eventArgs); - - } while (eventsInProcess); + } while (_eventsInProcess); } /// @@ -269,11 +268,11 @@ namespace System.Management.Automation.Remoting EventHandler handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent]; if (handler != null) { - _trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); + s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); handler(this, fsmEventArg); - _trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); + s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); } } @@ -294,7 +293,7 @@ namespace System.Management.Automation.Remoting /// private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -304,10 +303,10 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CreateSession, "StateEvent must be CreateSession"); Dbg.Assert(_state == RemoteSessionState.Idle, "DoCreateSession cannot only be called in Idle state"); - DoNegotiationPending(sender, fsmEventArg); + DoNegotiationPending(sender, fsmEventArg); } } - + /// /// This is the handler for NegotiationPending event. /// NegotiationPending state can be in reached in the following cases @@ -323,7 +322,7 @@ namespace System.Management.Automation.Remoting /// private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -353,10 +352,10 @@ namespace System.Management.Automation.Remoting /// If the parameter is not NegotiationReceived event or it does not hold the /// client negotiation packet. /// - + private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -366,7 +365,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived"); Dbg.Assert(fsmEventArg.RemoteSessionCapability != null, "RemoteSessioncapability must be non-null"); Dbg.Assert(_state == RemoteSessionState.NegotiationPending, "state must be in NegotiationPending state"); - + if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived) { throw PSTraceSource.NewArgumentException("fsmEventArg"); @@ -376,7 +375,7 @@ namespace System.Management.Automation.Remoting { throw PSTraceSource.NewArgumentException("fsmEventArg"); } - + SetState(RemoteSessionState.NegotiationReceived, null); } } @@ -394,7 +393,7 @@ namespace System.Management.Automation.Remoting /// /// If the parameter is null. /// - + private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { if (fsmEventArg == null) @@ -422,10 +421,10 @@ namespace System.Management.Automation.Remoting /// /// If the parameter is null. /// - + private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -451,10 +450,10 @@ namespace System.Management.Automation.Remoting /// /// If the parameter is null. /// - + private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -475,7 +474,7 @@ namespace System.Management.Automation.Remoting } SetState(RemoteSessionState.Established, null); - } + } } /// @@ -495,7 +494,7 @@ namespace System.Management.Automation.Remoting /// internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -552,7 +551,7 @@ namespace System.Management.Automation.Remoting } else { - _trace.WriteLine(@"Server received data for Runspace (id: {0}), + s_trace.WriteLine(@"Server received data for Runspace (id: {0}), but the Runspace cannot be found", clientRunspacePoolId); PSRemotingDataStructureException reasonOfFailure = new @@ -572,13 +571,13 @@ namespace System.Management.Automation.Remoting break; default: - _trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface); + s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface); PSRemotingDataStructureException reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface); RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2); RaiseEvent(unknownTargetArg); break; - } + } } } @@ -600,7 +599,7 @@ namespace System.Management.Automation.Remoting /// private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -639,7 +638,7 @@ namespace System.Management.Automation.Remoting /// private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -685,13 +684,13 @@ namespace System.Management.Automation.Remoting /// private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } - + RemoteSessionState oldState = _state; switch (oldState) @@ -719,9 +718,9 @@ namespace System.Management.Automation.Remoting default: Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed); SetState(RemoteSessionState.Closed, forcedCloseException); - break; + break; } - + CleanAll(); } } @@ -740,7 +739,7 @@ namespace System.Management.Automation.Remoting /// private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -771,7 +770,7 @@ namespace System.Management.Automation.Remoting /// private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -802,7 +801,7 @@ namespace System.Management.Automation.Remoting /// private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -812,7 +811,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationFailed, "StateEvent must be NegotiationFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); - + RaiseEventPrivate(closeArg); } } @@ -832,7 +831,7 @@ namespace System.Management.Automation.Remoting /// private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -848,7 +847,7 @@ namespace System.Management.Automation.Remoting } RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); - + RaiseEventPrivate(closeArg); } } @@ -868,7 +867,7 @@ namespace System.Management.Automation.Remoting /// private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -878,7 +877,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.SendFailed, "StateEvent must be SendFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); - + RaiseEventPrivate(closeArg); } } @@ -898,7 +897,7 @@ namespace System.Management.Automation.Remoting /// private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - using (_trace.TraceEventHandlers()) + using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { @@ -908,7 +907,7 @@ namespace System.Management.Automation.Remoting Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ReceiveFailed, "StateEvent must be ReceivedFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); - + RaiseEventPrivate(closeArg); } } @@ -921,7 +920,6 @@ namespace System.Management.Automation.Remoting /// event args private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eventArgs) { - //There are corner cases with disconnect that can result in client receiving outdated key exchange packets //***TODO*** Deal with this on the client side. Key exchange packets should have additional information //that identify the context of negotiation. Just like callId in SetMax and SetMinRunspaces messages @@ -932,7 +930,6 @@ namespace System.Management.Automation.Remoting { case RemoteSessionEvent.KeyReceived: { - //does the server ever start key exchange process??? This may not be required if (_state == RemoteSessionState.EstablishedAndKeyRequested) { @@ -942,7 +939,6 @@ namespace System.Management.Automation.Remoting { tmp.Dispose(); } - } // the key import would have been done @@ -1014,7 +1010,6 @@ namespace System.Management.Automation.Remoting new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerKeyExchangeFailed); RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception)); - } // SetStateHandler #endregion Event Handlers @@ -1043,7 +1038,7 @@ namespace System.Management.Automation.Remoting if (newState != oldState) { _state = newState; - _trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); + s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); } // TODO: else should we close the session here? } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs index c0b942e11..a7b8ee567 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs @@ -40,17 +40,17 @@ namespace System.Management.Automation.Remoting /// Makes a connect call asynchronously. /// internal abstract void ConnectAsync(); - + /// /// Send capability negotiation asynchronously. /// internal abstract void SendNegotiationAsync(); - + /// /// This event indicates that a client's capability negotiation packet has been received. /// - internal abstract event EventHandler NegotiationReceived; - + internal abstract event EventHandler NegotiationReceived; + /// /// Close the connection asynchronously. /// @@ -58,12 +58,12 @@ namespace System.Management.Automation.Remoting /// Message describing why the session is closing /// internal abstract void CloseConnectionAsync(Exception reasonForClose); - + /// /// Event that raised when session datastructure handler is closing. /// internal abstract event EventHandler SessionClosing; - + /// /// This event indicates a request for creating a new runspace pool /// has been received on the server side @@ -85,7 +85,7 @@ namespace System.Management.Automation.Remoting { get; } - + /// /// This method is used by the client data dispatching mechanism. /// diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index 068198a52..cdbe42f09 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -12,7 +12,7 @@ using System.Management.Automation.Remoting.Server; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting -{ +{ /// /// This class is an implementation of the abstract class ServerRemoteSessionDataStructureHandler. /// @@ -70,10 +70,10 @@ namespace System.Management.Automation.Remoting internal override void SendNegotiationAsync() { RemoteSessionCapability serverCapability = _session.Context.ServerCapability; - RemoteDataObject data = RemotingEncoder.GenerateServerSessionCapability(serverCapability, + RemoteDataObject data = RemotingEncoder.GenerateServerSessionCapability(serverCapability, Guid.Empty); - RemoteSessionStateMachineEventArgs negotiationSendCompletedArg = + RemoteSessionStateMachineEventArgs negotiationSendCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendCompleted); _stateMachine.RaiseEvent(negotiationSendCompletedArg); @@ -88,7 +88,7 @@ namespace System.Management.Automation.Remoting /// This event indicates that the client capability negotiation packet has been received. /// internal override event EventHandler NegotiationReceived; - + /// /// Event that raised when session datastructure handler is closing. /// @@ -101,8 +101,8 @@ namespace System.Management.Automation.Remoting /// /// encrypted session key /// as a string - internal override void SendEncryptedSessionKey(string encryptedSessionKey) - { + internal override void SendEncryptedSessionKey(string encryptedSessionKey) + { _transportManager.SendDataToClient(RemotingEncoder.GenerateEncryptedSessionKeyResponse( Guid.Empty, encryptedSessionKey), true); } @@ -114,7 +114,6 @@ namespace System.Management.Automation.Remoting { _transportManager.SendDataToClient( RemotingEncoder.GeneratePublicKeyRequest(Guid.Empty), true); - } /// @@ -241,13 +240,10 @@ namespace System.Management.Automation.Remoting default: throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType); - - } + } } #endregion Overrides - } - } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 08d2f8e97..0725977e0 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -59,7 +59,7 @@ namespace System.Management.Automation.Language /// getting the type or value from a DynamicMetaObject, but also help to generate binding restrictions that /// account for values that are optionally wrapped in PSObject. /// - static class DynamicMetaObjectExtensions + internal static class DynamicMetaObjectExtensions { internal static readonly DynamicMetaObject FakeError = new DynamicMetaObject(ExpressionCache.NullConstant, BindingRestrictions.Empty); @@ -107,7 +107,7 @@ namespace System.Management.Automation.Language var temp = Expression.Variable(typeof(object[])); test = Expression.Block( - new [] { temp }, + new[] { temp }, Expression.Assign(temp, Expression.TypeAs(Expression.Call(CachedReflectionInfo.PSObject_Base, obj.Expression), typeof(object[]))), Expression.AndAlso( Expression.NotEqual(temp, ExpressionCache.NullObjectArray), @@ -277,7 +277,7 @@ namespace System.Management.Automation.Language var conversion = LanguagePrimitives.FigureConversion(target.Value, parameterType, out debase); var invokeConverter = PSConvertBinder.InvokeConverter(conversion, targetTemp, parameterType, debase, ExpressionCache.InvariantCulture); var expr = - Expression.Block(new[] {targetTemp}, + Expression.Block(new[] { targetTemp }, Expression.TryCatch( Expression.Block( Expression.Assign(targetTemp, target.Expression), @@ -321,7 +321,7 @@ namespace System.Management.Automation.Language target.CombineRestrictions(args).Merge(moreTests)); } - internal static DynamicMetaObject ThrowRuntimeError(this DynamicMetaObject target, BindingRestrictions bindingRestrictions, + internal static DynamicMetaObject ThrowRuntimeError(this DynamicMetaObject target, BindingRestrictions bindingRestrictions, string errorID, string resourceString, params Expression[] exceptionArgs) { return new DynamicMetaObject(Compiler.ThrowRuntimeError(errorID, resourceString, exceptionArgs), @@ -336,7 +336,7 @@ namespace System.Management.Automation.Language #endif } - static class DynamicMetaObjectBinderExtentions + internal static class DynamicMetaObjectBinderExtentions { internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder binder, params DynamicMetaObject[] args) @@ -461,11 +461,11 @@ namespace System.Management.Automation.Language /// internal class PSEnumerableBinder : ConvertBinder { - private static readonly PSEnumerableBinder _binder = new PSEnumerableBinder(); + private static readonly PSEnumerableBinder s_binder = new PSEnumerableBinder(); static internal PSEnumerableBinder Get() { - return _binder; + return s_binder; } private PSEnumerableBinder() @@ -511,7 +511,7 @@ namespace System.Management.Automation.Language var tmp = Expression.Parameter(typeof(object), "value"); return Expression.Block( - new ParameterExpression[] {tmp}, + new ParameterExpression[] { tmp }, Expression.Assign(tmp, Expression.Call(CachedReflectionInfo.PSObject_Base, target.Expression)), Expression.Condition( targetValue == null ? @@ -673,7 +673,7 @@ namespace System.Management.Automation.Language } // This is to reduce the runtime overhead of the feature query - private static readonly TypeInfo ComObjectTypeInfo = GetComObjectType(); + private static readonly TypeInfo s_comObjectTypeInfo = GetComObjectType(); private static TypeInfo GetComObjectType() { @@ -688,7 +688,7 @@ namespace System.Management.Automation.Language { // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust obj = PSObject.Base(obj); - return obj != null && ComObjectTypeInfo != null && ComObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo()); + return obj != null && s_comObjectTypeInfo != null && s_comObjectTypeInfo.IsAssignableFrom(obj.GetType().GetTypeInfo()); } private static IEnumerator AutomationNullRule(CallSite site, object obj) @@ -713,7 +713,7 @@ namespace System.Management.Automation.Language var psobj = obj as PSObject; return psobj != null && obj != AutomationNull.Value ? NotEnumerableRule(site, PSObject.Base(obj)) - : ((CallSite>) site).Update(site, obj); + : ((CallSite>)site).Update(site, obj); } private static IEnumerator ArrayRule(CallSite site, object obj) @@ -726,7 +726,7 @@ namespace System.Management.Automation.Language private static IEnumerator StringRule(CallSite site, object obj) { return obj is string ? null : ((CallSite>)site).Update(site, obj); - } + } private static IEnumerator PSObjectStringRule(CallSite site, object obj) { @@ -739,13 +739,13 @@ namespace System.Management.Automation.Language /// /// This binder is used for the @() operator. /// - class PSToObjectArrayBinder : DynamicMetaObjectBinder + internal class PSToObjectArrayBinder : DynamicMetaObjectBinder { - private static readonly PSToObjectArrayBinder _binder = new PSToObjectArrayBinder(); + private static readonly PSToObjectArrayBinder s_binder = new PSToObjectArrayBinder(); static internal PSToObjectArrayBinder Get() { - return _binder; + return s_binder; } private PSToObjectArrayBinder() @@ -795,13 +795,13 @@ namespace System.Management.Automation.Language } } - class PSPipeWriterBinder : DynamicMetaObjectBinder + internal class PSPipeWriterBinder : DynamicMetaObjectBinder { - private static readonly PSPipeWriterBinder _binder = new PSPipeWriterBinder(); + private static readonly PSPipeWriterBinder s_binder = new PSPipeWriterBinder(); static internal PSPipeWriterBinder Get() { - return _binder; + return s_binder; } private PSPipeWriterBinder() @@ -890,26 +890,26 @@ namespace System.Management.Automation.Language /// The target in this binder is the RHS, the result expression is an IList where the Count matches the /// number of values assigned (_elements) on the left hand side of the assign. /// - class PSArrayAssignmentRHSBinder : DynamicMetaObjectBinder + internal class PSArrayAssignmentRHSBinder : DynamicMetaObjectBinder { - private static readonly List _binders = new List(); + private static readonly List s_binders = new List(); private readonly int _elements; internal static PSArrayAssignmentRHSBinder Get(int i) { - lock (_binders) + lock (s_binders) { - while (_binders.Count <= i) + while (s_binders.Count <= i) { - _binders.Add(null); + s_binders.Add(null); } - return _binders[i] ?? (_binders[i] = new PSArrayAssignmentRHSBinder(i)); + return s_binders[i] ?? (s_binders[i] = new PSArrayAssignmentRHSBinder(i)); } } private PSArrayAssignmentRHSBinder(int elements) { - this._elements = elements; + _elements = elements; } public override string ToString() @@ -991,7 +991,7 @@ namespace System.Management.Automation.Language // We have a single element, the rest must be null. return (new DynamicMetaObject( - Expression.NewArrayInit(typeof(object),Enumerable.Repeat(ExpressionCache.NullConstant, _elements - 1) + Expression.NewArrayInit(typeof(object), Enumerable.Repeat(ExpressionCache.NullConstant, _elements - 1) .Prepend(target.Expression.Cast(typeof(object)))), target.PSGetTypeRestriction())).WriteToDebugLog(this); } @@ -1007,13 +1007,13 @@ namespace System.Management.Automation.Language /// case, the format string is generated by the parser, so we know that there is no custom /// formatting to consider. /// - class PSToStringBinder : DynamicMetaObjectBinder + internal class PSToStringBinder : DynamicMetaObjectBinder { - private static readonly PSToStringBinder _binder = new PSToStringBinder(); + private static readonly PSToStringBinder s_binder = new PSToStringBinder(); static internal PSToStringBinder Get() { - return _binder; + return s_binder; } public override Type ReturnType { get { return typeof(string); } } @@ -1074,11 +1074,11 @@ namespace System.Management.Automation.Language /// internal class PSPipelineResultToBoolBinder : DynamicMetaObjectBinder { - private static readonly PSPipelineResultToBoolBinder _binder = new PSPipelineResultToBoolBinder(); + private static readonly PSPipelineResultToBoolBinder s_binder = new PSPipelineResultToBoolBinder(); static internal PSPipelineResultToBoolBinder Get() { - return _binder; + return s_binder; } private PSPipelineResultToBoolBinder() @@ -1109,23 +1109,23 @@ namespace System.Management.Automation.Language BindingRestrictions restrictions; switch (pipelineResult.Count) { - case 0: - result = ExpressionCache.Constant(false); - restrictions = BindingRestrictions.GetExpressionRestriction( - Expression.Equal(countExpr, ExpressionCache.Constant(0))); - break; - case 1: - result = Expression.Call(ilistExpr, - CachedReflectionInfo.IList_get_Item, - ExpressionCache.Constant(0)).Convert(typeof(bool)); - restrictions = BindingRestrictions.GetExpressionRestriction( - Expression.Equal(countExpr, ExpressionCache.Constant(1))); - break; - default: - result = ExpressionCache.Constant(true); - restrictions = BindingRestrictions.GetExpressionRestriction( - Expression.GreaterThan(countExpr, ExpressionCache.Constant(1))); - break; + case 0: + result = ExpressionCache.Constant(false); + restrictions = BindingRestrictions.GetExpressionRestriction( + Expression.Equal(countExpr, ExpressionCache.Constant(0))); + break; + case 1: + result = Expression.Call(ilistExpr, + CachedReflectionInfo.IList_get_Item, + ExpressionCache.Constant(0)).Convert(typeof(bool)); + restrictions = BindingRestrictions.GetExpressionRestriction( + Expression.Equal(countExpr, ExpressionCache.Constant(1))); + break; + default: + result = ExpressionCache.Constant(true); + restrictions = BindingRestrictions.GetExpressionRestriction( + Expression.GreaterThan(countExpr, ExpressionCache.Constant(1))); + break; } return (new DynamicMetaObject(result, restrictions)).WriteToDebugLog(this); @@ -1134,7 +1134,7 @@ namespace System.Management.Automation.Language internal class PSInvokeDynamicMemberBinder : DynamicMetaObjectBinder { - class KeyComparer : IEqualityComparer + private class KeyComparer : IEqualityComparer { public bool Equals(PSInvokeDynamicMemberBinderKeyType x, PSInvokeDynamicMemberBinderKeyType y) { @@ -1152,7 +1152,7 @@ namespace System.Management.Automation.Language } private static readonly - Dictionary _binderCache + Dictionary s_binderCache = new Dictionary(new KeyComparer()); internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitionAst classScopeAst, bool @static, bool propertySetter, PSMethodInvocationConstraints constraints) @@ -1160,13 +1160,13 @@ namespace System.Management.Automation.Language PSInvokeDynamicMemberBinder result; var classScope = classScopeAst != null ? classScopeAst.Type : null; - lock (_binderCache) + lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope); - if (!_binderCache.TryGetValue(key, out result)) + if (!s_binderCache.TryGetValue(key, out result)) { result = new PSInvokeDynamicMemberBinder(callInfo, @static, propertySetter, constraints, classScope); - _binderCache.Add(key, result); + s_binderCache.Add(key, result); } } return result; @@ -1177,7 +1177,7 @@ namespace System.Management.Automation.Language private readonly bool _propertySetter; private readonly PSMethodInvocationConstraints _constraints; private readonly Type _classScope; - + private PSInvokeDynamicMemberBinder(CallInfo callInfo, bool @static, bool propertySetter, PSMethodInvocationConstraints constraints, Type classScope) { Diagnostics.Assert(callInfo != null, "callers make sure 'callInfo' is not null"); @@ -1229,7 +1229,7 @@ namespace System.Management.Automation.Language } } - class PSDynamicGetOrSetBinderKeyComparer : IEqualityComparer + internal class PSDynamicGetOrSetBinderKeyComparer : IEqualityComparer { public bool Equals(PSGetOrSetDynamicMemberBinderKeyType x, PSGetOrSetDynamicMemberBinderKeyType y) { @@ -1244,20 +1244,20 @@ namespace System.Management.Automation.Language internal class PSGetDynamicMemberBinder : DynamicMetaObjectBinder { - private static readonly Dictionary _binderCache = + private static readonly Dictionary s_binderCache = new Dictionary(new PSDynamicGetOrSetBinderKeyComparer()); internal static PSGetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool @static) { PSGetDynamicMemberBinder binder; - lock (_binderCache) + lock (s_binderCache) { var type = classScope != null ? classScope.Type : null; var tuple = Tuple.Create(type, @static); - if (!_binderCache.TryGetValue(tuple, out binder)) + if (!s_binderCache.TryGetValue(tuple, out binder)) { binder = new PSGetDynamicMemberBinder(type, @static); - _binderCache.Add(tuple, binder); + s_binderCache.Add(tuple, binder); } } @@ -1268,8 +1268,8 @@ namespace System.Management.Automation.Language private readonly Type _classScope; private PSGetDynamicMemberBinder(Type classScope, bool @static) { - this._static = @static; - this._classScope = classScope; + _static = @static; + _classScope = classScope; } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) @@ -1332,7 +1332,7 @@ namespace System.Management.Automation.Language key = PSObject.Base(key); if (hash.Contains(key)) { - return hash[key]; + return hash[key]; } } catch (InvalidOperationException) @@ -1352,20 +1352,20 @@ namespace System.Management.Automation.Language internal class PSSetDynamicMemberBinder : DynamicMetaObjectBinder { - private static readonly Dictionary _binderCache = + private static readonly Dictionary s_binderCache = new Dictionary(new PSDynamicGetOrSetBinderKeyComparer()); internal static PSSetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool @static) { PSSetDynamicMemberBinder binder; - lock (_binderCache) + lock (s_binderCache) { var type = classScope != null ? classScope.Type : null; var tuple = Tuple.Create(type, @static); - if (!_binderCache.TryGetValue(tuple, out binder)) + if (!s_binderCache.TryGetValue(tuple, out binder)) { binder = new PSSetDynamicMemberBinder(type, @static); - _binderCache.Add(tuple, binder); + s_binderCache.Add(tuple, binder); } } @@ -1377,8 +1377,8 @@ namespace System.Management.Automation.Language private PSSetDynamicMemberBinder(Type classScope, bool @static) { - this._static = @static; - this._classScope = classScope; + _static = @static; + _classScope = classScope; } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) @@ -1428,7 +1428,7 @@ namespace System.Management.Automation.Language // And if that fails, try arg[0] converted to string, setting a property, etc. var exception = Expression.Variable(typeof(Exception)); - var indexResult = PSSetIndexBinder.Get(1).FallbackSetIndex(target, new [] {args[0]}, args[1]); + var indexResult = PSSetIndexBinder.Get(1).FallbackSetIndex(target, new[] { args[0] }, args[1]); resultExpr = Expression.TryCatch( indexResult.Expression, Expression.Catch(exception, @@ -1450,20 +1450,20 @@ namespace System.Management.Automation.Language // Increase this cache size if we add a new flag to the switch statement that: // - Influences evaluation of switch elements // - Is commonly used - private static readonly PSSwitchClauseEvalBinder[] _binderCache = new PSSwitchClauseEvalBinder[32]; + private static readonly PSSwitchClauseEvalBinder[] s_binderCache = new PSSwitchClauseEvalBinder[32]; private readonly SwitchFlags _flags; internal static PSSwitchClauseEvalBinder Get(SwitchFlags flags) { - lock (_binderCache) + lock (s_binderCache) { - return _binderCache[(int)flags] ?? (_binderCache[(int)flags] = new PSSwitchClauseEvalBinder(flags)); + return s_binderCache[(int)flags] ?? (s_binderCache[(int)flags] = new PSSwitchClauseEvalBinder(flags)); } } private PSSwitchClauseEvalBinder(SwitchFlags flags) { - this._flags = flags; + _flags = flags; } public override Type ReturnType { get { return typeof(bool); } } @@ -1529,7 +1529,7 @@ namespace System.Management.Automation.Language if (target.Value is Regex || (_flags & SwitchFlags.Regex) != 0) { - var call = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex, + var call = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex, /*caseSensitive=*/ ExpressionCache.Constant((_flags & SwitchFlags.CaseSensitive) != 0), /*condition=*/ target.Expression.Cast(typeof(object)), /*errorPosition=*/ ExpressionCache.NullExtent, @@ -1567,18 +1567,18 @@ namespace System.Management.Automation.Language // The ArgumentNames are not used to invoke a constructor, instead they are used to set properties/fields in the attribute. internal class PSAttributeGenerator : CreateInstanceBinder { - private static readonly Dictionary _binderCache = + private static readonly Dictionary s_binderCache = new Dictionary(); internal static PSAttributeGenerator Get(CallInfo callInfo) { - lock (_binderCache) + lock (s_binderCache) { PSAttributeGenerator binder; - if (!_binderCache.TryGetValue(callInfo, out binder)) + if (!s_binderCache.TryGetValue(callInfo, out binder)) { binder = new PSAttributeGenerator(callInfo); - _binderCache.Add(callInfo, binder); + s_binderCache.Add(callInfo, binder); } return binder; } @@ -1649,7 +1649,7 @@ namespace System.Management.Automation.Language // (which ignores method arguments with disallowed types) var conversion = LanguagePrimitives.FigureConversion(args[argIndex].Value, elementType, out debase); Diagnostics.Assert(conversion.Rank != ConversionRank.None, "FindBestMethod should have failed if there is no conversion"); - + paramsArray.Add( PSConvertBinder.InvokeConverter(conversion, args[i].Expression, elementType, debase, ExpressionCache.InvariantCulture)); } @@ -1705,8 +1705,8 @@ namespace System.Management.Automation.Language { propertyType = ((FieldInfo)member).FieldType; lhs = Expression.Field(tmp.Cast(member.DeclaringType), (FieldInfo)member); - } - + } + bool debase; // ConstrainedLanguage note - calls to these property assignment conversions are enforced by the @@ -1715,7 +1715,7 @@ namespace System.Management.Automation.Language if (conversion.Rank == ConversionRank.None) { return PSConvertBinder.ThrowNoConversion(args[argIndex], propertyType, this, -1, - args.Except(new DynamicMetaObject[]{ args[argIndex] }).Prepend(target).ToArray()); + args.Except(new DynamicMetaObject[] { args[argIndex] }).Prepend(target).ToArray()); } blockExprs.Add( @@ -1736,20 +1736,20 @@ namespace System.Management.Automation.Language Compiler.ThrowRuntimeErrorWithInnerException("PropertyAssignmentException", Expression.Property(exception, "Message"), exception, typeof(void))))), // The result of the block is the object constructed, so the tmp must be the last expr in the block. tmp); - result = Expression.Block(new ParameterExpression[] {tmp}, block); + result = Expression.Block(new ParameterExpression[] { tmp }, block); } return new DynamicMetaObject(result, target.CombineRestrictions(args)); } } - class PSCustomObjectConverter : DynamicMetaObjectBinder + internal class PSCustomObjectConverter : DynamicMetaObjectBinder { - static readonly PSCustomObjectConverter _binder = new PSCustomObjectConverter(); + private static readonly PSCustomObjectConverter s_binder = new PSCustomObjectConverter(); internal static PSCustomObjectConverter Get() { - return _binder; + return s_binder; } private PSCustomObjectConverter() @@ -1779,17 +1779,17 @@ namespace System.Management.Automation.Language } } - class PSDynamicConvertBinder : DynamicMetaObjectBinder + internal class PSDynamicConvertBinder : DynamicMetaObjectBinder { - static readonly PSDynamicConvertBinder _binder = new PSDynamicConvertBinder(); + private static readonly PSDynamicConvertBinder s_binder = new PSDynamicConvertBinder(); internal static PSDynamicConvertBinder Get() { - return _binder; + return s_binder; } private PSDynamicConvertBinder() - { + { } public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) @@ -1810,21 +1810,21 @@ namespace System.Management.Automation.Language return new DynamicMetaObject( DynamicExpression.Dynamic(PSConvertBinder.Get(toType), toType, arg.Expression).Cast(typeof(object)), - bindingRestrictions).WriteToDebugLog(this); + bindingRestrictions).WriteToDebugLog(this); } } /// /// This binder is used to copy mutable value types when assigning to variables, otherwise just assigning the target object directly. /// - class PSVariableAssignmentBinder : DynamicMetaObjectBinder + internal class PSVariableAssignmentBinder : DynamicMetaObjectBinder { - static readonly PSVariableAssignmentBinder _binder = new PSVariableAssignmentBinder(); - private static int _mutableValueWithInstanceMemberVersion; + private static readonly PSVariableAssignmentBinder s_binder = new PSVariableAssignmentBinder(); + internal static int s_mutableValueWithInstanceMemberVersion; internal static PSVariableAssignmentBinder Get() { - return _binder; + return s_binder; } private PSVariableAssignmentBinder() @@ -1919,7 +1919,7 @@ namespace System.Management.Automation.Language Expression expr; bool needVersionCheck = true; - if (MutableValueTypesWithInstanceMembers.ContainsKey(type)) + if (s_mutableValueTypesWithInstanceMembers.ContainsKey(type)) { var genericMethodInfo = CachedReflectionInfo.PSVariableAssignmentBinder_CopyInstanceMembersOfValueType.MakeGenericMethod(new Type[] { type }); expr = Expression.Call(genericMethodInfo, convertedExpr, originalExpr); @@ -1941,7 +1941,7 @@ namespace System.Management.Automation.Language if (needVersionCheck) { - restrictions = restrictions.Merge(GetVersionCheck(_mutableValueWithInstanceMemberVersion)); + restrictions = restrictions.Merge(GetVersionCheck(s_mutableValueWithInstanceMemberVersion)); } return expr; } @@ -2018,7 +2018,7 @@ namespace System.Management.Automation.Language return false; } - private static readonly ConcurrentDictionary MutableValueTypesWithInstanceMembers = + private static readonly ConcurrentDictionary s_mutableValueTypesWithInstanceMembers = new ConcurrentDictionary(); internal static void NoteTypeHasInstanceMemberOrTypeName(Type type) @@ -2028,9 +2028,9 @@ namespace System.Management.Automation.Language return; } - if (MutableValueTypesWithInstanceMembers.TryAdd(type, true)) + if (s_mutableValueTypesWithInstanceMembers.TryAdd(type, true)) { - _mutableValueWithInstanceMemberVersion += 1; + s_mutableValueWithInstanceMemberVersion += 1; } } @@ -2056,30 +2056,30 @@ namespace System.Management.Automation.Language } } -#endregion PowerShell non-standard language binders + #endregion PowerShell non-standard language binders -#region Standard binders + #region Standard binders /// /// The binder for common binary operators. PowerShell specific binary operators are handled elsewhere. /// internal class PSBinaryOperationBinder : BinaryOperationBinder { -#region Constructors and factory methods + #region Constructors and factory methods - private static readonly Dictionary, PSBinaryOperationBinder> _binderCache = + private static readonly Dictionary, PSBinaryOperationBinder> s_binderCache = new Dictionary, PSBinaryOperationBinder>(); internal static PSBinaryOperationBinder Get(ExpressionType operation, bool ignoreCase = true, bool scalarCompare = false) { PSBinaryOperationBinder result; - lock (_binderCache) + lock (s_binderCache) { var key = Tuple.Create(operation, ignoreCase, scalarCompare); - if (!_binderCache.TryGetValue(key, out result)) + if (!s_binderCache.TryGetValue(key, out result)) { result = new PSBinaryOperationBinder(operation, ignoreCase, scalarCompare); - _binderCache.Add(key, result); + s_binderCache.Add(key, result); } } return result; @@ -2092,18 +2092,18 @@ namespace System.Management.Automation.Language private PSBinaryOperationBinder(ExpressionType operation, bool ignoreCase, bool scalarCompare) : base(operation) { - this._ignoreCase = ignoreCase; - this._scalarCompare = scalarCompare; + _ignoreCase = ignoreCase; + _scalarCompare = scalarCompare; this._version = 0; } -#endregion Constructors and factory methods + #endregion Constructors and factory methods -#region Delegates for enumerable comparisons + #region Delegates for enumerable comparisons private Func _compareDelegate; - Func GetScalarCompareDelegate() + private Func GetScalarCompareDelegate() { if (_compareDelegate == null) { @@ -2119,7 +2119,7 @@ namespace System.Management.Automation.Language return _compareDelegate; } -#endregion Delegates for enumerable comparisons + #endregion Delegates for enumerable comparisons public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { @@ -2142,38 +2142,38 @@ namespace System.Management.Automation.Language switch (Operation) { - case ExpressionType.Add: - return BinaryAdd(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Subtract: - return BinarySub(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Multiply: - return BinaryMultiply(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Divide: - return BinaryDivide(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Modulo: - return BinaryRemainder(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.And: - return BinaryBitwiseAnd(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Or: - return BinaryBitwiseOr(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.ExclusiveOr: - return BinaryBitwiseXor(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Equal: - return CompareEQ(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.NotEqual: - return CompareNE(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.GreaterThan: - return CompareGT(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.GreaterThanOrEqual: - return CompareGE(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.LessThan: - return CompareLT(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.LessThanOrEqual: - return CompareLE(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.LeftShift: - return LeftShift(target, arg, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.RightShift: - return RightShift(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Add: + return BinaryAdd(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Subtract: + return BinarySub(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Multiply: + return BinaryMultiply(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Divide: + return BinaryDivide(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Modulo: + return BinaryRemainder(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.And: + return BinaryBitwiseAnd(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Or: + return BinaryBitwiseOr(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.ExclusiveOr: + return BinaryBitwiseXor(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Equal: + return CompareEQ(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.NotEqual: + return CompareNE(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.GreaterThan: + return CompareGT(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.GreaterThanOrEqual: + return CompareGE(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.LessThan: + return CompareLT(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.LessThanOrEqual: + return CompareLE(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.LeftShift: + return LeftShift(target, arg, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.RightShift: + return RightShift(target, arg, errorSuggestion).WriteToDebugLog(this); } return (errorSuggestion ?? @@ -2182,7 +2182,7 @@ namespace System.Management.Automation.Language target.CombineRestrictions(arg))).WriteToDebugLog(this); } -#region Helpers + #region Helpers public override string ToString() { @@ -2192,9 +2192,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSBinaryOperationBinder binder in _binderCache.Values) + foreach (PSBinaryOperationBinder binder in s_binderCache.Values) { binder._version += 1; } @@ -2205,22 +2205,22 @@ namespace System.Management.Automation.Language { switch (Operation) { - case ExpressionType.Add: return TokenKind.Plus.Text(); - case ExpressionType.Subtract: return TokenKind.Minus.Text(); - case ExpressionType.Multiply: return TokenKind.Multiply.Text(); - case ExpressionType.Divide: return TokenKind.Divide.Text(); - case ExpressionType.Modulo: return TokenKind.Rem.Text(); - case ExpressionType.And: return TokenKind.Band.Text(); - case ExpressionType.Or: return TokenKind.Bor.Text(); - case ExpressionType.ExclusiveOr: return TokenKind.Bxor.Text(); - case ExpressionType.Equal: return _ignoreCase ? TokenKind.Ieq.Text() : TokenKind.Ceq.Text(); - case ExpressionType.NotEqual: return _ignoreCase ? TokenKind.Ine.Text() : TokenKind.Cne.Text(); - case ExpressionType.GreaterThan: return _ignoreCase ? TokenKind.Igt.Text() : TokenKind.Cgt.Text(); - case ExpressionType.GreaterThanOrEqual: return _ignoreCase ? TokenKind.Ige.Text() : TokenKind.Cge.Text(); - case ExpressionType.LessThan: return _ignoreCase ? TokenKind.Ilt.Text() : TokenKind.Clt.Text(); - case ExpressionType.LessThanOrEqual: return _ignoreCase ? TokenKind.Ile.Text() : TokenKind.Cle.Text(); - case ExpressionType.LeftShift: return TokenKind.Shl.Text(); - case ExpressionType.RightShift: return TokenKind.Shr.Text(); + case ExpressionType.Add: return TokenKind.Plus.Text(); + case ExpressionType.Subtract: return TokenKind.Minus.Text(); + case ExpressionType.Multiply: return TokenKind.Multiply.Text(); + case ExpressionType.Divide: return TokenKind.Divide.Text(); + case ExpressionType.Modulo: return TokenKind.Rem.Text(); + case ExpressionType.And: return TokenKind.Band.Text(); + case ExpressionType.Or: return TokenKind.Bor.Text(); + case ExpressionType.ExclusiveOr: return TokenKind.Bxor.Text(); + case ExpressionType.Equal: return _ignoreCase ? TokenKind.Ieq.Text() : TokenKind.Ceq.Text(); + case ExpressionType.NotEqual: return _ignoreCase ? TokenKind.Ine.Text() : TokenKind.Cne.Text(); + case ExpressionType.GreaterThan: return _ignoreCase ? TokenKind.Igt.Text() : TokenKind.Cgt.Text(); + case ExpressionType.GreaterThanOrEqual: return _ignoreCase ? TokenKind.Ige.Text() : TokenKind.Cge.Text(); + case ExpressionType.LessThan: return _ignoreCase ? TokenKind.Ilt.Text() : TokenKind.Clt.Text(); + case ExpressionType.LessThanOrEqual: return _ignoreCase ? TokenKind.Ile.Text() : TokenKind.Cle.Text(); + case ExpressionType.LeftShift: return TokenKind.Shl.Text(); + case ExpressionType.RightShift: return TokenKind.Shr.Text(); } Diagnostics.Assert(false, "Unexpected operator"); return ""; @@ -2253,10 +2253,10 @@ namespace System.Management.Automation.Language { switch (typeCode) { - case TypeCode.SByte: return (sbyte)value < 0; - case TypeCode.Int16: return (short)value < 0; - case TypeCode.Int32: return (int)value < 0; - case TypeCode.Int64: return (long)value < 0; + case TypeCode.SByte: return (sbyte)value < 0; + case TypeCode.Int16: return (short)value < 0; + case TypeCode.Int32: return (int)value < 0; + case TypeCode.Int64: return (long)value < 0; } Diagnostics.Assert(false, "Invalid type code for testing negative value"); @@ -2267,10 +2267,10 @@ namespace System.Management.Automation.Language { switch (typeCode) { - case TypeCode.SByte: return Expression.Constant((sbyte)0); - case TypeCode.Int16: return Expression.Constant((short)0); - case TypeCode.Int32: return ExpressionCache.Constant(0); - case TypeCode.Int64: return Expression.Constant((long)0); + case TypeCode.SByte: return Expression.Constant((sbyte)0); + case TypeCode.Int16: return Expression.Constant((short)0); + case TypeCode.Int32: return ExpressionCache.Constant(0); + case TypeCode.Int64: return Expression.Constant((long)0); } Diagnostics.Assert(false, "Invalid type code for testing negative value"); @@ -2288,12 +2288,12 @@ namespace System.Management.Automation.Language switch (currentOpType) { case TypeCode.UInt32: - opImplType = typeof (LongOps); - argType = typeof (long); + opImplType = typeof(LongOps); + argType = typeof(long); break; case TypeCode.UInt64: - opImplType = typeof (DecimalOps); - argType = typeof (decimal); + opImplType = typeof(DecimalOps); + argType = typeof(decimal); // multiply operation may overflow within the [decimal] context, i.e. [int64]::minvalue * [uint64]::maxvalue. // if overflow happens, we fallback to the [double] context shouldFallbackToDoubleInCaseOfOverflow = true; @@ -2425,8 +2425,8 @@ namespace System.Management.Automation.Language if (fallbackToDoubleInCaseOfOverflow) { - Type doubleOpType = typeof (DoubleOps); - Type doubleArgType = typeof (double); + Type doubleOpType = typeof(DoubleOps); + Type doubleArgType = typeof(double); Expression fallbackToDoubleExpr = Expression.Call(doubleOpType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static), target.Expression.Cast(target.LimitType).Cast(doubleArgType), @@ -2438,7 +2438,7 @@ namespace System.Management.Automation.Language exception, Expression.Block( Expression.IfThen( - Expression.Not(Expression.TypeIs(Expression.Property(exception, "InnerException"), typeof (OverflowException))), + Expression.Not(Expression.TypeIs(Expression.Property(exception, "InnerException"), typeof(OverflowException))), Expression.Rethrow()), fallbackToDoubleExpr) ); @@ -2453,16 +2453,16 @@ namespace System.Management.Automation.Language // Make sure the result type is an enum unless we were expecting a bool. switch (Operation) { - case ExpressionType.Equal: - case ExpressionType.NotEqual: - case ExpressionType.GreaterThan: - case ExpressionType.GreaterThanOrEqual: - case ExpressionType.LessThan: - case ExpressionType.LessThanOrEqual: - break; - default: - expr = expr.Cast(target.LimitType).Cast(typeof(object)); - break; + case ExpressionType.Equal: + case ExpressionType.NotEqual: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + break; + default: + expr = expr.Cast(target.LimitType).Cast(typeof(object)); + break; } } @@ -2494,7 +2494,7 @@ namespace System.Management.Automation.Language if (target.LimitType == typeof(string)) { Diagnostics.Assert( - Operation == ExpressionType.Subtract || Operation == ExpressionType.Divide + Operation == ExpressionType.Subtract || Operation == ExpressionType.Divide || Operation == ExpressionType.Modulo || Operation == ExpressionType.And || Operation == ExpressionType.Or || Operation == ExpressionType.ExclusiveOr || Operation == ExpressionType.LeftShift || Operation == ExpressionType.RightShift, @@ -2585,9 +2585,9 @@ namespace System.Management.Automation.Language return opType; } -#endregion Helpers + #endregion Helpers -#region "Arithmetic" operations + #region "Arithmetic" operations private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { @@ -2673,7 +2673,7 @@ namespace System.Management.Automation.Language target.CombineRestrictions(arg)); } - return target.ThrowRuntimeError(new DynamicMetaObject[] {arg}, BindingRestrictions.Empty, + return target.ThrowRuntimeError(new DynamicMetaObject[] { arg }, BindingRestrictions.Empty, "AddHashTableToNonHashTable", ParserStrings.AddHashTableToNonHashTable); } @@ -2735,7 +2735,6 @@ namespace System.Management.Automation.Language target.Expression.Cast(elementType.MakeArrayType()), argExpr), target.CombineRestrictions(arg)); - } return new DynamicMetaObject( @@ -2834,7 +2833,7 @@ namespace System.Management.Automation.Language } var targetExpr = target.Expression.Cast(target.LimitType); - numericArg = Expression.And(numericArg, Expression.Constant(typeCode < TypeCode.Int64 ? 0x1f : 0x3f, typeof(int))); + numericArg = Expression.And(numericArg, Expression.Constant(typeCode < TypeCode.Int64 ? 0x1f : 0x3f, typeof(int))); return new DynamicMetaObject( exprGenerator(targetExpr, numericArg).Cast(typeof(object)), @@ -2865,7 +2864,7 @@ namespace System.Management.Automation.Language { return BinaryBitwiseOp(target, arg, errorSuggestion, Expression.And, "op_BitwiseAnd", "-band", "BAnd"); } - + private DynamicMetaObject BinaryBitwiseOp(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion, @@ -2910,7 +2909,7 @@ namespace System.Management.Automation.Language numericTarget = target; numericArg = arg; } - if (opTypeCode==TypeCode.Decimal) + if (opTypeCode == TypeCode.Decimal) { opImplType = typeof(DecimalOps); toType = typeof(decimal); @@ -2938,7 +2937,7 @@ namespace System.Management.Automation.Language // For float, double, and decimal operands, we used to use long because V2 did. // Because we use unsigned for -bnot, to be consistent, we promote to unsigned here too (-band,-bor,-xor) opType = GetBitwiseOpType((int)leftTypeCode >= (int)rightTypeCode ? leftTypeCode : rightTypeCode); - + if (numericTarget != null && numericArg != null) { var expr = exprGenerator(numericTarget.Expression.Cast(target.LimitType).Cast(opType), @@ -2959,10 +2958,10 @@ namespace System.Management.Automation.Language return CallImplicitOp(implicitMethodName, target, arg, errorOperatorName, errorSuggestion); } - -#endregion "Arithmetic" operations -#region Comparison operations + #endregion "Arithmetic" operations + + #region Comparison operations private DynamicMetaObject CompareEQ(DynamicMetaObject target, DynamicMetaObject arg, @@ -3319,12 +3318,12 @@ namespace System.Management.Automation.Language string numericMethod = null; switch (Operation) { - case ExpressionType.Equal: numericMethod = "CompareEq"; break; - case ExpressionType.NotEqual: numericMethod = "CompareNe"; break; - case ExpressionType.GreaterThan: numericMethod = "CompareGt"; break; - case ExpressionType.GreaterThanOrEqual: numericMethod = "CompareGe"; break; - case ExpressionType.LessThan: numericMethod = "CompareLt"; break; - case ExpressionType.LessThanOrEqual: numericMethod = "CompareLe"; break; + case ExpressionType.Equal: numericMethod = "CompareEq"; break; + case ExpressionType.NotEqual: numericMethod = "CompareNe"; break; + case ExpressionType.GreaterThan: numericMethod = "CompareGt"; break; + case ExpressionType.GreaterThanOrEqual: numericMethod = "CompareGe"; break; + case ExpressionType.LessThan: numericMethod = "CompareLt"; break; + case ExpressionType.LessThanOrEqual: numericMethod = "CompareLe"; break; } return BinaryNumericOp(numericMethod, target, numericArg); } @@ -3338,7 +3337,7 @@ namespace System.Management.Automation.Language return null; } -#endregion Comparison operations + #endregion Comparison operations } /// @@ -3346,41 +3345,41 @@ namespace System.Management.Automation.Language /// internal class PSUnaryOperationBinder : UnaryOperationBinder { - private static PSUnaryOperationBinder _notBinder; - private static PSUnaryOperationBinder _bnotBinder; - private static PSUnaryOperationBinder _unaryMinus; - private static PSUnaryOperationBinder _unaryPlusBinder; - private static PSUnaryOperationBinder _incrementBinder; - private static PSUnaryOperationBinder _decrementBinder; + private static PSUnaryOperationBinder s_notBinder; + private static PSUnaryOperationBinder s_bnotBinder; + private static PSUnaryOperationBinder s_unaryMinus; + private static PSUnaryOperationBinder s_unaryPlusBinder; + private static PSUnaryOperationBinder s_incrementBinder; + private static PSUnaryOperationBinder s_decrementBinder; internal static PSUnaryOperationBinder Get(ExpressionType operation) { switch (operation) { - case ExpressionType.Not: - if (_notBinder == null) - Interlocked.CompareExchange(ref _notBinder, new PSUnaryOperationBinder(operation), null); - return _notBinder; - case ExpressionType.OnesComplement: - if (_bnotBinder == null) - Interlocked.CompareExchange(ref _bnotBinder, new PSUnaryOperationBinder(operation), null); - return _bnotBinder; - case ExpressionType.UnaryPlus: - if (_unaryPlusBinder == null) - Interlocked.CompareExchange(ref _unaryPlusBinder, new PSUnaryOperationBinder(operation), null); - return _unaryPlusBinder; - case ExpressionType.Negate: - if (_unaryMinus == null) - Interlocked.CompareExchange(ref _unaryMinus, new PSUnaryOperationBinder(operation), null); - return _unaryMinus; - case ExpressionType.Increment: - if (_incrementBinder == null) - Interlocked.CompareExchange(ref _incrementBinder, new PSUnaryOperationBinder(operation), null); - return _incrementBinder; - case ExpressionType.Decrement: - if (_decrementBinder == null) - Interlocked.CompareExchange(ref _decrementBinder, new PSUnaryOperationBinder(operation), null); - return _decrementBinder; + case ExpressionType.Not: + if (s_notBinder == null) + Interlocked.CompareExchange(ref s_notBinder, new PSUnaryOperationBinder(operation), null); + return s_notBinder; + case ExpressionType.OnesComplement: + if (s_bnotBinder == null) + Interlocked.CompareExchange(ref s_bnotBinder, new PSUnaryOperationBinder(operation), null); + return s_bnotBinder; + case ExpressionType.UnaryPlus: + if (s_unaryPlusBinder == null) + Interlocked.CompareExchange(ref s_unaryPlusBinder, new PSUnaryOperationBinder(operation), null); + return s_unaryPlusBinder; + case ExpressionType.Negate: + if (s_unaryMinus == null) + Interlocked.CompareExchange(ref s_unaryMinus, new PSUnaryOperationBinder(operation), null); + return s_unaryMinus; + case ExpressionType.Increment: + if (s_incrementBinder == null) + Interlocked.CompareExchange(ref s_incrementBinder, new PSUnaryOperationBinder(operation), null); + return s_incrementBinder; + case ExpressionType.Decrement: + if (s_decrementBinder == null) + Interlocked.CompareExchange(ref s_decrementBinder, new PSUnaryOperationBinder(operation), null); + return s_decrementBinder; } throw new NotImplementedException("Unimplemented unary operation"); } @@ -3403,18 +3402,18 @@ namespace System.Management.Automation.Language switch (Operation) { - case ExpressionType.Not: - return Not(target, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.OnesComplement: - return BNot(target, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.UnaryPlus: - return UnaryPlus(target, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Negate: - return UnaryMinus(target, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Increment: - return IncrDecr(target, 1, errorSuggestion).WriteToDebugLog(this); - case ExpressionType.Decrement: - return IncrDecr(target, -1, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Not: + return Not(target, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.OnesComplement: + return BNot(target, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.UnaryPlus: + return UnaryPlus(target, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Negate: + return UnaryMinus(target, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Increment: + return IncrDecr(target, 1, errorSuggestion).WriteToDebugLog(this); + case ExpressionType.Decrement: + return IncrDecr(target, -1, errorSuggestion).WriteToDebugLog(this); } throw new NotImplementedException(); } @@ -3656,19 +3655,19 @@ namespace System.Management.Automation.Language /// internal class PSConvertBinder : ConvertBinder { - private static readonly Dictionary _binderCache = new Dictionary(); + private static readonly Dictionary s_binderCache = new Dictionary(); internal int _version; public static PSConvertBinder Get(Type type) { PSConvertBinder result; - lock (_binderCache) + lock (s_binderCache) { - if (!_binderCache.TryGetValue(type, out result)) + if (!s_binderCache.TryGetValue(type, out result)) { result = new PSConvertBinder(type); - _binderCache.Add(type, result); + s_binderCache.Add(type, result); } } return result; @@ -3724,9 +3723,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSConvertBinder binder in _binderCache.Values) + foreach (PSConvertBinder binder in s_binderCache.Values) { binder._version += 1; } @@ -3819,7 +3818,7 @@ namespace System.Management.Automation.Language /// internal class PSGetIndexBinder : GetIndexBinder { - private static readonly Dictionary, PSGetIndexBinder> _binderCache + private static readonly Dictionary, PSGetIndexBinder> s_binderCache = new Dictionary, PSGetIndexBinder>(); private readonly PSMethodInvocationConstraints _constraints; @@ -3828,14 +3827,14 @@ namespace System.Management.Automation.Language public static PSGetIndexBinder Get(int argCount, PSMethodInvocationConstraints constraints, bool allowSlicing = true) { - lock (_binderCache) + lock (s_binderCache) { PSGetIndexBinder binder; var tuple = Tuple.Create(new CallInfo(argCount), constraints, allowSlicing); - if (!_binderCache.TryGetValue(tuple, out binder)) + if (!s_binderCache.TryGetValue(tuple, out binder)) { binder = new PSGetIndexBinder(tuple); - _binderCache.Add(tuple, binder); + s_binderCache.Add(tuple, binder); } return binder; } @@ -3844,8 +3843,8 @@ namespace System.Management.Automation.Language private PSGetIndexBinder(Tuple tuple) : base(tuple.Item1) { - this._constraints = tuple.Item2; - this._allowSlicing = tuple.Item3; + _constraints = tuple.Item2; + _allowSlicing = tuple.Item3; this._version = 0; } @@ -3862,9 +3861,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSGetIndexBinder binder in _binderCache.Values) + foreach (PSGetIndexBinder binder in s_binderCache.Values) { binder._version += 1; } @@ -4006,7 +4005,7 @@ namespace System.Management.Automation.Language var outParam = Expression.Parameter(parameters[1].ParameterType.GetElementType(), "outParam"); return new DynamicMetaObject( Expression.Block( - new ParameterExpression[] {outParam}, + new ParameterExpression[] { outParam }, Expression.Condition( Expression.Call(target.Expression.Cast(idictionary), tryGetValue, keyExpr, outParam), outParam.Cast(typeof(object)), @@ -4060,7 +4059,7 @@ namespace System.Management.Automation.Language var indexTmp = Expression.Parameter(typeof(int), "index"); Expression block = Expression.Block( - new ParameterExpression[] {targetTmp, lenTmp, indexTmp}, + new ParameterExpression[] { targetTmp, lenTmp, indexTmp }, // Save the target because we use it multiple times. Expression.Assign(targetTmp, target.Expression.Cast(target.LimitType)), // Save the length because we use it multiple times. @@ -4114,8 +4113,8 @@ namespace System.Management.Automation.Language } return IndexWithNegativeChecks( - new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), - new DynamicMetaObject(indexAsInt, indexes[0].PSGetTypeRestriction()), + new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), + new DynamicMetaObject(indexAsInt, indexes[0].PSGetTypeRestriction()), target.LimitType.GetProperty("Length"), (t, i) => Expression.ArrayIndex(t, i).Cast(typeof(object))); } @@ -4352,7 +4351,7 @@ namespace System.Management.Automation.Language /// internal class PSSetIndexBinder : SetIndexBinder { - private static readonly Dictionary, PSSetIndexBinder> _binderCache + private static readonly Dictionary, PSSetIndexBinder> s_binderCache = new Dictionary, PSSetIndexBinder>(); private readonly PSMethodInvocationConstraints _constraints; @@ -4360,14 +4359,14 @@ namespace System.Management.Automation.Language public static PSSetIndexBinder Get(int argCount, PSMethodInvocationConstraints constraints = null) { - lock (_binderCache) + lock (s_binderCache) { PSSetIndexBinder binder; var tuple = Tuple.Create(new CallInfo(argCount), constraints); - if (!_binderCache.TryGetValue(tuple, out binder)) + if (!s_binderCache.TryGetValue(tuple, out binder)) { binder = new PSSetIndexBinder(tuple); - _binderCache.Add(tuple, binder); + s_binderCache.Add(tuple, binder); } return binder; } @@ -4376,7 +4375,7 @@ namespace System.Management.Automation.Language private PSSetIndexBinder(Tuple tuple) : base(tuple.Item1) { - this._constraints = tuple.Item2; + _constraints = tuple.Item2; this._version = 0; } @@ -4389,9 +4388,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSSetIndexBinder binder in _binderCache.Values) + foreach (PSSetIndexBinder binder in s_binderCache.Values) { binder._version += 1; } @@ -4527,7 +4526,7 @@ namespace System.Management.Automation.Language new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), new DynamicMetaObject(indexExprs[0], indexes[0].PSGetTypeRestriction()), - new DynamicMetaObject(indexExprs[1], value.PSGetTypeRestriction()), + new DynamicMetaObject(indexExprs[1], value.PSGetTypeRestriction()), lengthProperty, (t, i, v) => Expression.Call(t, setter, i, v)); } @@ -4643,14 +4642,13 @@ namespace System.Management.Automation.Language } return IndexWithNegativeChecks( - new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), - new DynamicMetaObject(intIndex, indexes[0].PSGetTypeRestriction()), + new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), + new DynamicMetaObject(intIndex, indexes[0].PSGetTypeRestriction()), new DynamicMetaObject(valueExpr, value.PSGetTypeRestriction()), target.LimitType.GetProperty("Length"), (t, i, v) => Expression.Assign(Expression.ArrayAccess(t, i), v)); - } - private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, + private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) @@ -4718,7 +4716,7 @@ namespace System.Management.Automation.Language /// internal class PSGetMemberBinder : GetMemberBinder { - class KeyComparer : IEqualityComparer + private class KeyComparer : IEqualityComparer { public bool Equals(PSGetMemberBinderKeyType x, PSGetMemberBinderKeyType y) { @@ -4754,26 +4752,26 @@ namespace System.Management.Automation.Language Expression targetExpr = null; switch (Name) { - case PSObject.AdaptedMemberSetName: - mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSAdaptedMemberSet; - targetExpr = target.Expression.Cast(typeof(object)); - break; - case PSObject.BaseObjectMemberSetName: - mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSBaseMemberSet; - targetExpr = target.Expression.Cast(typeof(object)); - break; - case PSObject.ExtendedMemberSetName: - mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSExtendedMemberSet; - targetExpr = target.Expression.Cast(typeof(object)); - break; - case PSObject.PSObjectMemberSetName: - mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSObjectMemberSet; - targetExpr = target.Expression.Cast(typeof(object)); - break; - case PSObject.PSTypeNames: - mi = CachedReflectionInfo.ReservedNameMembers_PSTypeNames; - targetExpr = target.Expression.Convert(typeof(PSObject)); - break; + case PSObject.AdaptedMemberSetName: + mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSAdaptedMemberSet; + targetExpr = target.Expression.Cast(typeof(object)); + break; + case PSObject.BaseObjectMemberSetName: + mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSBaseMemberSet; + targetExpr = target.Expression.Cast(typeof(object)); + break; + case PSObject.ExtendedMemberSetName: + mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSExtendedMemberSet; + targetExpr = target.Expression.Cast(typeof(object)); + break; + case PSObject.PSObjectMemberSetName: + mi = CachedReflectionInfo.ReservedNameMembers_GeneratePSObjectMemberSet; + targetExpr = target.Expression.Cast(typeof(object)); + break; + case PSObject.PSTypeNames: + mi = CachedReflectionInfo.ReservedNameMembers_PSTypeNames; + targetExpr = target.Expression.Convert(typeof(PSObject)); + break; } Diagnostics.Assert(mi != null, "ReservedMemberBinder doesn't support member Name"); @@ -4781,26 +4779,26 @@ namespace System.Management.Automation.Language } } - private static readonly Dictionary _binderCache + private static readonly Dictionary s_binderCache = new Dictionary(new KeyComparer()); // Because the non-static binder is case-sensitive, we need a list of all binders for a given // name when we discover an instance member or type table member for that given name so we // can update each of those binders. - private static readonly ConcurrentDictionary> _binderCacheIgnoringCase + private static readonly ConcurrentDictionary> s_binderCacheIgnoringCase = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); static PSGetMemberBinder() { - _binderCache.Add(Tuple.Create(PSObject.AdaptedMemberSetName, (Type)null, false, false), + s_binderCache.Add(Tuple.Create(PSObject.AdaptedMemberSetName, (Type)null, false, false), new ReservedMemberBinder(PSObject.AdaptedMemberSetName, ignoreCase: true, @static: false)); - _binderCache.Add(Tuple.Create(PSObject.ExtendedMemberSetName, (Type)null, false, false), + s_binderCache.Add(Tuple.Create(PSObject.ExtendedMemberSetName, (Type)null, false, false), new ReservedMemberBinder(PSObject.ExtendedMemberSetName, ignoreCase: true, @static: false)); - _binderCache.Add(Tuple.Create(PSObject.BaseObjectMemberSetName, (Type)null, false, false), + s_binderCache.Add(Tuple.Create(PSObject.BaseObjectMemberSetName, (Type)null, false, false), new ReservedMemberBinder(PSObject.BaseObjectMemberSetName, ignoreCase: true, @static: false)); - _binderCache.Add(Tuple.Create(PSObject.PSObjectMemberSetName, (Type)null, false, false), + s_binderCache.Add(Tuple.Create(PSObject.PSObjectMemberSetName, (Type)null, false, false), new ReservedMemberBinder(PSObject.PSObjectMemberSetName, ignoreCase: true, @static: false)); - _binderCache.Add(Tuple.Create(PSObject.PSTypeNames, (Type)null, false, false), + s_binderCache.Add(Tuple.Create(PSObject.PSTypeNames, (Type)null, false, false), new ReservedMemberBinder(PSObject.PSTypeNames, ignoreCase: true, @static: false)); } @@ -4835,7 +4833,7 @@ namespace System.Management.Automation.Language // This way, we can avoid the call to TryGetInstanceMember for binders when we know there aren't any instance // members, yet invalidate those rules once somebody adds an instance member. - var binderList = _binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); lock (binderList) { @@ -4865,7 +4863,7 @@ namespace System.Management.Automation.Language private bool _hasTypeTableMember; internal static void TypeTableMemberAdded(string memberName) { - var binderList = _binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); lock (binderList) { @@ -4888,7 +4886,7 @@ namespace System.Management.Automation.Language internal static void TypeTableMemberPossiblyUpdated(string memberName) { - var binderList = _binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); lock (binderList) { @@ -4911,17 +4909,17 @@ namespace System.Management.Automation.Language private PSGetMemberBinder GetNonEnumeratingBinder() { - return Get(this.Name, this._classScope, @static: false, nonEnumerating: true); + return Get(this.Name, _classScope, @static: false, nonEnumerating: true); } private static PSGetMemberBinder Get(string memberName, Type classScope, bool @static, bool nonEnumerating) { PSGetMemberBinder result; - lock (_binderCache) + lock (s_binderCache) { var tuple = Tuple.Create(memberName, classScope, @static, nonEnumerating); - if (!_binderCache.TryGetValue(tuple, out result)) + if (!s_binderCache.TryGetValue(tuple, out result)) { // We might be seeing a reserved name with a different case. Check for that before // creating a new binder. For reserved names, we can safely use a single binder for @@ -4929,14 +4927,14 @@ namespace System.Management.Automation.Language if (PSMemberInfoCollection.IsReservedName(memberName)) { var tupleLower = Tuple.Create(memberName.ToLowerInvariant(), (Type)null, @static, nonEnumerating); - result = _binderCache[tupleLower]; + result = s_binderCache[tupleLower]; } else { result = new PSGetMemberBinder(memberName, classScope, true, @static, nonEnumerating); if (!@static) { - var binderList = _binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); lock (binderList) { if (binderList.Any()) @@ -4953,19 +4951,19 @@ namespace System.Management.Automation.Language } } } - _binderCache.Add(tuple, result); + s_binderCache.Add(tuple, result); } } return result; } - PSGetMemberBinder(string name, Type classScope, bool ignoreCase, bool @static, bool nonEnumerating) + private PSGetMemberBinder(string name, Type classScope, bool ignoreCase, bool @static, bool nonEnumerating) : base(name, ignoreCase) { - this._static = @static; - this._classScope = classScope; + _static = @static; + _classScope = classScope; this._version = 0; - this._nonEnumerating = nonEnumerating; + _nonEnumerating = nonEnumerating; } public override string ToString() @@ -5040,7 +5038,7 @@ namespace System.Management.Automation.Language this.GetUpdateExpression(typeof(object))); expr = WrapGetMemberInTry(expr); - return (new DynamicMetaObject(Expression.Block(new [] {memberInfoVar}, expr), BinderUtils.GetVersionCheck(this, _version))).WriteToDebugLog(this); + return (new DynamicMetaObject(Expression.Block(new[] { memberInfoVar }, expr), BinderUtils.GetVersionCheck(this, _version))).WriteToDebugLog(this); } bool canOptimize; @@ -5120,7 +5118,7 @@ namespace System.Management.Automation.Language Diagnostics.Assert(codeProperty.GetterCodeReference != null, "CodeProperty isn't gettable, should have generated error code above."); Diagnostics.Assert(codeProperty.GetterCodeReference.IsStatic, "CodeProperty should be a static method."); - expr = PSInvokeMemberBinder.InvokeMethod(codeProperty.GetterCodeReference, null, new[] { target }, + expr = PSInvokeMemberBinder.InvokeMethod(codeProperty.GetterCodeReference, null, new[] { target }, false, PSInvokeMemberBinder.MethodInvocationType.Getter); } @@ -5165,7 +5163,7 @@ namespace System.Management.Automation.Language var method = isGeneric ? CachedReflectionInfo.PSGetMemberBinder_TryGetGenericDictionaryValue.MakeGenericMethod(genericTypeArg) : CachedReflectionInfo.PSGetMemberBinder_TryGetIDictionaryValue; - expr = Expression.Block(new[] {temp}, + expr = Expression.Block(new[] { temp }, Expression.Condition( Expression.Call(method, GetTargetExpr(target, method.GetParameters()[0].ParameterType), Expression.Constant(Name), temp), temp, @@ -5223,7 +5221,7 @@ namespace System.Management.Automation.Language value = PSObject.Base(value); } - var type = castToType ?? ((value != null) ? value.GetType() : typeof(object)); + var type = castToType ?? ((value != null) ? value.GetType() : typeof(object)); #if CORECLR var typeInfo = type.GetTypeInfo(); // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up @@ -5256,7 +5254,7 @@ namespace System.Management.Automation.Language /// /// Return the binding result when no property exists. /// - DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingRestrictions restrictions) + private DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingRestrictions restrictions) { // If the property does not exist, but the target is enumerable, we'll turn this expression into roughly the equivalent // pipeline: @@ -5305,12 +5303,12 @@ namespace System.Management.Automation.Language return new DynamicMetaObject(result, restrictions); } - Expression ThrowPropertyNotFoundStrict() + private Expression ThrowPropertyNotFoundStrict() { return Compiler.CreateThrow(typeof(object), typeof(PropertyNotFoundException), - new[] {typeof(string), typeof(Exception), typeof(string), typeof(object[])}, + new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, "PropertyNotFoundStrict", null, ParserStrings.PropertyNotFoundStrict, - new object[] {Name}); + new object[] { Name }); } internal static DynamicMetaObject EnsureAllowedInLanguageMode(PSLanguageMode languageMode, DynamicMetaObject target, Object targetValue, @@ -5356,7 +5354,7 @@ namespace System.Management.Automation.Language var expr = Expression.Call(CachedReflectionInfo.PSGetMemberBinder_TryGetInstanceMember, target.Expression.Cast(typeof(object)), Expression.Constant(Name), memberInfoVar); - return BindingRestrictions.GetExpressionRestriction(Expression.Block(new [] {memberInfoVar}, Expression.Not(expr))); + return BindingRestrictions.GetExpressionRestriction(Expression.Block(new[] { memberInfoVar }, Expression.Not(expr))); } private static Expression WrapGetMemberInTry(Expression expr) @@ -5383,13 +5381,13 @@ namespace System.Management.Automation.Language /// /// Resolve the alias, throwing an exception if a cycle is detected while resolving the alias. /// - private PSMemberInfo ResolveAlias(PSAliasProperty alias, DynamicMetaObject target, HashSet aliases, + private PSMemberInfo ResolveAlias(PSAliasProperty alias, DynamicMetaObject target, HashSet aliases, List aliasRestrictions) { Diagnostics.Assert(null != aliasRestrictions, "aliasRestrictions cannot be null"); if (aliases == null) { - aliases = new HashSet {alias.Name}; + aliases = new HashSet { alias.Name }; } else { @@ -5412,7 +5410,7 @@ namespace System.Management.Automation.Language } PSMemberInfo result = binder.GetPSMemberInfo(target, out restrictions, out canOptimize, out aliasConversionType, aliases, aliasRestrictions); - + return result; } @@ -5534,7 +5532,6 @@ namespace System.Management.Automation.Language { restrictions = restrictions.Merge(aliasRestriction); } - } if (_classScope != null && (target.LimitType == _classScope || target.LimitType.IsSubclassOf(_classScope)) && adapterSet.OriginalAdapter == PSObject.dotNetInstanceAdapter) @@ -5641,7 +5638,7 @@ namespace System.Management.Automation.Language return memberInfo; } -#region Runtime helper methods + #region Runtime helper methods internal static PSMemberInfo CloneMemberInfo(PSMemberInfo memberInfo, object obj) { @@ -5708,7 +5705,7 @@ namespace System.Management.Automation.Language return (memberInfo != null); } - + internal static bool TryGetIDictionaryValue(IDictionary hash, string memberName, out object value) { try @@ -5741,7 +5738,7 @@ namespace System.Management.Automation.Language return false; } -#endregion Runtime helper methods + #endregion Runtime helper methods } /// @@ -5749,7 +5746,7 @@ namespace System.Management.Automation.Language /// internal class PSSetMemberBinder : SetMemberBinder { - class KeyComparer : IEqualityComparer + private class KeyComparer : IEqualityComparer { public bool Equals(PSSetMemberBinderKeyType x, PSSetMemberBinderKeyType y) { @@ -5770,7 +5767,7 @@ namespace System.Management.Automation.Language obj.Item3.GetHashCode()); } } - private static readonly Dictionary _binderCache + private static readonly Dictionary s_binderCache = new Dictionary(new KeyComparer()); private readonly bool _static; @@ -5786,13 +5783,13 @@ namespace System.Management.Automation.Language { PSSetMemberBinder result; - lock (_binderCache) + lock (s_binderCache) { var tuple = Tuple.Create(memberName, classScope, @static); - if (!_binderCache.TryGetValue(tuple, out result)) + if (!s_binderCache.TryGetValue(tuple, out result)) { result = new PSSetMemberBinder(memberName, true, @static, classScope); - _binderCache.Add(tuple, result); + s_binderCache.Add(tuple, result); } } return result; @@ -5801,9 +5798,9 @@ namespace System.Management.Automation.Language public PSSetMemberBinder(string name, bool ignoreCase, bool @static, Type classScope) : base(name, ignoreCase) { - this._static = @static; - this._classScope = classScope; - this._getMemberBinder = PSGetMemberBinder.Get(name, _classScope, @static); + _static = @static; + _classScope = classScope; + _getMemberBinder = PSGetMemberBinder.Get(name, _classScope, @static); } public override string ToString() @@ -5825,16 +5822,16 @@ namespace System.Management.Automation.Language Expression transformedExpression = originalExpression.Convert(typeof(object)); var engineIntrinsicsTempVar = Expression.Variable(typeof(EngineIntrinsics)); // apply tranformation attributes from right to left - for (int i = attributesArray.Length-1; i >= 0; i--) + for (int i = attributesArray.Length - 1; i >= 0; i--) { transformedExpression = Expression.Call(Expression.Constant(attributesArray[i]), CachedReflectionInfo.ArgumentTransformationAttribute_Transform, engineIntrinsicsTempVar, transformedExpression); } - return Expression.Block(new [] {engineIntrinsicsTempVar}, + return Expression.Block(new[] { engineIntrinsicsTempVar }, Expression.Assign( - engineIntrinsicsTempVar, + engineIntrinsicsTempVar, Expression.Property(ExpressionCache.GetExecutionContextFromTLS, CachedReflectionInfo.ExecutionContext_EngineIntrinsics)), transformedExpression); @@ -5868,7 +5865,7 @@ namespace System.Management.Automation.Language var targetValue = PSObject.Base(target.Value); if (targetValue == null) { - return (target.ThrowRuntimeError(new[] {value}, BindingRestrictions.Empty, "PropertyNotFound", + return (target.ThrowRuntimeError(new[] { value }, BindingRestrictions.Empty, "PropertyNotFound", ParserStrings.PropertyNotFound, Expression.Constant(Name))).WriteToDebugLog(this); } @@ -5944,7 +5941,7 @@ namespace System.Management.Automation.Language var valueExpr = PSConvertBinder.InvokeConverter(conversion, value.Expression, elementType, debase, ExpressionCache.InvariantCulture); return new DynamicMetaObject( - Expression.Block(new [] { temp }, + Expression.Block(new[] { temp }, Expression.Assign(temp, valueExpr), Expression.Call(PSGetMemberBinder.GetTargetExpr(target, hashType), mi, Expression.Constant(Name), valueExpr), @@ -5976,7 +5973,7 @@ namespace System.Management.Automation.Language if (runtimeError != null) { return runtimeError.WriteToDebugLog(this); - } + } } if (!canOptimize) @@ -6084,7 +6081,7 @@ namespace System.Management.Automation.Language expr = Expression.Block( new[] { tmp }, Expression.Assign(tmp, assignmentExpression), - Expression.Assign(lhs, Expression.New(lhsType.GetConstructor(new[] {nullableUnderlyingType}), tmp)), + Expression.Assign(lhs, Expression.New(lhsType.GetConstructor(new[] { nullableUnderlyingType }), tmp)), tmp.Cast(typeof(object))); } } @@ -6133,7 +6130,7 @@ namespace System.Management.Automation.Language Expression.Block( new[] { temp }, Expression.Assign(temp, value.CastOrConvert(temp.Type)), - PSInvokeMemberBinder.InvokeMethod(codeProperty.SetterCodeReference, null, new[] { target, value }, + PSInvokeMemberBinder.InvokeMethod(codeProperty.SetterCodeReference, null, new[] { target, value }, false, PSInvokeMemberBinder.MethodInvocationType.Setter), temp), restrictions).WriteToDebugLog(this); @@ -6203,7 +6200,7 @@ namespace System.Management.Automation.Language { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); } - + if (memberInfo == null && adapterSet.DotNetAdapter != null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, member); @@ -6234,9 +6231,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate regular binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSSetMemberBinder binder in _binderCache.Values) + foreach (PSSetMemberBinder binder in s_binderCache.Values) { binder._getMemberBinder._version += 1; } @@ -6258,7 +6255,6 @@ namespace System.Management.Automation.Language internal class PSInvokeMemberBinder : InvokeMemberBinder { - internal enum MethodInvocationType { Ordinary, @@ -6268,7 +6264,7 @@ namespace System.Management.Automation.Language NonVirtual, } - class KeyComparer : IEqualityComparer + private class KeyComparer : IEqualityComparer { public bool Equals(PSInvokeMemberBinderKeyType x, PSInvokeMemberBinderKeyType y) { @@ -6295,7 +6291,7 @@ namespace System.Management.Automation.Language } private static readonly - Dictionary _binderCache = new Dictionary (new KeyComparer()); + Dictionary s_binderCache = new Dictionary(new KeyComparer()); internal readonly PSMethodInvocationConstraints _invocationConstraints; internal readonly PSGetMemberBinder _getMemberBinder; @@ -6316,13 +6312,13 @@ namespace System.Management.Automation.Language { PSInvokeMemberBinder result; - lock (_binderCache) + lock (s_binderCache) { var key = Tuple.Create(memberName, callInfo, propertySetter, nonEnumerating, constraints, @static, classScope); - if (!_binderCache.TryGetValue(key, out result)) + if (!s_binderCache.TryGetValue(key, out result)) { result = new PSInvokeMemberBinder(memberName, true, @static, propertySetter, nonEnumerating, callInfo, constraints, classScope); - _binderCache.Add(key, result); + s_binderCache.Add(key, result); } } return result; @@ -6343,11 +6339,11 @@ namespace System.Management.Automation.Language Type classScope) : base(name, ignoreCase, callInfo) { - this._static = @static; - this._propertySetter = propertySetter; - this._nonEnumerating = nonEnumerating; + _static = @static; + _propertySetter = propertySetter; + _nonEnumerating = nonEnumerating; this._invocationConstraints = invocationConstraints; - this._classScope = classScope; + _classScope = classScope; this._getMemberBinder = PSGetMemberBinder.Get(name, classScope, @static); } @@ -6457,7 +6453,7 @@ namespace System.Management.Automation.Language // the language check to unsafe types, as a safe type might have an unsafe method. if (ExecutionContext.HasEverUsedConstrainedLanguage) { - restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); + restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); // Validate that this is allowed in the current language mode var context = LocalPipeline.GetExecutionContextFromTLS(); @@ -6467,7 +6463,7 @@ namespace System.Management.Automation.Language if (runtimeError != null) { return runtimeError.WriteToDebugLog(this); - } + } } if (!canOptimize) @@ -6511,14 +6507,14 @@ namespace System.Management.Automation.Language // We add restriction to do this check only if the methodInfo is a .NET method/parameterizedProperty, otherwise it's not affected by the above cases, for example, a PSScriptMethod // defined in the TypeTable will only get affected by the PSTypeNames. if (methodInfo is PSMethod || methodInfo is PSParameterizedProperty) - { + { var psObj = target.Value as PSObject; if (psObj != null && (targetValue.GetType() == typeof(Hashtable) || targetValue.GetType() == typeof(ArrayList))) { // If we get here, then the target value should have 'isDeserialized == false', otherwise we cannot get a .NET methodInfo // from _getMemberBinder.GetPSMemberInfo(). This is because when 'isDeserialized' is true, we use the PSObject to find the // corresponding Adapter -- PSObjectAdapter, which cannot be optimized. - Diagnostics.Assert(psObj.isDeserialized == false, + Diagnostics.Assert(psObj.isDeserialized == false, "isDeserialized should be false, because if not, we cannot get a .NET method/parameterizedProperty from GetPSMemberInfo"); restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction( @@ -6630,7 +6626,7 @@ namespace System.Management.Automation.Language { var argTypes = (psMethodInvocationConstraints == null) ? new Type[numArgs] - : psMethodInvocationConstraints.ParameterTypes.ToArray(); + : psMethodInvocationConstraints.ParameterTypes.ToArray(); psMethodInvocationConstraints = new PSMethodInvocationConstraints(target.Value.GetType(), argTypes); } @@ -6662,7 +6658,7 @@ namespace System.Management.Automation.Language return new DynamicMetaObject(expr, restrictions); } - expr = expr.Cast(typeof (object)); + expr = expr.Cast(typeof(object)); // Likewise, when calling methods in types defined by PowerShell, we don't // want to wrap the exception. @@ -6823,7 +6819,7 @@ namespace System.Management.Automation.Language var methodInfo = mi as MethodInfo; if (methodInfo == null) { - constructorInfo = (ConstructorInfo) mi; + constructorInfo = (ConstructorInfo)mi; } Expression call; @@ -6852,8 +6848,8 @@ namespace System.Management.Automation.Language call = Expression.Call( methodInfo.ReturnType == typeof(void) ? CachedReflectionInfo.ClassOps_CallVoidMethodNonVirtually - : CachedReflectionInfo.ClassOps_CallMethodNonVirtually , - PSGetMemberBinder.GetTargetExpr(target, methodInfo.DeclaringType), + : CachedReflectionInfo.ClassOps_CallMethodNonVirtually, + PSGetMemberBinder.GetTargetExpr(target, methodInfo.DeclaringType), Expression.Constant(methodInfo, typeof(MethodInfo)), Expression.NewArrayInit(typeof(object), argExprs.Select(x => x.Cast(typeof(object))))); } @@ -6883,7 +6879,7 @@ namespace System.Management.Automation.Language return call; } - DynamicMetaObject InvokeMemberOnCollection(DynamicMetaObject targetEnumerator, DynamicMetaObject[] args, Type typeForMessage, BindingRestrictions restrictions) + private DynamicMetaObject InvokeMemberOnCollection(DynamicMetaObject targetEnumerator, DynamicMetaObject[] args, Type typeForMessage, BindingRestrictions restrictions) { var d = DynamicExpression.Dynamic(this, this.ReturnType, args.Select(a => a.Expression).Prepend(ExpressionCache.NullConstant)); return new DynamicMetaObject( @@ -6904,7 +6900,7 @@ namespace System.Management.Automation.Language if (enumerableTarget == null) { // Wrap the target in an array. - enumerableTarget = PSEnumerableBinder.IsEnumerable( + enumerableTarget = PSEnumerableBinder.IsEnumerable( new DynamicMetaObject( Expression.NewArrayInit(typeof(object), target.Expression.Cast(typeof(object))), target.GetSimpleTypeRestriction())); @@ -6919,54 +6915,55 @@ namespace System.Management.Automation.Language /// the matching behaviour returning the first, last or all matching elements. /// /// The binding restrictions for the arguments. - DynamicMetaObject InvokeWhereOnCollection(DynamicMetaObject target, DynamicMetaObject[] args, BindingRestrictions argRestrictions) + private DynamicMetaObject InvokeWhereOnCollection(DynamicMetaObject target, DynamicMetaObject[] args, BindingRestrictions argRestrictions) { var lhsEnumerator = GetTargetAsEnumerable(target); switch (args.Length) { - case 1: - return new DynamicMetaObject( - Expression.Call(CachedReflectionInfo.EnumerableOps_Where, - lhsEnumerator.Expression, - PSGetMemberBinder.GetTargetExpr(args[0]).Convert(typeof(ScriptBlock)), - Expression.Constant(WhereOperatorSelectionMode.Default), - Expression.Constant(0)), - lhsEnumerator.Restrictions.Merge(argRestrictions)); - case 2: - return new DynamicMetaObject( + case 1: + return new DynamicMetaObject( + Expression.Call(CachedReflectionInfo.EnumerableOps_Where, + lhsEnumerator.Expression, + PSGetMemberBinder.GetTargetExpr(args[0]).Convert(typeof(ScriptBlock)), + Expression.Constant(WhereOperatorSelectionMode.Default), + Expression.Constant(0)), + lhsEnumerator.Restrictions.Merge(argRestrictions)); + case 2: + return new DynamicMetaObject( + Expression.Call(CachedReflectionInfo.EnumerableOps_Where, + lhsEnumerator.Expression, + PSGetMemberBinder.GetTargetExpr(args[0]).Convert(typeof(ScriptBlock)), + PSGetMemberBinder.GetTargetExpr(args[1]).Convert(typeof(WhereOperatorSelectionMode)), + Expression.Constant(0)), + lhsEnumerator.Restrictions.Merge(argRestrictions)); + case 3: + return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.EnumerableOps_Where, lhsEnumerator.Expression, PSGetMemberBinder.GetTargetExpr(args[0]).Convert(typeof(ScriptBlock)), PSGetMemberBinder.GetTargetExpr(args[1]).Convert(typeof(WhereOperatorSelectionMode)), - Expression.Constant(0)), + PSGetMemberBinder.GetTargetExpr(args[2]).Convert(typeof(int))), lhsEnumerator.Restrictions.Merge(argRestrictions)); - case 3: - return new DynamicMetaObject( - Expression.Call(CachedReflectionInfo.EnumerableOps_Where, - lhsEnumerator.Expression, - PSGetMemberBinder.GetTargetExpr(args[0]).Convert(typeof(ScriptBlock)), - PSGetMemberBinder.GetTargetExpr(args[1]).Convert(typeof(WhereOperatorSelectionMode)), - PSGetMemberBinder.GetTargetExpr(args[2]).Convert(typeof(int))), - lhsEnumerator.Restrictions.Merge(argRestrictions)); - default: - { - // If the arity is wrong, throw the extended type system exception. - return new DynamicMetaObject( - Expression.Throw( - Expression.New(CachedReflectionInfo.MethodException_ctor, - Expression.Constant("MethodCountCouldNotFindBest"), - Expression.Constant(null, typeof(Exception)), - Expression.Constant(ExtendedTypeSystem.MethodArgumentCountException), - Expression.NewArrayInit(typeof(object), - Expression.Constant(".Where({ expression } [, mode [, numberToReturn]])").Cast(typeof(object)), - ExpressionCache.Constant(args.Length).Cast(typeof(object)))), - this.ReturnType), - lhsEnumerator.Restrictions.Merge(argRestrictions)); - }} + default: + { + // If the arity is wrong, throw the extended type system exception. + return new DynamicMetaObject( + Expression.Throw( + Expression.New(CachedReflectionInfo.MethodException_ctor, + Expression.Constant("MethodCountCouldNotFindBest"), + Expression.Constant(null, typeof(Exception)), + Expression.Constant(ExtendedTypeSystem.MethodArgumentCountException), + Expression.NewArrayInit(typeof(object), + Expression.Constant(".Where({ expression } [, mode [, numberToReturn]])").Cast(typeof(object)), + ExpressionCache.Constant(args.Length).Cast(typeof(object)))), + this.ReturnType), + lhsEnumerator.Restrictions.Merge(argRestrictions)); + } + } } - DynamicMetaObject InvokeForEachOnCollection(DynamicMetaObject targetEnumerator, DynamicMetaObject[] args, BindingRestrictions restrictions) + private DynamicMetaObject InvokeForEachOnCollection(DynamicMetaObject targetEnumerator, DynamicMetaObject[] args, BindingRestrictions restrictions) { targetEnumerator = GetTargetAsEnumerable(targetEnumerator); @@ -7003,7 +7000,7 @@ namespace System.Management.Automation.Language targetEnumerator.Restrictions.Merge(restrictions)); } -#region Runtime helpers + #region Runtime helpers internal static bool IsHomogenousArray(object[] args) { @@ -7113,26 +7110,26 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate regular binders - lock (_binderCache) + lock (s_binderCache) { - foreach (PSInvokeMemberBinder binder in _binderCache.Values) + foreach (PSInvokeMemberBinder binder in s_binderCache.Values) { binder._getMemberBinder._version += 1; } } } -#endregion + #endregion } - class PSCreateInstanceBinder : CreateInstanceBinder + internal class PSCreateInstanceBinder : CreateInstanceBinder { private readonly CallInfo _callInfo; private readonly PSMethodInvocationConstraints _constraints; private readonly bool _publicTypeOnly; private int _version; - class KeyComparer : IEqualityComparer> + private class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -7150,7 +7147,7 @@ namespace System.Management.Automation.Language private static readonly Dictionary, PSCreateInstanceBinder> - _binderCache = + s_binderCache = new Dictionary , PSCreateInstanceBinder>( new KeyComparer()); @@ -7159,13 +7156,13 @@ namespace System.Management.Automation.Language { PSCreateInstanceBinder result; - lock (_binderCache) + lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints, publicTypeOnly); - if (!_binderCache.TryGetValue(key, out result)) + if (!s_binderCache.TryGetValue(key, out result)) { result = new PSCreateInstanceBinder(callInfo, constraints, publicTypeOnly); - _binderCache.Add(key, result); + s_binderCache.Add(key, result); } } return result; @@ -7173,9 +7170,9 @@ namespace System.Management.Automation.Language internal static void InvalidateCache() { // Invalidate binders - lock (_binderCache) + lock (s_binderCache) { - foreach (var binder in _binderCache.Values) + foreach (var binder in s_binderCache.Values) { binder._version += 1; } @@ -7248,7 +7245,7 @@ namespace System.Management.Automation.Language restrictions = args.Aggregate(restrictions, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); var newConstructors = DotNetAdapter.GetMethodInformationArray(ctors); return PSInvokeMemberBinder.InvokeDotNetMethod(_callInfo, "new", _constraints, PSInvokeMemberBinder.MethodInvocationType.Ordinary, - target, args, restrictions, newConstructors , typeof(MethodException)).WriteToDebugLog(this); + target, args, restrictions, newConstructors, typeof(MethodException)).WriteToDebugLog(this); } /// @@ -7276,12 +7273,12 @@ namespace System.Management.Automation.Language } } - class PSInvokeBaseCtorBinder : InvokeMemberBinder + internal class PSInvokeBaseCtorBinder : InvokeMemberBinder { private readonly CallInfo _callInfo; private readonly PSMethodInvocationConstraints _constraints; - class KeyComparer : IEqualityComparer> + private class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -7298,7 +7295,7 @@ namespace System.Management.Automation.Language private static readonly Dictionary, PSInvokeBaseCtorBinder> - _binderCache = + s_binderCache = new Dictionary , PSInvokeBaseCtorBinder>( new KeyComparer()); @@ -7307,13 +7304,13 @@ namespace System.Management.Automation.Language { PSInvokeBaseCtorBinder result; - lock (_binderCache) + lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints); - if (!_binderCache.TryGetValue(key, out result)) + if (!s_binderCache.TryGetValue(key, out result)) { result = new PSInvokeBaseCtorBinder(callInfo, constraints); - _binderCache.Add(key, result); + s_binderCache.Add(key, result); } } return result; @@ -7357,5 +7354,5 @@ namespace System.Management.Automation.Language } } -#endregion Standard binders + #endregion Standard binders } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 65d9c32c6..2ba238358 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -51,7 +51,7 @@ namespace System.Management.Automation { internal CompiledScriptBlockData(IParameterMetadataProvider ast, bool isFilter) { - this._ast = ast; + _ast = ast; this.IsFilter = isFilter; this.Id = Guid.NewGuid(); } @@ -59,7 +59,7 @@ namespace System.Management.Automation internal CompiledScriptBlockData(string scriptText, bool isProductCode) { this.IsProductCode = isProductCode; - this._scriptText = scriptText; + _scriptText = scriptText; this.Id = Guid.NewGuid(); } @@ -114,7 +114,7 @@ namespace System.Management.Automation { if (attribute is CmdletBindingAttribute) { - cmdletBindingAttribute = cmdletBindingAttribute ?? (CmdletBindingAttribute) attribute; + cmdletBindingAttribute = cmdletBindingAttribute ?? (CmdletBindingAttribute)attribute; } else if (attribute is DebuggerHiddenAttribute) { @@ -211,7 +211,7 @@ namespace System.Management.Automation if (AmsiUtils.ScanContent(scriptExtent.Text, scriptExtent.File) == AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED) { var parseError = new ParseError(scriptExtent, "ScriptContainedMaliciousContent", ParserStrings.ScriptContainedMaliciousContent); - throw new ParseException(new [] {parseError}); + throw new ParseException(new[] { parseError }); } if (ScriptBlock.CheckSuspiciousContent(scriptBlockAst) != null) @@ -282,7 +282,8 @@ namespace System.Management.Automation return scriptBlockAst != null && scriptBlockAst.IsConfiguration; } - internal bool HasSuspiciousContent { + internal bool HasSuspiciousContent + { get { Diagnostics.Assert(_compiledOptimized || _compiledUnoptimized, "HasSuspiciousContent is not set correctly before being compiled"); @@ -413,7 +414,7 @@ namespace System.Management.Automation private ScriptBlock(CompiledScriptBlockData scriptBlockData) { - this._scriptBlockData = scriptBlockData; + _scriptBlockData = scriptBlockData; // LanguageMode is a nullable PSLanguageMode enumeration because script blocks // need to inherit the language mode from the context in which they are executing. @@ -439,7 +440,7 @@ namespace System.Management.Automation { } - private static readonly ConcurrentDictionary, ScriptBlock> _cachedScripts = + private static readonly ConcurrentDictionary, ScriptBlock> s_cachedScripts = new ConcurrentDictionary, ScriptBlock>(); internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string fileContents) { @@ -450,7 +451,7 @@ namespace System.Management.Automation ScriptBlock scriptBlock; var key = Tuple.Create(fileName, fileContents); - if (_cachedScripts.TryGetValue(key, out scriptBlock)) + if (s_cachedScripts.TryGetValue(key, out scriptBlock)) { Diagnostics.Assert(scriptBlock.SessionStateInternal == null, "A cached scriptblock should not have it's session state bound, that causes a memory leak."); @@ -461,7 +462,7 @@ namespace System.Management.Automation private static bool IsDynamicKeyword(Ast ast) { - var cmdAst = ast as CommandAst; + var cmdAst = ast as CommandAst; return (cmdAst != null && cmdAst.DefiningKeyword != null); } @@ -488,18 +489,18 @@ namespace System.Management.Automation // // using is always a top-level statements in scriptBlock, we don't need to search in child blocks. - if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null || + if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null || scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) != null) { return; } - if (_cachedScripts.Count > 1024) + if (s_cachedScripts.Count > 1024) { - _cachedScripts.Clear(); + s_cachedScripts.Clear(); } var key = Tuple.Create(fileName, fileContents); - _cachedScripts.TryAdd(key, scriptBlock); + s_cachedScripts.TryAdd(key, scriptBlock); } /// @@ -507,7 +508,7 @@ namespace System.Management.Automation /// internal static void ClearScriptBlockCache() { - _cachedScripts.Clear(); + s_cachedScripts.Clear(); } internal static ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock("", isProductCode: true); @@ -1195,7 +1196,7 @@ namespace System.Management.Automation } optimized = _scriptBlockData.Compile(optimized); - + if (optimized) { switch (clauseToInvoke) @@ -1296,7 +1297,7 @@ namespace System.Management.Automation "Software\\Policies\\Microsoft\\Windows\\EventLog", "ProtectedEventLogging", Utils.RegLocalMachine); if (protectedEventLoggingSettings != null) { - lock (syncObject) + lock (s_syncObject) { // Populates the encryptionRecipients list from the Group Policy, if possible. If not possible, // does all appropriate logging and encryptionRecipients is 'null'. 'CouldLog' being false @@ -1309,12 +1310,12 @@ namespace System.Management.Automation // If we have recipients to encrypt to, then do so. Otherwise, we'll just log the plain text // version. - if (encryptionRecipients != null) + if (s_encryptionRecipients != null) { ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS(); ErrorRecord error = null; byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(textToLog); - string encodedContent = CmsUtils.Encrypt(contentBytes, encryptionRecipients, executionContext.SessionState, out error); + string encodedContent = CmsUtils.Encrypt(contentBytes, s_encryptionRecipients, executionContext.SessionState, out error); // Can't cache the reporting of encryption errors, as they are likely content-based. if (error != null) @@ -1399,14 +1400,14 @@ namespace System.Management.Automation ResetCertificateCacheIfNeeded(fullCertificateContent); // If we have valid recipients, no need for further analysis. - if (encryptionRecipients != null) + if (s_encryptionRecipients != null) { return true; } // If we've already verified all of the properties of the cert we care about (even if it // didn't result in a valid cert), return now. - if (hasProcessedCertificate) + if (s_hasProcessedCertificate) { return true; } @@ -1414,7 +1415,7 @@ namespace System.Management.Automation // Resolve the certificate to a recipient CmsMessageRecipient recipient = new CmsMessageRecipient(fullCertificateContent); recipient.Resolve(sessionState, ResolutionPurpose.Encryption, out error); - hasProcessedCertificate = true; + s_hasProcessedCertificate = true; // If there's an error that we haven't already reported, report it in the event log. // We only do this once, as the error will always be the same for a given certificate. @@ -1433,7 +1434,7 @@ namespace System.Management.Automation } // Now, save the certificate. We'll be comfortable using this one from now on. - encryptionRecipients = new CmsMessageRecipient[] { recipient }; + s_encryptionRecipients = new CmsMessageRecipient[] { recipient }; // Check if the certificate has a private key, and report a warning if so. // We only do this once, as the error will always be the same for a given certificate. @@ -1462,19 +1463,19 @@ namespace System.Management.Automation return true; } - private static object syncObject = new Object(); - private static string lastSeenCertificate = String.Empty; - private static bool hasProcessedCertificate = false; - private static CmsMessageRecipient[] encryptionRecipients = null; + private static object s_syncObject = new Object(); + private static string s_lastSeenCertificate = String.Empty; + private static bool s_hasProcessedCertificate = false; + private static CmsMessageRecipient[] s_encryptionRecipients = null; // Reset any static caches if the certificate has changed private static void ResetCertificateCacheIfNeeded(string certificate) { - if (!String.Equals(lastSeenCertificate, certificate, StringComparison.Ordinal)) + if (!String.Equals(s_lastSeenCertificate, certificate, StringComparison.Ordinal)) { - hasProcessedCertificate = false; - lastSeenCertificate = certificate; - encryptionRecipients = null; + s_hasProcessedCertificate = false; + s_lastSeenCertificate = certificate; + s_encryptionRecipients = null; } } @@ -1528,7 +1529,7 @@ namespace System.Management.Automation { if (foundSignature == null) { - if (signatures.Contains(element)) + if (s_signatures.Contains(element)) { foundSignature = element; loopState.Break(); @@ -1550,7 +1551,7 @@ namespace System.Management.Automation return (!ast.HasSuspiciousContent) && (ast.Parent.HasSuspiciousContent); }, true); - if(foundAst != null) + if (foundAst != null) { return foundAst.Parent.Extent.Text; } @@ -1564,7 +1565,7 @@ namespace System.Management.Automation } // Extract tokens of a-z A-Z and dash - static IEnumerable TokenizeWordElements(string scriptBlockText) + private static IEnumerable TokenizeWordElements(string scriptBlockText) { StringBuilder currentElement = new StringBuilder(100); @@ -1614,8 +1615,7 @@ namespace System.Management.Automation } // Regular string signatures that can be detected with just string comparison. - private static HashSet signatures = new HashSet(StringComparer.OrdinalIgnoreCase) { - + private static HashSet s_signatures = new HashSet(StringComparer.OrdinalIgnoreCase) { // Calling Add-Type "Add-Type", "DllImport", @@ -1643,7 +1643,7 @@ namespace System.Management.Automation // Suspicious Win32 API calls "OpenProcess", "VirtualAlloc", "VirtualFree", "WriteProcessMemory", "CreateUserThread", "CloseHandle", "GetDelegateForFunctionPointer", "kernel32", "CreateThread", "memcpy", "LoadLibrary", "GetModuleHandle", - "GetProcAddress", "VirtualProtect", "FreeLibrary", "ReadProcessMemory", "CreateRemoteThread", + "GetProcAddress", "VirtualProtect", "FreeLibrary", "ReadProcessMemory", "CreateRemoteThread", "AdjustTokenPrivileges", "WriteByte", "WriteInt32", "OpenThreadToken", "PtrToString", "FreeHGlobal", "ZeroFreeGlobalAllocUnicode", "OpenProcessToken", "GetTokenInformation", "SetThreadToken", "ImpersonateLoggedOnUser", "RevertToSelf", "GetLogonSessionData", "CreateProcessWithToken", @@ -1665,8 +1665,8 @@ namespace System.Management.Automation "ScriptBlockLogging", "LogPipelineExecutionDetails", "ProtectedEventLogging", }; - internal static bool ScriptBlockLoggingExplicitlyDisabled() - { + internal static bool ScriptBlockLoggingExplicitlyDisabled() + { // Verify they haven't explicitly turned off script block logging. Dictionary groupPolicySettings = Utils.GetGroupPolicySetting("ScriptBlockLogging", Utils.RegLocalMachineThenCurrentUser); if (groupPolicySettings != null) @@ -1683,8 +1683,8 @@ namespace System.Management.Automation } } - return false; - } + return false; + } internal static void LogScriptBlockStart(ScriptBlock scriptBlock, Guid runspaceId) { @@ -1743,14 +1743,14 @@ namespace System.Management.Automation [Serializable] internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference { - private readonly string scriptText; + private readonly string _scriptText; private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); - scriptText = info.GetValue("ScriptText", typeof(string)) as string; - if (scriptText == null) + _scriptText = info.GetValue("ScriptText", typeof(string)) as string; + if (_scriptText == null) { throw PSTraceSource.NewArgumentNullException("info"); } @@ -1763,7 +1763,7 @@ namespace System.Management.Automation /// A script block that corresponds to the version deserialized public Object GetRealObject(StreamingContext context) { - return ScriptBlock.Create(scriptText); + return ScriptBlock.Create(_scriptText); } /// @@ -1792,14 +1792,14 @@ namespace System.Management.Automation public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, ExecutionContext context) { - this._scriptBlock = scriptBlock; - this._useLocalScope = useNewScope; - this._fromScriptFile = fromScriptFile; - this._runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope); - this._localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized); + _scriptBlock = scriptBlock; + _useLocalScope = useNewScope; + _fromScriptFile = fromScriptFile; + _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope); + _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized); _localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, context); - this._functionContext = new FunctionContext + _functionContext = new FunctionContext { _localsTuple = _localsTuple, _scriptBlock = _scriptBlock, @@ -1809,7 +1809,7 @@ namespace System.Management.Automation _debuggerStepThrough = _scriptBlock.DebuggerStepThrough, _executionContext = context, }; - this._rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit; + _rethrowExitException = context.ScriptCommandProcessorShouldRethrowExit; context.ScriptCommandProcessorShouldRethrowExit = false; } @@ -1818,11 +1818,11 @@ namespace System.Management.Automation // commandRuntime and the execution context are set here and in GetDynamicParameters. GetDynamicParameters isn't // called unless the scriptblock has a dynamicparam block, so we must set these values in both places. It'd // be cleaner to set in the constructor, but neither the commandRuntime nor the context are set when being constructed. - this._commandRuntime = (MshCommandRuntime)commandRuntime; + _commandRuntime = (MshCommandRuntime)commandRuntime; // We don't set the output pipe until after GetDynamicParameters because dynamic parameters aren't written to the // command processors pipe, but once we enter begin, we will write to the default pipe. - this._functionContext._outputPipe = _commandRuntime.OutputPipe; + _functionContext._outputPipe = _commandRuntime.OutputPipe; SetPreferenceVariables(); @@ -1871,7 +1871,7 @@ namespace System.Management.Automation private void EnterScope() { - this._commandRuntime.SetVariableListsInPipe(); + _commandRuntime.SetVariableListsInPipe(); if (!_useLocalScope) { @@ -1881,7 +1881,7 @@ namespace System.Management.Automation private void ExitScope() { - this._commandRuntime.RemoveVariableListsInPipe(); + _commandRuntime.RemoveVariableListsInPipe(); if (!_useLocalScope) { @@ -1897,11 +1897,11 @@ namespace System.Management.Automation // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if ((this._scriptBlock.LanguageMode.HasValue) && - (this._scriptBlock.LanguageMode != Context.LanguageMode)) + if ((_scriptBlock.LanguageMode.HasValue) && + (_scriptBlock.LanguageMode != Context.LanguageMode)) { oldLanguageMode = Context.LanguageMode; - newLanguageMode = this._scriptBlock.LanguageMode; + newLanguageMode = _scriptBlock.LanguageMode; } try @@ -1957,12 +1957,12 @@ namespace System.Management.Automation } catch (ExitException ee) { - if (!this._fromScriptFile || _rethrowExitException) + if (!_fromScriptFile || _rethrowExitException) { throw; } - this._exitWasCalled = true; + _exitWasCalled = true; int exitCode = (int)ee.Argument; this.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode); @@ -1991,7 +1991,7 @@ namespace System.Management.Automation public object GetDynamicParameters() { - this._commandRuntime = (MshCommandRuntime)commandRuntime; + _commandRuntime = (MshCommandRuntime)commandRuntime; if (_scriptBlock.HasDynamicParameters) { @@ -2020,41 +2020,40 @@ namespace System.Management.Automation _localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, commandLineParameters.GetValueToBindToPSBoundParameters(), this.Context); _localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, MyInvocation, this.Context); - } private void SetPreferenceVariables() { - if (this._commandRuntime.IsDebugFlagSet) + if (_commandRuntime.IsDebugFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Debug, - this._commandRuntime.Debug ? ActionPreference.Inquire : ActionPreference.SilentlyContinue); + _commandRuntime.Debug ? ActionPreference.Inquire : ActionPreference.SilentlyContinue); } - if (this._commandRuntime.IsVerboseFlagSet) + if (_commandRuntime.IsVerboseFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Verbose, - this._commandRuntime.Verbose ? ActionPreference.Continue : ActionPreference.SilentlyContinue); + _commandRuntime.Verbose ? ActionPreference.Continue : ActionPreference.SilentlyContinue); } - if (this._commandRuntime.IsErrorActionSet) + if (_commandRuntime.IsErrorActionSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Error, this._commandRuntime.ErrorAction); + _localsTuple.SetPreferenceVariable(PreferenceVariable.Error, _commandRuntime.ErrorAction); } - if (this._commandRuntime.IsWarningActionSet) + if (_commandRuntime.IsWarningActionSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Warning, this._commandRuntime.WarningPreference); + _localsTuple.SetPreferenceVariable(PreferenceVariable.Warning, _commandRuntime.WarningPreference); } - if (this._commandRuntime.IsInformationActionSet) + if (_commandRuntime.IsInformationActionSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.Information, this._commandRuntime.InformationPreference); + _localsTuple.SetPreferenceVariable(PreferenceVariable.Information, _commandRuntime.InformationPreference); } - if (this._commandRuntime.IsWhatIfFlagSet) + if (_commandRuntime.IsWhatIfFlagSet) { - _localsTuple.SetPreferenceVariable(PreferenceVariable.WhatIf, this._commandRuntime.WhatIf); + _localsTuple.SetPreferenceVariable(PreferenceVariable.WhatIf, _commandRuntime.WhatIf); } - if (this._commandRuntime.IsConfirmFlagSet) + if (_commandRuntime.IsConfirmFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.Confirm, - this._commandRuntime.Confirm ? ConfirmImpact.Low : ConfirmImpact.None); + _commandRuntime.Confirm ? ConfirmImpact.Low : ConfirmImpact.None); } } @@ -2099,6 +2098,5 @@ namespace System.Management.Automation } #endregion IDispose - } } diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index e382afc93..da85a0fa1 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -29,9 +29,10 @@ namespace System.Management.Automation { using DynamicNull = System.Management.Automation.LanguagePrimitives.Null; - internal abstract class MutableTuple { + internal abstract class MutableTuple + { private const int MaxSize = 128; - private static readonly Dictionary _sizeDict = new Dictionary(); + private static readonly Dictionary s_sizeDict = new Dictionary(); private int _size; protected BitArray _valuesSet; @@ -39,7 +40,8 @@ namespace System.Management.Automation internal bool IsValueSet(int index) { - if (_size < MutableTuple.MaxSize) { + if (_size < MutableTuple.MaxSize) + { // fast path return _valuesSet[index]; } @@ -146,16 +148,22 @@ namespace System.Management.Automation /// Sets the value at the given index for a tuple of the given size. This set supports /// walking through nested tuples to get the correct final index. /// - private void SetNestedValue(int size, int index, object value) { - if (size < MutableTuple.MaxSize) { + private void SetNestedValue(int size, int index, object value) + { + if (size < MutableTuple.MaxSize) + { // fast path SetValueImpl(index, value); - } else { + } + else + { // slow path MutableTuple res = this; int lastAccess = -1; - foreach (int i in GetAccessPath(size, index)) { - if (lastAccess != -1) { + foreach (int i in GetAccessPath(size, index)) + { + if (lastAccess != -1) + { res = (MutableTuple)res.GetValueImpl(lastAccess); } lastAccess = i; @@ -168,14 +176,19 @@ namespace System.Management.Automation /// Gets the value at the given index for a tuple of the given size. This get /// supports walking through nested tuples to get the correct final index. /// - private object GetNestedValue(int size, int index) { - if (size < MutableTuple.MaxSize) { + private object GetNestedValue(int size, int index) + { + if (size < MutableTuple.MaxSize) + { // fast path return GetValueImpl(index); - } else { + } + else + { // slow path object res = this; - foreach (int i in GetAccessPath(size, index)) { + foreach (int i in GetAccessPath(size, index)) + { res = ((MutableTuple)res).GetValueImpl(i); } return res; @@ -185,29 +198,46 @@ namespace System.Management.Automation /// /// Gets the unbound generic Tuple type which has at lease size slots or null if a large enough tuple is not available. /// - private static Type GetTupleType(int size) { + private static Type GetTupleType(int size) + { #region Generated Tuple Get From Size // *** BEGIN GENERATED CODE *** // generated by function: gen_get_size from: generate_tuples.py - if (size <= MutableTuple.MaxSize) { - if (size <= 1) { + if (size <= MutableTuple.MaxSize) + { + if (size <= 1) + { return typeof(MutableTuple<>); - } else if (size <= 2) { - return typeof(MutableTuple<, >); - } else if (size <= 4) { - return typeof(MutableTuple<, , , >); - } else if (size <= 8) { - return typeof(MutableTuple<, , , , , , , >); - } else if (size <= 16) { - return typeof(MutableTuple<, , , , , , , , , , , , , , , >); - } else if (size <= 32) { - return typeof(MutableTuple<, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , >); - } else if (size <= 64) { - return typeof(MutableTuple<, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , >); - } else { - return typeof(MutableTuple<, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , >); + } + else if (size <= 2) + { + return typeof(MutableTuple<,>); + } + else if (size <= 4) + { + return typeof(MutableTuple<,,,>); + } + else if (size <= 8) + { + return typeof(MutableTuple<,,,,,,,>); + } + else if (size <= 16) + { + return typeof(MutableTuple<,,,,,,,,,,,,,,,>); + } + else if (size <= 32) + { + return typeof(MutableTuple<,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>); + } + else if (size <= 64) + { + return typeof(MutableTuple<,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>); + } + else + { + return typeof(MutableTuple<,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>); } } @@ -225,7 +255,8 @@ namespace System.Management.Automation /// create a single tuple. If it's greater then we create nested tuples /// (e.g. a Tuple`2 which contains a Tuple`128 and a Tuple`8 if we had a size of 136). /// - public static Type MakeTupleType(params Type[] types) { + public static Type MakeTupleType(params Type[] types) + { //ContractUtils.RequiresNotNull(types, "types"); return MakeTupleType(types, 0, types.Length); @@ -234,18 +265,22 @@ namespace System.Management.Automation /// /// Gets the number of usable slots in the provided Tuple type including slots available in nested tuples. /// - public static int GetSize(Type tupleType) { + public static int GetSize(Type tupleType) + { //ContractUtils.RequiresNotNull(tupleType, "tupleType"); int count = 0; - lock(_sizeDict) if (_sizeDict.TryGetValue(tupleType, out count)) return count; - Stack types = new Stack(tupleType.GetGenericArguments()); + lock (s_sizeDict) if (s_sizeDict.TryGetValue(tupleType, out count)) return count; + Stack types = new Stack(tupleType.GetGenericArguments()); - while (types.Count != 0) { + while (types.Count != 0) + { Type t = types.Pop(); - if (typeof(MutableTuple).IsAssignableFrom(t)) { - foreach (Type subtype in t.GetGenericArguments()) { + if (typeof(MutableTuple).IsAssignableFrom(t)) + { + foreach (Type subtype in t.GetGenericArguments()) + { types.Push(subtype); } continue; @@ -256,27 +291,28 @@ namespace System.Management.Automation count++; } - lock (_sizeDict) _sizeDict[tupleType] = count; + lock (s_sizeDict) s_sizeDict[tupleType] = count; return count; } - private static readonly ConcurrentDictionary> _tupleCreators = + private static readonly ConcurrentDictionary> s_tupleCreators = new ConcurrentDictionary>(concurrencyLevel: 3, capacity: 100); public static Func TupleCreator(Type type) { - return _tupleCreators.GetOrAdd(type, + return s_tupleCreators.GetOrAdd(type, t => { var newExpr = Expression.New(t); return Expression.Lambda>(newExpr.Cast(typeof(MutableTuple))).Compile(); }); - } + } /// /// Creates a new instance of tupleType with the specified args. If the tuple is a nested /// tuple the values are added in their nested forms. /// - public static MutableTuple MakeTuple(Type tupleType, Dictionary nameToIndexMap, Func creator = null) { + public static MutableTuple MakeTuple(Type tupleType, Dictionary nameToIndexMap, Func creator = null) + { //ContractUtils.RequiresNotNull(tupleType, "tupleType"); //ContractUtils.RequiresNotNull(args, "args"); @@ -290,7 +326,8 @@ namespace System.Management.Automation /// /// Gets the values from a tuple including unpacking nested values. /// - public static object[] GetTupleValues(MutableTuple tuple) { + public static object[] GetTupleValues(MutableTuple tuple) + { //ContractUtils.RequiresNotNull(tuple, "tuple"); List res = new List(); @@ -303,19 +340,22 @@ namespace System.Management.Automation /// /// Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. /// - public static IEnumerable GetAccessPath(Type tupleType, int index) { + public static IEnumerable GetAccessPath(Type tupleType, int index) + { return GetAccessProperties(tupleType, GetSize(tupleType), index); } /// /// Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. /// - internal static IEnumerable GetAccessProperties(Type tupleType, int size, int index) { + internal static IEnumerable GetAccessProperties(Type tupleType, int size, int index) + { //ContractUtils.RequiresNotNull(tupleType, "tupleType"); if (index < 0 || index >= size) throw new ArgumentException("index"); - foreach (int curIndex in GetAccessPath(size, index)) { + foreach (int curIndex in GetAccessPath(size, index)) + { PropertyInfo pi = tupleType.GetProperty("Item" + String.Format(CultureInfo.InvariantCulture, "{0:D3}", curIndex)); Diagnostics.Assert(pi != null, "reflection should always find Item"); yield return pi; @@ -323,7 +363,8 @@ namespace System.Management.Automation } } - internal static IEnumerable GetAccessPath(int size, int index) { + internal static IEnumerable GetAccessPath(int size, int index) + { // We get the final index by breaking the index into groups of bits. The more significant bits // represent the indexes into the outermost tuples and the least significant bits index into the // inner most tuples. The mask is initialized to mask the upper bits and adjust is initialized @@ -335,14 +376,16 @@ namespace System.Management.Automation int mask = MutableTuple.MaxSize - 1; int adjust = 1; int count = size; - while (count > MutableTuple.MaxSize) { + while (count > MutableTuple.MaxSize) + { depth++; count /= MutableTuple.MaxSize; mask *= MutableTuple.MaxSize; adjust *= MutableTuple.MaxSize; } - while (depth-- >= 0) { + while (depth-- >= 0) + { Diagnostics.Assert(mask != 0, "mask should never be 0."); int curIndex = (index & mask) / adjust; @@ -354,26 +397,35 @@ namespace System.Management.Automation } } - private static void GetTupleValues(MutableTuple tuple, List args) { + private static void GetTupleValues(MutableTuple tuple, List args) + { Type[] types = tuple.GetType().GetGenericArguments(); - for (int i = 0; i < types.Length; i++) { - if (typeof(MutableTuple).IsAssignableFrom(types[i])) { + for (int i = 0; i < types.Length; i++) + { + if (typeof(MutableTuple).IsAssignableFrom(types[i])) + { GetTupleValues((MutableTuple)tuple.GetValue(i), args); - } else if (types[i] != typeof(DynamicNull)) { + } + else if (types[i] != typeof(DynamicNull)) + { args.Add(tuple.GetValue(i)); } } } - private static MutableTuple MakeTuple(Func creator, Type tupleType, int size, BitArray bitArray) { + private static MutableTuple MakeTuple(Func creator, Type tupleType, int size, BitArray bitArray) + { MutableTuple res = (creator ?? MutableTuple.TupleCreator(tupleType))(); res._size = size; res._valuesSet = bitArray; - if (size > MutableTuple.MaxSize) { - while (size > MutableTuple.MaxSize) { + if (size > MutableTuple.MaxSize) + { + while (size > MutableTuple.MaxSize) + { size = (size + MutableTuple.MaxSize - 1) / MutableTuple.MaxSize; } - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { PropertyInfo pi = tupleType.GetProperty("Item" + String.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); res.SetValueImpl(i, MakeTuple(pi.PropertyType, null, null)); } @@ -382,24 +434,29 @@ namespace System.Management.Automation return res; } - private static Type MakeTupleType(Type[] types, int start, int end) { + private static Type MakeTupleType(Type[] types, int start, int end) + { int size = end - start; Type type = GetTupleType(size); - if (type != null) { + if (type != null) + { Type[] typeArr = new Type[type.GetGenericArguments().Length]; int index = 0; - for (int i = start; i < end; i++) { + for (int i = start; i < end; i++) + { typeArr[index++] = types[i]; } - while (index < typeArr.Length) { + while (index < typeArr.Length) + { typeArr[index++] = typeof(DynamicNull); } return type.MakeGenericType(typeArr); } int multiplier = 1; - while (size > MutableTuple.MaxSize) { + while (size > MutableTuple.MaxSize) + { size = (size + MutableTuple.MaxSize - 1) / MutableTuple.MaxSize; multiplier *= MutableTuple.MaxSize; } @@ -407,54 +464,62 @@ namespace System.Management.Automation type = MutableTuple.GetTupleType(size); Diagnostics.Assert(type != null, "type cannot be null"); Type[] nestedTypes = new Type[type.GetGenericArguments().Length]; - for (int i = 0; i < size; i++) { - + for (int i = 0; i < size; i++) + { int newStart = start + (i * multiplier); int newEnd = System.Math.Min(end, start + ((i + 1) * multiplier)); nestedTypes[i] = MakeTupleType(types, newStart, newEnd); } - for (int i = size; i < nestedTypes.Length; i++) { + for (int i = size; i < nestedTypes.Length; i++) + { nestedTypes[i] = typeof(DynamicNull); } return type.MakeGenericType(nestedTypes); } - public abstract int Capacity { + public abstract int Capacity + { get; } /// /// Provides an expression for creating a tuple with the specified values. /// - public static Expression Create(params Expression[] values) { + public static Expression Create(params Expression[] values) + { return CreateNew(MakeTupleType(values.Select(x => x.Type).ToArray()), 0, values.Length, values); } - private static int PowerOfTwoRound(int value) { + private static int PowerOfTwoRound(int value) + { int res = 1; - while (value > res) { + while (value > res) + { res = res << 1; } return res; } - internal static Expression CreateNew(Type tupleType, int start, int end, Expression[] values) { + internal static Expression CreateNew(Type tupleType, int start, int end, Expression[] values) + { int size = end - start; Diagnostics.Assert(tupleType != null, "tupleType cannot be null"); Diagnostics.Assert(tupleType.IsSubclassOf(typeof(MutableTuple)), "tupleType must be derived from MutableTuple"); Expression[] newValues; - if (size > MutableTuple.MaxSize) { - + if (size > MutableTuple.MaxSize) + { int multiplier = 1; - while (size > MutableTuple.MaxSize) { + while (size > MutableTuple.MaxSize) + { size = (size + MutableTuple.MaxSize - 1) / MutableTuple.MaxSize; multiplier *= MutableTuple.MaxSize; } newValues = new Expression[PowerOfTwoRound(size)]; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { int newStart = start + (i * multiplier); int newEnd = System.Math.Min(end, start + ((i + 1) * multiplier)); @@ -463,20 +528,25 @@ namespace System.Management.Automation newValues[i] = CreateNew(pi.PropertyType, newStart, newEnd, values); } - for (int i = size; i < newValues.Length; i++) { - newValues[i] = Expression.Constant(null, typeof(DynamicNull)); - } - } else { - newValues = new Expression[PowerOfTwoRound(size)]; - for (int i = 0; i < size; i++) { - newValues[i] = values[i + start]; - } - - for (int i = size; i < newValues.Length; i++) { + for (int i = size; i < newValues.Length; i++) + { newValues[i] = Expression.Constant(null, typeof(DynamicNull)); } } - + else + { + newValues = new Expression[PowerOfTwoRound(size)]; + for (int i = 0; i < size; i++) + { + newValues[i] = values[i + start]; + } + + for (int i = size; i < newValues.Length; i++) + { + newValues[i] = Expression.Constant(null, typeof(DynamicNull)); + } + } + return Expression.New(tupleType.GetConstructor(newValues.Select(x => x.Type).ToArray()), newValues); } } @@ -487,83 +557,103 @@ namespace System.Management.Automation // generated by function: gen_tuples from: generate_tuples.py [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0) - : base() { + : base() + { _item0 = item0; } private T0 _item0; - public T0 Item000 { + public T0 Item000 + { get { return _item0; } set { _item0 = value; _valuesSet[0] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; default: throw new ArgumentOutOfRangeException("index"); } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 1; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1) - : base(item0) { + : base(item0) + { _item1 = item1; } private T1 _item1; - public T1 Item001 { + public T1 Item001 + { get { return _item1; } set { _item1 = value; _valuesSet[1] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; default: throw new ArgumentOutOfRangeException("index"); } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 2; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3) - : base(item0, item1) { + : base(item0, item1) + { _item2 = item2; _item3 = item3; } @@ -571,17 +661,21 @@ namespace System.Management.Automation private T2 _item2; private T3 _item3; - public T2 Item002 { + public T2 Item002 + { get { return _item2; } - set { _item2= value; _valuesSet[2] = true; } + set { _item2 = value; _valuesSet[2] = true; } } - public T3 Item003 { + public T3 Item003 + { get { return _item3; } set { _item3 = value; _valuesSet[3] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -590,8 +684,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -599,18 +695,22 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 4; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) - : base(item0, item1, item2, item3) { + : base(item0, item1, item2, item3) + { _item4 = item4; _item5 = item5; _item6 = item6; @@ -622,25 +722,31 @@ namespace System.Management.Automation private T6 _item6; private T7 _item7; - public T4 Item004 { + public T4 Item004 + { get { return _item4; } set { _item4 = value; _valuesSet[4] = true; } } - public T5 Item005 { + public T5 Item005 + { get { return _item5; } set { _item5 = value; _valuesSet[5] = true; } } - public T6 Item006 { + public T6 Item006 + { get { return _item6; } set { _item6 = value; _valuesSet[6] = true; } } - public T7 Item007 { + public T7 Item007 + { get { return _item7; } set { _item7 = value; _valuesSet[7] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -653,8 +759,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -666,18 +774,22 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 8; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15) - : base(item0, item1, item2, item3, item4, item5, item6, item7) { + : base(item0, item1, item2, item3, item4, item5, item6, item7) + { _item8 = item8; _item9 = item9; _item10 = item10; @@ -697,41 +809,51 @@ namespace System.Management.Automation private T14 _item14; private T15 _item15; - public T8 Item008 { + public T8 Item008 + { get { return _item8; } set { _item8 = value; _valuesSet[8] = true; } } - public T9 Item009 { + public T9 Item009 + { get { return _item9; } set { _item9 = value; _valuesSet[9] = true; } } - public T10 Item010 { + public T10 Item010 + { get { return _item10; } set { _item10 = value; _valuesSet[10] = true; } } - public T11 Item011 { + public T11 Item011 + { get { return _item11; } set { _item11 = value; _valuesSet[11] = true; } } - public T12 Item012 { + public T12 Item012 + { get { return _item12; } set { _item12 = value; _valuesSet[12] = true; } } - public T13 Item013 { + public T13 Item013 + { get { return _item13; } set { _item13 = value; _valuesSet[13] = true; } } - public T14 Item014 { + public T14 Item014 + { get { return _item14; } set { _item14 = value; _valuesSet[14] = true; } } - public T15 Item015 { + public T15 Item015 + { get { return _item15; } set { _item15 = value; _valuesSet[15] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -752,8 +874,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -773,18 +897,22 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 16; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18, T19 item19, T20 item20, T21 item21, T22 item22, T23 item23, T24 item24, T25 item25, T26 item26, T27 item27, T28 item28, T29 item29, T30 item30, T31 item31) - : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15) { + : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15) + { _item16 = item16; _item17 = item17; _item18 = item18; @@ -820,73 +948,91 @@ namespace System.Management.Automation private T30 _item30; private T31 _item31; - public T16 Item016 { + public T16 Item016 + { get { return _item16; } set { _item16 = value; _valuesSet[16] = true; } } - public T17 Item017 { + public T17 Item017 + { get { return _item17; } set { _item17 = value; _valuesSet[17] = true; } } - public T18 Item018 { + public T18 Item018 + { get { return _item18; } set { _item18 = value; _valuesSet[18] = true; } } - public T19 Item019 { + public T19 Item019 + { get { return _item19; } set { _item19 = value; _valuesSet[19] = true; } } - public T20 Item020 { + public T20 Item020 + { get { return _item20; } set { _item20 = value; _valuesSet[20] = true; } } - public T21 Item021 { + public T21 Item021 + { get { return _item21; } set { _item21 = value; _valuesSet[21] = true; } } - public T22 Item022 { + public T22 Item022 + { get { return _item22; } set { _item22 = value; _valuesSet[22] = true; } } - public T23 Item023 { + public T23 Item023 + { get { return _item23; } set { _item23 = value; _valuesSet[23] = true; } } - public T24 Item024 { + public T24 Item024 + { get { return _item24; } set { _item24 = value; _valuesSet[24] = true; } } - public T25 Item025 { + public T25 Item025 + { get { return _item25; } set { _item25 = value; _valuesSet[25] = true; } } - public T26 Item026 { + public T26 Item026 + { get { return _item26; } set { _item26 = value; _valuesSet[26] = true; } } - public T27 Item027 { + public T27 Item027 + { get { return _item27; } set { _item27 = value; _valuesSet[27] = true; } } - public T28 Item028 { + public T28 Item028 + { get { return _item28; } set { _item28 = value; _valuesSet[28] = true; } } - public T29 Item029 { + public T29 Item029 + { get { return _item29; } set { _item29 = value; _valuesSet[29] = true; } } - public T30 Item030 { + public T30 Item030 + { get { return _item30; } set { _item30 = value; _valuesSet[30] = true; } } - public T31 Item031 { + public T31 Item031 + { get { return _item31; } set { _item31 = value; _valuesSet[31] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -923,8 +1069,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -960,18 +1108,22 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 32; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18, T19 item19, T20 item20, T21 item21, T22 item22, T23 item23, T24 item24, T25 item25, T26 item26, T27 item27, T28 item28, T29 item29, T30 item30, T31 item31, T32 item32, T33 item33, T34 item34, T35 item35, T36 item36, T37 item37, T38 item38, T39 item39, T40 item40, T41 item41, T42 item42, T43 item43, T44 item44, T45 item45, T46 item46, T47 item47, T48 item48, T49 item49, T50 item50, T51 item51, T52 item52, T53 item53, T54 item54, T55 item55, T56 item56, T57 item57, T58 item58, T59 item59, T60 item60, T61 item61, T62 item62, T63 item63) - : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20, item21, item22, item23, item24, item25, item26, item27, item28, item29, item30, item31) { + : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20, item21, item22, item23, item24, item25, item26, item27, item28, item29, item30, item31) + { _item32 = item32; _item33 = item33; _item34 = item34; @@ -1039,137 +1191,171 @@ namespace System.Management.Automation private T62 _item62; private T63 _item63; - public T32 Item032 { + public T32 Item032 + { get { return _item32; } set { _item32 = value; _valuesSet[32] = true; } } - public T33 Item033 { + public T33 Item033 + { get { return _item33; } set { _item33 = value; _valuesSet[33] = true; } } - public T34 Item034 { + public T34 Item034 + { get { return _item34; } set { _item34 = value; _valuesSet[34] = true; } } - public T35 Item035 { + public T35 Item035 + { get { return _item35; } set { _item35 = value; _valuesSet[35] = true; } } - public T36 Item036 { + public T36 Item036 + { get { return _item36; } set { _item36 = value; _valuesSet[36] = true; } } - public T37 Item037 { + public T37 Item037 + { get { return _item37; } set { _item37 = value; _valuesSet[37] = true; } } - public T38 Item038 { + public T38 Item038 + { get { return _item38; } set { _item38 = value; _valuesSet[38] = true; } } - public T39 Item039 { + public T39 Item039 + { get { return _item39; } set { _item39 = value; _valuesSet[39] = true; } } - public T40 Item040 { + public T40 Item040 + { get { return _item40; } set { _item40 = value; _valuesSet[40] = true; } } - public T41 Item041 { + public T41 Item041 + { get { return _item41; } set { _item41 = value; _valuesSet[41] = true; } } - public T42 Item042 { + public T42 Item042 + { get { return _item42; } set { _item42 = value; _valuesSet[42] = true; } } - public T43 Item043 { + public T43 Item043 + { get { return _item43; } set { _item43 = value; _valuesSet[43] = true; } } - public T44 Item044 { + public T44 Item044 + { get { return _item44; } set { _item44 = value; _valuesSet[44] = true; } } - public T45 Item045 { + public T45 Item045 + { get { return _item45; } set { _item45 = value; _valuesSet[45] = true; } } - public T46 Item046 { + public T46 Item046 + { get { return _item46; } set { _item46 = value; _valuesSet[46] = true; } } - public T47 Item047 { + public T47 Item047 + { get { return _item47; } set { _item47 = value; _valuesSet[47] = true; } } - public T48 Item048 { + public T48 Item048 + { get { return _item48; } set { _item48 = value; _valuesSet[48] = true; } } - public T49 Item049 { + public T49 Item049 + { get { return _item49; } set { _item49 = value; _valuesSet[49] = true; } } - public T50 Item050 { + public T50 Item050 + { get { return _item50; } set { _item50 = value; _valuesSet[50] = true; } } - public T51 Item051 { + public T51 Item051 + { get { return _item51; } set { _item51 = value; _valuesSet[51] = true; } } - public T52 Item052 { + public T52 Item052 + { get { return _item52; } set { _item52 = value; _valuesSet[52] = true; } } - public T53 Item053 { + public T53 Item053 + { get { return _item53; } set { _item53 = value; _valuesSet[53] = true; } } - public T54 Item054 { + public T54 Item054 + { get { return _item54; } set { _item54 = value; _valuesSet[54] = true; } } - public T55 Item055 { + public T55 Item055 + { get { return _item55; } set { _item55 = value; _valuesSet[55] = true; } } - public T56 Item056 { + public T56 Item056 + { get { return _item56; } set { _item56 = value; _valuesSet[56] = true; } } - public T57 Item057 { + public T57 Item057 + { get { return _item57; } set { _item57 = value; _valuesSet[57] = true; } } - public T58 Item058 { + public T58 Item058 + { get { return _item58; } set { _item58 = value; _valuesSet[58] = true; } } - public T59 Item059 { + public T59 Item059 + { get { return _item59; } set { _item59 = value; _valuesSet[59] = true; } } - public T60 Item060 { + public T60 Item060 + { get { return _item60; } set { _item60 = value; _valuesSet[60] = true; } } - public T61 Item061 { + public T61 Item061 + { get { return _item61; } set { _item61 = value; _valuesSet[61] = true; } } - public T62 Item062 { + public T62 Item062 + { get { return _item62; } set { _item62 = value; _valuesSet[62] = true; } } - public T63 Item063 { + public T63 Item063 + { get { return _item63; } set { _item63 = value; _valuesSet[63] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -1238,8 +1424,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -1307,18 +1495,22 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 64; } } } [GeneratedCode("DLR", "2.0")] - internal class MutableTuple : MutableTuple { + internal class MutableTuple : MutableTuple + { public MutableTuple() { } public MutableTuple(T0 item0, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18, T19 item19, T20 item20, T21 item21, T22 item22, T23 item23, T24 item24, T25 item25, T26 item26, T27 item27, T28 item28, T29 item29, T30 item30, T31 item31, T32 item32, T33 item33, T34 item34, T35 item35, T36 item36, T37 item37, T38 item38, T39 item39, T40 item40, T41 item41, T42 item42, T43 item43, T44 item44, T45 item45, T46 item46, T47 item47, T48 item48, T49 item49, T50 item50, T51 item51, T52 item52, T53 item53, T54 item54, T55 item55, T56 item56, T57 item57, T58 item58, T59 item59, T60 item60, T61 item61, T62 item62, T63 item63, T64 item64, T65 item65, T66 item66, T67 item67, T68 item68, T69 item69, T70 item70, T71 item71, T72 item72, T73 item73, T74 item74, T75 item75, T76 item76, T77 item77, T78 item78, T79 item79, T80 item80, T81 item81, T82 item82, T83 item83, T84 item84, T85 item85, T86 item86, T87 item87, T88 item88, T89 item89, T90 item90, T91 item91, T92 item92, T93 item93, T94 item94, T95 item95, T96 item96, T97 item97, T98 item98, T99 item99, T100 item100, T101 item101, T102 item102, T103 item103, T104 item104, T105 item105, T106 item106, T107 item107, T108 item108, T109 item109, T110 item110, T111 item111, T112 item112, T113 item113, T114 item114, T115 item115, T116 item116, T117 item117, T118 item118, T119 item119, T120 item120, T121 item121, T122 item122, T123 item123, T124 item124, T125 item125, T126 item126, T127 item127) - : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20, item21, item22, item23, item24, item25, item26, item27, item28, item29, item30, item31, item32, item33, item34, item35, item36, item37, item38, item39, item40, item41, item42, item43, item44, item45, item46, item47, item48, item49, item50, item51, item52, item53, item54, item55, item56, item57, item58, item59, item60, item61, item62, item63) { + : base(item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20, item21, item22, item23, item24, item25, item26, item27, item28, item29, item30, item31, item32, item33, item34, item35, item36, item37, item38, item39, item40, item41, item42, item43, item44, item45, item46, item47, item48, item49, item50, item51, item52, item53, item54, item55, item56, item57, item58, item59, item60, item61, item62, item63) + { _item64 = item64; _item65 = item65; _item66 = item66; @@ -1450,265 +1642,331 @@ namespace System.Management.Automation private T126 _item126; private T127 _item127; - public T64 Item064 { + public T64 Item064 + { get { return _item64; } set { _item64 = value; _valuesSet[64] = true; } } - public T65 Item065 { + public T65 Item065 + { get { return _item65; } set { _item65 = value; _valuesSet[65] = true; } } - public T66 Item066 { + public T66 Item066 + { get { return _item66; } set { _item66 = value; _valuesSet[66] = true; } } - public T67 Item067 { + public T67 Item067 + { get { return _item67; } set { _item67 = value; _valuesSet[67] = true; } } - public T68 Item068 { + public T68 Item068 + { get { return _item68; } set { _item68 = value; _valuesSet[68] = true; } } - public T69 Item069 { + public T69 Item069 + { get { return _item69; } set { _item69 = value; _valuesSet[69] = true; } } - public T70 Item070 { + public T70 Item070 + { get { return _item70; } set { _item70 = value; _valuesSet[70] = true; } } - public T71 Item071 { + public T71 Item071 + { get { return _item71; } set { _item71 = value; _valuesSet[71] = true; } } - public T72 Item072 { + public T72 Item072 + { get { return _item72; } set { _item72 = value; _valuesSet[72] = true; } } - public T73 Item073 { + public T73 Item073 + { get { return _item73; } set { _item73 = value; _valuesSet[73] = true; } } - public T74 Item074 { + public T74 Item074 + { get { return _item74; } set { _item74 = value; _valuesSet[74] = true; } } - public T75 Item075 { + public T75 Item075 + { get { return _item75; } set { _item75 = value; _valuesSet[75] = true; } } - public T76 Item076 { + public T76 Item076 + { get { return _item76; } set { _item76 = value; _valuesSet[76] = true; } } - public T77 Item077 { + public T77 Item077 + { get { return _item77; } set { _item77 = value; _valuesSet[77] = true; } } - public T78 Item078 { + public T78 Item078 + { get { return _item78; } set { _item78 = value; _valuesSet[78] = true; } } - public T79 Item079 { + public T79 Item079 + { get { return _item79; } set { _item79 = value; _valuesSet[79] = true; } } - public T80 Item080 { + public T80 Item080 + { get { return _item80; } set { _item80 = value; _valuesSet[80] = true; } } - public T81 Item081 { + public T81 Item081 + { get { return _item81; } set { _item81 = value; _valuesSet[81] = true; } } - public T82 Item082 { + public T82 Item082 + { get { return _item82; } set { _item82 = value; _valuesSet[82] = true; } } - public T83 Item083 { + public T83 Item083 + { get { return _item83; } set { _item83 = value; _valuesSet[83] = true; } } - public T84 Item084 { + public T84 Item084 + { get { return _item84; } set { _item84 = value; _valuesSet[84] = true; } } - public T85 Item085 { + public T85 Item085 + { get { return _item85; } set { _item85 = value; _valuesSet[85] = true; } } - public T86 Item086 { + public T86 Item086 + { get { return _item86; } set { _item86 = value; _valuesSet[86] = true; } } - public T87 Item087 { + public T87 Item087 + { get { return _item87; } set { _item87 = value; _valuesSet[87] = true; } } - public T88 Item088 { + public T88 Item088 + { get { return _item88; } set { _item88 = value; _valuesSet[88] = true; } } - public T89 Item089 { + public T89 Item089 + { get { return _item89; } set { _item89 = value; _valuesSet[89] = true; } } - public T90 Item090 { + public T90 Item090 + { get { return _item90; } set { _item90 = value; _valuesSet[90] = true; } } - public T91 Item091 { + public T91 Item091 + { get { return _item91; } set { _item91 = value; _valuesSet[91] = true; } } - public T92 Item092 { + public T92 Item092 + { get { return _item92; } set { _item92 = value; _valuesSet[92] = true; } } - public T93 Item093 { + public T93 Item093 + { get { return _item93; } set { _item93 = value; _valuesSet[93] = true; } } - public T94 Item094 { + public T94 Item094 + { get { return _item94; } set { _item94 = value; _valuesSet[94] = true; } } - public T95 Item095 { + public T95 Item095 + { get { return _item95; } set { _item95 = value; _valuesSet[95] = true; } } - public T96 Item096 { + public T96 Item096 + { get { return _item96; } set { _item96 = value; _valuesSet[96] = true; } } - public T97 Item097 { + public T97 Item097 + { get { return _item97; } set { _item97 = value; _valuesSet[97] = true; } } - public T98 Item098 { + public T98 Item098 + { get { return _item98; } set { _item98 = value; _valuesSet[98] = true; } } - public T99 Item099 { + public T99 Item099 + { get { return _item99; } set { _item99 = value; _valuesSet[99] = true; } } - public T100 Item100 { + public T100 Item100 + { get { return _item100; } set { _item100 = value; _valuesSet[100] = true; } } - public T101 Item101 { + public T101 Item101 + { get { return _item101; } set { _item101 = value; _valuesSet[101] = true; } } - public T102 Item102 { + public T102 Item102 + { get { return _item102; } set { _item102 = value; _valuesSet[102] = true; } } - public T103 Item103 { + public T103 Item103 + { get { return _item103; } set { _item103 = value; _valuesSet[103] = true; } } - public T104 Item104 { + public T104 Item104 + { get { return _item104; } set { _item104 = value; _valuesSet[104] = true; } } - public T105 Item105 { + public T105 Item105 + { get { return _item105; } set { _item105 = value; _valuesSet[105] = true; } } - public T106 Item106 { + public T106 Item106 + { get { return _item106; } set { _item106 = value; _valuesSet[106] = true; } } - public T107 Item107 { + public T107 Item107 + { get { return _item107; } set { _item107 = value; _valuesSet[107] = true; } } - public T108 Item108 { + public T108 Item108 + { get { return _item108; } set { _item108 = value; _valuesSet[108] = true; } } - public T109 Item109 { + public T109 Item109 + { get { return _item109; } set { _item109 = value; _valuesSet[109] = true; } } - public T110 Item110 { + public T110 Item110 + { get { return _item110; } set { _item110 = value; _valuesSet[110] = true; } } - public T111 Item111 { + public T111 Item111 + { get { return _item111; } set { _item111 = value; _valuesSet[111] = true; } } - public T112 Item112 { + public T112 Item112 + { get { return _item112; } set { _item112 = value; _valuesSet[112] = true; } } - public T113 Item113 { + public T113 Item113 + { get { return _item113; } set { _item113 = value; _valuesSet[113] = true; } } - public T114 Item114 { + public T114 Item114 + { get { return _item114; } set { _item114 = value; _valuesSet[114] = true; } } - public T115 Item115 { + public T115 Item115 + { get { return _item115; } set { _item115 = value; _valuesSet[115] = true; } } - public T116 Item116 { + public T116 Item116 + { get { return _item116; } set { _item116 = value; _valuesSet[116] = true; } } - public T117 Item117 { + public T117 Item117 + { get { return _item117; } set { _item117 = value; _valuesSet[117] = true; } } - public T118 Item118 { + public T118 Item118 + { get { return _item118; } set { _item118 = value; _valuesSet[118] = true; } } - public T119 Item119 { + public T119 Item119 + { get { return _item119; } set { _item119 = value; _valuesSet[119] = true; } } - public T120 Item120 { + public T120 Item120 + { get { return _item120; } set { _item120 = value; _valuesSet[120] = true; } } - public T121 Item121 { + public T121 Item121 + { get { return _item121; } set { _item121 = value; _valuesSet[121] = true; } } - public T122 Item122 { + public T122 Item122 + { get { return _item122; } set { _item122 = value; _valuesSet[122] = true; } } - public T123 Item123 { + public T123 Item123 + { get { return _item123; } set { _item123 = value; _valuesSet[123] = true; } } - public T124 Item124 { + public T124 Item124 + { get { return _item124; } set { _item124 = value; _valuesSet[124] = true; } } - public T125 Item125 { + public T125 Item125 + { get { return _item125; } set { _item125 = value; _valuesSet[125] = true; } } - public T126 Item126 { + public T126 Item126 + { get { return _item126; } set { _item126 = value; _valuesSet[126] = true; } } - public T127 Item127 { + public T127 Item127 + { get { return _item127; } set { _item127 = value; _valuesSet[127] = true; } } - protected override object GetValueImpl(int index) { - switch(index) { + protected override object GetValueImpl(int index) + { + switch (index) + { case 0: return Item000; case 1: return Item001; case 2: return Item002; @@ -1841,8 +2099,10 @@ namespace System.Management.Automation } } - protected override void SetValueImpl(int index, object value) { - switch(index) { + protected override void SetValueImpl(int index, object value) + { + switch (index) + { case 0: Item000 = LanguagePrimitives.ConvertTo(value); break; case 1: Item001 = LanguagePrimitives.ConvertTo(value); break; case 2: Item002 = LanguagePrimitives.ConvertTo(value); break; @@ -1974,8 +2234,10 @@ namespace System.Management.Automation default: throw new ArgumentOutOfRangeException("index"); } } - public override int Capacity { - get { + public override int Capacity + { + get + { return 128; } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index ffc606d85..c2051c912 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -11,7 +11,7 @@ using System.Management.Automation.Runspaces; namespace System.Management.Automation { - static class ArrayOps + internal static class ArrayOps { internal static object[] SlicingIndex(object target, object[] indexes, Func indexer) { @@ -224,7 +224,7 @@ namespace System.Management.Automation "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, array.Rank, msgString); } - private static string IndexStringMessage(object index) + internal static string IndexStringMessage(object index) { // Convert this index into something printable (we hope)... string msgString = PSObject.ToString(null, index, ",", null, null, true, true); diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index fd094c6a0..94aaa52d3 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -17,6 +17,7 @@ using System.Threading; // // Because they are called from other assemblies, we have to make them public. // We put them in Internal namespace to emphasise that despite the fact that they are public, it's not part of API contract. + namespace System.Management.Automation.Internal { /// @@ -159,7 +160,6 @@ namespace System.Management.Automation.Internal var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; foreach (var validateAttribute in validateAttributes) { - validateAttribute.InternalValidate(value, engineIntrinsics); } } @@ -202,7 +202,7 @@ namespace System.Management.Automation.Internal /// A cache for the DynamicMethod objects that call to base method non-virtually. /// The cache can clean up the outdated WeakReference entries by itself. /// - private static readonly ConditionalWeakTable NonVirtualCallCache = + private static readonly ConditionalWeakTable s_nonVirtualCallCache = new ConditionalWeakTable(); /// @@ -213,7 +213,7 @@ namespace System.Management.Automation.Internal /// arguments for invocation private static object CallMethodNonVirtuallyImpl(object target, MethodInfo mi, object[] args) { - DynamicMethod dm = NonVirtualCallCache.GetValue(mi, CreateDynamicMethod); + DynamicMethod dm = s_nonVirtualCallCache.GetValue(mi, CreateDynamicMethod); // The target object will be passed to the hidden parameter 'this' of the instance method var newArgs = new List(args.Length + 1) { target }; diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index bc9b2161b..a3c6b4e71 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -23,7 +23,7 @@ using Microsoft.PowerShell.Commands; namespace System.Management.Automation { - static class PipelineOps + internal static class PipelineOps { private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, @@ -134,7 +134,7 @@ namespace System.Management.Automation if (rte.ErrorRecord.InvocationInfo == null) { InvocationInfo invocationInfo = new InvocationInfo(null, commandExtent, context) - {InvocationName = invocationName}; + { InvocationName = invocationName }; rte.ErrorRecord.SetInvocationInfo(invocationInfo); } throw; @@ -157,7 +157,7 @@ namespace System.Management.Automation if (cpi.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase) && !isNativeCommand) { continue; - } + } } if (cpi.ArgumentSplatted) @@ -239,7 +239,7 @@ namespace System.Management.Automation else { commandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput; - } + } } if (!redirectedWarning && (context.ExpressionWarningOutputPipe != null)) { @@ -288,7 +288,6 @@ namespace System.Management.Automation { commandProcessor.CommandRuntime.InformationOutputPipe = context.CurrentCommandProcessor.CommandRuntime.InformationOutputPipe; } - } return commandProcessor; @@ -447,7 +446,7 @@ namespace System.Management.Automation private static void AddNoopCommandProcessor(PipelineProcessor pipelineProcessor, ExecutionContext context) { - var commandInfo = new CmdletInfo("Out-Null", typeof (OutNullCommand)); + var commandInfo = new CmdletInfo("Out-Null", typeof(OutNullCommand)); var commandProcessor = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, useLocalScope: false, @@ -477,7 +476,7 @@ namespace System.Management.Automation } } } - + return objArray; } @@ -522,7 +521,7 @@ namespace System.Management.Automation Compiler.DottedLocalsNameIndexMap); object[] remainingArgs = ScriptBlock.BindArgumentsForScripblockInvoke( - (RuntimeDefinedParameter[])scriptBlock.RuntimeDefinedParameters.Data, + (RuntimeDefinedParameter[])scriptBlock.RuntimeDefinedParameters.Data, args, context, false, null, locals); locals.SetAutomaticVariable(AutomaticVariable.Args, remainingArgs, context); newScope.LocalsTuple = locals; @@ -694,12 +693,12 @@ namespace System.Management.Automation } // This is to work around a DLR problem with gotos in try/catch to the end of a lambda. - internal static void Nop() {} + internal static void Nop() { } } #region Redirections - abstract class CommandRedirection + internal abstract class CommandRedirection { protected CommandRedirection(RedirectionStream from) { @@ -721,37 +720,37 @@ namespace System.Management.Automation var context = funcContext._executionContext; switch (FromStream) { - case RedirectionStream.All: - funcContext._outputPipe = pipes[(int)RedirectionStream.Output]; - context.ShellFunctionErrorOutputPipe = pipes[(int)RedirectionStream.Error]; - context.ExpressionWarningOutputPipe = pipes[(int)RedirectionStream.Warning]; - context.ExpressionVerboseOutputPipe = pipes[(int)RedirectionStream.Verbose]; - context.ExpressionDebugOutputPipe = pipes[(int)RedirectionStream.Debug]; - context.ExpressionInformationOutputPipe = pipes[(int)RedirectionStream.Information]; - break; - case RedirectionStream.Output: - funcContext._outputPipe = pipes[(int)RedirectionStream.Output]; - break; - case RedirectionStream.Error: - context.ShellFunctionErrorOutputPipe = pipes[(int)FromStream]; - break; - case RedirectionStream.Warning: - context.ExpressionWarningOutputPipe = pipes[(int)FromStream]; - break; - case RedirectionStream.Verbose: - context.ExpressionVerboseOutputPipe = pipes[(int)FromStream]; - break; - case RedirectionStream.Debug: - context.ExpressionDebugOutputPipe = pipes[(int)FromStream]; - break; - case RedirectionStream.Information: - context.ExpressionInformationOutputPipe = pipes[(int)FromStream]; - break; + case RedirectionStream.All: + funcContext._outputPipe = pipes[(int)RedirectionStream.Output]; + context.ShellFunctionErrorOutputPipe = pipes[(int)RedirectionStream.Error]; + context.ExpressionWarningOutputPipe = pipes[(int)RedirectionStream.Warning]; + context.ExpressionVerboseOutputPipe = pipes[(int)RedirectionStream.Verbose]; + context.ExpressionDebugOutputPipe = pipes[(int)RedirectionStream.Debug]; + context.ExpressionInformationOutputPipe = pipes[(int)RedirectionStream.Information]; + break; + case RedirectionStream.Output: + funcContext._outputPipe = pipes[(int)RedirectionStream.Output]; + break; + case RedirectionStream.Error: + context.ShellFunctionErrorOutputPipe = pipes[(int)FromStream]; + break; + case RedirectionStream.Warning: + context.ExpressionWarningOutputPipe = pipes[(int)FromStream]; + break; + case RedirectionStream.Verbose: + context.ExpressionVerboseOutputPipe = pipes[(int)FromStream]; + break; + case RedirectionStream.Debug: + context.ExpressionDebugOutputPipe = pipes[(int)FromStream]; + break; + case RedirectionStream.Information: + context.ExpressionInformationOutputPipe = pipes[(int)FromStream]; + break; } } } - class MergingRedirection : CommandRedirection + internal class MergingRedirection : CommandRedirection { internal MergingRedirection(RedirectionStream from, RedirectionStream to) : base(from) @@ -761,7 +760,6 @@ namespace System.Management.Automation throw InterpreterError.NewInterpreterException(to, typeof(ArgumentException), null, "RedirectionStreamCanOnlyMergeToOutputStream", ParserStrings.RedirectionStreamCanOnlyMergeToOutputStream); - } //this.ToStream = to; @@ -869,7 +867,7 @@ namespace System.Management.Automation } } - class FileRedirection : CommandRedirection, IDisposable + internal class FileRedirection : CommandRedirection, IDisposable { internal FileRedirection(RedirectionStream from, bool appending, string file) : base(from) @@ -899,49 +897,49 @@ namespace System.Management.Automation switch (FromStream) { - case RedirectionStream.All: - // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - // Normally, context.CurrentCommandProcessor will not be null. But in legacy DRTs from ParserTest.cs, - // a scriptblock may be invoked through 'DoInvokeReturnAsIs' using .NET reflection. In that case, - // context.CurrentCommandProcessor will be null. We don't try passing along variable lists in such case. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.CommandRuntime. - OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + case RedirectionStream.All: + // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. + // Normally, context.CurrentCommandProcessor will not be null. But in legacy DRTs from ParserTest.cs, + // a scriptblock may be invoked through 'DoInvokeReturnAsIs' using .NET reflection. In that case, + // context.CurrentCommandProcessor will be null. We don't try passing along variable lists in such case. + if (context.CurrentCommandProcessor != null) + { + context.CurrentCommandProcessor.CommandRuntime. + OutputPipe.SetVariableListForTemporaryPipe(pipe); + } - commandProcessor.CommandRuntime.OutputPipe = pipe; - commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; - commandProcessor.CommandRuntime.WarningOutputPipe = pipe; - commandProcessor.CommandRuntime.VerboseOutputPipe = pipe; - commandProcessor.CommandRuntime.DebugOutputPipe = pipe; - commandProcessor.CommandRuntime.InformationOutputPipe = pipe; - break; - case RedirectionStream.Output: - // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.CommandRuntime. - OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + commandProcessor.CommandRuntime.OutputPipe = pipe; + commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; + commandProcessor.CommandRuntime.WarningOutputPipe = pipe; + commandProcessor.CommandRuntime.VerboseOutputPipe = pipe; + commandProcessor.CommandRuntime.DebugOutputPipe = pipe; + commandProcessor.CommandRuntime.InformationOutputPipe = pipe; + break; + case RedirectionStream.Output: + // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. + if (context.CurrentCommandProcessor != null) + { + context.CurrentCommandProcessor.CommandRuntime. + OutputPipe.SetVariableListForTemporaryPipe(pipe); + } - commandProcessor.CommandRuntime.OutputPipe = pipe; - break; - case RedirectionStream.Error: - commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; - break; - case RedirectionStream.Warning: - commandProcessor.CommandRuntime.WarningOutputPipe = pipe; - break; - case RedirectionStream.Verbose: - commandProcessor.CommandRuntime.VerboseOutputPipe = pipe; - break; - case RedirectionStream.Debug: - commandProcessor.CommandRuntime.DebugOutputPipe = pipe; - break; - case RedirectionStream.Information: - commandProcessor.CommandRuntime.InformationOutputPipe = pipe; - break; + commandProcessor.CommandRuntime.OutputPipe = pipe; + break; + case RedirectionStream.Error: + commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; + break; + case RedirectionStream.Warning: + commandProcessor.CommandRuntime.WarningOutputPipe = pipe; + break; + case RedirectionStream.Verbose: + commandProcessor.CommandRuntime.VerboseOutputPipe = pipe; + break; + case RedirectionStream.Debug: + commandProcessor.CommandRuntime.DebugOutputPipe = pipe; + break; + case RedirectionStream.Information: + commandProcessor.CommandRuntime.InformationOutputPipe = pipe; + break; } } @@ -957,49 +955,49 @@ namespace System.Management.Automation switch (FromStream) { - case RedirectionStream.All: - oldPipes[(int)RedirectionStream.Output] = funcContext._outputPipe; - oldPipes[(int)RedirectionStream.Error] = context.ShellFunctionErrorOutputPipe; - oldPipes[(int)RedirectionStream.Warning] = context.ExpressionWarningOutputPipe; - oldPipes[(int)RedirectionStream.Verbose] = context.ExpressionVerboseOutputPipe; - oldPipes[(int)RedirectionStream.Debug] = context.ExpressionDebugOutputPipe; - oldPipes[(int)RedirectionStream.Information] = context.ExpressionInformationOutputPipe; + case RedirectionStream.All: + oldPipes[(int)RedirectionStream.Output] = funcContext._outputPipe; + oldPipes[(int)RedirectionStream.Error] = context.ShellFunctionErrorOutputPipe; + oldPipes[(int)RedirectionStream.Warning] = context.ExpressionWarningOutputPipe; + oldPipes[(int)RedirectionStream.Verbose] = context.ExpressionVerboseOutputPipe; + oldPipes[(int)RedirectionStream.Debug] = context.ExpressionDebugOutputPipe; + oldPipes[(int)RedirectionStream.Information] = context.ExpressionInformationOutputPipe; - // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - funcContext._outputPipe.SetVariableListForTemporaryPipe(pipe); - funcContext._outputPipe = pipe; - context.ShellFunctionErrorOutputPipe = pipe; - context.ExpressionWarningOutputPipe = pipe; - context.ExpressionVerboseOutputPipe = pipe; - context.ExpressionDebugOutputPipe = pipe; - context.ExpressionInformationOutputPipe = pipe; - break; - case RedirectionStream.Output: - oldPipes[(int)RedirectionStream.Output] = funcContext._outputPipe; - // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - funcContext._outputPipe.SetVariableListForTemporaryPipe(pipe); - funcContext._outputPipe = pipe; - break; - case RedirectionStream.Error: - oldPipes[(int)FromStream] = context.ShellFunctionErrorOutputPipe; - context.ShellFunctionErrorOutputPipe = pipe; - break; - case RedirectionStream.Warning: - oldPipes[(int)FromStream] = context.ExpressionWarningOutputPipe; - context.ExpressionWarningOutputPipe = pipe; - break; - case RedirectionStream.Verbose: - oldPipes[(int)FromStream] = context.ExpressionVerboseOutputPipe; - context.ExpressionVerboseOutputPipe = pipe; - break; - case RedirectionStream.Debug: - oldPipes[(int)FromStream] = context.ExpressionDebugOutputPipe; - context.ExpressionDebugOutputPipe = pipe; - break; - case RedirectionStream.Information: - oldPipes[(int)FromStream] = context.ExpressionInformationOutputPipe; - context.ExpressionInformationOutputPipe = pipe; - break; + // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. + funcContext._outputPipe.SetVariableListForTemporaryPipe(pipe); + funcContext._outputPipe = pipe; + context.ShellFunctionErrorOutputPipe = pipe; + context.ExpressionWarningOutputPipe = pipe; + context.ExpressionVerboseOutputPipe = pipe; + context.ExpressionDebugOutputPipe = pipe; + context.ExpressionInformationOutputPipe = pipe; + break; + case RedirectionStream.Output: + oldPipes[(int)RedirectionStream.Output] = funcContext._outputPipe; + // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. + funcContext._outputPipe.SetVariableListForTemporaryPipe(pipe); + funcContext._outputPipe = pipe; + break; + case RedirectionStream.Error: + oldPipes[(int)FromStream] = context.ShellFunctionErrorOutputPipe; + context.ShellFunctionErrorOutputPipe = pipe; + break; + case RedirectionStream.Warning: + oldPipes[(int)FromStream] = context.ExpressionWarningOutputPipe; + context.ExpressionWarningOutputPipe = pipe; + break; + case RedirectionStream.Verbose: + oldPipes[(int)FromStream] = context.ExpressionVerboseOutputPipe; + context.ExpressionVerboseOutputPipe = pipe; + break; + case RedirectionStream.Debug: + oldPipes[(int)FromStream] = context.ExpressionDebugOutputPipe; + context.ExpressionDebugOutputPipe = pipe; + break; + case RedirectionStream.Information: + oldPipes[(int)FromStream] = context.ExpressionInformationOutputPipe; + context.ExpressionInformationOutputPipe = pipe; + break; } return oldPipes; } @@ -1008,7 +1006,7 @@ namespace System.Management.Automation { if (String.IsNullOrWhiteSpace(File)) { - return new Pipe {NullPipe = true}; + return new Pipe { NullPipe = true }; } CommandProcessorBase commandProcessor = context.CreateCommand("out-file", false); @@ -1089,7 +1087,7 @@ namespace System.Management.Automation #endregion Redirections - static class FunctionOps + internal static class FunctionOps { internal static void DefineFunction(ExecutionContext context, FunctionDefinitionAst functionDefinitionAst, @@ -1164,7 +1162,7 @@ namespace System.Management.Automation internal ScriptBlockExpressionWrapper(IParameterMetadataProvider ast) { - this._ast = ast; + _ast = ast; } internal ScriptBlock GetScriptBlock(ExecutionContext context, bool isFilter) @@ -1180,7 +1178,7 @@ namespace System.Management.Automation } } - static class HashtableOps + internal static class HashtableOps { internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent) { @@ -1238,9 +1236,9 @@ namespace System.Management.Automation } } - static class ExceptionHandlingOps + internal static class ExceptionHandlingOps { - internal class CatchAll {} + internal class CatchAll { } internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte, Type[] types, ExecutionContext context) { @@ -1491,18 +1489,18 @@ namespace System.Management.Automation newScope.LocalsTuple = locals; var trapFuncContext = new FunctionContext - { - _file = funcContext._file, - _scriptBlock = funcContext._scriptBlock, - _sequencePoints = funcContext._sequencePoints, - _debuggerHidden = funcContext._debuggerHidden, - _debuggerStepThrough = funcContext._debuggerStepThrough, - _executionContext = funcContext._executionContext, - _boundBreakpoints = funcContext._boundBreakpoints, - _outputPipe = funcContext._outputPipe, - _breakPoints = funcContext._breakPoints, - _localsTuple = locals, - }; + { + _file = funcContext._file, + _scriptBlock = funcContext._scriptBlock, + _sequencePoints = funcContext._sequencePoints, + _debuggerHidden = funcContext._debuggerHidden, + _debuggerStepThrough = funcContext._debuggerStepThrough, + _executionContext = funcContext._executionContext, + _boundBreakpoints = funcContext._boundBreakpoints, + _outputPipe = funcContext._outputPipe, + _breakPoints = funcContext._breakPoints, + _localsTuple = locals, + }; handlers[handler](trapFuncContext); } @@ -1763,7 +1761,7 @@ namespace System.Management.Automation // Win8: 178063. Allow flow control related exceptions for PowerShell hosting API if ((exception is FlowControlException || exception is ScriptCallDepthException || - exception is PipelineStoppedException) && + exception is PipelineStoppedException) && ((memberInfo == null) || ((memberInfo.DeclaringType != typeof(PowerShell)) && (memberInfo.DeclaringType != typeof(Pipeline))))) { return; @@ -1811,7 +1809,7 @@ namespace System.Management.Automation } } - static class TypeOps + internal static class TypeOps { internal static Type ResolveTypeName(ITypeName typeName, IScriptExtent errorPos) { @@ -1822,14 +1820,14 @@ namespace System.Management.Automation { if (exception != null) { - if (exception is InvalidCastException && - exception.InnerException != null && + if (exception is InvalidCastException && + exception.InnerException != null && exception.InnerException is TypeResolver.AmbiguousTypeException) { throw exception; } - throw InterpreterError.NewInterpreterException(typeName, typeof (RuntimeException), errorPos, + throw InterpreterError.NewInterpreterException(typeName, typeof(RuntimeException), errorPos, "TypeNotFoundWithMessage", ParserStrings.TypeNotFoundWithMessage, typeName.FullName, exception.Message); @@ -1853,7 +1851,7 @@ namespace System.Management.Automation catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); - throw InterpreterError.NewInterpreterException(typeName, typeof (RuntimeException), errorPos, + throw InterpreterError.NewInterpreterException(typeName, typeof(RuntimeException), errorPos, "TypeNotFoundWithMessage", ParserStrings.TypeNotFoundWithMessage, typeName.FullName, e.Message); @@ -1867,7 +1865,7 @@ namespace System.Management.Automation ResolveTypeName(arrayTypeName.ElementType, errorPos); } - throw InterpreterError.NewInterpreterException(typeName, typeof (RuntimeException), errorPos, + throw InterpreterError.NewInterpreterException(typeName, typeof(RuntimeException), errorPos, "TypeNotFound", ParserStrings.TypeNotFound, typeName.FullName); } @@ -2045,7 +2043,7 @@ namespace System.Management.Automation } } - static class SwitchOps + internal static class SwitchOps { internal static bool ConditionSatisfiedWildcard(bool caseSensitive, object condition, @@ -2198,7 +2196,6 @@ namespace System.Management.Automation rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorExtent, context)); throw; } - } } @@ -2233,7 +2230,7 @@ namespace System.Management.Automation Split = 5, } - static class EnumerableOps + internal static class EnumerableOps { /// /// Implements the Where(expression) operation on collections @@ -2357,7 +2354,7 @@ namespace System.Management.Automation { notMatched = new Collection(); } - var resultCollection = new List(); + var resultCollection = new List(); Pipe outputPipe = new Pipe(resultCollection); bool returnTheRest = false; @@ -2466,7 +2463,7 @@ namespace System.Management.Automation } return new System.Object[] { matches, notMatched }; } - + return matches; } @@ -2638,7 +2635,7 @@ namespace System.Management.Automation nullRefException.GetType().Name, nullRefException, ExtendedTypeSystem.MethodInvocationException, - name, arguments.Length, nullRefException.Message); + name, arguments.Length, nullRefException.Message); } continue; } @@ -2665,9 +2662,8 @@ namespace System.Management.Automation else { throw InterpreterError.NewInterpreterException(ie, typeof(NullReferenceException), null, "ForEachNonexistentMemberReference", - ParserStrings.ForEachNonexistentMemberReference, name); + ParserStrings.ForEachNonexistentMemberReference, name); } - } var method = member as PSMethodInfo; @@ -2701,19 +2697,19 @@ namespace System.Management.Automation switch (numArgs) { case 0: - // No args: do a get - result.Add(PSObject.AsPSObject(property.Value)); - break; + // No args: do a get + result.Add(PSObject.AsPSObject(property.Value)); + break; case 1: - // 1 arg: set as a scalar - property.Value = arguments[0]; - break; + // 1 arg: set as a scalar + property.Value = arguments[0]; + break; default: - // more than one arg, just assign as is - property.Value = arguments; - break; + // more than one arg, just assign as is + property.Value = arguments; + break; } } } @@ -2759,12 +2755,11 @@ namespace System.Management.Automation result.Add(o); } } - } else { result.Add(o); - } + } } private static void PropertyGetterWorker(CallSite> getMemberBinderSite, @@ -2872,7 +2867,7 @@ namespace System.Management.Automation // will get wrapped in a new TargetInvocationException. throw tie.InnerException; } - } + } } // Call some method(s) named by binder on all objects from enumerator - applied recursively if an object is itself enumerable @@ -2978,33 +2973,33 @@ namespace System.Management.Automation internal static IEnumerator Create(object obj) { return new NonEnumerableObjectEnumerator - { - obj = obj, - realEnumerator = (new[] {obj}).GetEnumerator() - }; + { + _obj = obj, + _realEnumerator = (new[] { obj }).GetEnumerator() + }; } - private object obj; - private IEnumerator realEnumerator; + private object _obj; + private IEnumerator _realEnumerator; bool IEnumerator.MoveNext() { - return realEnumerator.MoveNext(); + return _realEnumerator.MoveNext(); } void IEnumerator.Reset() { - realEnumerator.Reset(); + _realEnumerator.Reset(); } object IEnumerator.Current { - get { return realEnumerator.Current; } + get { return _realEnumerator.Current; } } internal object GetNonEnumerableObject() { - return obj; + return _obj; } } @@ -3194,7 +3189,7 @@ namespace System.Management.Automation } } - return resultArray.ToArray(); + return resultArray.ToArray(); } internal static void WriteEnumerableToPipe(IEnumerator enumerator, Pipe pipe, ExecutionContext context, bool dispose) diff --git a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs index 4c834a804..81db2a428 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs @@ -9,13 +9,13 @@ using System.Globalization; namespace System.Management.Automation { - static class Boxed + internal static class Boxed { internal static object True = (object)true; internal static object False = (object)false; } - static class IntOps + internal static class IntOps { internal static object Add(int lhs, int rhs) { @@ -128,7 +128,7 @@ namespace System.Management.Automation } } - static class UIntOps + internal static class UIntOps { internal static object Add(uint lhs, uint rhs) { @@ -202,7 +202,7 @@ namespace System.Management.Automation internal static object CompareGe(uint lhs, uint rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } - static class LongOps + internal static class LongOps { internal static object Add(long lhs, long rhs) { @@ -293,7 +293,7 @@ namespace System.Management.Automation internal static object CompareGe(long lhs, long rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } - static class ULongOps + internal static class ULongOps { internal static object Add(ulong lhs, ulong rhs) { @@ -370,7 +370,7 @@ namespace System.Management.Automation internal static object CompareGe(ulong lhs, ulong rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } - static class DecimalOps + internal static class DecimalOps { internal static object Add(decimal lhs, decimal rhs) { @@ -465,7 +465,6 @@ namespace System.Management.Automation LanguagePrimitives.ThrowInvalidCastException(val, typeof(int)); Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException."); return null; - } internal static object BOr(decimal lhs, decimal rhs) @@ -504,14 +503,14 @@ namespace System.Management.Automation { ulong l = ConvertToUlong(lhs); ulong r = ConvertToUlong(rhs); - + // If either operand is signed, return signed result - if (lhs <0 || rhs<0) + if (lhs < 0 || rhs < 0) { unchecked { return (long)(l & r); - } + } } return l & r; } @@ -528,7 +527,7 @@ namespace System.Management.Automation } return LanguagePrimitives.ConvertTo(val); } - + internal static object LeftShift(decimal val, int count) { if (val <= int.MaxValue && val >= int.MinValue) @@ -639,7 +638,7 @@ namespace System.Management.Automation internal static object CompareGe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); } } - static class DoubleOps + internal static class DoubleOps { internal static object Add(double lhs, double rhs) { @@ -831,7 +830,7 @@ namespace System.Management.Automation internal static object CompareGe(double lhs, double rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; } } - static class CharOps + internal static class CharOps { internal static object CompareStringIeq(char lhs, string rhs) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs index 4502adc48..eb2221907 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation { using Dbg = Diagnostics; - static class StringOps + internal static class StringOps { internal static string Add(string lhs, string rhs) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index c64e5f9bd..02a1b8029 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -13,9 +13,9 @@ namespace System.Management.Automation using Dbg = Diagnostics; using System.Collections.ObjectModel; - static class VariableOps + internal static class VariableOps { - static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts) + internal static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts) { SessionStateInternal sessionState = executionContext.EngineSessionState; CommandOrigin origin = sessionState.CurrentScope.ScopeOrigin; @@ -87,7 +87,7 @@ namespace System.Management.Automation return value; } - static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionContext, VariableExpressionAst varAst) + private static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionContext, VariableExpressionAst varAst) { // In some limited cases, the compiler knows we don't want an error, like when we're backing up // $foreach and $switch, which might not be set. In that case, the ast passed is null. @@ -118,7 +118,7 @@ namespace System.Management.Automation return false; } - static object GetAutomaticVariableValue(int tupleIndex, ExecutionContext executionContext, VariableExpressionAst varAst) + internal static object GetAutomaticVariableValue(int tupleIndex, ExecutionContext executionContext, VariableExpressionAst varAst) { Diagnostics.Assert(tupleIndex < SpecialVariables.AutomaticVariableTypes.Length, "caller to verify a valid tuple index is used"); @@ -171,13 +171,13 @@ namespace System.Management.Automation if (ThrowStrictModeUndefinedVariable(executionContext, varAst)) { throw InterpreterError.NewInterpreterException(variablePath.UserPath, typeof(RuntimeException), - varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, variablePath.UserPath); + varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, variablePath.UserPath); } return null; } - static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType) + internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType) { Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable."); @@ -212,7 +212,7 @@ namespace System.Management.Automation return PSReference.CreateInstance(var, staticType); } - static Collection GetAttributeCollection(AttributeBaseAst[] attributeAsts) + private static Collection GetAttributeCollection(AttributeBaseAst[] attributeAsts) { var result = new Collection(); foreach (var attributeAst in attributeAsts) @@ -222,7 +222,7 @@ namespace System.Management.Automation return result; } - static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usingExpressionKey, int index) + private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usingExpressionKey, int index) { var boundParameters = tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary; @@ -251,7 +251,7 @@ namespace System.Management.Automation public object Value { get; set; } } - static object GetUsingValue(MutableTuple tuple, string usingExpressionKey, int index, ExecutionContext context) + internal static object GetUsingValue(MutableTuple tuple, string usingExpressionKey, int index, ExecutionContext context) { UsingResult result = GetUsingValueFromTuple(tuple, usingExpressionKey, index); if (result != null) diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 76b93ef5d..545b3b80c 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -196,7 +196,7 @@ namespace System.Management.Automation return AstVisitAction.SkipChildren; } - return CheckScriptBlock(ast); + return CheckScriptBlock(ast); } } @@ -208,7 +208,7 @@ namespace System.Management.Automation { private readonly PowerShell _powershell; private ExecutionContext _context; - private Dictionary _usingValueMap; + private Dictionary _usingValueMap; private bool? _createLocalScope; private ScriptBlockToPowerShellConverter() @@ -388,7 +388,7 @@ namespace System.Management.Automation var variableAst = usingAst.SubExpression as VariableExpressionAst; if (variableAst == null) { - throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), + throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text); } @@ -417,7 +417,7 @@ namespace System.Management.Automation catch (RuntimeException rte) { if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal)) - { + { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingAst.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, rte.ErrorRecord.TargetObject); } @@ -466,12 +466,12 @@ namespace System.Management.Automation /// The ScriptBlockAst that represents the scope of the previously analyzed UsingExpressions private static bool HasUsingExpressionsInDifferentScopes(UsingExpressionAst usingExpr, Ast topLevelParent, ref ScriptBlockAst sbClosestToPreviousUsingExpr) { - Diagnostics.Assert(topLevelParent is ScriptBlockAst || topLevelParent is FunctionDefinitionAst, + Diagnostics.Assert(topLevelParent is ScriptBlockAst || topLevelParent is FunctionDefinitionAst, "the top level parent should be either a ScriptBlockAst or FunctionDefinitionAst"); // Scan up the parents of a UsingExpression to check if it's in a nested function/filter/ScriptBlock Ast current = usingExpr; - do + do { current = current.Parent; @@ -521,7 +521,6 @@ namespace System.Management.Automation // The current UsingExpression is in a different scope from the previous UsingExpression we analyzed. return true; } - } while (current != topLevelParent); Diagnostics.Assert(false, "Unreachable Code. Top level parent is eitehr ScriptBlockAst or FunctionDefinitionAst, so it should return within the loop for sure."); @@ -529,7 +528,7 @@ namespace System.Management.Automation return true; } - void ConvertPipeline(PipelineAst pipelineAst, bool isTrustedInput) + private void ConvertPipeline(PipelineAst pipelineAst, bool isTrustedInput) { foreach (var command in pipelineAst.PipelineElements) { @@ -663,15 +662,14 @@ namespace System.Management.Automation { try { - argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell); + argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell); } catch (System.Exception) { - throw new ScriptBlockToPowerShellNotSupportedException( "CantConvertWithDynamicExpression", null, - AutomationExceptions.CantConvertWithDynamicExpression, + AutomationExceptions.CantConvertWithDynamicExpression, exprAst.Extent.Text); } } diff --git a/src/System.Management.Automation/engine/scriptparameterbinder.cs b/src/System.Management.Automation/engine/scriptparameterbinder.cs index 254e34233..0fd0f4ef3 100644 --- a/src/System.Management.Automation/engine/scriptparameterbinder.cs +++ b/src/System.Management.Automation/engine/scriptparameterbinder.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Linq; diff --git a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs index 2d7bf093f..2842eba48 100644 --- a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs +++ b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -169,7 +170,7 @@ namespace System.Management.Automation // the parameter might be a positional argument MergedCompiledCommandParameter parameter = - BindableParameters.GetMatchingParameter ( + BindableParameters.GetMatchingParameter( argument.ParameterName, false, true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); @@ -184,7 +185,7 @@ namespace System.Management.Automation if (BoundParameters.ContainsKey(parameter.Parameter.Name)) { - ParameterBindingException bindingException = + ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, @@ -226,7 +227,7 @@ namespace System.Management.Automation /// /// An array containing the values that were bound to $args. /// - void HandleRemainingArguments(Collection arguments) + private void HandleRemainingArguments(Collection arguments) { List args = new List(); @@ -288,7 +289,8 @@ namespace System.Management.Automation if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] == null) { var noteProperty = new PSNoteProperty(NotePropertyNameForSplattingParametersInArgs, - parameter.ParameterName) {IsHidden = true}; + parameter.ParameterName) + { IsHidden = true }; parameterText.Properties.Add(noteProperty); } args.Add(parameterText); diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 230cff1df..cbfe69b26 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -35,18 +35,18 @@ using MailAddress = System.Net.Mail.MailAddress; namespace System.Management.Automation { - [Flags] - internal enum SerializationOptions - { - None = 0, - UseDepthFromTypes = 1, - NoRootElement = 2, - NoNamespace = 4, - NoObjectRefIds = 8, - PreserveSerializationSettingOfOriginal = 16, + [Flags] + internal enum SerializationOptions + { + None = 0, + UseDepthFromTypes = 1, + NoRootElement = 2, + NoNamespace = 4, + NoObjectRefIds = 8, + PreserveSerializationSettingOfOriginal = 16, - RemotingOptions = UseDepthFromTypes | NoRootElement | NoNamespace | PreserveSerializationSettingOfOriginal, - } + RemotingOptions = UseDepthFromTypes | NoRootElement | NoNamespace | PreserveSerializationSettingOfOriginal, + } internal class SerializationContext { @@ -59,9 +59,9 @@ namespace System.Management.Automation internal SerializationContext(int depth, bool useDepthFromTypes) : this( - depth, + depth, (useDepthFromTypes ? SerializationOptions.UseDepthFromTypes : SerializationOptions.None) | - SerializationOptions.PreserveSerializationSettingOfOriginal, + SerializationOptions.PreserveSerializationSettingOfOriginal, null) { } @@ -77,7 +77,7 @@ namespace System.Management.Automation this.options = options; this.cryptoHelper = cryptoHelper; } - + internal readonly int depth; internal readonly SerializationOptions options; internal readonly PSRemotingCryptoHelper cryptoHelper; @@ -85,302 +85,302 @@ namespace System.Management.Automation internal readonly CimClassSerializationCache cimClassSerializationIdCache = new CimClassSerializationCache(); } - /// - /// This class provides public functionality for serializing a PSObject - /// - public class PSSerializer - { - internal PSSerializer() { } + /// + /// This class provides public functionality for serializing a PSObject + /// + public class PSSerializer + { + internal PSSerializer() { } - /// - /// Serializes an object into PowerShell CliXml - /// - /// The input object to serialize. Serializes to a default depth of 1 - /// The serialized object, as CliXml - public static string Serialize(Object source) - { - return Serialize(source, mshDefaultSerializationDepth); - } + /// + /// Serializes an object into PowerShell CliXml + /// + /// The input object to serialize. Serializes to a default depth of 1 + /// The serialized object, as CliXml + public static string Serialize(Object source) + { + return Serialize(source, s_mshDefaultSerializationDepth); + } - /// - /// Serializes an object into PowerShell CliXml - /// - /// The input object to serialize - /// The depth of the members to serialize - /// The serialized object, as CliXml - public static string Serialize(Object source, int depth) - { - // Create an xml writer - StringBuilder sb = new StringBuilder(); - XmlWriterSettings xmlSettings = new XmlWriterSettings(); - xmlSettings.CloseOutput = true; - xmlSettings.Encoding = System.Text.Encoding.Unicode; - xmlSettings.Indent = true; - xmlSettings.OmitXmlDeclaration = true; - XmlWriter xw = XmlWriter.Create(sb, xmlSettings); + /// + /// Serializes an object into PowerShell CliXml + /// + /// The input object to serialize + /// The depth of the members to serialize + /// The serialized object, as CliXml + public static string Serialize(Object source, int depth) + { + // Create an xml writer + StringBuilder sb = new StringBuilder(); + XmlWriterSettings xmlSettings = new XmlWriterSettings(); + xmlSettings.CloseOutput = true; + xmlSettings.Encoding = System.Text.Encoding.Unicode; + xmlSettings.Indent = true; + xmlSettings.OmitXmlDeclaration = true; + XmlWriter xw = XmlWriter.Create(sb, xmlSettings); - // Serialize the objects - Serializer serializer = new Serializer(xw, depth, true); - serializer.Serialize(source); - serializer.Done(); - serializer = null; + // Serialize the objects + Serializer serializer = new Serializer(xw, depth, true); + serializer.Serialize(source); + serializer.Done(); + serializer = null; - // Return the output - return sb.ToString(); - } + // Return the output + return sb.ToString(); + } - /// - /// Deserializes PowerShell CliXml into an object. - /// - /// The CliXml the represents the object to deserialize. - /// An object that represents the serialized content - public static object Deserialize(string source) - { - Object[] results = DeserializeAsList(source); + /// + /// Deserializes PowerShell CliXml into an object. + /// + /// The CliXml the represents the object to deserialize. + /// An object that represents the serialized content + public static object Deserialize(string source) + { + Object[] results = DeserializeAsList(source); - // Return the results - if (results.Length == 0) - { - return null; - } - else if (results.Length == 1) - { - return results[0]; - } - else - { - return results; - } - } + // Return the results + if (results.Length == 0) + { + return null; + } + else if (results.Length == 1) + { + return results[0]; + } + else + { + return results; + } + } - /// - /// Deserializes PowerShell CliXml into a list of objects. - /// - /// The CliXml the represents the object to deserialize. - /// An object array represents the serialized content - public static object[] DeserializeAsList(string source) - { + /// + /// Deserializes PowerShell CliXml into a list of objects. + /// + /// The CliXml the represents the object to deserialize. + /// An object array represents the serialized content + public static object[] DeserializeAsList(string source) + { List results = new List(); - // Create the text reader to hold the content - TextReader textReader = new StringReader(source); - XmlReader xmlReader = XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); + // Create the text reader to hold the content + TextReader textReader = new StringReader(source); + XmlReader xmlReader = XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); - // Deserialize the content - Deserializer deserializer = new Deserializer(xmlReader); - while (!deserializer.Done()) - { - object result = deserializer.Deserialize(); - results.Add(result); - } + // Deserialize the content + Deserializer deserializer = new Deserializer(xmlReader); + while (!deserializer.Done()) + { + object result = deserializer.Deserialize(); + results.Add(result); + } - return results.ToArray(); - } + return results.ToArray(); + } - /// - /// Default depth of serialization - /// - private static int mshDefaultSerializationDepth = 1; - } + /// + /// Default depth of serialization + /// + private static int s_mshDefaultSerializationDepth = 1; + } - /// - /// This class provides functionality for serializing a PSObject - /// - internal class Serializer - { - #region constructor + /// + /// This class provides functionality for serializing a PSObject + /// + internal class Serializer + { + #region constructor - private readonly InternalSerializer _serializer; + private readonly InternalSerializer _serializer; - /// - /// Creates a Serializer using default serialization context - /// - /// writer to be used for serialization - internal Serializer(XmlWriter writer) - : this(writer, new SerializationContext()) - { - } + /// + /// Creates a Serializer using default serialization context + /// + /// writer to be used for serialization + internal Serializer(XmlWriter writer) + : this(writer, new SerializationContext()) + { + } - /// - /// Creates a Serializer using specified serialization context - /// - /// writer to be used for serialization - /// depth of serialization - /// - /// if true then types.ps1xml can override depth - /// for a particular types (using SerializationDepth property) - /// - internal Serializer(XmlWriter writer, int depth, bool useDepthFromTypes) - : this(writer, new SerializationContext(depth, useDepthFromTypes)) - { - } + /// + /// Creates a Serializer using specified serialization context + /// + /// writer to be used for serialization + /// depth of serialization + /// + /// if true then types.ps1xml can override depth + /// for a particular types (using SerializationDepth property) + /// + internal Serializer(XmlWriter writer, int depth, bool useDepthFromTypes) + : this(writer, new SerializationContext(depth, useDepthFromTypes)) + { + } - /// - /// Creates a Serializer using specified serialization context - /// - /// writer to be used for serialization - /// serialization context - internal Serializer(XmlWriter writer, SerializationContext context) - { - if (writer == null) - { - throw PSTraceSource.NewArgumentException("writer"); - } - if (context == null) - { - throw PSTraceSource.NewArgumentException("context"); - } + /// + /// Creates a Serializer using specified serialization context + /// + /// writer to be used for serialization + /// serialization context + internal Serializer(XmlWriter writer, SerializationContext context) + { + if (writer == null) + { + throw PSTraceSource.NewArgumentException("writer"); + } + if (context == null) + { + throw PSTraceSource.NewArgumentException("context"); + } - _serializer = new InternalSerializer(writer, context); - _serializer.Start(); - } + _serializer = new InternalSerializer(writer, context); + _serializer.Start(); + } - #endregion constructor + #endregion constructor - #region public methods / properties + #region public methods / properties - /// - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Serializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - /// - internal TypeTable TypeTable - { - get { return _serializer.TypeTable; } - set { _serializer.TypeTable = value; } - } + /// + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Serializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + /// + internal TypeTable TypeTable + { + get { return _serializer.TypeTable; } + set { _serializer.TypeTable = value; } + } - /// - /// Serializes the object - /// - /// object to be serialized - /// - /// Please note that this method shouldn't throw any exceptions. - /// If it throws - please open a bug. - /// - internal void Serialize(object source) - { - Serialize(source, null); - } + /// + /// Serializes the object + /// + /// object to be serialized + /// + /// Please note that this method shouldn't throw any exceptions. + /// If it throws - please open a bug. + /// + internal void Serialize(object source) + { + Serialize(source, null); + } - /// - /// Serializes passed in object - /// - /// - /// object to be serialized - /// - /// - /// Stream to which this object belong. Ex: Output, Error etc. - /// - /// - /// Please note that this method shouldn't throw any exceptions. - /// If it throws - please open a bug. - /// - internal void Serialize(object source, string streamName) - { - _serializer.WriteOneTopLevelObject(source, streamName); - } + /// + /// Serializes passed in object + /// + /// + /// object to be serialized + /// + /// + /// Stream to which this object belong. Ex: Output, Error etc. + /// + /// + /// Please note that this method shouldn't throw any exceptions. + /// If it throws - please open a bug. + /// + internal void Serialize(object source, string streamName) + { + _serializer.WriteOneTopLevelObject(source, streamName); + } - /// - /// Write the end of root element - /// - internal void Done() - { - _serializer.End(); - } + /// + /// Write the end of root element + /// + internal void Done() + { + _serializer.End(); + } - internal void Stop() - { - _serializer.Stop(); - } + internal void Stop() + { + _serializer.Stop(); + } - #endregion - } + #endregion + } - [Flags] - internal enum DeserializationOptions - { - None = 0, - NoRootElement = 256, // I start at 256 to try not to overlap - NoNamespace = 512, // with SerializationOptions and to catch bugs early - DeserializeScriptBlocks = 1024, + [Flags] + internal enum DeserializationOptions + { + None = 0, + NoRootElement = 256, // I start at 256 to try not to overlap + NoNamespace = 512, // with SerializationOptions and to catch bugs early + DeserializeScriptBlocks = 1024, - RemotingOptions = NoRootElement | NoNamespace, - } + RemotingOptions = NoRootElement | NoNamespace, + } - internal class DeserializationContext - { - internal DeserializationContext() - : this(DeserializationOptions.None, null) - { - } + internal class DeserializationContext + { + internal DeserializationContext() + : this(DeserializationOptions.None, null) + { + } - internal DeserializationContext(DeserializationOptions options, PSRemotingCryptoHelper cryptoHelper) - { - this.options = options; - this.cryptoHelper = cryptoHelper; - } + internal DeserializationContext(DeserializationOptions options, PSRemotingCryptoHelper cryptoHelper) + { + this.options = options; + this.cryptoHelper = cryptoHelper; + } - /// - /// Limits the total data processed by the deserialization context. Deserialization context - /// is used by PriorityReceivedDataCollection (remoting) to process incoming data from the - /// remote end. A value of Null means that the max memory is unlimited. - /// - internal Nullable MaximumAllowedMemory - { - set { maxAllowedMemory = value; } - get { return maxAllowedMemory; } - } + /// + /// Limits the total data processed by the deserialization context. Deserialization context + /// is used by PriorityReceivedDataCollection (remoting) to process incoming data from the + /// remote end. A value of Null means that the max memory is unlimited. + /// + internal Nullable MaximumAllowedMemory + { + set { _maxAllowedMemory = value; } + get { return _maxAllowedMemory; } + } - /// - /// Logs that memory used by deserialized objects is not related to the size of input xml. - /// Used mainly to account for memory usage of cloned TypeNames when calculating memory quota usage. - /// - /// - internal void LogExtraMemoryUsage(int amountOfExtraMemory) - { - if (amountOfExtraMemory < 0) - { - return; - } + /// + /// Logs that memory used by deserialized objects is not related to the size of input xml. + /// Used mainly to account for memory usage of cloned TypeNames when calculating memory quota usage. + /// + /// + internal void LogExtraMemoryUsage(int amountOfExtraMemory) + { + if (amountOfExtraMemory < 0) + { + return; + } - if (maxAllowedMemory.HasValue) - { - if (amountOfExtraMemory > (maxAllowedMemory.Value - totalDataProcessedSoFar)) - { - string message = StringUtil.Format(Serialization.DeserializationMemoryQuota, ((double) maxAllowedMemory.Value)/(1 << 20), - ConfigurationDataFromXML.MAXRCVDOBJSIZETOKEN_CamelCase, - ConfigurationDataFromXML.MAXRCVDCMDSIZETOKEN_CamelCase); - throw new XmlException(message); - } + if (_maxAllowedMemory.HasValue) + { + if (amountOfExtraMemory > (_maxAllowedMemory.Value - _totalDataProcessedSoFar)) + { + string message = StringUtil.Format(Serialization.DeserializationMemoryQuota, ((double)_maxAllowedMemory.Value) / (1 << 20), + ConfigurationDataFromXML.MAXRCVDOBJSIZETOKEN_CamelCase, + ConfigurationDataFromXML.MAXRCVDCMDSIZETOKEN_CamelCase); + throw new XmlException(message); + } - totalDataProcessedSoFar = totalDataProcessedSoFar + amountOfExtraMemory; - } - } + _totalDataProcessedSoFar = _totalDataProcessedSoFar + amountOfExtraMemory; + } + } - private int totalDataProcessedSoFar; - private Nullable maxAllowedMemory; + private int _totalDataProcessedSoFar; + private Nullable _maxAllowedMemory; - internal readonly DeserializationOptions options; - internal readonly PSRemotingCryptoHelper cryptoHelper; + internal readonly DeserializationOptions options; + internal readonly PSRemotingCryptoHelper cryptoHelper; - internal static int MaxItemsInCimClassCache = 100; - internal readonly CimClassDeserializationCache cimClassSerializationIdCache = new CimClassDeserializationCache(); - } + internal static int MaxItemsInCimClassCache = 100; + internal readonly CimClassDeserializationCache cimClassSerializationIdCache = new CimClassDeserializationCache(); + } - internal class CimClassDeserializationCache - { - private readonly Dictionary _cimClassIdToClass = new Dictionary(); + internal class CimClassDeserializationCache + { + private readonly Dictionary _cimClassIdToClass = new Dictionary(); - internal void AddCimClassToCache(TKey key, CimClass cimClass) - { - if (_cimClassIdToClass.Count >= DeserializationContext.MaxItemsInCimClassCache) - { - _cimClassIdToClass.Clear(); - } - _cimClassIdToClass.Add(key, cimClass); + internal void AddCimClassToCache(TKey key, CimClass cimClass) + { + if (_cimClassIdToClass.Count >= DeserializationContext.MaxItemsInCimClassCache) + { + _cimClassIdToClass.Clear(); + } + _cimClassIdToClass.Add(key, cimClass); - /* PRINTF DEBUG + /* PRINTF DEBUG Console.WriteLine("Contents of deserialization cache (after a call to AddCimClassToCache ({0})):", key); Console.WriteLine(" Count = {0}", this._cimClassIdToClass.Count); foreach (var t in this._cimClassIdToClass.Keys) @@ -388,49 +388,48 @@ namespace System.Management.Automation Console.WriteLine(" {0}", t); } */ + } - } - - internal CimClass GetCimClassFromCache(TKey key) - { - CimClass cimClass; - if (this._cimClassIdToClass.TryGetValue(key, out cimClass)) - { - /* PRINTF DEBUG + internal CimClass GetCimClassFromCache(TKey key) + { + CimClass cimClass; + if (_cimClassIdToClass.TryGetValue(key, out cimClass)) + { + /* PRINTF DEBUG Console.WriteLine("GetCimClassFromCache - class found: {0}", key); */ - return cimClass; - } + return cimClass; + } - /* PRINTF DEBUG + /* PRINTF DEBUG Console.WriteLine("GetCimClassFromCache - class NOT found: {0}", key); */ - return null; - } - } + return null; + } + } - internal class CimClassSerializationCache - { - private readonly HashSet _cimClassesHeldByDeserializer = new HashSet(EqualityComparer.Default); - - internal bool DoesDeserializerAlreadyHaveCimClass(TKey key) - { - return _cimClassesHeldByDeserializer.Contains(key); - } + internal class CimClassSerializationCache + { + private readonly HashSet _cimClassesHeldByDeserializer = new HashSet(EqualityComparer.Default); - internal void AddClassToCache(TKey key) - { - Dbg.Assert(!_cimClassesHeldByDeserializer.Contains(key), "This method should not be called for classes already in the cache"); + internal bool DoesDeserializerAlreadyHaveCimClass(TKey key) + { + return _cimClassesHeldByDeserializer.Contains(key); + } - if (_cimClassesHeldByDeserializer.Count >= DeserializationContext.MaxItemsInCimClassCache) - { - _cimClassesHeldByDeserializer.Clear(); - } - _cimClassesHeldByDeserializer.Add(key); + internal void AddClassToCache(TKey key) + { + Dbg.Assert(!_cimClassesHeldByDeserializer.Contains(key), "This method should not be called for classes already in the cache"); - /* PRINTF DEBUG + if (_cimClassesHeldByDeserializer.Count >= DeserializationContext.MaxItemsInCimClassCache) + { + _cimClassesHeldByDeserializer.Clear(); + } + _cimClassesHeldByDeserializer.Add(key); + + /* PRINTF DEBUG Console.WriteLine("Contents of serialization cache (after adding {0}):", key); Console.WriteLine(" Count = {0}", this._cimClassesHeldByDeserializer.Count); foreach (var t in _cimClassesHeldByDeserializer) @@ -438,182 +437,182 @@ namespace System.Management.Automation Console.WriteLine(" {0}", t); } */ - } - } + } + } - internal class CimClassSerializationId : Tuple - { - public CimClassSerializationId(string className, string namespaceName, string computerName, int hashCode) - : base(className, namespaceName, computerName, hashCode) - { - } + internal class CimClassSerializationId : Tuple + { + public CimClassSerializationId(string className, string namespaceName, string computerName, int hashCode) + : base(className, namespaceName, computerName, hashCode) + { + } - public string ClassName { get { return this.Item1; } } - public string NamespaceName { get { return this.Item2; } } - public string ComputerName { get { return this.Item3; } } - public int ClassHashCode { get { return this.Item4; } } - } + public string ClassName { get { return this.Item1; } } + public string NamespaceName { get { return this.Item2; } } + public string ComputerName { get { return this.Item3; } } + public int ClassHashCode { get { return this.Item4; } } + } - /// - /// This class provides functionality for deserializing a PSObject - /// - internal class Deserializer - { - #region constructor + /// + /// This class provides functionality for deserializing a PSObject + /// + internal class Deserializer + { + #region constructor - private readonly XmlReader _reader; - private readonly InternalDeserializer _deserializer; - private readonly DeserializationContext _context; + private readonly XmlReader _reader; + private readonly InternalDeserializer _deserializer; + private readonly DeserializationContext _context; - /// - /// Creates a Deserializer using default deserialization context - /// - /// reader to be used for deserialization - /// - /// Thrown when the xml is in an incorrect format - /// - internal Deserializer(XmlReader reader) - : this(reader, new DeserializationContext()) - { - } + /// + /// Creates a Deserializer using default deserialization context + /// + /// reader to be used for deserialization + /// + /// Thrown when the xml is in an incorrect format + /// + internal Deserializer(XmlReader reader) + : this(reader, new DeserializationContext()) + { + } - /// - /// Creates a Deserializer using specified serialization context - /// - /// reader to be used for deserialization - /// serialization context - /// - /// Thrown when the xml is in an incorrect format - /// - internal Deserializer(XmlReader reader, DeserializationContext context) - { - if (reader == null) - { - throw PSTraceSource.NewArgumentNullException("reader"); - } + /// + /// Creates a Deserializer using specified serialization context + /// + /// reader to be used for deserialization + /// serialization context + /// + /// Thrown when the xml is in an incorrect format + /// + internal Deserializer(XmlReader reader, DeserializationContext context) + { + if (reader == null) + { + throw PSTraceSource.NewArgumentNullException("reader"); + } - _reader = reader; - _context = context; - _deserializer = new InternalDeserializer(_reader, _context); + _reader = reader; + _context = context; + _deserializer = new InternalDeserializer(_reader, _context); - try - { - Start(); - } - catch (XmlException exception) - { - ReportExceptionForETW(exception); - throw; - } - } + try + { + Start(); + } + catch (XmlException exception) + { + ReportExceptionForETW(exception); + throw; + } + } - #endregion constructor + #endregion constructor - #region public method / properties + #region public method / properties - private static void ReportExceptionForETW(XmlException exception) - { - PSEtwLog.LogAnalyticError( - PSEventId.Serializer_XmlExceptionWhenDeserializing, PSOpcode.Exception, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - exception.LineNumber, exception.LinePosition, exception.ToString()); - } + private static void ReportExceptionForETW(XmlException exception) + { + PSEtwLog.LogAnalyticError( + PSEventId.Serializer_XmlExceptionWhenDeserializing, PSOpcode.Exception, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + exception.LineNumber, exception.LinePosition, exception.ToString()); + } - private bool _done = false; + private bool _done = false; - /// - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Deserializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - /// - internal TypeTable TypeTable - { - get { return _deserializer.TypeTable; } - set { _deserializer.TypeTable = value; } - } + /// + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Deserializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + /// + internal TypeTable TypeTable + { + get { return _deserializer.TypeTable; } + set { _deserializer.TypeTable = value; } + } - /// - /// Read the root element tag and set the cursor to start tag of - /// first object. - /// - private void Start() - { - Dbg.Assert(_reader.ReadState == ReadState.Initial, "When deserialization starts we should have XmlReader.ReadState == Initial"); - Dbg.Assert(_reader.NodeType == XmlNodeType.None, "When deserialization starts we should have XmlReader.NodeType == None"); - _reader.Read(); + /// + /// Read the root element tag and set the cursor to start tag of + /// first object. + /// + private void Start() + { + Dbg.Assert(_reader.ReadState == ReadState.Initial, "When deserialization starts we should have XmlReader.ReadState == Initial"); + Dbg.Assert(_reader.NodeType == XmlNodeType.None, "When deserialization starts we should have XmlReader.NodeType == None"); + _reader.Read(); - //If version is not provided, we assume it is the default - string version = InternalSerializer.DefaultVersion; - if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) - { - _done = _reader.EOF; - } - else - { - // Make sure the reader is positioned on the root ( ) element (not on XmlDeclaration for example) - _reader.MoveToContent(); - Dbg.Assert(_reader.EOF || (_reader.NodeType == XmlNodeType.Element), "When deserialization starts reading we should have XmlReader.NodeType == Element"); + //If version is not provided, we assume it is the default + string version = InternalSerializer.DefaultVersion; + if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) + { + _done = _reader.EOF; + } + else + { + // Make sure the reader is positioned on the root ( ) element (not on XmlDeclaration for example) + _reader.MoveToContent(); + Dbg.Assert(_reader.EOF || (_reader.NodeType == XmlNodeType.Element), "When deserialization starts reading we should have XmlReader.NodeType == Element"); - //Read version attribute and validate it. - string versionAttribute = _reader.GetAttribute(SerializationStrings.VersionAttribute); - if (versionAttribute != null) - { - version = versionAttribute; - } + //Read version attribute and validate it. + string versionAttribute = _reader.GetAttribute(SerializationStrings.VersionAttribute); + if (versionAttribute != null) + { + version = versionAttribute; + } - //If the root element tag is empty, there are no objects to read. - if (!_deserializer.ReadStartElementAndHandleEmpty(SerializationStrings.RootElementTag)) - { - _done = true; - } - } - _deserializer.ValidateVersion(version); - } + //If the root element tag is empty, there are no objects to read. + if (!_deserializer.ReadStartElementAndHandleEmpty(SerializationStrings.RootElementTag)) + { + _done = true; + } + } + _deserializer.ValidateVersion(version); + } - internal bool Done() - { - if (_done == false) - { - if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) - { - _done = _reader.EOF; - } - else - { - if (_reader.NodeType == XmlNodeType.EndElement) - { - try - { - _reader.ReadEndElement(); - } - catch (XmlException exception) - { - ReportExceptionForETW(exception); - throw; - } - _done = true; - } - } - } - return _done; - } + internal bool Done() + { + if (_done == false) + { + if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) + { + _done = _reader.EOF; + } + else + { + if (_reader.NodeType == XmlNodeType.EndElement) + { + try + { + _reader.ReadEndElement(); + } + catch (XmlException exception) + { + ReportExceptionForETW(exception); + throw; + } + _done = true; + } + } + } + return _done; + } - internal void Stop() - { - _deserializer.Stop(); - } + internal void Stop() + { + _deserializer.Stop(); + } - /// - /// Deserializes next object. - /// - /// - /// Thrown when the xml is in an incorrect format - /// - internal object Deserialize() - { - string ignore; - return Deserialize(out ignore); - } + /// + /// Deserializes next object. + /// + /// + /// Thrown when the xml is in an incorrect format + /// + internal object Deserialize() + { + string ignore; + return Deserialize(out ignore); + } /// /// Deserializes next object. @@ -640,1567 +639,1565 @@ namespace System.Management.Automation } } - #endregion public methods + #endregion public methods - #region Helper methods for dealing with "Deserialized." prefix + #region Helper methods for dealing with "Deserialized." prefix - /// - /// Adds "Deserialized." prefix to passed in argument if not already present - /// - /// - internal static void AddDeserializationPrefix(ref string type) - { - Dbg.Assert(type != null, "caller should validate the parameter"); - if (!type.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase)) - { - type = type.Insert(0, Deserializer.DeserializationTypeNamePrefix); - } - } + /// + /// Adds "Deserialized." prefix to passed in argument if not already present + /// + /// + internal static void AddDeserializationPrefix(ref string type) + { + Dbg.Assert(type != null, "caller should validate the parameter"); + if (!type.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase)) + { + type = type.Insert(0, Deserializer.DeserializationTypeNamePrefix); + } + } - /// - /// Checks if an object is either a live or deserialized instance of class or one of its subclasses. - /// - /// - /// - /// true if is either a live or deserialized instance of class or one of its subclasses; false otherwise - internal static bool IsInstanceOfType(object o, Type type) - { - if (type == null) - { - throw PSTraceSource.NewArgumentNullException("type"); - } - if (o == null) - { - return false; - } + /// + /// Checks if an object is either a live or deserialized instance of class or one of its subclasses. + /// + /// + /// + /// true if is either a live or deserialized instance of class or one of its subclasses; false otherwise + internal static bool IsInstanceOfType(object o, Type type) + { + if (type == null) + { + throw PSTraceSource.NewArgumentNullException("type"); + } + if (o == null) + { + return false; + } - return type.IsInstanceOfType(PSObject.Base(o)) || IsDeserializedInstanceOfType(o, type); - } + return type.IsInstanceOfType(PSObject.Base(o)) || IsDeserializedInstanceOfType(o, type); + } - /// - /// Checks if an object is a deserialized instance of class or one of its subclasses. - /// - /// - /// - /// true if is a deserialized instance of class or one of its subclasses; false otherwise - internal static bool IsDeserializedInstanceOfType(object o, Type type) - { - if (type == null) - { - throw PSTraceSource.NewArgumentNullException("type"); - } - if (o == null) - { - return false; - } + /// + /// Checks if an object is a deserialized instance of class or one of its subclasses. + /// + /// + /// + /// true if is a deserialized instance of class or one of its subclasses; false otherwise + internal static bool IsDeserializedInstanceOfType(object o, Type type) + { + if (type == null) + { + throw PSTraceSource.NewArgumentNullException("type"); + } + if (o == null) + { + return false; + } - PSObject pso = o as PSObject; - if (pso != null) - { - IEnumerable typeNames = pso.InternalTypeNames; - if (typeNames != null) - { - foreach (string typeName in typeNames) - { - if (typeName.Length == Deserializer.DeserializationTypeNamePrefix.Length + type.FullName.Length && - typeName.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase) && - typeName.EndsWith(type.FullName, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - } - } + PSObject pso = o as PSObject; + if (pso != null) + { + IEnumerable typeNames = pso.InternalTypeNames; + if (typeNames != null) + { + foreach (string typeName in typeNames) + { + if (typeName.Length == Deserializer.DeserializationTypeNamePrefix.Length + type.FullName.Length && + typeName.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase) && + typeName.EndsWith(type.FullName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + } - // not the right type - return false; - } + // not the right type + return false; + } - internal static string MaskDeserializationPrefix(string typeName) - { - if (typeName == null) - { - return null; - } + internal static string MaskDeserializationPrefix(string typeName) + { + if (typeName == null) + { + return null; + } - if (typeName.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase)) - { - typeName = typeName.Substring(Deserializer.DeserializationTypeNamePrefix.Length); - } + if (typeName.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase)) + { + typeName = typeName.Substring(Deserializer.DeserializationTypeNamePrefix.Length); + } - return typeName; - } + return typeName; + } - /// - /// Gets a new collection of typenames without "Deserialization." prefix - /// in the typename. This will allow to map type info/format info of the orignal type - /// for deserialized objects. - /// - /// - /// - /// Null if no type with "Deserialized." prefix is found. - /// Otherwise with the prefix removed if any. - /// - internal static Collection MaskDeserializationPrefix(Collection typeNames) - { - Dbg.Assert(null != typeNames, "typeNames cannot be null"); + /// + /// Gets a new collection of typenames without "Deserialization." prefix + /// in the typename. This will allow to map type info/format info of the orignal type + /// for deserialized objects. + /// + /// + /// + /// Null if no type with "Deserialized." prefix is found. + /// Otherwise with the prefix removed if any. + /// + internal static Collection MaskDeserializationPrefix(Collection typeNames) + { + Dbg.Assert(null != typeNames, "typeNames cannot be null"); - bool atleastOneDeserializedTypeFound = false; + bool atleastOneDeserializedTypeFound = false; - Collection typesWithoutPrefix = new Collection(); - foreach (string type in typeNames) - { - if (type.StartsWith(Deserializer.DeserializationTypeNamePrefix, - StringComparison.OrdinalIgnoreCase)) - { - atleastOneDeserializedTypeFound = true; - // remove *only* the prefix - typesWithoutPrefix.Add(type.Substring(Deserializer.DeserializationTypeNamePrefix.Length)); - } - else - { - typesWithoutPrefix.Add(type); - } - } + Collection typesWithoutPrefix = new Collection(); + foreach (string type in typeNames) + { + if (type.StartsWith(Deserializer.DeserializationTypeNamePrefix, + StringComparison.OrdinalIgnoreCase)) + { + atleastOneDeserializedTypeFound = true; + // remove *only* the prefix + typesWithoutPrefix.Add(type.Substring(Deserializer.DeserializationTypeNamePrefix.Length)); + } + else + { + typesWithoutPrefix.Add(type); + } + } - if (atleastOneDeserializedTypeFound) - { - return typesWithoutPrefix; - } + if (atleastOneDeserializedTypeFound) + { + return typesWithoutPrefix; + } - return null; - } + return null; + } - /// - /// Used to prefix a typename for deserialization. - /// - private const string DeserializationTypeNamePrefix = "Deserialized."; + /// + /// Used to prefix a typename for deserialization. + /// + private const string DeserializationTypeNamePrefix = "Deserialized."; - #endregion - } + #endregion + } - /// - /// Types of known type container supported by monad - /// - internal enum ContainerType - { - Dictionary, - Queue, - Stack, - List, - Enumerable, - None - }; + /// + /// Types of known type container supported by monad + /// + internal enum ContainerType + { + Dictionary, + Queue, + Stack, + List, + Enumerable, + None + }; - /// - /// This internal helper class provides methods for serializing mshObject. - /// - internal class InternalSerializer - { - #region constructor + /// + /// This internal helper class provides methods for serializing mshObject. + /// + internal class InternalSerializer + { + #region constructor - internal const string DefaultVersion = "1.1.0.1"; + internal const string DefaultVersion = "1.1.0.1"; - /// - /// Xml writer to be used - /// - private readonly XmlWriter _writer; + /// + /// Xml writer to be used + /// + private readonly XmlWriter _writer; - /// - /// Serialization context - /// - private readonly SerializationContext _context; + /// + /// Serialization context + /// + private readonly SerializationContext _context; - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Serializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - private TypeTable _typeTable; + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Serializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + private TypeTable _typeTable; - /// - /// Depth below top level - used to prevent infinitely deep serialization - /// (without this protection it would be possible i.e. with SerializationDepth and recursion) - /// - private int depthBelowTopLevel; + /// + /// Depth below top level - used to prevent infinitely deep serialization + /// (without this protection it would be possible i.e. with SerializationDepth and recursion) + /// + private int _depthBelowTopLevel; - private const int MaxDepthBelowTopLevel = 50; + private const int MaxDepthBelowTopLevel = 50; - private readonly ReferenceIdHandlerForSerializer objectRefIdHandler; - private readonly ReferenceIdHandlerForSerializer typeRefIdHandler; + private readonly ReferenceIdHandlerForSerializer _objectRefIdHandler; + private readonly ReferenceIdHandlerForSerializer _typeRefIdHandler; - internal InternalSerializer(XmlWriter writer, SerializationContext context) - { - Dbg.Assert(writer != null, "caller should validate the parameter"); - Dbg.Assert(context != null, "caller should validate the parameter"); - _writer = writer; - _context = context; + internal InternalSerializer(XmlWriter writer, SerializationContext context) + { + Dbg.Assert(writer != null, "caller should validate the parameter"); + Dbg.Assert(context != null, "caller should validate the parameter"); + _writer = writer; + _context = context; - IDictionary objectRefIdDictionary = null; - if ((_context.options & SerializationOptions.NoObjectRefIds) == 0) - { - objectRefIdDictionary = new WeakReferenceDictionary(); - } - this.objectRefIdHandler = new ReferenceIdHandlerForSerializer(objectRefIdDictionary); + IDictionary objectRefIdDictionary = null; + if ((_context.options & SerializationOptions.NoObjectRefIds) == 0) + { + objectRefIdDictionary = new WeakReferenceDictionary(); + } + _objectRefIdHandler = new ReferenceIdHandlerForSerializer(objectRefIdDictionary); - this.typeRefIdHandler = new ReferenceIdHandlerForSerializer( - new Dictionary(ConsolidatedString.EqualityComparer)); - } + _typeRefIdHandler = new ReferenceIdHandlerForSerializer( + new Dictionary(ConsolidatedString.EqualityComparer)); + } - #endregion + #endregion - /// - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Serializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - /// - internal TypeTable TypeTable - { - get { return _typeTable; } - set { _typeTable = value; } - } + /// + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Serializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + /// + internal TypeTable TypeTable + { + get { return _typeTable; } + set { _typeTable = value; } + } - /// - /// Writes the start of root element - /// - internal void Start() - { - if (SerializationOptions.NoRootElement != (this._context.options & SerializationOptions.NoRootElement)) - { - this.WriteStartElement(SerializationStrings.RootElementTag); - this.WriteAttribute(SerializationStrings.VersionAttribute, InternalSerializer.DefaultVersion); - } - } + /// + /// Writes the start of root element + /// + internal void Start() + { + if (SerializationOptions.NoRootElement != (_context.options & SerializationOptions.NoRootElement)) + { + this.WriteStartElement(SerializationStrings.RootElementTag); + this.WriteAttribute(SerializationStrings.VersionAttribute, InternalSerializer.DefaultVersion); + } + } - /// - /// Writes the end of root element - /// - internal void End() - { - if (SerializationOptions.NoRootElement != (this._context.options & SerializationOptions.NoRootElement)) - { - _writer.WriteEndElement(); - } - _writer.Flush(); - } + /// + /// Writes the end of root element + /// + internal void End() + { + if (SerializationOptions.NoRootElement != (_context.options & SerializationOptions.NoRootElement)) + { + _writer.WriteEndElement(); + } + _writer.Flush(); + } - private bool isStopping = false; + private bool _isStopping = false; - /// - /// Called from a separate thread will stop the serialization process - /// - internal void Stop() - { - this.isStopping = true; - } + /// + /// Called from a separate thread will stop the serialization process + /// + internal void Stop() + { + _isStopping = true; + } private void CheckIfStopping() { - if (this.isStopping) + if (_isStopping) { throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping); } } - internal static bool IsPrimitiveKnownType(Type input) - { - //Check if source is of primitive known type - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(input); - return (pktInfo != null); - } + internal static bool IsPrimitiveKnownType(Type input) + { + //Check if source is of primitive known type + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(input); + return (pktInfo != null); + } - /// - /// This writes one object. - /// - /// - /// source to be serialized. - /// - /// - /// Stream to which source belongs - /// - internal void WriteOneTopLevelObject - ( - object source, - string streamName - ) - { - Dbg.Assert(this.depthBelowTopLevel == 0, "InternalSerializer.depthBelowTopLevel should be 0 at top-level"); - WriteOneObject(source, streamName, null, _context.depth); - } + /// + /// This writes one object. + /// + /// + /// source to be serialized. + /// + /// + /// Stream to which source belongs + /// + internal void WriteOneTopLevelObject + ( + object source, + string streamName + ) + { + Dbg.Assert(_depthBelowTopLevel == 0, "InternalSerializer.depthBelowTopLevel should be 0 at top-level"); + WriteOneObject(source, streamName, null, _context.depth); + } - private void WriteOneObject - ( - object source, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero"); - this.CheckIfStopping(); + private void WriteOneObject + ( + object source, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero"); + this.CheckIfStopping(); - if (source == null) - { - WriteNull(streamName, property); - return; - } + if (source == null) + { + WriteNull(streamName, property); + return; + } - try - { - this.depthBelowTopLevel++; - Dbg.Assert(this.depthBelowTopLevel <= MaxDepthBelowTopLevel, "depthBelowTopLevel should be <= MaxDepthBelowTopLevel"); - if (HandleMaxDepth(source, streamName, property)) - { - return; - } - - depth = GetDepthOfSerialization(source, depth); - - if (HandlePrimitiveKnownTypeByConvertingToPSObject(source, streamName, property, depth)) - { - return; - } + try + { + _depthBelowTopLevel++; + Dbg.Assert(_depthBelowTopLevel <= MaxDepthBelowTopLevel, "depthBelowTopLevel should be <= MaxDepthBelowTopLevel"); + if (HandleMaxDepth(source, streamName, property)) + { + return; + } - //Object is not of primitive known type. Check if this has - //already been serialized. - string refId = this.objectRefIdHandler.GetRefId(source); - if (refId != null) - { - WritePSObjectReference(streamName, property, refId); - return; - } + depth = GetDepthOfSerialization(source, depth); - if (HandlePrimitiveKnownTypePSObject(source, streamName, property, depth)) - { - return; - } + if (HandlePrimitiveKnownTypeByConvertingToPSObject(source, streamName, property, depth)) + { + return; + } - //Note: We do not use containers in depth calculation. i.e even if the - //current depth is zero, we serialize the container. All contained items will - //get serialized with depth zero. - if (HandleKnownContainerTypes(source, streamName, property, depth)) - { - return; - } + //Object is not of primitive known type. Check if this has + //already been serialized. + string refId = _objectRefIdHandler.GetRefId(source); + if (refId != null) + { + WritePSObjectReference(streamName, property, refId); + return; + } - PSObject mshSource = PSObject.AsPSObject(source); - //If depth is zero, complex type should be serialized as string. - if (depth == 0 || SerializeAsString(mshSource)) - { - HandlePSObjectAsString(mshSource, streamName, property, depth); - return; - } + if (HandlePrimitiveKnownTypePSObject(source, streamName, property, depth)) + { + return; + } - HandleComplexTypePSObject(source, streamName, property, depth); - return; - } - finally - { - this.depthBelowTopLevel--; - Dbg.Assert(this.depthBelowTopLevel >= 0, "depthBelowTopLevel should be >= 0"); - } - } + //Note: We do not use containers in depth calculation. i.e even if the + //current depth is zero, we serialize the container. All contained items will + //get serialized with depth zero. + if (HandleKnownContainerTypes(source, streamName, property, depth)) + { + return; + } - private bool HandleMaxDepth(object source, string streamName, string property) - { - if (this.depthBelowTopLevel == MaxDepthBelowTopLevel) - { - // assert commented out because of clashes with Wei's tests - // Dbg.Assert(false, "We should never reach MaxDepthBelowTopLevel with non-malicious input"); + PSObject mshSource = PSObject.AsPSObject(source); + //If depth is zero, complex type should be serialized as string. + if (depth == 0 || SerializeAsString(mshSource)) + { + HandlePSObjectAsString(mshSource, streamName, property, depth); + return; + } - PSEtwLog.LogAnalyticError(PSEventId.Serializer_MaxDepthWhenSerializing, PSOpcode.Exception, - PSTask.Serialization, PSKeyword.Serializer, source.GetType().AssemblyQualifiedName, property, this.depthBelowTopLevel); + HandleComplexTypePSObject(source, streamName, property, depth); + return; + } + finally + { + _depthBelowTopLevel--; + Dbg.Assert(_depthBelowTopLevel >= 0, "depthBelowTopLevel should be >= 0"); + } + } - string content = Serialization.DeserializationTooDeep; - HandlePrimitiveKnownType(content, streamName, property); - return true; - } - else - { - return false; - } - } + private bool HandleMaxDepth(object source, string streamName, string property) + { + if (_depthBelowTopLevel == MaxDepthBelowTopLevel) + { + // assert commented out because of clashes with Wei's tests + // Dbg.Assert(false, "We should never reach MaxDepthBelowTopLevel with non-malicious input"); - /// - /// Serializes Primitive Known Types. - /// - /// - /// true if source is handled, else false. - /// - private bool HandlePrimitiveKnownType - ( - object source, - string streamName, - string property - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); + PSEtwLog.LogAnalyticError(PSEventId.Serializer_MaxDepthWhenSerializing, PSOpcode.Exception, + PSTask.Serialization, PSKeyword.Serializer, source.GetType().AssemblyQualifiedName, property, _depthBelowTopLevel); - //Check if source is of primitive known type - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); - if (pktInfo != null) - { - WriteOnePrimitiveKnownType(this, streamName, property, source, pktInfo); - return true; - } - return false; - } + string content = Serialization.DeserializationTooDeep; + HandlePrimitiveKnownType(content, streamName, property); + return true; + } + else + { + return false; + } + } - /// - /// Handles primitive known type by first converting it to a PSObject.In W8, extended - /// property data is stored external to PSObject. By coverting to PSObject, we will - /// be able to retrieve and serialize the extended properties. This is tracked by - /// Win8: 414042 - /// - /// - /// - /// - /// - /// - private bool HandlePrimitiveKnownTypeByConvertingToPSObject( - object source, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); - //Check if source is of primitive known type - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); - if (pktInfo != null) - { - PSObject pktInfoPSObject = PSObject.AsPSObject(source); - return HandlePrimitiveKnownTypePSObject(pktInfoPSObject, streamName, property, depth); - } - return false; - } + /// + /// Serializes Primitive Known Types. + /// + /// + /// true if source is handled, else false. + /// + private bool HandlePrimitiveKnownType + ( + object source, + string streamName, + string property + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + + //Check if source is of primitive known type + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); + if (pktInfo != null) + { + WriteOnePrimitiveKnownType(this, streamName, property, source, pktInfo); + return true; + } + return false; + } + + /// + /// Handles primitive known type by first converting it to a PSObject.In W8, extended + /// property data is stored external to PSObject. By coverting to PSObject, we will + /// be able to retrieve and serialize the extended properties. This is tracked by + /// Win8: 414042 + /// + /// + /// + /// + /// + /// + private bool HandlePrimitiveKnownTypeByConvertingToPSObject( + object source, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + //Check if source is of primitive known type + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); + if (pktInfo != null) + { + PSObject pktInfoPSObject = PSObject.AsPSObject(source); + return HandlePrimitiveKnownTypePSObject(pktInfoPSObject, streamName, property, depth); + } + return false; + } - /// - /// - /// - /// - /// - /// - /// - private bool HandleSecureString(object source, string streamName, string property) - { - Dbg.Assert(source != null, "caller should validate the parameter"); + /// + /// + /// + /// + /// + /// + /// + private bool HandleSecureString(object source, string streamName, string property) + { + Dbg.Assert(source != null, "caller should validate the parameter"); - SecureString secureString = null; - secureString = source as SecureString; - PSObject moSource; + SecureString secureString = null; + secureString = source as SecureString; + PSObject moSource; - if (secureString != null) - { - moSource = PSObject.AsPSObject(secureString); - } - else - { - moSource= source as PSObject; - } + if (secureString != null) + { + moSource = PSObject.AsPSObject(secureString); + } + else + { + moSource = source as PSObject; + } - if (moSource != null && !moSource.immediateBaseObjectIsEmpty) - { - // check if source is of type secure string + if (moSource != null && !moSource.immediateBaseObjectIsEmpty) + { + // check if source is of type secure string secureString = moSource.ImmediateBaseObject as SecureString; if (secureString != null) - { - // the principle used in serialization is that serialization - // never throws, and if something can't be serialized nothing - // is written. So we write the elements only if encryption succeeds - try - { - String encryptedString; - if (_context.cryptoHelper != null) - { - encryptedString = _context.cryptoHelper.EncryptSecureString(secureString); - } - else - { - encryptedString = Microsoft.PowerShell.SecureStringHelper.Protect(secureString); - } + { + // the principle used in serialization is that serialization + // never throws, and if something can't be serialized nothing + // is written. So we write the elements only if encryption succeeds + try + { + String encryptedString; + if (_context.cryptoHelper != null) + { + encryptedString = _context.cryptoHelper.EncryptSecureString(secureString); + } + else + { + encryptedString = Microsoft.PowerShell.SecureStringHelper.Protect(secureString); + } - if (property != null) - { - WriteStartElement(SerializationStrings.SecureStringTag); - WriteNameAttribute(property); - } - else - { - WriteStartElement(SerializationStrings.SecureStringTag); - } + if (property != null) + { + WriteStartElement(SerializationStrings.SecureStringTag); + WriteNameAttribute(property); + } + else + { + WriteStartElement(SerializationStrings.SecureStringTag); + } - if (streamName != null) - { - WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + if (streamName != null) + { + WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - //Note: We do not use WriteRaw for serializing secure string. WriteString - //does necessary escaping which may be needed for certain - //characters. - _writer.WriteString(encryptedString); + //Note: We do not use WriteRaw for serializing secure string. WriteString + //does necessary escaping which may be needed for certain + //characters. + _writer.WriteString(encryptedString); - _writer.WriteEndElement(); + _writer.WriteEndElement(); - return true; + return true; + } + catch (PSCryptoException) + { + // do nothing + } + } // if (source ... + } - } - catch (PSCryptoException) - { - // do nothing - } + return false; + } - } // if (source ... - } + /// + /// Serializes PSObject whose base objects are of primitive known type + /// + /// + /// + /// + /// + /// + /// true if source is handled, else false. + /// + private bool HandlePrimitiveKnownTypePSObject + ( + object source, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); - return false; - } + bool sourceHandled = false; + PSObject moSource = source as PSObject; + if (moSource != null && !moSource.immediateBaseObjectIsEmpty) + { + //Check if baseObject is primitive known type + object baseObject = moSource.ImmediateBaseObject; + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); + if (pktInfo != null) + { + WritePrimitiveTypePSObject(moSource, baseObject, pktInfo, streamName, property, depth); + sourceHandled = true; + } + } + return sourceHandled; + } - /// - /// Serializes PSObject whose base objects are of primitive known type - /// - /// - /// - /// - /// - /// - /// true if source is handled, else false. - /// - private bool HandlePrimitiveKnownTypePSObject - ( - object source, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); + private bool HandleKnownContainerTypes + ( + object source, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); - bool sourceHandled = false; - PSObject moSource = source as PSObject; - if (moSource != null && !moSource.immediateBaseObjectIsEmpty) - { - //Check if baseObject is primitive known type - object baseObject = moSource.ImmediateBaseObject; - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); - if (pktInfo != null) - { - WritePrimitiveTypePSObject(moSource, baseObject, pktInfo, streamName, property, depth); - sourceHandled = true; - } - } - return sourceHandled; - } + ContainerType ct = ContainerType.None; + PSObject mshSource = source as PSObject; + IEnumerable enumerable = null; + IDictionary dictionary = null; - private bool HandleKnownContainerTypes - ( - object source, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); + //If passed in object is PSObject with no baseobject, return false. + if (mshSource != null && mshSource.immediateBaseObjectIsEmpty) + { + return false; + } - ContainerType ct = ContainerType.None; - PSObject mshSource = source as PSObject; - IEnumerable enumerable = null; - IDictionary dictionary = null; + //Check if source (or baseobject in mshSource) is known container type + SerializationUtilities.GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, + out dictionary, out enumerable); - //If passed in object is PSObject with no baseobject, return false. - if (mshSource != null && mshSource.immediateBaseObjectIsEmpty) - { - return false; - } + if (ct == ContainerType.None) + return false; - //Check if source (or baseobject in mshSource) is known container type - SerializationUtilities.GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, - out dictionary, out enumerable); + string refId = _objectRefIdHandler.SetRefId(source); + WriteStartOfPSObject( + mshSource ?? PSObject.AsPSObject(source), + streamName, + property, + refId, + true, // always write TypeNames information for known container types + null); // never write ToString information for known container types - if (ct == ContainerType.None) - return false; + switch (ct) + { + case ContainerType.Dictionary: + WriteDictionary(dictionary, SerializationStrings.DictionaryTag, depth); + break; + case ContainerType.Stack: + WriteEnumerable(enumerable, SerializationStrings.StackTag, depth); + break; + case ContainerType.Queue: + WriteEnumerable(enumerable, SerializationStrings.QueueTag, depth); + break; + case ContainerType.List: + WriteEnumerable(enumerable, SerializationStrings.ListTag, depth); + break; + case ContainerType.Enumerable: + WriteEnumerable(enumerable, SerializationStrings.CollectionTag, depth); + break; + default: + Dbg.Assert(false, "All containers should be handled in the switch"); + break; + } - string refId = this.objectRefIdHandler.SetRefId(source); - WriteStartOfPSObject( - mshSource ?? PSObject.AsPSObject(source), - streamName, - property, - refId, - true, // always write TypeNames information for known container types - null); // never write ToString information for known container types - - switch (ct) - { - case ContainerType.Dictionary: - WriteDictionary(dictionary, SerializationStrings.DictionaryTag, depth); - break; - case ContainerType.Stack: - WriteEnumerable(enumerable, SerializationStrings.StackTag, depth); - break; - case ContainerType.Queue: - WriteEnumerable(enumerable, SerializationStrings.QueueTag, depth); - break; - case ContainerType.List: - WriteEnumerable(enumerable, SerializationStrings.ListTag, depth); - break; - case ContainerType.Enumerable: - WriteEnumerable(enumerable, SerializationStrings.CollectionTag, depth); - break; - default: - Dbg.Assert(false, "All containers should be handled in the switch"); - break; - } - - if (depth != 0) - { - // An object which is orignially enumerable becomes an PSObject with ArrayList on deserialization. + if (depth != 0) + { + // An object which is orignially enumerable becomes an PSObject with ArrayList on deserialization. // So on roundtrip it will show up as List. - // We serialize properties of enumerable and on deserialization mark the object as Deserialized. + // We serialize properties of enumerable and on deserialization mark the object as Deserialized. // So if object is marked deserialized, we should write properties. - if (ct == ContainerType.Enumerable || (mshSource != null && mshSource.isDeserialized)) - { - PSObject sourceAsPSObject = PSObject.AsPSObject(source); + if (ct == ContainerType.Enumerable || (mshSource != null && mshSource.isDeserialized)) + { + PSObject sourceAsPSObject = PSObject.AsPSObject(source); PSMemberInfoInternalCollection specificPropertiesToSerialize = SerializationUtilities.GetSpecificPropertiesToSerialize(sourceAsPSObject, AllPropertiesCollection, _typeTable); - WritePSObjectProperties(sourceAsPSObject, depth, specificPropertiesToSerialize); - SerializeExtendedProperties(sourceAsPSObject, depth, specificPropertiesToSerialize); - } - // always serialize instance properties if there are any - else if (mshSource != null) - { - SerializeInstanceProperties(mshSource, depth); - } - } + WritePSObjectProperties(sourceAsPSObject, depth, specificPropertiesToSerialize); + SerializeExtendedProperties(sourceAsPSObject, depth, specificPropertiesToSerialize); + } + // always serialize instance properties if there are any + else if (mshSource != null) + { + SerializeInstanceProperties(mshSource, depth); + } + } - _writer.WriteEndElement(); + _writer.WriteEndElement(); - return true; - } + return true; + } - #region Write PSObject + #region Write PSObject - /// - /// Writes PSObject Reference Element - /// - private void WritePSObjectReference - ( - string streamName, - string property, - string refId - ) - { - Dbg.Assert(!string.IsNullOrEmpty(refId), "caller should validate the parameter"); + /// + /// Writes PSObject Reference Element + /// + private void WritePSObjectReference + ( + string streamName, + string property, + string refId + ) + { + Dbg.Assert(!string.IsNullOrEmpty(refId), "caller should validate the parameter"); - WriteStartElement(SerializationStrings.ReferenceTag); - if (streamName != null) - { - WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } - if (property != null) - { - WriteNameAttribute(property); - } - WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); - _writer.WriteEndElement(); - } + WriteStartElement(SerializationStrings.ReferenceTag); + if (streamName != null) + { + WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } + if (property != null) + { + WriteNameAttribute(property); + } + WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); + _writer.WriteEndElement(); + } - static private bool PSObjectHasModifiedTypesCollection(PSObject pso) - { - ConsolidatedString currentTypes = pso.InternalTypeNames; - Collection originalTypes = pso.InternalAdapter.BaseGetTypeNameHierarchy(pso.ImmediateBaseObject); + static private bool PSObjectHasModifiedTypesCollection(PSObject pso) + { + ConsolidatedString currentTypes = pso.InternalTypeNames; + Collection originalTypes = pso.InternalAdapter.BaseGetTypeNameHierarchy(pso.ImmediateBaseObject); - if (currentTypes.Count != originalTypes.Count) - { - return true; - } + if (currentTypes.Count != originalTypes.Count) + { + return true; + } - IEnumerator currentEnumerator = currentTypes.GetEnumerator(); - IEnumerator originalEnumerator = originalTypes.GetEnumerator(); - while (currentEnumerator.MoveNext() && originalEnumerator.MoveNext()) - { - if (!currentEnumerator.Current.Equals(originalEnumerator.Current, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } + IEnumerator currentEnumerator = currentTypes.GetEnumerator(); + IEnumerator originalEnumerator = originalTypes.GetEnumerator(); + while (currentEnumerator.MoveNext() && originalEnumerator.MoveNext()) + { + if (!currentEnumerator.Current.Equals(originalEnumerator.Current, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } - return false; - } + return false; + } - /// - /// Serializes an PSObject whose baseobject is of primitive type. - /// - /// - /// source from which notes are written - /// - /// - /// primitive object which is written as base object. In most cases it - /// is same source.ImmediateBaseObject. When PSObject is serialized as string, - /// it can be different. for more info. - /// - /// - /// TypeSerializationInfo for the primitive. - /// - /// - /// - /// - private void WritePrimitiveTypePSObject - ( - PSObject source, - object primitive, - TypeSerializationInfo pktInfo, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "Caller should validate source != null"); + /// + /// Serializes an PSObject whose baseobject is of primitive type. + /// + /// + /// source from which notes are written + /// + /// + /// primitive object which is written as base object. In most cases it + /// is same source.ImmediateBaseObject. When PSObject is serialized as string, + /// it can be different. for more info. + /// + /// + /// TypeSerializationInfo for the primitive. + /// + /// + /// + /// + private void WritePrimitiveTypePSObject + ( + PSObject source, + object primitive, + TypeSerializationInfo pktInfo, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "Caller should validate source != null"); - string toStringValue = SerializationUtilities.GetToStringForPrimitiveObject(source); - bool hasModifiedTypesCollection = PSObjectHasModifiedTypesCollection(source); - bool hasNotes = PSObjectHasNotes(source); - bool hasModifiedToString = (toStringValue != null); + string toStringValue = SerializationUtilities.GetToStringForPrimitiveObject(source); + bool hasModifiedTypesCollection = PSObjectHasModifiedTypesCollection(source); + bool hasNotes = PSObjectHasNotes(source); + bool hasModifiedToString = (toStringValue != null); - if (hasNotes || hasModifiedTypesCollection || hasModifiedToString) - { - WritePrimitiveTypePSObjectWithNotes( - source, - primitive, - hasModifiedTypesCollection, - toStringValue, - pktInfo, - streamName, - property, - depth); - return; - } - else - { - if (primitive != null) - { - WriteOnePrimitiveKnownType(this, streamName, property, primitive, pktInfo); - return; - } - else - { - WriteNull(streamName, property); - return; - } - } - } + if (hasNotes || hasModifiedTypesCollection || hasModifiedToString) + { + WritePrimitiveTypePSObjectWithNotes( + source, + primitive, + hasModifiedTypesCollection, + toStringValue, + pktInfo, + streamName, + property, + depth); + return; + } + else + { + if (primitive != null) + { + WriteOnePrimitiveKnownType(this, streamName, property, primitive, pktInfo); + return; + } + else + { + WriteNull(streamName, property); + return; + } + } + } - /// - /// Serializes an PSObject whose baseobject is of primitive type - /// and which has notes. - /// - /// - /// source from which notes are written - /// - /// - /// primitive object which is written as base object. In most cases it - /// is same source.ImmediateBaseObject. When PSObject is serialized as string, - /// it can be different. for more info. - /// - /// - /// - /// - /// TypeSerializationInfo for the primitive. - /// - /// - /// - /// - private void WritePrimitiveTypePSObjectWithNotes - ( - PSObject source, - object primitive, - bool hasModifiedTypesCollection, - string toStringValue, - TypeSerializationInfo pktInfo, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); - Dbg.Assert(pktInfo != null, "Caller should validate pktInfo != null"); + /// + /// Serializes an PSObject whose baseobject is of primitive type + /// and which has notes. + /// + /// + /// source from which notes are written + /// + /// + /// primitive object which is written as base object. In most cases it + /// is same source.ImmediateBaseObject. When PSObject is serialized as string, + /// it can be different. for more info. + /// + /// + /// + /// + /// TypeSerializationInfo for the primitive. + /// + /// + /// + /// + private void WritePrimitiveTypePSObjectWithNotes + ( + PSObject source, + object primitive, + bool hasModifiedTypesCollection, + string toStringValue, + TypeSerializationInfo pktInfo, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(pktInfo != null, "Caller should validate pktInfo != null"); - string refId = this.objectRefIdHandler.SetRefId(source); - WriteStartOfPSObject( - source, - streamName, - property, - refId, - hasModifiedTypesCollection, // preserve TypeNames information if different from the primitive type - toStringValue); // preserve ToString information only if got it from deserialization or overridden by PSObject - // (example where preservation of TypeNames and ToString is needed: enums serialized as ints, help string with custom type names (HelpInfoShort)) + string refId = _objectRefIdHandler.SetRefId(source); + WriteStartOfPSObject( + source, + streamName, + property, + refId, + hasModifiedTypesCollection, // preserve TypeNames information if different from the primitive type + toStringValue); // preserve ToString information only if got it from deserialization or overridden by PSObject + // (example where preservation of TypeNames and ToString is needed: enums serialized as ints, help string with custom type names (HelpInfoShort)) - if (pktInfo != null) - { - WriteOnePrimitiveKnownType(this, streamName, null, primitive, pktInfo); - } + if (pktInfo != null) + { + WriteOnePrimitiveKnownType(this, streamName, null, primitive, pktInfo); + } - // serialize only instance properties - members from type table are - // always going to be available for known primitive types - SerializeInstanceProperties(source, depth); + // serialize only instance properties - members from type table are + // always going to be available for known primitive types + SerializeInstanceProperties(source, depth); - _writer.WriteEndElement(); - } + _writer.WriteEndElement(); + } - private void HandleComplexTypePSObject - ( - object source, - string streamName, - string property, - int depth - ) - { - Dbg.Assert(source != null, "caller should validate the parameter"); - PSObject mshSource = PSObject.AsPSObject(source); + private void HandleComplexTypePSObject + ( + object source, + string streamName, + string property, + int depth + ) + { + Dbg.Assert(source != null, "caller should validate the parameter"); + PSObject mshSource = PSObject.AsPSObject(source); - // Figure out what kind of object we are dealing with - bool isErrorRecord = false; - bool isInformationalRecord = false; - bool isEnum = false; - bool isPSObject = false; - bool isCimInstance = false; + // Figure out what kind of object we are dealing with + bool isErrorRecord = false; + bool isInformationalRecord = false; + bool isEnum = false; + bool isPSObject = false; + bool isCimInstance = false; - if (!mshSource.immediateBaseObjectIsEmpty) - { - do // false loop - { - CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance; - if (cimInstance != null) - { - isCimInstance = true; - break; - } + if (!mshSource.immediateBaseObjectIsEmpty) + { + do // false loop + { + CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance; + if (cimInstance != null) + { + isCimInstance = true; + break; + } - ErrorRecord errorRecord = mshSource.ImmediateBaseObject as ErrorRecord; - if (errorRecord != null) - { - errorRecord.ToPSObjectForRemoting(mshSource); - isErrorRecord = true; - break; - } + ErrorRecord errorRecord = mshSource.ImmediateBaseObject as ErrorRecord; + if (errorRecord != null) + { + errorRecord.ToPSObjectForRemoting(mshSource); + isErrorRecord = true; + break; + } - InformationalRecord informationalRecord = mshSource.ImmediateBaseObject as InformationalRecord; - if (informationalRecord != null) - { - informationalRecord.ToPSObjectForRemoting(mshSource); - isInformationalRecord = true; - break; - } + InformationalRecord informationalRecord = mshSource.ImmediateBaseObject as InformationalRecord; + if (informationalRecord != null) + { + informationalRecord.ToPSObjectForRemoting(mshSource); + isInformationalRecord = true; + break; + } - isEnum = mshSource.ImmediateBaseObject is Enum; - isPSObject = mshSource.ImmediateBaseObject is PSObject; - } while (false); - } + isEnum = mshSource.ImmediateBaseObject is Enum; + isPSObject = mshSource.ImmediateBaseObject is PSObject; + } while (false); + } - bool writeToString = true; - if (mshSource.ToStringFromDeserialization == null) // continue to write ToString from deserialized objects, but... - { - if (mshSource.immediateBaseObjectIsEmpty) // ... don't write ToString for property bags - { - writeToString = false; - } - } + bool writeToString = true; + if (mshSource.ToStringFromDeserialization == null) // continue to write ToString from deserialized objects, but... + { + if (mshSource.immediateBaseObjectIsEmpty) // ... don't write ToString for property bags + { + writeToString = false; + } + } - string refId = this.objectRefIdHandler.SetRefId(source); - WriteStartOfPSObject( - mshSource, - streamName, - property, - refId, - true, // always write TypeNames for complex objects - writeToString ? SerializationUtilities.GetToString(mshSource) : null); + string refId = _objectRefIdHandler.SetRefId(source); + WriteStartOfPSObject( + mshSource, + streamName, + property, + refId, + true, // always write TypeNames for complex objects + writeToString ? SerializationUtilities.GetToString(mshSource) : null); PSMemberInfoInternalCollection specificPropertiesToSerialize = SerializationUtilities.GetSpecificPropertiesToSerialize(mshSource, AllPropertiesCollection, _typeTable); - if (isEnum) - { - object baseObject = mshSource.ImmediateBaseObject; - WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), null, null, depth); - } - else if (isPSObject) - { - WriteOneObject(mshSource.ImmediateBaseObject, null, null, depth); - } - else if (isErrorRecord || isInformationalRecord) - { - // nothing to do - } - else - { - WritePSObjectProperties(mshSource, depth, specificPropertiesToSerialize); - } + if (isEnum) + { + object baseObject = mshSource.ImmediateBaseObject; + WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), null, null, depth); + } + else if (isPSObject) + { + WriteOneObject(mshSource.ImmediateBaseObject, null, null, depth); + } + else if (isErrorRecord || isInformationalRecord) + { + // nothing to do + } + else + { + WritePSObjectProperties(mshSource, depth, specificPropertiesToSerialize); + } - if (isCimInstance) - { - CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance; - PrepareCimInstanceForSerialization(mshSource, cimInstance); - } + if (isCimInstance) + { + CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance; + PrepareCimInstanceForSerialization(mshSource, cimInstance); + } - SerializeExtendedProperties(mshSource, depth, specificPropertiesToSerialize); + SerializeExtendedProperties(mshSource, depth, specificPropertiesToSerialize); - _writer.WriteEndElement(); - } + _writer.WriteEndElement(); + } - private static Lazy cimSerializer = new Lazy(CimSerializer.Create); + private static Lazy s_cimSerializer = new Lazy(CimSerializer.Create); - private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance cimInstance) - { - Queue serializedClasses = new Queue(); + private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance cimInstance) + { + Queue serializedClasses = new Queue(); - // - // CREATE SERIALIZED FORM OF THE CLASS METADATA - // + // + // CREATE SERIALIZED FORM OF THE CLASS METADATA + // ArrayList psoClasses = new ArrayList(); - for (CimClass cimClass = cimInstance.CimClass; cimClass != null; cimClass = cimClass.CimSuperClass) - { - PSObject psoClass = new PSObject(); - psoClass.TypeNames.Clear(); - psoClasses.Add(psoClass); - - psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimClassNameProperty, cimClass.CimSystemProperties.ClassName)); - psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimNamespaceProperty, cimClass.CimSystemProperties.Namespace)); - psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimServerNameProperty, cimClass.CimSystemProperties.ServerName)); - psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimHashCodeProperty, cimClass.GetHashCode())); - - CimClassSerializationId cimClassSerializationId = new CimClassSerializationId( - cimClass.CimSystemProperties.ClassName, - cimClass.CimSystemProperties.Namespace, - cimClass.CimSystemProperties.ServerName, - cimClass.GetHashCode()); - if (this._context.cimClassSerializationIdCache.DoesDeserializerAlreadyHaveCimClass(cimClassSerializationId)) - { - break; - } - - serializedClasses.Enqueue(cimClassSerializationId); - byte[] miXmlBytes = cimSerializer.Value.Serialize(cimClass, ClassSerializationOptions.None); - string miXmlString = Encoding.Unicode.GetString(miXmlBytes, 0, miXmlBytes.Length); - psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimMiXmlProperty, miXmlString)); - } - psoClasses.Reverse(); - - // - // UPDATE CLASSDECL CACHE - // - foreach (CimClassSerializationId serializedClassId in serializedClasses) - { - this._context.cimClassSerializationIdCache.AddClassToCache(serializedClassId); - } - - // - // ATTACH CLASS METADATA TO THE OBJECT BEING SERIALIZED - // - PSPropertyInfo classMetadataProperty = psObject.Properties[InternalDeserializer.CimClassMetadataProperty]; - if (classMetadataProperty != null) - { - classMetadataProperty.Value = psoClasses; - } - else - { - PSNoteProperty classMetadataNote = new PSNoteProperty( - InternalDeserializer.CimClassMetadataProperty, - psoClasses); - classMetadataNote.IsHidden = true; - psObject.Properties.Add(classMetadataNote); - } - - // ATTACH INSTANCE METADATA TO THE OBJECT BEING SERIALIZED - List namesOfModifiedProperties = cimInstance - .CimInstanceProperties - .Where(p => p.IsValueModified) - .Select(p => p.Name) - .ToList(); - if (namesOfModifiedProperties.Count != 0) - { - PSObject instanceMetadata = new PSObject(); - PSPropertyInfo instanceMetadataProperty = psObject.Properties[InternalDeserializer.CimInstanceMetadataProperty]; - if (instanceMetadataProperty != null) - { - instanceMetadataProperty.Value = instanceMetadata; - } - else - { - PSNoteProperty instanceMetadataNote = new PSNoteProperty(InternalDeserializer.CimInstanceMetadataProperty, instanceMetadata); - instanceMetadataNote.IsHidden = true; - psObject.Properties.Add(instanceMetadataNote); - } - - instanceMetadata.InternalTypeNames = ConsolidatedString.Empty; - - instanceMetadata.Properties.Add( - new PSNoteProperty( - InternalDeserializer.CimModifiedProperties, - string.Join(" ", namesOfModifiedProperties))); - } - } - - /// - /// Writes start element, attributes and typeNames for PSObject. - /// - /// - /// - /// - /// - /// if true, TypeName information is written, else not. - /// if not null then ToString information is written - private void WriteStartOfPSObject - ( - PSObject mshObject, - string streamName, - string property, - string refId, - bool writeTypeNames, - string toStringValue - ) - { - Dbg.Assert(mshObject != null, "caller should validate the parameter"); - - //Write PSObject start element. - WriteStartElement(SerializationStrings.PSObjectTag); - - if (streamName != null) - { - WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } - - if (property != null) - { - WriteNameAttribute(property); - } - - if (refId != null) - { - WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); - } - - if (writeTypeNames) - { - //Write TypeNames - ConsolidatedString typeNames = mshObject.InternalTypeNames; - if (typeNames.Count > 0) - { - string typeNameHierarchyReferenceId = this.typeRefIdHandler.GetRefId(typeNames); - if (typeNameHierarchyReferenceId == null) - { - WriteStartElement(SerializationStrings.TypeNamesTag); - - //Create a new refId and write it as attribute - string tnRefId = this.typeRefIdHandler.SetRefId(typeNames); - Dbg.Assert(tnRefId != null, "SetRefId should always succeed for strings"); - WriteAttribute(SerializationStrings.ReferenceIdAttribute, tnRefId); - - foreach (string type in typeNames) - { - WriteEncodedElementString(SerializationStrings.TypeNamesItemTag, type); - } - _writer.WriteEndElement(); - } - else - { - WriteStartElement(SerializationStrings.TypeNamesReferenceTag); - WriteAttribute(SerializationStrings.ReferenceIdAttribute, typeNameHierarchyReferenceId); - _writer.WriteEndElement(); - } - } - } - - if (toStringValue != null) - { - WriteEncodedElementString(SerializationStrings.ToStringElementTag, toStringValue); - } - } - - #region membersets - - /// - /// Returns true if PSObject has notes. - /// - /// - /// - /// - private static bool PSObjectHasNotes(PSObject source) - { - Dbg.Assert(source != null, "Caller should validate the parameter"); - if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) - { - return true; - } - return false; - } - - private bool? canUseDefaultRunspaceInThreadSafeManner; - - private bool CanUseDefaultRunspaceInThreadSafeManner - { - get - { - if (!canUseDefaultRunspaceInThreadSafeManner.HasValue) - { - canUseDefaultRunspaceInThreadSafeManner = Runspace.CanUseDefaultRunspace; - } - - return canUseDefaultRunspaceInThreadSafeManner.Value; - } - } - - /// - /// Serialize member set. This method serializes without writing - /// enclosing tags and attributes. - /// - /// - /// enumerable containing members - /// - /// - /// - /// if this is true, write an enclosing "" tag. - /// - /// - private void WriteMemberInfoCollection - ( - IEnumerable me, - int depth, - bool writeEnclosingMemberSetElementTag - ) - { - Dbg.Assert(me != null, "caller should validate the parameter"); - - bool enclosingTagWritten = false; - foreach (PSMemberInfo info in me) - { - if (!info.ShouldSerialize) - { - continue; - } - int depthOfMember = info.IsInstance ? depth : depth - 1; - - if (info.MemberType == (info.MemberType & PSMemberTypes.Properties)) - { - bool gotValue; - object value = SerializationUtilities.GetPropertyValueInThreadSafeManner((PSPropertyInfo)info, this.CanUseDefaultRunspaceInThreadSafeManner,out gotValue); - if (gotValue) - { - if (writeEnclosingMemberSetElementTag && !enclosingTagWritten) - { - enclosingTagWritten = true; - WriteStartElement(SerializationStrings.MemberSet); - } - - WriteOneObject(value, null, info.Name, depthOfMember); - } - } - else if (info.MemberType == PSMemberTypes.MemberSet) - { - if (writeEnclosingMemberSetElementTag && !enclosingTagWritten) - { - enclosingTagWritten = true; - WriteStartElement(SerializationStrings.MemberSet); - } - WriteMemberSet((PSMemberSet)info, depthOfMember); - } - } - if (enclosingTagWritten) - { - _writer.WriteEndElement(); - } - } - - /// - /// Serializes MemberSet. - /// - private void WriteMemberSet - ( - PSMemberSet set, - int depth - ) - { - Dbg.Assert(set != null, "Caller should validate the parameter"); - - if (!set.ShouldSerialize) - { - return; - } - WriteStartElement(SerializationStrings.MemberSet); - WriteNameAttribute(set.Name); - WriteMemberInfoCollection(set.Members, depth, false); - _writer.WriteEndElement(); - } - - #endregion membersets - - #region properties - - /// - /// Serializes properties of PSObject - /// - private void WritePSObjectProperties - ( - PSObject source, - int depth, - IEnumerable specificPropertiesToSerialize - ) - { - Dbg.Assert(source != null, "caller should validate the information"); - - //Depth available for each property is one less - --depth; - Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); - - if (specificPropertiesToSerialize != null) - { - SerializeProperties(specificPropertiesToSerialize, SerializationStrings.AdapterProperties, depth); - } - else - { - if (source.ShouldSerializeAdapter()) - { - IEnumerable adapterCollection = null; - adapterCollection = source.GetAdaptedProperties(); - if (adapterCollection != null) - { - SerializeProperties(adapterCollection, SerializationStrings.AdapterProperties, depth); - } - } - } - } - - private void SerializeInstanceProperties - ( - PSObject source, - int depth - ) - { - //Serialize instanceMembers - Dbg.Assert(source != null, "caller should validate the information"); - PSMemberInfoCollection instanceMembers = source.InstanceMembers; - if (instanceMembers != null) - { - WriteMemberInfoCollection(instanceMembers, depth, true); - } - } - - private Collection> extendedMembersCollection; - private Collection> ExtendedMembersCollection - { - get - { - if (extendedMembersCollection == null) - { - extendedMembersCollection = PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable); - } - return extendedMembersCollection; - } - } - - private Collection> allPropertiesCollection; - private Collection> AllPropertiesCollection - { - get - { - if (allPropertiesCollection == null) - { - allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); - } - return allPropertiesCollection; - } - } - - private void SerializeExtendedProperties - ( - PSObject source, - int depth, - IEnumerable specificPropertiesToSerialize - ) - { - Dbg.Assert(source != null, "caller should validate the information"); - - IEnumerable extendedMembersEnumerable = null; - if (specificPropertiesToSerialize == null) - { - // Get only extended members including hidden members from the psobect source. - PSMemberInfoIntegratingCollection membersToSearch = - new PSMemberInfoIntegratingCollection(source, ExtendedMembersCollection); - extendedMembersEnumerable = membersToSearch.Match( - "*", - PSMemberTypes.Properties | PSMemberTypes.PropertySet | PSMemberTypes.MemberSet, - MshMemberMatchOptions.IncludeHidden | MshMemberMatchOptions.OnlySerializable); - } - else - { - List extendedMembersList = new List(source.InstanceMembers); - extendedMembersEnumerable = extendedMembersList; - - foreach (PSMemberInfo member in specificPropertiesToSerialize) - { - if (member.IsInstance) - { - continue; - } - - if (member is PSProperty) - { - continue; - } - - extendedMembersList.Add(member); - } - } - - if (extendedMembersEnumerable != null) - { - WriteMemberInfoCollection(extendedMembersEnumerable, depth, true); - } - } - - /// - /// Serializes properties from collection - /// - /// - /// Collection of properties to serialize - /// - /// - /// Name for enclosing element tag - /// - /// - /// depth to which each property should be - /// serialized - /// - private void SerializeProperties - ( - IEnumerable propertyCollection, - string name, - int depth - ) - { - Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); - bool startElementWritten = false; - - foreach (PSMemberInfo info in propertyCollection) - { - PSProperty prop = info as PSProperty; - if (prop == null) - { - continue; - } - - if (!startElementWritten) - { - WriteStartElement(name); - startElementWritten = true; - } - - bool success; - object value = SerializationUtilities.GetPropertyValueInThreadSafeManner(prop, this.CanUseDefaultRunspaceInThreadSafeManner, out success); - if (success) - { - WriteOneObject(value, null, prop.Name, depth); - } - } - - if (startElementWritten) - { - _writer.WriteEndElement(); - } - } - - #endregion base properties - - #endregion WritePSObject - - #region enumerable and dictionary - - /// - /// Serializes IEnumerable - /// - /// - /// enumerable which is serialized - /// - /// - /// - /// - private void WriteEnumerable - ( - IEnumerable enumerable, - string tag, - int depth - ) - { - Dbg.Assert(enumerable != null, "caller should validate the parameter"); - Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); - - //Start element - WriteStartElement(tag); - - IEnumerator enumerator = null; - try - { - enumerator = enumerable.GetEnumerator(); - try - { - enumerator.Reset(); - } - catch (System.NotSupportedException) - { - //ignore exceptions thrown when the enumerator doesn't support Reset() method as in win8:948569 - } - } - catch (Exception exception) - { - // Catch-all OK. This is a third-party call-out. - CommandProcessorBase.CheckForSevereException(exception); - - PSEtwLog.LogAnalyticWarning( - PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - enumerable.GetType().AssemblyQualifiedName, - exception.ToString()); - - enumerator = null; - } - - //AD has incorrect implementation of IEnumerable where they returned null - //for GetEnumerator instead of empty enumerator - if (enumerator != null) - { - while (true) - { - object item = null; - try - { - if (!enumerator.MoveNext()) - { - break; - } - else - { - item = enumerator.Current; - } - } - catch (Exception exception) - { - // Catch-all OK. This is a third-party call-out. - CommandProcessorBase.CheckForSevereException(exception); - - PSEtwLog.LogAnalyticWarning( - PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - enumerable.GetType().AssemblyQualifiedName, - exception.ToString()); - - break; - } - WriteOneObject(item, null, null, depth); - } - } - //End element - _writer.WriteEndElement(); - } - - /// - /// Serializes IDictionary - /// - /// dictionary which is serialized - /// - /// - private void WriteDictionary - ( - IDictionary dictionary, - string tag, - int depth - ) - { - Dbg.Assert(dictionary != null, "caller should validate the parameter"); - Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); - - //Start element - WriteStartElement(tag); - - IDictionaryEnumerator dictionaryEnum = null; - try - { - dictionaryEnum = dictionary.GetEnumerator(); - } - catch (Exception exception) // ignore non-severe exceptions - { - // Catch-all OK. This is a third-party call-out. - CommandProcessorBase.CheckForSevereException(exception); - - PSEtwLog.LogAnalyticWarning( - PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - dictionary.GetType().AssemblyQualifiedName, - exception.ToString()); - } - - if (dictionaryEnum != null) - { - while (true) - { - object key = null; - object value = null; - try - { - if (!dictionaryEnum.MoveNext()) - { - break; - } - else - { - key = dictionaryEnum.Key; - value = dictionaryEnum.Value; - } - } - catch (Exception exception) - { - // Catch-all OK. This is a third-party call-out. - CommandProcessorBase.CheckForSevereException(exception); - - PSEtwLog.LogAnalyticWarning( - PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - dictionary.GetType().AssemblyQualifiedName, - exception.ToString()); - - break; - } - - Dbg.Assert(key != null, "Dictionary keys should never be null"); - if (key == null) break; - - WriteStartElement(SerializationStrings.DictionaryEntryTag); - WriteOneObject(key, null, SerializationStrings.DictionaryKey, depth); - WriteOneObject(value, null, SerializationStrings.DictionaryValue, depth); - _writer.WriteEndElement(); - } - } - - //End element - _writer.WriteEndElement(); - } - - #endregion enumerable and dictionary - - #region serialize as string - - private void HandlePSObjectAsString( - PSObject source, - string streamName, - string property, - int depth) - { - Dbg.Assert(source != null, "caller should validate the information"); - - string value = GetSerializationString(source); - - TypeSerializationInfo pktInfo = null; - if (value != null) - { - pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); - } - - WritePrimitiveTypePSObject(source, value, pktInfo, streamName, property, depth); - } + for (CimClass cimClass = cimInstance.CimClass; cimClass != null; cimClass = cimClass.CimSuperClass) + { + PSObject psoClass = new PSObject(); + psoClass.TypeNames.Clear(); + psoClasses.Add(psoClass); + + psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimClassNameProperty, cimClass.CimSystemProperties.ClassName)); + psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimNamespaceProperty, cimClass.CimSystemProperties.Namespace)); + psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimServerNameProperty, cimClass.CimSystemProperties.ServerName)); + psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimHashCodeProperty, cimClass.GetHashCode())); + + CimClassSerializationId cimClassSerializationId = new CimClassSerializationId( + cimClass.CimSystemProperties.ClassName, + cimClass.CimSystemProperties.Namespace, + cimClass.CimSystemProperties.ServerName, + cimClass.GetHashCode()); + if (_context.cimClassSerializationIdCache.DoesDeserializerAlreadyHaveCimClass(cimClassSerializationId)) + { + break; + } + + serializedClasses.Enqueue(cimClassSerializationId); + byte[] miXmlBytes = s_cimSerializer.Value.Serialize(cimClass, ClassSerializationOptions.None); + string miXmlString = Encoding.Unicode.GetString(miXmlBytes, 0, miXmlBytes.Length); + psoClass.Properties.Add(new PSNoteProperty(InternalDeserializer.CimMiXmlProperty, miXmlString)); + } + psoClasses.Reverse(); + + // + // UPDATE CLASSDECL CACHE + // + foreach (CimClassSerializationId serializedClassId in serializedClasses) + { + _context.cimClassSerializationIdCache.AddClassToCache(serializedClassId); + } + + // + // ATTACH CLASS METADATA TO THE OBJECT BEING SERIALIZED + // + PSPropertyInfo classMetadataProperty = psObject.Properties[InternalDeserializer.CimClassMetadataProperty]; + if (classMetadataProperty != null) + { + classMetadataProperty.Value = psoClasses; + } + else + { + PSNoteProperty classMetadataNote = new PSNoteProperty( + InternalDeserializer.CimClassMetadataProperty, + psoClasses); + classMetadataNote.IsHidden = true; + psObject.Properties.Add(classMetadataNote); + } + + // ATTACH INSTANCE METADATA TO THE OBJECT BEING SERIALIZED + List namesOfModifiedProperties = cimInstance + .CimInstanceProperties + .Where(p => p.IsValueModified) + .Select(p => p.Name) + .ToList(); + if (namesOfModifiedProperties.Count != 0) + { + PSObject instanceMetadata = new PSObject(); + PSPropertyInfo instanceMetadataProperty = psObject.Properties[InternalDeserializer.CimInstanceMetadataProperty]; + if (instanceMetadataProperty != null) + { + instanceMetadataProperty.Value = instanceMetadata; + } + else + { + PSNoteProperty instanceMetadataNote = new PSNoteProperty(InternalDeserializer.CimInstanceMetadataProperty, instanceMetadata); + instanceMetadataNote.IsHidden = true; + psObject.Properties.Add(instanceMetadataNote); + } + + instanceMetadata.InternalTypeNames = ConsolidatedString.Empty; + + instanceMetadata.Properties.Add( + new PSNoteProperty( + InternalDeserializer.CimModifiedProperties, + string.Join(" ", namesOfModifiedProperties))); + } + } + + /// + /// Writes start element, attributes and typeNames for PSObject. + /// + /// + /// + /// + /// + /// if true, TypeName information is written, else not. + /// if not null then ToString information is written + private void WriteStartOfPSObject + ( + PSObject mshObject, + string streamName, + string property, + string refId, + bool writeTypeNames, + string toStringValue + ) + { + Dbg.Assert(mshObject != null, "caller should validate the parameter"); + + //Write PSObject start element. + WriteStartElement(SerializationStrings.PSObjectTag); + + if (streamName != null) + { + WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } + + if (property != null) + { + WriteNameAttribute(property); + } + + if (refId != null) + { + WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); + } + + if (writeTypeNames) + { + //Write TypeNames + ConsolidatedString typeNames = mshObject.InternalTypeNames; + if (typeNames.Count > 0) + { + string typeNameHierarchyReferenceId = _typeRefIdHandler.GetRefId(typeNames); + if (typeNameHierarchyReferenceId == null) + { + WriteStartElement(SerializationStrings.TypeNamesTag); + + //Create a new refId and write it as attribute + string tnRefId = _typeRefIdHandler.SetRefId(typeNames); + Dbg.Assert(tnRefId != null, "SetRefId should always succeed for strings"); + WriteAttribute(SerializationStrings.ReferenceIdAttribute, tnRefId); + + foreach (string type in typeNames) + { + WriteEncodedElementString(SerializationStrings.TypeNamesItemTag, type); + } + _writer.WriteEndElement(); + } + else + { + WriteStartElement(SerializationStrings.TypeNamesReferenceTag); + WriteAttribute(SerializationStrings.ReferenceIdAttribute, typeNameHierarchyReferenceId); + _writer.WriteEndElement(); + } + } + } + + if (toStringValue != null) + { + WriteEncodedElementString(SerializationStrings.ToStringElementTag, toStringValue); + } + } + + #region membersets + + /// + /// Returns true if PSObject has notes. + /// + /// + /// + /// + private static bool PSObjectHasNotes(PSObject source) + { + Dbg.Assert(source != null, "Caller should validate the parameter"); + if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) + { + return true; + } + return false; + } + + private bool? _canUseDefaultRunspaceInThreadSafeManner; + + private bool CanUseDefaultRunspaceInThreadSafeManner + { + get + { + if (!_canUseDefaultRunspaceInThreadSafeManner.HasValue) + { + _canUseDefaultRunspaceInThreadSafeManner = Runspace.CanUseDefaultRunspace; + } + + return _canUseDefaultRunspaceInThreadSafeManner.Value; + } + } + + /// + /// Serialize member set. This method serializes without writing + /// enclosing tags and attributes. + /// + /// + /// enumerable containing members + /// + /// + /// + /// if this is true, write an enclosing "" tag. + /// + /// + private void WriteMemberInfoCollection + ( + IEnumerable me, + int depth, + bool writeEnclosingMemberSetElementTag + ) + { + Dbg.Assert(me != null, "caller should validate the parameter"); + + bool enclosingTagWritten = false; + foreach (PSMemberInfo info in me) + { + if (!info.ShouldSerialize) + { + continue; + } + int depthOfMember = info.IsInstance ? depth : depth - 1; + + if (info.MemberType == (info.MemberType & PSMemberTypes.Properties)) + { + bool gotValue; + object value = SerializationUtilities.GetPropertyValueInThreadSafeManner((PSPropertyInfo)info, this.CanUseDefaultRunspaceInThreadSafeManner, out gotValue); + if (gotValue) + { + if (writeEnclosingMemberSetElementTag && !enclosingTagWritten) + { + enclosingTagWritten = true; + WriteStartElement(SerializationStrings.MemberSet); + } + + WriteOneObject(value, null, info.Name, depthOfMember); + } + } + else if (info.MemberType == PSMemberTypes.MemberSet) + { + if (writeEnclosingMemberSetElementTag && !enclosingTagWritten) + { + enclosingTagWritten = true; + WriteStartElement(SerializationStrings.MemberSet); + } + WriteMemberSet((PSMemberSet)info, depthOfMember); + } + } + if (enclosingTagWritten) + { + _writer.WriteEndElement(); + } + } + + /// + /// Serializes MemberSet. + /// + private void WriteMemberSet + ( + PSMemberSet set, + int depth + ) + { + Dbg.Assert(set != null, "Caller should validate the parameter"); + + if (!set.ShouldSerialize) + { + return; + } + WriteStartElement(SerializationStrings.MemberSet); + WriteNameAttribute(set.Name); + WriteMemberInfoCollection(set.Members, depth, false); + _writer.WriteEndElement(); + } + + #endregion membersets + + #region properties + + /// + /// Serializes properties of PSObject + /// + private void WritePSObjectProperties + ( + PSObject source, + int depth, + IEnumerable specificPropertiesToSerialize + ) + { + Dbg.Assert(source != null, "caller should validate the information"); + + //Depth available for each property is one less + --depth; + Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); + + if (specificPropertiesToSerialize != null) + { + SerializeProperties(specificPropertiesToSerialize, SerializationStrings.AdapterProperties, depth); + } + else + { + if (source.ShouldSerializeAdapter()) + { + IEnumerable adapterCollection = null; + adapterCollection = source.GetAdaptedProperties(); + if (adapterCollection != null) + { + SerializeProperties(adapterCollection, SerializationStrings.AdapterProperties, depth); + } + } + } + } + + private void SerializeInstanceProperties + ( + PSObject source, + int depth + ) + { + //Serialize instanceMembers + Dbg.Assert(source != null, "caller should validate the information"); + PSMemberInfoCollection instanceMembers = source.InstanceMembers; + if (instanceMembers != null) + { + WriteMemberInfoCollection(instanceMembers, depth, true); + } + } + + private Collection> _extendedMembersCollection; + private Collection> ExtendedMembersCollection + { + get + { + if (_extendedMembersCollection == null) + { + _extendedMembersCollection = PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable); + } + return _extendedMembersCollection; + } + } + + private Collection> _allPropertiesCollection; + private Collection> AllPropertiesCollection + { + get + { + if (_allPropertiesCollection == null) + { + _allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); + } + return _allPropertiesCollection; + } + } + + private void SerializeExtendedProperties + ( + PSObject source, + int depth, + IEnumerable specificPropertiesToSerialize + ) + { + Dbg.Assert(source != null, "caller should validate the information"); + + IEnumerable extendedMembersEnumerable = null; + if (specificPropertiesToSerialize == null) + { + // Get only extended members including hidden members from the psobect source. + PSMemberInfoIntegratingCollection membersToSearch = + new PSMemberInfoIntegratingCollection(source, ExtendedMembersCollection); + extendedMembersEnumerable = membersToSearch.Match( + "*", + PSMemberTypes.Properties | PSMemberTypes.PropertySet | PSMemberTypes.MemberSet, + MshMemberMatchOptions.IncludeHidden | MshMemberMatchOptions.OnlySerializable); + } + else + { + List extendedMembersList = new List(source.InstanceMembers); + extendedMembersEnumerable = extendedMembersList; + + foreach (PSMemberInfo member in specificPropertiesToSerialize) + { + if (member.IsInstance) + { + continue; + } + + if (member is PSProperty) + { + continue; + } + + extendedMembersList.Add(member); + } + } + + if (extendedMembersEnumerable != null) + { + WriteMemberInfoCollection(extendedMembersEnumerable, depth, true); + } + } + + /// + /// Serializes properties from collection + /// + /// + /// Collection of properties to serialize + /// + /// + /// Name for enclosing element tag + /// + /// + /// depth to which each property should be + /// serialized + /// + private void SerializeProperties + ( + IEnumerable propertyCollection, + string name, + int depth + ) + { + Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); + bool startElementWritten = false; + + foreach (PSMemberInfo info in propertyCollection) + { + PSProperty prop = info as PSProperty; + if (prop == null) + { + continue; + } + + if (!startElementWritten) + { + WriteStartElement(name); + startElementWritten = true; + } + + bool success; + object value = SerializationUtilities.GetPropertyValueInThreadSafeManner(prop, this.CanUseDefaultRunspaceInThreadSafeManner, out success); + if (success) + { + WriteOneObject(value, null, prop.Name, depth); + } + } + + if (startElementWritten) + { + _writer.WriteEndElement(); + } + } + + #endregion base properties + + #endregion WritePSObject + + #region enumerable and dictionary + + /// + /// Serializes IEnumerable + /// + /// + /// enumerable which is serialized + /// + /// + /// + /// + private void WriteEnumerable + ( + IEnumerable enumerable, + string tag, + int depth + ) + { + Dbg.Assert(enumerable != null, "caller should validate the parameter"); + Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); + + //Start element + WriteStartElement(tag); + + IEnumerator enumerator = null; + try + { + enumerator = enumerable.GetEnumerator(); + try + { + enumerator.Reset(); + } + catch (System.NotSupportedException) + { + //ignore exceptions thrown when the enumerator doesn't support Reset() method as in win8:948569 + } + } + catch (Exception exception) + { + // Catch-all OK. This is a third-party call-out. + CommandProcessorBase.CheckForSevereException(exception); + + PSEtwLog.LogAnalyticWarning( + PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + enumerable.GetType().AssemblyQualifiedName, + exception.ToString()); + + enumerator = null; + } + + //AD has incorrect implementation of IEnumerable where they returned null + //for GetEnumerator instead of empty enumerator + if (enumerator != null) + { + while (true) + { + object item = null; + try + { + if (!enumerator.MoveNext()) + { + break; + } + else + { + item = enumerator.Current; + } + } + catch (Exception exception) + { + // Catch-all OK. This is a third-party call-out. + CommandProcessorBase.CheckForSevereException(exception); + + PSEtwLog.LogAnalyticWarning( + PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + enumerable.GetType().AssemblyQualifiedName, + exception.ToString()); + + break; + } + WriteOneObject(item, null, null, depth); + } + } + //End element + _writer.WriteEndElement(); + } + + /// + /// Serializes IDictionary + /// + /// dictionary which is serialized + /// + /// + private void WriteDictionary + ( + IDictionary dictionary, + string tag, + int depth + ) + { + Dbg.Assert(dictionary != null, "caller should validate the parameter"); + Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); + + //Start element + WriteStartElement(tag); + + IDictionaryEnumerator dictionaryEnum = null; + try + { + dictionaryEnum = dictionary.GetEnumerator(); + } + catch (Exception exception) // ignore non-severe exceptions + { + // Catch-all OK. This is a third-party call-out. + CommandProcessorBase.CheckForSevereException(exception); + + PSEtwLog.LogAnalyticWarning( + PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + dictionary.GetType().AssemblyQualifiedName, + exception.ToString()); + } + + if (dictionaryEnum != null) + { + while (true) + { + object key = null; + object value = null; + try + { + if (!dictionaryEnum.MoveNext()) + { + break; + } + else + { + key = dictionaryEnum.Key; + value = dictionaryEnum.Value; + } + } + catch (Exception exception) + { + // Catch-all OK. This is a third-party call-out. + CommandProcessorBase.CheckForSevereException(exception); + + PSEtwLog.LogAnalyticWarning( + PSEventId.Serializer_EnumerationFailed, PSOpcode.Exception, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + dictionary.GetType().AssemblyQualifiedName, + exception.ToString()); + + break; + } + + Dbg.Assert(key != null, "Dictionary keys should never be null"); + if (key == null) break; + + WriteStartElement(SerializationStrings.DictionaryEntryTag); + WriteOneObject(key, null, SerializationStrings.DictionaryKey, depth); + WriteOneObject(value, null, SerializationStrings.DictionaryValue, depth); + _writer.WriteEndElement(); + } + } + + //End element + _writer.WriteEndElement(); + } + + #endregion enumerable and dictionary + + #region serialize as string + + private void HandlePSObjectAsString( + PSObject source, + string streamName, + string property, + int depth) + { + Dbg.Assert(source != null, "caller should validate the information"); + + string value = GetSerializationString(source); + + TypeSerializationInfo pktInfo = null; + if (value != null) + { + pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); + } + + WritePrimitiveTypePSObject(source, value, pktInfo, streamName, property, depth); + } /// /// Gets the string from PSObject using the information from @@ -2278,1481 +2275,1480 @@ namespace System.Management.Automation } } - #endregion serialize as string + #endregion serialize as string - /// - /// compute the serialization depth for an PSObject instance subtree - /// - /// PSObject whose serialization depth has to be computed - /// current depth - /// - private int GetDepthOfSerialization(object source, int depth) - { - Dbg.Assert(source != null, "Caller should verify source != null"); + /// + /// compute the serialization depth for an PSObject instance subtree + /// + /// PSObject whose serialization depth has to be computed + /// current depth + /// + private int GetDepthOfSerialization(object source, int depth) + { + Dbg.Assert(source != null, "Caller should verify source != null"); - PSObject pso = PSObject.AsPSObject(source); - if (pso == null) - { - return depth; - } + PSObject pso = PSObject.AsPSObject(source); + if (pso == null) + { + return depth; + } - if (pso.BaseObject is CimInstance) - { - return 1; - } + if (pso.BaseObject is CimInstance) + { + return 1; + } - if (pso.BaseObject is PSCredential) - { - return 1; - } + if (pso.BaseObject is PSCredential) + { + return 1; + } - if (pso.BaseObject is PSSenderInfo) - { - return 4; - } + if (pso.BaseObject is PSSenderInfo) + { + return 4; + } - if (pso.BaseObject is SwitchParameter) - { - return 1; - } + if (pso.BaseObject is SwitchParameter) + { + return 1; + } - if (0 != (_context.options & SerializationOptions.UseDepthFromTypes)) - { - // get the depth from the PSObject - // NOTE: we assume that the depth out of the PSObject is > 0 - // else we consider it not set in types.ps1xml - int typesPs1xmlDepth = pso.GetSerializationDepth(_typeTable); - if (typesPs1xmlDepth > 0) - { - if (typesPs1xmlDepth != depth) - { - PSEtwLog.LogAnalyticVerbose( - PSEventId.Serializer_DepthOverride, PSOpcode.SerializationSettings, PSTask.Serialization, - PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, - pso.InternalTypeNames.Key, depth, typesPs1xmlDepth, this.depthBelowTopLevel); + if (0 != (_context.options & SerializationOptions.UseDepthFromTypes)) + { + // get the depth from the PSObject + // NOTE: we assume that the depth out of the PSObject is > 0 + // else we consider it not set in types.ps1xml + int typesPs1xmlDepth = pso.GetSerializationDepth(_typeTable); + if (typesPs1xmlDepth > 0) + { + if (typesPs1xmlDepth != depth) + { + PSEtwLog.LogAnalyticVerbose( + PSEventId.Serializer_DepthOverride, PSOpcode.SerializationSettings, PSTask.Serialization, + PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, + pso.InternalTypeNames.Key, depth, typesPs1xmlDepth, _depthBelowTopLevel); - return typesPs1xmlDepth; - } - } - } + return typesPs1xmlDepth; + } + } + } - if (0 != (_context.options & SerializationOptions.PreserveSerializationSettingOfOriginal)) - { - if ((pso.isDeserialized) && (depth <= 0)) - { - return 1; - } - } + if (0 != (_context.options & SerializationOptions.PreserveSerializationSettingOfOriginal)) + { + if ((pso.isDeserialized) && (depth <= 0)) + { + return 1; + } + } - return depth; - } + return depth; + } - /// - /// Writes null - /// - /// - /// - private void WriteNull(string streamName, string property) - { - WriteStartElement(SerializationStrings.NilTag); + /// + /// Writes null + /// + /// + /// + private void WriteNull(string streamName, string property) + { + WriteStartElement(SerializationStrings.NilTag); - if (streamName != null) - { - WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + if (streamName != null) + { + WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - if (property != null) - { - WriteNameAttribute(property); - } - _writer.WriteEndElement(); - } + if (property != null) + { + WriteNameAttribute(property); + } + _writer.WriteEndElement(); + } - #region known type serialization + #region known type serialization - /// - /// Writes raw string as item or property in Monad namespace - /// - /// The serializer to which the object is serialized. - /// name of the stream to write. Do not write if null. - /// name of property. Pass null for item - /// string to write - /// serialization information - private static void WriteRawString - ( - InternalSerializer serializer, - string streamName, - string property, - string raw, - TypeSerializationInfo entry - ) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(raw != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes raw string as item or property in Monad namespace + /// + /// The serializer to which the object is serialized. + /// name of the stream to write. Do not write if null. + /// name of property. Pass null for item + /// string to write + /// serialization information + private static void WriteRawString + ( + InternalSerializer serializer, + string streamName, + string property, + string raw, + TypeSerializationInfo entry + ) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(raw != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - if (property != null) - { - serializer.WriteStartElement(entry.PropertyTag); - serializer.WriteNameAttribute(property); - } - else - { - serializer.WriteStartElement(entry.ItemTag); - } + if (property != null) + { + serializer.WriteStartElement(entry.PropertyTag); + serializer.WriteNameAttribute(property); + } + else + { + serializer.WriteStartElement(entry.ItemTag); + } - if (streamName != null) - { - serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + if (streamName != null) + { + serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - serializer._writer.WriteRaw(raw); - serializer._writer.WriteEndElement(); - } + serializer._writer.WriteRaw(raw); + serializer._writer.WriteEndElement(); + } - /// - /// Writes an item or property in Monad namespace - /// - /// The serializer to which the object is serialized. - /// - /// name of property. Pass null for item - /// object to be written - /// serialization information about source - private static void WriteOnePrimitiveKnownType - ( - InternalSerializer serializer, - string streamName, - string property, - object source, - TypeSerializationInfo entry - ) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes an item or property in Monad namespace + /// + /// The serializer to which the object is serialized. + /// + /// name of property. Pass null for item + /// object to be written + /// serialization information about source + private static void WriteOnePrimitiveKnownType + ( + InternalSerializer serializer, + string streamName, + string property, + object source, + TypeSerializationInfo entry + ) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - if (entry.Serializer == null) - { - // we are not using GetToString, because we assume that - // ToString() for primitive types never throws - string value = Convert.ToString(source, CultureInfo.InvariantCulture); - Dbg.Assert(value != null, "ToString shouldn't return null for primitive types"); - WriteRawString(serializer, streamName, property, value, entry); - } - else - { - entry.Serializer(serializer, streamName, property, source, entry); - } - } + if (entry.Serializer == null) + { + // we are not using GetToString, because we assume that + // ToString() for primitive types never throws + string value = Convert.ToString(source, CultureInfo.InvariantCulture); + Dbg.Assert(value != null, "ToString shouldn't return null for primitive types"); + WriteRawString(serializer, streamName, property, value, entry); + } + else + { + entry.Serializer(serializer, streamName, property, source, entry); + } + } - /// - /// Writes DateTime as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// DateTime to write - /// serialization information about source - internal static void WriteDateTime(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes DateTime as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// DateTime to write + /// serialization information about source + internal static void WriteDateTime(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((DateTime)source, XmlDateTimeSerializationMode.RoundtripKind), entry); - } + } - /// - /// Writes Version - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// Version to write - /// serialization information about source - internal static void WriteVersion(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(source is Version, "Caller should verify that typeof(source) is Version"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Version + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// Version to write + /// serialization information about source + internal static void WriteVersion(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is Version, "Caller should verify that typeof(source) is Version"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteRawString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); - } + WriteRawString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); + } - /// - /// Serialize scriptblock as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// scriptblock to write - /// serialization information about source - internal static void WriteScriptBlock(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(source is ScriptBlock, "Caller should verify that typeof(source) is ScriptBlock"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Serialize scriptblock as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// scriptblock to write + /// serialization information about source + internal static void WriteScriptBlock(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is ScriptBlock, "Caller should verify that typeof(source) is ScriptBlock"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); - } + WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); + } - /// - /// Serialize URI as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// URI to write - /// serialization information about source - internal static void WriteUri(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(source is Uri, "Caller should verify that typeof(source) is Uri"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Serialize URI as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// URI to write + /// serialization information about source + internal static void WriteUri(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is Uri, "Caller should verify that typeof(source) is Uri"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); - } + WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); + } - /// - /// Serialize string as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// string to write - /// serialization information about source - internal static void WriteEncodedString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(source is string, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Serialize string as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// string to write + /// serialization information about source + internal static void WriteEncodedString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is string, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - if (property != null) - { - serializer.WriteStartElement(entry.PropertyTag); - serializer.WriteNameAttribute(property); - } - else - { - serializer.WriteStartElement(entry.ItemTag); - } + if (property != null) + { + serializer.WriteStartElement(entry.PropertyTag); + serializer.WriteNameAttribute(property); + } + else + { + serializer.WriteStartElement(entry.ItemTag); + } - if (streamName != null) - { - serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + if (streamName != null) + { + serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - //Note: We do not use WriteRaw for serializing string. WriteString - //does necessary escaping which may be needed for certain - //characters. - Dbg.Assert(source is string, "Caller should verify that typeof(source) is String"); - string s = (string)source; - string encoded = EncodeString(s); - serializer._writer.WriteString(encoded); + //Note: We do not use WriteRaw for serializing string. WriteString + //does necessary escaping which may be needed for certain + //characters. + Dbg.Assert(source is string, "Caller should verify that typeof(source) is String"); + string s = (string)source; + string encoded = EncodeString(s); + serializer._writer.WriteString(encoded); - serializer._writer.WriteEndElement(); - } + serializer._writer.WriteEndElement(); + } - /// - /// Writes Double as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// Double to write - /// serialization information about source - internal static void WriteDouble(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Double as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// Double to write + /// serialization information about source + internal static void WriteDouble(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteRawString(serializer, streamName, property, XmlConvert.ToString((Double)source), entry); - } + WriteRawString(serializer, streamName, property, XmlConvert.ToString((Double)source), entry); + } - /// - /// Writes Char as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// Char to write - /// serialization information about source - internal static void WriteChar(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Char as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// Char to write + /// serialization information about source + internal static void WriteChar(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - //Char is defined as unsigned short in schema - WriteRawString(serializer, streamName, property, XmlConvert.ToString((UInt16)(Char)source), entry); - } + //Char is defined as unsigned short in schema + WriteRawString(serializer, streamName, property, XmlConvert.ToString((UInt16)(Char)source), entry); + } - /// - /// Writes Boolean as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// Boolean to write - /// serialization information about source - internal static void WriteBoolean(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Boolean as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// Boolean to write + /// serialization information about source + internal static void WriteBoolean(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteRawString(serializer, streamName, property, XmlConvert.ToString((Boolean)source), entry); - } + WriteRawString(serializer, streamName, property, XmlConvert.ToString((Boolean)source), entry); + } - /// - /// Writes Single as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// single to write - /// serialization information about source - internal static void WriteSingle(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Single as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// single to write + /// serialization information about source + internal static void WriteSingle(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteRawString(serializer, streamName, property, XmlConvert.ToString((Single)source), entry); - } + WriteRawString(serializer, streamName, property, XmlConvert.ToString((Single)source), entry); + } - /// - /// Writes TimeSpan as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// DateTime to write - /// serialization information about source - internal static void WriteTimeSpan(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes TimeSpan as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// DateTime to write + /// serialization information about source + internal static void WriteTimeSpan(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - WriteRawString(serializer, streamName, property, XmlConvert.ToString((TimeSpan)source), entry); - } + WriteRawString(serializer, streamName, property, XmlConvert.ToString((TimeSpan)source), entry); + } - /// - /// Writes Single as item or property - /// - /// The serializer to which the object is serialized. - /// - /// name of property. pass null for item - /// bytearray to write - /// serialization information about source - internal static void WriteByteArray(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + /// + /// Writes Single as item or property + /// + /// The serializer to which the object is serialized. + /// + /// name of property. pass null for item + /// bytearray to write + /// serialization information about source + internal static void WriteByteArray(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - Byte[] bytes = (Byte[])source; - if (property != null) - { - serializer.WriteStartElement(entry.PropertyTag); - serializer.WriteNameAttribute(property); - } - else - { - serializer.WriteStartElement(entry.ItemTag); - } + Byte[] bytes = (Byte[])source; + if (property != null) + { + serializer.WriteStartElement(entry.PropertyTag); + serializer.WriteNameAttribute(property); + } + else + { + serializer.WriteStartElement(entry.ItemTag); + } - if (streamName != null) - { - serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + if (streamName != null) + { + serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - serializer._writer.WriteBase64(bytes, 0, bytes.Length); - serializer._writer.WriteEndElement(); - } + serializer._writer.WriteBase64(bytes, 0, bytes.Length); + serializer._writer.WriteEndElement(); + } - internal static void WriteXmlDocument(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + internal static void WriteXmlDocument(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - string xml = ((XmlDocument)source).OuterXml; - WriteEncodedString(serializer, streamName, property, xml, entry); - } + string xml = ((XmlDocument)source).OuterXml; + WriteEncodedString(serializer, streamName, property, xml, entry); + } - internal static void WriteProgressRecord(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + internal static void WriteProgressRecord(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - ProgressRecord rec = (ProgressRecord)source; - serializer.WriteStartElement(entry.PropertyTag); - if (property != null) - { - serializer.WriteNameAttribute(property); - } - if (streamName != null) - { - serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); - } + ProgressRecord rec = (ProgressRecord)source; + serializer.WriteStartElement(entry.PropertyTag); + if (property != null) + { + serializer.WriteNameAttribute(property); + } + if (streamName != null) + { + serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); + } - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordActivity, rec.Activity); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordActivityId, rec.ActivityId.ToString(CultureInfo.InvariantCulture)); - serializer.WriteOneObject(rec.CurrentOperation, null, null, 1); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordParentActivityId, rec.ParentActivityId.ToString(CultureInfo.InvariantCulture)); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordPercentComplete, rec.PercentComplete.ToString(CultureInfo.InvariantCulture)); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordType, rec.RecordType.ToString()); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordSecondsRemaining, rec.SecondsRemaining.ToString(CultureInfo.InvariantCulture)); - serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordStatusDescription, rec.StatusDescription); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordActivity, rec.Activity); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordActivityId, rec.ActivityId.ToString(CultureInfo.InvariantCulture)); + serializer.WriteOneObject(rec.CurrentOperation, null, null, 1); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordParentActivityId, rec.ParentActivityId.ToString(CultureInfo.InvariantCulture)); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordPercentComplete, rec.PercentComplete.ToString(CultureInfo.InvariantCulture)); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordType, rec.RecordType.ToString()); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordSecondsRemaining, rec.SecondsRemaining.ToString(CultureInfo.InvariantCulture)); + serializer.WriteEncodedElementString(SerializationStrings.ProgressRecordStatusDescription, rec.StatusDescription); - serializer._writer.WriteEndElement(); - } + serializer._writer.WriteEndElement(); + } - internal static void WriteSecureString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) - { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + internal static void WriteSecureString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) + { + Dbg.Assert(serializer != null, "caller should have validated the information"); + Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(entry != null, "caller should have validated the information"); - serializer.HandleSecureString(source, streamName, property); - } + serializer.HandleSecureString(source, streamName, property); + } - #endregion known type serialization + #endregion known type serialization - #region misc + #region misc - /// - /// Writes start element in Monad namespace - /// - /// tag of element - private void WriteStartElement(string elementTag) - { - Dbg.Assert(!string.IsNullOrEmpty(elementTag), "Caller should validate the parameter"); - if (SerializationOptions.NoNamespace == (this._context.options & SerializationOptions.NoNamespace)) - { - _writer.WriteStartElement(elementTag); - } - else - { - _writer.WriteStartElement(elementTag, SerializationStrings.MonadNamespace); - } - } + /// + /// Writes start element in Monad namespace + /// + /// tag of element + private void WriteStartElement(string elementTag) + { + Dbg.Assert(!string.IsNullOrEmpty(elementTag), "Caller should validate the parameter"); + if (SerializationOptions.NoNamespace == (_context.options & SerializationOptions.NoNamespace)) + { + _writer.WriteStartElement(elementTag); + } + else + { + _writer.WriteStartElement(elementTag, SerializationStrings.MonadNamespace); + } + } - /// - /// Writes attribute in monad namespace - /// - /// name of attribute - /// value of attribute - private void WriteAttribute(string name, string value) - { - Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); - Dbg.Assert(value != null, "Caller should validate the parameter"); - _writer.WriteAttributeString(name, value); - } + /// + /// Writes attribute in monad namespace + /// + /// name of attribute + /// value of attribute + private void WriteAttribute(string name, string value) + { + Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); + Dbg.Assert(value != null, "Caller should validate the parameter"); + _writer.WriteAttributeString(name, value); + } - private void WriteNameAttribute(string value) - { - Dbg.Assert(!string.IsNullOrEmpty(value), "Caller should validate the parameter"); - WriteAttribute( - SerializationStrings.NameAttribute, - EncodeString(value)); - } + private void WriteNameAttribute(string value) + { + Dbg.Assert(!string.IsNullOrEmpty(value), "Caller should validate the parameter"); + WriteAttribute( + SerializationStrings.NameAttribute, + EncodeString(value)); + } - /// - /// Encodes the string to escape characters which would make XmlWriter.WriteString throw an exception. - /// - /// string to encode - /// encoded string - /// - /// Output from this method can be reverted using XmlConvert.DecodeName method - /// (or InternalDeserializer.DecodeString). - /// This method has been introduced to produce shorter output than XmlConvert.EncodeName - /// (which escapes everything that can't be part of an xml name - whitespace, punctuation). - /// - /// This method has been split into 2 parts to optimize its performance: - /// 1) part1 (this method) checks if there are any encodable characters and - /// if there aren't it simply (and efficiently) returns the original string - /// 2) part2 (EncodeString(string, int)) picks up when part1 detects the first encodable - /// character. It avoids looking at the characters already verified by part1 - /// and copies those already verified characters and then starts encoding - /// the rest of the string. - /// - internal static string EncodeString(string s) - { - Dbg.Assert(s != null, "Caller should validate the parameter"); + /// + /// Encodes the string to escape characters which would make XmlWriter.WriteString throw an exception. + /// + /// string to encode + /// encoded string + /// + /// Output from this method can be reverted using XmlConvert.DecodeName method + /// (or InternalDeserializer.DecodeString). + /// This method has been introduced to produce shorter output than XmlConvert.EncodeName + /// (which escapes everything that can't be part of an xml name - whitespace, punctuation). + /// + /// This method has been split into 2 parts to optimize its performance: + /// 1) part1 (this method) checks if there are any encodable characters and + /// if there aren't it simply (and efficiently) returns the original string + /// 2) part2 (EncodeString(string, int)) picks up when part1 detects the first encodable + /// character. It avoids looking at the characters already verified by part1 + /// and copies those already verified characters and then starts encoding + /// the rest of the string. + /// + internal static string EncodeString(string s) + { + Dbg.Assert(s != null, "Caller should validate the parameter"); - int slen = s.Length; - for (int i = 0; i < slen; ++i) - { - char c = s[i]; - // A control character is in ranges 0x00-0x1F or 0x7F-0x9F - // The escape character is 0x5F ('_') if followed by an 'x' - // A surrogate character is in range 0xD800-0xDFFF - if (c <= 0x1F - || (c >= 0x7F && c <= 0x9F) - || (c >= 0xD800 && c <= 0xDFFF) - || (c == 0x5F && (i + 1 < slen) && - ((s[i + 1] == 'x') || (s[i + 1] == 'X')) - )) - { - return EncodeString(s, i); - } - } - // No encodable characters were found above - simply return the original string - return s; - } + int slen = s.Length; + for (int i = 0; i < slen; ++i) + { + char c = s[i]; + // A control character is in ranges 0x00-0x1F or 0x7F-0x9F + // The escape character is 0x5F ('_') if followed by an 'x' + // A surrogate character is in range 0xD800-0xDFFF + if (c <= 0x1F + || (c >= 0x7F && c <= 0x9F) + || (c >= 0xD800 && c <= 0xDFFF) + || (c == 0x5F && (i + 1 < slen) && + ((s[i + 1] == 'x') || (s[i + 1] == 'X')) + )) + { + return EncodeString(s, i); + } + } + // No encodable characters were found above - simply return the original string + return s; + } - private static readonly char[] hexlookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + private static readonly char[] s_hexlookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - /// - /// This is the real workhorse that encodes strings. - /// See for more information. - /// - /// string to encode - /// indexOfFirstEncodableCharacter - /// encoded string - private static string EncodeString(string s, int indexOfFirstEncodableCharacter) - { - Dbg.Assert(s != null, "Caller should validate the 's' parameter"); - Dbg.Assert(indexOfFirstEncodableCharacter >= 0, "Caller should verify validity of indexOfFirstEncodableCharacter"); - Dbg.Assert(indexOfFirstEncodableCharacter < s.Length, "Caller should verify validity of indexOfFirstEncodableCharacter"); + /// + /// This is the real workhorse that encodes strings. + /// See for more information. + /// + /// string to encode + /// indexOfFirstEncodableCharacter + /// encoded string + private static string EncodeString(string s, int indexOfFirstEncodableCharacter) + { + Dbg.Assert(s != null, "Caller should validate the 's' parameter"); + Dbg.Assert(indexOfFirstEncodableCharacter >= 0, "Caller should verify validity of indexOfFirstEncodableCharacter"); + Dbg.Assert(indexOfFirstEncodableCharacter < s.Length, "Caller should verify validity of indexOfFirstEncodableCharacter"); - int slen = s.Length; - char[] result = new char[indexOfFirstEncodableCharacter + (slen - indexOfFirstEncodableCharacter) * 7]; + int slen = s.Length; + char[] result = new char[indexOfFirstEncodableCharacter + (slen - indexOfFirstEncodableCharacter) * 7]; - s.CopyTo(0, result, 0, indexOfFirstEncodableCharacter); - int rlen = indexOfFirstEncodableCharacter; + s.CopyTo(0, result, 0, indexOfFirstEncodableCharacter); + int rlen = indexOfFirstEncodableCharacter; - for (int i = indexOfFirstEncodableCharacter; i < slen; ++i) - { - char c = s[i]; - // A control character is in ranges 0x00-0x1F or 0x7F-0x9F - // The escape character is 0x5F ('_') if followed by an 'x' - // A surrogate character is in range 0xD800-0xDFFF - if (c > 0x1F - && (c < 0x7F || c > 0x9F) - && (c < 0xD800 || c > 0xDFFF) - && (c != 0x5F || ((i + 1 >= slen) || - ((s[i + 1] != 'x') && (s[i + 1] != 'X')) - ))) - { - result[rlen++] = c; - } - else if (c == 0x5F) - { - // Special case the escape character, encode _ - result[rlen + 0] = '_'; - result[rlen + 1] = 'x'; - result[rlen + 2] = '0'; - result[rlen + 3] = '0'; - result[rlen + 4] = '5'; - result[rlen + 5] = 'F'; - result[rlen + 6] = '_'; - rlen += 7; - } - else - { - // It is a control character or a unicode surrogate - result[rlen + 0] = '_'; - result[rlen + 1] = 'x'; + for (int i = indexOfFirstEncodableCharacter; i < slen; ++i) + { + char c = s[i]; + // A control character is in ranges 0x00-0x1F or 0x7F-0x9F + // The escape character is 0x5F ('_') if followed by an 'x' + // A surrogate character is in range 0xD800-0xDFFF + if (c > 0x1F + && (c < 0x7F || c > 0x9F) + && (c < 0xD800 || c > 0xDFFF) + && (c != 0x5F || ((i + 1 >= slen) || + ((s[i + 1] != 'x') && (s[i + 1] != 'X')) + ))) + { + result[rlen++] = c; + } + else if (c == 0x5F) + { + // Special case the escape character, encode _ + result[rlen + 0] = '_'; + result[rlen + 1] = 'x'; + result[rlen + 2] = '0'; + result[rlen + 3] = '0'; + result[rlen + 4] = '5'; + result[rlen + 5] = 'F'; + result[rlen + 6] = '_'; + rlen += 7; + } + else + { + // It is a control character or a unicode surrogate + result[rlen + 0] = '_'; + result[rlen + 1] = 'x'; - result[rlen + 2 + 3] = hexlookup[c & 0x0F]; - c >>= 4; - result[rlen + 2 + 2] = hexlookup[c & 0x0F]; - c >>= 4; - result[rlen + 2 + 1] = hexlookup[c & 0x0F]; - c >>= 4; - result[rlen + 2 + 0] = hexlookup[c & 0x0F]; + result[rlen + 2 + 3] = s_hexlookup[c & 0x0F]; + c >>= 4; + result[rlen + 2 + 2] = s_hexlookup[c & 0x0F]; + c >>= 4; + result[rlen + 2 + 1] = s_hexlookup[c & 0x0F]; + c >>= 4; + result[rlen + 2 + 0] = s_hexlookup[c & 0x0F]; - result[rlen + 6] = '_'; + result[rlen + 6] = '_'; - rlen += 7; - } - } - return new String(result, 0, rlen); - } + rlen += 7; + } + } + return new String(result, 0, rlen); + } - /// - /// Writes element string in monad namespace - /// - /// - /// - private void WriteEncodedElementString(string name, string value) - { - Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); - Dbg.Assert(value != null, "Caller should validate the parameter"); - this.CheckIfStopping(); + /// + /// Writes element string in monad namespace + /// + /// + /// + private void WriteEncodedElementString(string name, string value) + { + Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); + Dbg.Assert(value != null, "Caller should validate the parameter"); + this.CheckIfStopping(); - value = EncodeString(value); + value = EncodeString(value); - if (SerializationOptions.NoNamespace == (this._context.options & SerializationOptions.NoNamespace)) - { - _writer.WriteElementString(name, value); - } - else - { - _writer.WriteElementString(name, SerializationStrings.MonadNamespace, value); - } - } + if (SerializationOptions.NoNamespace == (_context.options & SerializationOptions.NoNamespace)) + { + _writer.WriteElementString(name, value); + } + else + { + _writer.WriteElementString(name, SerializationStrings.MonadNamespace, value); + } + } - #endregion misc - - } + #endregion misc + } - /// - /// This internal class provides methods for de-serializing mshObject. - /// - internal class InternalDeserializer - { - #region constructor + /// + /// This internal class provides methods for de-serializing mshObject. + /// + internal class InternalDeserializer + { + #region constructor - /// - /// XmlReader from which object is deserialized - /// - private readonly XmlReader _reader; + /// + /// XmlReader from which object is deserialized + /// + private readonly XmlReader _reader; - /// - /// Deserialization context - /// - private readonly DeserializationContext _context; + /// + /// Deserialization context + /// + private readonly DeserializationContext _context; - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Serializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - private TypeTable _typeTable; + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Serializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + private TypeTable _typeTable; - /// - /// If true, unknowntags are allowed inside PSObject - /// - private bool UnknownTagsAllowed - { - get - { - Dbg.Assert(this._version.Major <= 1, "Deserializer assumes clixml version is <= 1.1"); - //If minor version is greater than 1, it means that there can be - //some unknown tags in xml. Deserialization should ignore such element. - return (this._version.Minor > 1); - } - } + /// + /// If true, unknowntags are allowed inside PSObject + /// + private bool UnknownTagsAllowed + { + get + { + Dbg.Assert(_version.Major <= 1, "Deserializer assumes clixml version is <= 1.1"); + //If minor version is greater than 1, it means that there can be + //some unknown tags in xml. Deserialization should ignore such element. + return (_version.Minor > 1); + } + } - private bool DuplicateRefIdsAllowed - { - get - { + private bool DuplicateRefIdsAllowed + { + get + { #if DEBUG - Dbg.Assert(this._version.Major <= 1, "Deserializer assumes clixml version is <= 1.1"); - Version boundaryVersion = new Version(1, 1, 0, 1); - return (this._version < boundaryVersion); + Dbg.Assert(_version.Major <= 1, "Deserializer assumes clixml version is <= 1.1"); + Version boundaryVersion = new Version(1, 1, 0, 1); + return (_version < boundaryVersion); #else - return true; // handle v1 stuff gracefully + return true; // handle v1 stuff gracefully #endif - } - } + } + } - /// - /// Depth below top level - used to prevent stack overflow during deserialization - /// - private int depthBelowTopLevel; + /// + /// Depth below top level - used to prevent stack overflow during deserialization + /// + private int _depthBelowTopLevel; - /// - /// Version declared by the clixml being read - /// - private Version _version; + /// + /// Version declared by the clixml being read + /// + private Version _version; - private const int MaxDepthBelowTopLevel = 50; + private const int MaxDepthBelowTopLevel = 50; - private readonly ReferenceIdHandlerForDeserializer objectRefIdHandler; - private readonly ReferenceIdHandlerForDeserializer typeRefIdHandler; + private readonly ReferenceIdHandlerForDeserializer _objectRefIdHandler; + private readonly ReferenceIdHandlerForDeserializer _typeRefIdHandler; - /// - /// - /// - /// - /// - internal InternalDeserializer(XmlReader reader, DeserializationContext context) - { - Dbg.Assert(reader != null, "caller should validate the parameter"); + /// + /// + /// + /// + /// + internal InternalDeserializer(XmlReader reader, DeserializationContext context) + { + Dbg.Assert(reader != null, "caller should validate the parameter"); - _reader = reader; - _context = context; + _reader = reader; + _context = context; - this.objectRefIdHandler = new ReferenceIdHandlerForDeserializer(); - this.typeRefIdHandler = new ReferenceIdHandlerForDeserializer(); - } + _objectRefIdHandler = new ReferenceIdHandlerForDeserializer(); + _typeRefIdHandler = new ReferenceIdHandlerForDeserializer(); + } - #endregion constructor + #endregion constructor - #region deserialization - /// - /// Used by Remoting infrastructure. This TypeTable instance - /// will be used by Deserializer if ExecutionContext is not - /// avaliable (to get the ExecutionContext's TypeTable) - /// - internal TypeTable TypeTable - { - get { return _typeTable; } - set { _typeTable = value; } - } + #region deserialization + /// + /// Used by Remoting infrastructure. This TypeTable instance + /// will be used by Deserializer if ExecutionContext is not + /// avaliable (to get the ExecutionContext's TypeTable) + /// + internal TypeTable TypeTable + { + get { return _typeTable; } + set { _typeTable = value; } + } - /// - /// Validates the version for correctness. Also validates that deserializer - /// can deserialize this version. - /// - /// - /// version in string format - /// - internal void ValidateVersion(string version) - { - Dbg.Assert(version != null, "Caller should validate the parameter"); + /// + /// Validates the version for correctness. Also validates that deserializer + /// can deserialize this version. + /// + /// + /// version in string format + /// + internal void ValidateVersion(string version) + { + Dbg.Assert(version != null, "Caller should validate the parameter"); - this._version = null; - Exception exceptionToRethrow = null; - try - { - this._version = new Version(version); - } - catch (ArgumentException e) - { - exceptionToRethrow = e; - } - catch (FormatException e) - { - exceptionToRethrow = e; - } - if (exceptionToRethrow != null) - { - throw NewXmlException(Serialization.InvalidVersion, exceptionToRethrow); - } + _version = null; + Exception exceptionToRethrow = null; + try + { + _version = new Version(version); + } + catch (ArgumentException e) + { + exceptionToRethrow = e; + } + catch (FormatException e) + { + exceptionToRethrow = e; + } + if (exceptionToRethrow != null) + { + throw NewXmlException(Serialization.InvalidVersion, exceptionToRethrow); + } - //Versioning Note:Future version of serialization can add new known types. - //This version will ignore those known types, if they are base object. - //It is expected that future version will still put information in base - //and adpater properties which this serializer can read and use. - //For example, assume the version 2 serialization engine supports a new known - //type IPAddress. The version 1 deserializer doesn't know IPAddress as known - //type and it must retrieve it as an PSObject. The version 2 serializer - //can serialize this as follows: - // - // ... - // - // 120.23.35.53 - // - // - // 120.23.34.53 - // A - // - // - // In above example, V1 serializer will ingore element and read - // properties from - // V2 serializer can read tag and ignore properties. - // Read serializion note doc for information. + //Versioning Note:Future version of serialization can add new known types. + //This version will ignore those known types, if they are base object. + //It is expected that future version will still put information in base + //and adpater properties which this serializer can read and use. + //For example, assume the version 2 serialization engine supports a new known + //type IPAddress. The version 1 deserializer doesn't know IPAddress as known + //type and it must retrieve it as an PSObject. The version 2 serializer + //can serialize this as follows: + // + // ... + // + // 120.23.35.53 + // + // + // 120.23.34.53 + // A + // + // + // In above example, V1 serializer will ingore element and read + // properties from + // V2 serializer can read tag and ignore properties. + // Read serializion note doc for information. - //Now validate the major version number is 1 - if (this._version.Major != 1) - { - throw NewXmlException(Serialization.UnexpectedVersion, null, this._version.Major); - } - } + //Now validate the major version number is 1 + if (_version.Major != 1) + { + throw NewXmlException(Serialization.UnexpectedVersion, null, _version.Major); + } + } - private object ReadOneDeserializedObject(out string streamName, out bool isKnownPrimitiveType) - { - if (_reader.NodeType != XmlNodeType.Element) - { - throw NewXmlException(Serialization.InvalidNodeType, null, - _reader.NodeType.ToString(), XmlNodeType.Element.ToString()); - } + private object ReadOneDeserializedObject(out string streamName, out bool isKnownPrimitiveType) + { + if (_reader.NodeType != XmlNodeType.Element) + { + throw NewXmlException(Serialization.InvalidNodeType, null, + _reader.NodeType.ToString(), XmlNodeType.Element.ToString()); + } - _trace.WriteLine("Processing start node {0}", _reader.LocalName); + s_trace.WriteLine("Processing start node {0}", _reader.LocalName); - streamName = _reader.GetAttribute(SerializationStrings.StreamNameAttribute); - isKnownPrimitiveType = false; + streamName = _reader.GetAttribute(SerializationStrings.StreamNameAttribute); + isKnownPrimitiveType = false; - //handle nil node - if (IsNextElement(SerializationStrings.NilTag)) - { - Skip(); - return null; - } + //handle nil node + if (IsNextElement(SerializationStrings.NilTag)) + { + Skip(); + return null; + } - //Handle reference to previous deserialized object. - if (IsNextElement(SerializationStrings.ReferenceTag)) - { - string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); + //Handle reference to previous deserialized object. + if (IsNextElement(SerializationStrings.ReferenceTag)) + { + string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); - if (refId == null) - { - throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); - } + if (refId == null) + { + throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); + } - object duplicate = this.objectRefIdHandler.GetReferencedObject(refId); - if (duplicate == null) - { - throw NewXmlException(Serialization.InvalidReferenceId, null, refId); - } + object duplicate = _objectRefIdHandler.GetReferencedObject(refId); + if (duplicate == null) + { + throw NewXmlException(Serialization.InvalidReferenceId, null, refId); + } - Skip(); - return duplicate; - } + Skip(); + return duplicate; + } - //Handle primitive known types - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); - if (pktInfo != null) - { - _trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); - isKnownPrimitiveType = true; - return ReadPrimaryKnownType(pktInfo); - } + //Handle primitive known types + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); + if (pktInfo != null) + { + s_trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); + isKnownPrimitiveType = true; + return ReadPrimaryKnownType(pktInfo); + } - //Handle PSObject - if (IsNextElement(SerializationStrings.PSObjectTag)) - { - _trace.WriteLine("PSObject Element"); - return ReadPSObject(); - } + //Handle PSObject + if (IsNextElement(SerializationStrings.PSObjectTag)) + { + s_trace.WriteLine("PSObject Element"); + return ReadPSObject(); + } - //If we are here, we have an unknown node. Unknown nodes may - //be allowed inside PSObject. We do not allow them at top level. + //If we are here, we have an unknown node. Unknown nodes may + //be allowed inside PSObject. We do not allow them at top level. - _trace.TraceError("Invalid element {0} tag found", _reader.LocalName); - throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); - } + s_trace.TraceError("Invalid element {0} tag found", _reader.LocalName); + throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); + } - private bool isStopping = false; + private bool _isStopping = false; - /// - /// Called from a separate thread will stop the serialization process - /// - internal void Stop() - { - this.isStopping = true; - } + /// + /// Called from a separate thread will stop the serialization process + /// + internal void Stop() + { + _isStopping = true; + } private void CheckIfStopping() { - if (this.isStopping) + if (_isStopping) { throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping); } } - internal const string CimInstanceMetadataProperty = "__InstanceMetadata"; - internal const string CimModifiedProperties = "Modified"; - internal const string CimClassMetadataProperty = "__ClassMetadata"; - internal const string CimClassNameProperty = "ClassName"; - internal const string CimNamespaceProperty = "Namespace"; - internal const string CimServerNameProperty = "ServerName"; - internal const string CimHashCodeProperty = "Hash"; - internal const string CimMiXmlProperty = "MiXml"; + internal const string CimInstanceMetadataProperty = "__InstanceMetadata"; + internal const string CimModifiedProperties = "Modified"; + internal const string CimClassMetadataProperty = "__ClassMetadata"; + internal const string CimClassNameProperty = "ClassName"; + internal const string CimNamespaceProperty = "Namespace"; + internal const string CimServerNameProperty = "ServerName"; + internal const string CimHashCodeProperty = "Hash"; + internal const string CimMiXmlProperty = "MiXml"; - private bool RehydrateCimInstanceProperty( - CimInstance cimInstance, - PSPropertyInfo deserializedProperty, - HashSet namesOfModifiedProperties) - { - Dbg.Assert(cimInstance != null, "Caller should make sure cimInstance != null"); - Dbg.Assert(deserializedProperty != null, "Caller should make sure deserializedProperty != null"); + private bool RehydrateCimInstanceProperty( + CimInstance cimInstance, + PSPropertyInfo deserializedProperty, + HashSet namesOfModifiedProperties) + { + Dbg.Assert(cimInstance != null, "Caller should make sure cimInstance != null"); + Dbg.Assert(deserializedProperty != null, "Caller should make sure deserializedProperty != null"); - if (deserializedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) - { - string psComputerNameValue = deserializedProperty.Value as string; - if (psComputerNameValue != null) - { - cimInstance.SetCimSessionComputerName(psComputerNameValue); - } - return true; - } + if (deserializedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) + { + string psComputerNameValue = deserializedProperty.Value as string; + if (psComputerNameValue != null) + { + cimInstance.SetCimSessionComputerName(psComputerNameValue); + } + return true; + } - CimProperty cimProperty = cimInstance.CimInstanceProperties[deserializedProperty.Name]; - if (cimProperty == null) - { - return false; - } + CimProperty cimProperty = cimInstance.CimInstanceProperties[deserializedProperty.Name]; + if (cimProperty == null) + { + return false; + } - // TODO/FIXME - think if it is possible to do the array handling in a more efficient way - object propertyValue = deserializedProperty.Value; - if (propertyValue != null) - { - PSObject psoPropertyValue = PSObject.AsPSObject(propertyValue); - if (psoPropertyValue.BaseObject is ArrayList) - { - if ((psoPropertyValue.InternalTypeNames == null) || (psoPropertyValue.InternalTypeNames.Count == 0)) - { - return false; - } - string originalArrayTypeName = Deserializer.MaskDeserializationPrefix(psoPropertyValue.InternalTypeNames[0]); - if (originalArrayTypeName == null) - { - return false; - } - Type originalArrayType; - if (!LanguagePrimitives.TryConvertTo(originalArrayTypeName, CultureInfo.InvariantCulture, out originalArrayType)) - { - return false; - } - if (!originalArrayType.IsArray) - { - return false; - } - object newPropertyValue; - if (!LanguagePrimitives.TryConvertTo(propertyValue, originalArrayType, CultureInfo.InvariantCulture, out newPropertyValue)) - { - return false; - } - psoPropertyValue = PSObject.AsPSObject(newPropertyValue); - } - propertyValue = psoPropertyValue.BaseObject; - } + // TODO/FIXME - think if it is possible to do the array handling in a more efficient way + object propertyValue = deserializedProperty.Value; + if (propertyValue != null) + { + PSObject psoPropertyValue = PSObject.AsPSObject(propertyValue); + if (psoPropertyValue.BaseObject is ArrayList) + { + if ((psoPropertyValue.InternalTypeNames == null) || (psoPropertyValue.InternalTypeNames.Count == 0)) + { + return false; + } + string originalArrayTypeName = Deserializer.MaskDeserializationPrefix(psoPropertyValue.InternalTypeNames[0]); + if (originalArrayTypeName == null) + { + return false; + } + Type originalArrayType; + if (!LanguagePrimitives.TryConvertTo(originalArrayTypeName, CultureInfo.InvariantCulture, out originalArrayType)) + { + return false; + } + if (!originalArrayType.IsArray) + { + return false; + } + object newPropertyValue; + if (!LanguagePrimitives.TryConvertTo(propertyValue, originalArrayType, CultureInfo.InvariantCulture, out newPropertyValue)) + { + return false; + } + psoPropertyValue = PSObject.AsPSObject(newPropertyValue); + } + propertyValue = psoPropertyValue.BaseObject; + } - try - { - cimProperty.Value = propertyValue; + try + { + cimProperty.Value = propertyValue; - if (!namesOfModifiedProperties.Contains(deserializedProperty.Name)) - { - cimProperty.IsValueModified = false; - } + if (!namesOfModifiedProperties.Contains(deserializedProperty.Name)) + { + cimProperty.IsValueModified = false; + } #if DEBUG - else - { - Dbg.Assert(cimProperty.IsValueModified, "Deserialized CIM properties should by default be marked as 'modified' "); - } + else + { + Dbg.Assert(cimProperty.IsValueModified, "Deserialized CIM properties should by default be marked as 'modified' "); + } #endif - } - catch (FormatException) - { - return false; - } - catch (InvalidCastException) - { - return false; - } - catch (ArgumentException) - { - return false; - } - catch (CimException) - { - return false; - } + } + catch (FormatException) + { + return false; + } + catch (InvalidCastException) + { + return false; + } + catch (ArgumentException) + { + return false; + } + catch (CimException) + { + return false; + } - return true; - } + return true; + } - private static Lazy cimDeserializer = new Lazy(CimDeserializer.Create); + private static Lazy s_cimDeserializer = new Lazy(CimDeserializer.Create); - private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) - { - if ((classMetadataProperty == null) || (classMetadataProperty.Value == null)) - { - return null; - } + private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) + { + if ((classMetadataProperty == null) || (classMetadataProperty.Value == null)) + { + return null; + } - IEnumerable deserializedClasses = LanguagePrimitives.GetEnumerable(classMetadataProperty.Value); - if (deserializedClasses == null) - { - return null; - } + IEnumerable deserializedClasses = LanguagePrimitives.GetEnumerable(classMetadataProperty.Value); + if (deserializedClasses == null) + { + return null; + } - Stack> cimClassesToAddToCache = new Stack>(); + Stack> cimClassesToAddToCache = new Stack>(); - // - // REHYDRATE CLASS METADATA - // - CimClass parentClass = null; - CimClass currentClass = null; - foreach (var deserializedClass in deserializedClasses) - { - parentClass = currentClass; + // + // REHYDRATE CLASS METADATA + // + CimClass parentClass = null; + CimClass currentClass = null; + foreach (var deserializedClass in deserializedClasses) + { + parentClass = currentClass; - if (deserializedClass == null) - { - return null; - } - PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass); + if (deserializedClass == null) + { + return null; + } + PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass); - PSPropertyInfo namespaceProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] as PSPropertyInfo; - if (namespaceProperty == null) - { - return null; - } - string cimNamespace = namespaceProperty.Value as string; + PSPropertyInfo namespaceProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] as PSPropertyInfo; + if (namespaceProperty == null) + { + return null; + } + string cimNamespace = namespaceProperty.Value as string; - PSPropertyInfo classNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] as PSPropertyInfo; - if (classNameProperty == null) - { - return null; - } - string cimClassName = classNameProperty.Value as string; + PSPropertyInfo classNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] as PSPropertyInfo; + if (classNameProperty == null) + { + return null; + } + string cimClassName = classNameProperty.Value as string; - PSPropertyInfo computerNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] as PSPropertyInfo; - if (computerNameProperty == null) - { - return null; - } - string computerName = computerNameProperty.Value as string; + PSPropertyInfo computerNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] as PSPropertyInfo; + if (computerNameProperty == null) + { + return null; + } + string computerName = computerNameProperty.Value as string; - PSPropertyInfo hashCodeProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] as PSPropertyInfo; - if (hashCodeProperty == null) - { - return null; - } - var hashCodeObject = hashCodeProperty.Value; - if (hashCodeObject == null) - { - return null; - } - if (hashCodeObject is PSObject) - { - hashCodeObject = ((PSObject) hashCodeObject).BaseObject; - } - if (!(hashCodeObject is int)) - { - return null; - } - int hashCode = (int)hashCodeObject; + PSPropertyInfo hashCodeProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] as PSPropertyInfo; + if (hashCodeProperty == null) + { + return null; + } + var hashCodeObject = hashCodeProperty.Value; + if (hashCodeObject == null) + { + return null; + } + if (hashCodeObject is PSObject) + { + hashCodeObject = ((PSObject)hashCodeObject).BaseObject; + } + if (!(hashCodeObject is int)) + { + return null; + } + int hashCode = (int)hashCodeObject; - CimClassSerializationId cimClassSerializationId = new CimClassSerializationId(cimClassName, cimNamespace, computerName, hashCode); - currentClass = this._context.cimClassSerializationIdCache.GetCimClassFromCache(cimClassSerializationId); - if (currentClass != null) - { - continue; - } + CimClassSerializationId cimClassSerializationId = new CimClassSerializationId(cimClassName, cimNamespace, computerName, hashCode); + currentClass = _context.cimClassSerializationIdCache.GetCimClassFromCache(cimClassSerializationId); + if (currentClass != null) + { + continue; + } - PSPropertyInfo miXmlProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimMiXmlProperty] as PSPropertyInfo; - if ((miXmlProperty == null) || (miXmlProperty.Value == null)) - { - return null; - } - string miXmlString = miXmlProperty.Value.ToString(); - byte[] miXmlBytes = Encoding.Unicode.GetBytes(miXmlString); - uint offset = 0; - try - { - currentClass = cimDeserializer.Value.DeserializeClass( - miXmlBytes, - ref offset, - parentClass, - computerName: computerName, - namespaceName: cimNamespace); - cimClassesToAddToCache.Push(new KeyValuePair(cimClassSerializationId, currentClass)); - } - catch (CimException) - { - return null; - } - } + PSPropertyInfo miXmlProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimMiXmlProperty] as PSPropertyInfo; + if ((miXmlProperty == null) || (miXmlProperty.Value == null)) + { + return null; + } + string miXmlString = miXmlProperty.Value.ToString(); + byte[] miXmlBytes = Encoding.Unicode.GetBytes(miXmlString); + uint offset = 0; + try + { + currentClass = s_cimDeserializer.Value.DeserializeClass( + miXmlBytes, + ref offset, + parentClass, + computerName: computerName, + namespaceName: cimNamespace); + cimClassesToAddToCache.Push(new KeyValuePair(cimClassSerializationId, currentClass)); + } + catch (CimException) + { + return null; + } + } - // - // UPDATE CLASSDECL DACHE - // - foreach (var cacheEntry in cimClassesToAddToCache) - { - this._context.cimClassSerializationIdCache.AddCimClassToCache(cacheEntry.Key, cacheEntry.Value); - } + // + // UPDATE CLASSDECL DACHE + // + foreach (var cacheEntry in cimClassesToAddToCache) + { + _context.cimClassSerializationIdCache.AddCimClassToCache(cacheEntry.Key, cacheEntry.Value); + } - return currentClass; - } + return currentClass; + } - // NOTE: Win7 change for refid-s that span multiple xml documents: ADMIN: changelist #226414 + // NOTE: Win7 change for refid-s that span multiple xml documents: ADMIN: changelist #226414 - private PSObject RehydrateCimInstance(PSObject deserializedObject) - { - if (!(deserializedObject.BaseObject is PSCustomObject)) - { - return deserializedObject; - } + private PSObject RehydrateCimInstance(PSObject deserializedObject) + { + if (!(deserializedObject.BaseObject is PSCustomObject)) + { + return deserializedObject; + } - PSPropertyInfo classMetadataProperty = deserializedObject.InstanceMembers[CimClassMetadataProperty] as PSPropertyInfo; - CimClass cimClass = RehydrateCimClass(classMetadataProperty); - if (cimClass == null) - { - return deserializedObject; - } - CimInstance cimInstance; - try - { - cimInstance = new CimInstance(cimClass); - } - catch (CimException) - { - return deserializedObject; - } - PSObject psoCimInstance = PSObject.AsPSObject(cimInstance); + PSPropertyInfo classMetadataProperty = deserializedObject.InstanceMembers[CimClassMetadataProperty] as PSPropertyInfo; + CimClass cimClass = RehydrateCimClass(classMetadataProperty); + if (cimClass == null) + { + return deserializedObject; + } + CimInstance cimInstance; + try + { + cimInstance = new CimInstance(cimClass); + } + catch (CimException) + { + return deserializedObject; + } + PSObject psoCimInstance = PSObject.AsPSObject(cimInstance); - // process __InstanceMetadata - HashSet namesOfModifiedProperties = new HashSet(StringComparer.OrdinalIgnoreCase); - PSPropertyInfo instanceMetadataProperty = deserializedObject.InstanceMembers[CimInstanceMetadataProperty] as PSPropertyInfo; - if ((instanceMetadataProperty != null) && (instanceMetadataProperty.Value != null)) - { - PSObject instanceMetadata = PSObject.AsPSObject(instanceMetadataProperty.Value); + // process __InstanceMetadata + HashSet namesOfModifiedProperties = new HashSet(StringComparer.OrdinalIgnoreCase); + PSPropertyInfo instanceMetadataProperty = deserializedObject.InstanceMembers[CimInstanceMetadataProperty] as PSPropertyInfo; + if ((instanceMetadataProperty != null) && (instanceMetadataProperty.Value != null)) + { + PSObject instanceMetadata = PSObject.AsPSObject(instanceMetadataProperty.Value); - PSPropertyInfo modifiedPropertiesProperty = instanceMetadata.InstanceMembers[CimModifiedProperties] as PSPropertyInfo; - if ((modifiedPropertiesProperty != null) && (modifiedPropertiesProperty.Value != null)) - { - string modifiedPropertiesString = modifiedPropertiesProperty.Value.ToString(); - foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(Utils.Separators.Space)) - { - namesOfModifiedProperties.Add(nameOfModifiedProperty); - } - } - } + PSPropertyInfo modifiedPropertiesProperty = instanceMetadata.InstanceMembers[CimModifiedProperties] as PSPropertyInfo; + if ((modifiedPropertiesProperty != null) && (modifiedPropertiesProperty.Value != null)) + { + string modifiedPropertiesString = modifiedPropertiesProperty.Value.ToString(); + foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(Utils.Separators.Space)) + { + namesOfModifiedProperties.Add(nameOfModifiedProperty); + } + } + } - // process properties that were originally "adapted" properties - if (deserializedObject.adaptedMembers != null) - { - foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.adaptedMembers) - { - PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; - if (deserializedProperty == null) - { - continue; - } + // process properties that were originally "adapted" properties + if (deserializedObject.adaptedMembers != null) + { + foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.adaptedMembers) + { + PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; + if (deserializedProperty == null) + { + continue; + } - bool propertyHandledSuccessfully = RehydrateCimInstanceProperty( - cimInstance, - deserializedProperty, - namesOfModifiedProperties); + bool propertyHandledSuccessfully = RehydrateCimInstanceProperty( + cimInstance, + deserializedProperty, + namesOfModifiedProperties); - if (!propertyHandledSuccessfully) - { - return deserializedObject; - } - } - } + if (!propertyHandledSuccessfully) + { + return deserializedObject; + } + } + } - // process properties that were originally "extended" properties - foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.InstanceMembers) - { - PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; - if (deserializedProperty == null) - { - continue; - } + // process properties that were originally "extended" properties + foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.InstanceMembers) + { + PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; + if (deserializedProperty == null) + { + continue; + } - // skip adapted properties - if ((deserializedObject.adaptedMembers != null) && (deserializedObject.adaptedMembers[deserializedProperty.Name] != null)) - { - continue; - } + // skip adapted properties + if ((deserializedObject.adaptedMembers != null) && (deserializedObject.adaptedMembers[deserializedProperty.Name] != null)) + { + continue; + } - // skip metadata introduced by CliXml/CimInstance serialization - if (deserializedProperty.Name.Equals(CimClassMetadataProperty, StringComparison.OrdinalIgnoreCase)) - { - continue; - } + // skip metadata introduced by CliXml/CimInstance serialization + if (deserializedProperty.Name.Equals(CimClassMetadataProperty, StringComparison.OrdinalIgnoreCase)) + { + continue; + } - // skip properties re-added by the client (i.e. through types.ps1xml) - if (psoCimInstance.Properties[deserializedProperty.Name] != null) - { - continue; - } + // skip properties re-added by the client (i.e. through types.ps1xml) + if (psoCimInstance.Properties[deserializedProperty.Name] != null) + { + continue; + } - PSNoteProperty noteProperty = new PSNoteProperty(deserializedProperty.Name, deserializedProperty.Value); - psoCimInstance.Properties.Add(noteProperty); - } + PSNoteProperty noteProperty = new PSNoteProperty(deserializedProperty.Name, deserializedProperty.Value); + psoCimInstance.Properties.Add(noteProperty); + } - return psoCimInstance; - } + return psoCimInstance; + } - /// - /// Reads one object. At this point reader should be positioned - /// at the start tag of object. - /// - /// - /// Deserialized Object. - /// - internal object ReadOneObject(out string streamName) - { - this.CheckIfStopping(); + /// + /// Reads one object. At this point reader should be positioned + /// at the start tag of object. + /// + /// + /// Deserialized Object. + /// + internal object ReadOneObject(out string streamName) + { + this.CheckIfStopping(); - try - { - this.depthBelowTopLevel++; + try + { + _depthBelowTopLevel++; - Dbg.Assert(this.depthBelowTopLevel <= MaxDepthBelowTopLevel, "depthBelowTopLevel should be <= MaxDepthBelowTopLevel"); - if (this.depthBelowTopLevel == MaxDepthBelowTopLevel) - { - throw NewXmlException(Serialization.DeserializationTooDeep, null); - } + Dbg.Assert(_depthBelowTopLevel <= MaxDepthBelowTopLevel, "depthBelowTopLevel should be <= MaxDepthBelowTopLevel"); + if (_depthBelowTopLevel == MaxDepthBelowTopLevel) + { + throw NewXmlException(Serialization.DeserializationTooDeep, null); + } - bool isKnownPrimitiveType; - object result = ReadOneDeserializedObject(out streamName, out isKnownPrimitiveType); - if (null == result) - { - return null; - } + bool isKnownPrimitiveType; + object result = ReadOneDeserializedObject(out streamName, out isKnownPrimitiveType); + if (null == result) + { + return null; + } - if (!isKnownPrimitiveType) - { - PSObject mshSource = PSObject.AsPSObject(result); - if (Deserializer.IsDeserializedInstanceOfType(mshSource, typeof (CimInstance))) - { - return RehydrateCimInstance(mshSource); - } + if (!isKnownPrimitiveType) + { + PSObject mshSource = PSObject.AsPSObject(result); + if (Deserializer.IsDeserializedInstanceOfType(mshSource, typeof(CimInstance))) + { + return RehydrateCimInstance(mshSource); + } - // Convert deserialized object to a user-defined type (specified in a types.ps1xml file) - Type targetType = mshSource.GetTargetTypeForDeserialization(_typeTable); - if (null != targetType) - { - Exception rehydrationException = null; - try - { - object rehydratedResult = LanguagePrimitives.ConvertTo( - result, targetType, true /* recurse */, CultureInfo.InvariantCulture, _typeTable); + // Convert deserialized object to a user-defined type (specified in a types.ps1xml file) + Type targetType = mshSource.GetTargetTypeForDeserialization(_typeTable); + if (null != targetType) + { + Exception rehydrationException = null; + try + { + object rehydratedResult = LanguagePrimitives.ConvertTo( + result, targetType, true /* recurse */, CultureInfo.InvariantCulture, _typeTable); - PSEtwLog.LogAnalyticVerbose(PSEventId.Serializer_RehydrationSuccess, - PSOpcode.Rehydration, PSTask.Serialization, PSKeyword.Serializer, - mshSource.InternalTypeNames.Key, targetType.FullName, - rehydratedResult.GetType().FullName); + PSEtwLog.LogAnalyticVerbose(PSEventId.Serializer_RehydrationSuccess, + PSOpcode.Rehydration, PSTask.Serialization, PSKeyword.Serializer, + mshSource.InternalTypeNames.Key, targetType.FullName, + rehydratedResult.GetType().FullName); - return rehydratedResult; - } - catch (InvalidCastException e) - { - rehydrationException = e; - } - catch (ArgumentException e) - { - rehydrationException = e; - } + return rehydratedResult; + } + catch (InvalidCastException e) + { + rehydrationException = e; + } + catch (ArgumentException e) + { + rehydrationException = e; + } - Dbg.Assert(rehydrationException != null, - "The only way to get here is with rehydrationException != null"); + Dbg.Assert(rehydrationException != null, + "The only way to get here is with rehydrationException != null"); - PSEtwLog.LogAnalyticError(PSEventId.Serializer_RehydrationFailure, - PSOpcode.Rehydration, PSTask.Serialization, PSKeyword.Serializer, - mshSource.InternalTypeNames.Key, - targetType.FullName, - rehydrationException.ToString(), - rehydrationException.InnerException == null - ? string.Empty - : rehydrationException.InnerException.ToString()); - } - } + PSEtwLog.LogAnalyticError(PSEventId.Serializer_RehydrationFailure, + PSOpcode.Rehydration, PSTask.Serialization, PSKeyword.Serializer, + mshSource.InternalTypeNames.Key, + targetType.FullName, + rehydrationException.ToString(), + rehydrationException.InnerException == null + ? string.Empty + : rehydrationException.InnerException.ToString()); + } + } - return result; - } - finally - { - this.depthBelowTopLevel--; - Dbg.Assert(this.depthBelowTopLevel >= 0, "depthBelowTopLevel should be >= 0"); - } - } + return result; + } + finally + { + _depthBelowTopLevel--; + Dbg.Assert(_depthBelowTopLevel >= 0, "depthBelowTopLevel should be >= 0"); + } + } - private object ReadOneObject() - { - string ignore; - return ReadOneObject(out ignore); - } + private object ReadOneObject() + { + string ignore; + return ReadOneObject(out ignore); + } - //Reads one PSObject - private PSObject ReadPSObject() - { - PSObject dso = ReadAttributeAndCreatePSObject(); + //Reads one PSObject + private PSObject ReadPSObject() + { + PSObject dso = ReadAttributeAndCreatePSObject(); - //Read start element tag - if (ReadStartElementAndHandleEmpty(SerializationStrings.PSObjectTag) == false) - { - //Empty element. - return dso; - } + //Read start element tag + if (ReadStartElementAndHandleEmpty(SerializationStrings.PSObjectTag) == false) + { + //Empty element. + return dso; + } - bool overrideTypeInfo = true; - //Process all the child nodes - while (_reader.NodeType == XmlNodeType.Element) - { - if (IsNextElement(SerializationStrings.TypeNamesTag) || - IsNextElement(SerializationStrings.TypeNamesReferenceTag)) - { - ReadTypeNames(dso); - overrideTypeInfo = false; - } - else if (IsNextElement(SerializationStrings.AdapterProperties)) - { - ReadProperties(dso); - } - else if (IsNextElement(SerializationStrings.MemberSet)) - { - ReadMemberSet(dso.InstanceMembers); - } - else if (IsNextElement(SerializationStrings.ToStringElementTag)) - { - dso.ToStringFromDeserialization = ReadDecodedElementString(SerializationStrings.ToStringElementTag); - dso.InstanceMembers.Add(PSObject.dotNetInstanceAdapter.GetDotNetMethod(dso, "ToString")); - PSGetMemberBinder.SetHasInstanceMember("ToString"); - // Fix for Win8:75437 - // The TokenText property is used in type conversion and it is not being populated during deserialization - // As a result, parameter binding fails in the following case on a remote session - // register-psssessionconfiguration -Name foo -psversion 3.0 - // The value "3.0" is treated as a double and since the TokenText property holds null, the type converter tries to convert - // from System.Double to System.Version using Parse method of System.Version and fails - dso.TokenText = dso.ToStringFromDeserialization; - } - else - { - //Handle BaseObject - object baseObject = null; - ContainerType ct = ContainerType.None; + bool overrideTypeInfo = true; + //Process all the child nodes + while (_reader.NodeType == XmlNodeType.Element) + { + if (IsNextElement(SerializationStrings.TypeNamesTag) || + IsNextElement(SerializationStrings.TypeNamesReferenceTag)) + { + ReadTypeNames(dso); + overrideTypeInfo = false; + } + else if (IsNextElement(SerializationStrings.AdapterProperties)) + { + ReadProperties(dso); + } + else if (IsNextElement(SerializationStrings.MemberSet)) + { + ReadMemberSet(dso.InstanceMembers); + } + else if (IsNextElement(SerializationStrings.ToStringElementTag)) + { + dso.ToStringFromDeserialization = ReadDecodedElementString(SerializationStrings.ToStringElementTag); + dso.InstanceMembers.Add(PSObject.dotNetInstanceAdapter.GetDotNetMethod(dso, "ToString")); + PSGetMemberBinder.SetHasInstanceMember("ToString"); + // Fix for Win8:75437 + // The TokenText property is used in type conversion and it is not being populated during deserialization + // As a result, parameter binding fails in the following case on a remote session + // register-psssessionconfiguration -Name foo -psversion 3.0 + // The value "3.0" is treated as a double and since the TokenText property holds null, the type converter tries to convert + // from System.Double to System.Version using Parse method of System.Version and fails + dso.TokenText = dso.ToStringFromDeserialization; + } + else + { + //Handle BaseObject + object baseObject = null; + ContainerType ct = ContainerType.None; - //Check if tag is PrimaryKnownType. - TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); - if (pktInfo != null) - { - _trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); - baseObject = ReadPrimaryKnownType(pktInfo); - } - else if (IsKnownContainerTag(out ct)) - { - _trace.WriteLine("Found container node {0}", ct); - baseObject = ReadKnownContainer(ct); - } - else if (IsNextElement(SerializationStrings.PSObjectTag)) - { - _trace.WriteLine("Found PSObject node"); - baseObject = ReadOneObject(); - } - else - { - //We have an unknwon tag - _trace.WriteLine("Unknwon tag {0} encountered", _reader.LocalName); - if (UnknownTagsAllowed) - { - Skip(); - } - else - { - throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); - } - } - if (baseObject != null) - { - dso.SetCoreOnDeserialization(baseObject, overrideTypeInfo); - } - } - } + //Check if tag is PrimaryKnownType. + TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); + if (pktInfo != null) + { + s_trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); + baseObject = ReadPrimaryKnownType(pktInfo); + } + else if (IsKnownContainerTag(out ct)) + { + s_trace.WriteLine("Found container node {0}", ct); + baseObject = ReadKnownContainer(ct); + } + else if (IsNextElement(SerializationStrings.PSObjectTag)) + { + s_trace.WriteLine("Found PSObject node"); + baseObject = ReadOneObject(); + } + else + { + //We have an unknwon tag + s_trace.WriteLine("Unknwon tag {0} encountered", _reader.LocalName); + if (UnknownTagsAllowed) + { + Skip(); + } + else + { + throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); + } + } + if (baseObject != null) + { + dso.SetCoreOnDeserialization(baseObject, overrideTypeInfo); + } + } + } - ReadEndElement(); + ReadEndElement(); - PSObject immediateBasePso = dso.ImmediateBaseObject as PSObject; - if (immediateBasePso != null) - { - PSObject.CopyDeserializerFields(source: immediateBasePso, target: dso); - } + PSObject immediateBasePso = dso.ImmediateBaseObject as PSObject; + if (immediateBasePso != null) + { + PSObject.CopyDeserializerFields(source: immediateBasePso, target: dso); + } - return dso; - } + return dso; + } - /// - /// This function reads the refId attribute and creates a - /// mshObject for that attribute - /// - /// mshObject which is created for refId - private PSObject ReadAttributeAndCreatePSObject() - { - string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); - PSObject sh = new PSObject(); + /// + /// This function reads the refId attribute and creates a + /// mshObject for that attribute + /// + /// mshObject which is created for refId + private PSObject ReadAttributeAndCreatePSObject() + { + string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); + PSObject sh = new PSObject(); - //RefId is not mandatory attribute - if (refId != null) - { - _trace.WriteLine("Read PSObject with refId: {0}", refId); - this.objectRefIdHandler.SetRefId(sh, refId, this.DuplicateRefIdsAllowed); - } - return sh; - } + //RefId is not mandatory attribute + if (refId != null) + { + s_trace.WriteLine("Read PSObject with refId: {0}", refId); + _objectRefIdHandler.SetRefId(sh, refId, this.DuplicateRefIdsAllowed); + } + return sh; + } - /// - /// Read type names - /// - /// - /// PSObject to which TypeNames are added - /// - private void ReadTypeNames(PSObject dso) - { - Dbg.Assert(dso != null, "caller should validate the parameter"); - Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "NodeType should be Element"); + /// + /// Read type names + /// + /// + /// PSObject to which TypeNames are added + /// + private void ReadTypeNames(PSObject dso) + { + Dbg.Assert(dso != null, "caller should validate the parameter"); + Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "NodeType should be Element"); - if (IsNextElement(SerializationStrings.TypeNamesTag)) - { - Collection typeNames = new Collection(); + if (IsNextElement(SerializationStrings.TypeNamesTag)) + { + Collection typeNames = new Collection(); - //Read refId attribute if available - string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); + //Read refId attribute if available + string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); - _trace.WriteLine("Processing TypeNamesTag with refId {0}", refId); + s_trace.WriteLine("Processing TypeNamesTag with refId {0}", refId); - if (ReadStartElementAndHandleEmpty(SerializationStrings.TypeNamesTag)) - { - while (_reader.NodeType == XmlNodeType.Element) - { - if (IsNextElement(SerializationStrings.TypeNamesItemTag)) - { - string item = ReadDecodedElementString(SerializationStrings.TypeNamesItemTag); - if (!string.IsNullOrEmpty(item)) - { - Deserializer.AddDeserializationPrefix(ref item); - typeNames.Add(item); - } - } - else - { - throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); - } - } - ReadEndElement(); - } - dso.InternalTypeNames = new ConsolidatedString(typeNames); + if (ReadStartElementAndHandleEmpty(SerializationStrings.TypeNamesTag)) + { + while (_reader.NodeType == XmlNodeType.Element) + { + if (IsNextElement(SerializationStrings.TypeNamesItemTag)) + { + string item = ReadDecodedElementString(SerializationStrings.TypeNamesItemTag); + if (!string.IsNullOrEmpty(item)) + { + Deserializer.AddDeserializationPrefix(ref item); + typeNames.Add(item); + } + } + else + { + throw NewXmlException(Serialization.InvalidElementTag, null, _reader.LocalName); + } + } + ReadEndElement(); + } + dso.InternalTypeNames = new ConsolidatedString(typeNames); - if (refId != null) - { - this.typeRefIdHandler.SetRefId(dso.InternalTypeNames, refId, this.DuplicateRefIdsAllowed); - } - } - else if (IsNextElement(SerializationStrings.TypeNamesReferenceTag)) - { - string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); - _trace.WriteLine("Processing TypeNamesReferenceTag with refId {0}", refId); - if (refId == null) - { - throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); - } + if (refId != null) + { + _typeRefIdHandler.SetRefId(dso.InternalTypeNames, refId, this.DuplicateRefIdsAllowed); + } + } + else if (IsNextElement(SerializationStrings.TypeNamesReferenceTag)) + { + string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); + s_trace.WriteLine("Processing TypeNamesReferenceTag with refId {0}", refId); + if (refId == null) + { + throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); + } - ConsolidatedString typeNames = this.typeRefIdHandler.GetReferencedObject(refId); - if (typeNames == null) - { - throw NewXmlException(Serialization.InvalidTypeHierarchyReferenceId, null, refId); - } + ConsolidatedString typeNames = _typeRefIdHandler.GetReferencedObject(refId); + if (typeNames == null) + { + throw NewXmlException(Serialization.InvalidTypeHierarchyReferenceId, null, refId); + } - // At this point we know that we will clone the ConsolidatedString object, so we might end up - // allocating much more memory than the length of the xml string - // We have to account for that to limit that to remoting quota and protect against OOM. - _context.LogExtraMemoryUsage( - typeNames.Key.Length * sizeof(char) // Key is shared among the cloned and original object - // but the list of strings isn't. The expression to the left - // is roughly the size of memory the list of strings occupies - - 29 // size of in UTF8 encoding - ); - dso.InternalTypeNames = new ConsolidatedString(typeNames); + // At this point we know that we will clone the ConsolidatedString object, so we might end up + // allocating much more memory than the length of the xml string + // We have to account for that to limit that to remoting quota and protect against OOM. + _context.LogExtraMemoryUsage( + typeNames.Key.Length * sizeof(char) // Key is shared among the cloned and original object + // but the list of strings isn't. The expression to the left + // is roughly the size of memory the list of strings occupies + - 29 // size of in UTF8 encoding + ); + dso.InternalTypeNames = new ConsolidatedString(typeNames); - //Skip the node - Skip(); - } - else - { - Dbg.Assert(false, "caller should validate that we do no reach here"); - } - } + //Skip the node + Skip(); + } + else + { + Dbg.Assert(false, "caller should validate that we do no reach here"); + } + } /// /// Read properties @@ -3788,356 +3784,356 @@ namespace System.Management.Automation } } - #region memberset + #region memberset - /// - /// Read memberset. - /// - /// - /// collection to which members are added - /// - private void ReadMemberSet(PSMemberInfoCollection collection) - { - Dbg.Assert(collection != null, "caller should validate the value"); + /// + /// Read memberset. + /// + /// + /// collection to which members are added + /// + private void ReadMemberSet(PSMemberInfoCollection collection) + { + Dbg.Assert(collection != null, "caller should validate the value"); - if (ReadStartElementAndHandleEmpty(SerializationStrings.MemberSet)) - { - while (_reader.NodeType == XmlNodeType.Element) - { - if (IsNextElement(SerializationStrings.MemberSet)) - { - string name = ReadNameAttribute(); - PSMemberSet set = new PSMemberSet(name); - collection.Add(set); - ReadMemberSet(set.Members); + if (ReadStartElementAndHandleEmpty(SerializationStrings.MemberSet)) + { + while (_reader.NodeType == XmlNodeType.Element) + { + if (IsNextElement(SerializationStrings.MemberSet)) + { + string name = ReadNameAttribute(); + PSMemberSet set = new PSMemberSet(name); + collection.Add(set); + ReadMemberSet(set.Members); - PSGetMemberBinder.SetHasInstanceMember(name); - } - else - { - PSNoteProperty note = ReadNoteProperty(); - collection.Add(note); + PSGetMemberBinder.SetHasInstanceMember(name); + } + else + { + PSNoteProperty note = ReadNoteProperty(); + collection.Add(note); - PSGetMemberBinder.SetHasInstanceMember(note.Name); - } - } + PSGetMemberBinder.SetHasInstanceMember(note.Name); + } + } - ReadEndElement(); - } - } + ReadEndElement(); + } + } - /// - /// read note - /// - /// - private PSNoteProperty ReadNoteProperty() - { - string name = ReadNameAttribute(); - object value = ReadOneObject(); - PSNoteProperty note = new PSNoteProperty(name, value); - return note; - } + /// + /// read note + /// + /// + private PSNoteProperty ReadNoteProperty() + { + string name = ReadNameAttribute(); + object value = ReadOneObject(); + PSNoteProperty note = new PSNoteProperty(name, value); + return note; + } - #endregion memberset + #endregion memberset - #region known container + #region known container - private bool IsKnownContainerTag(out ContainerType ct) - { - Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "Expected node type is element"); + private bool IsKnownContainerTag(out ContainerType ct) + { + Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "Expected node type is element"); - if (IsNextElement(SerializationStrings.DictionaryTag)) - { - ct = ContainerType.Dictionary; - } - else if (IsNextElement(SerializationStrings.QueueTag)) - { - ct = ContainerType.Queue; - } - else if (IsNextElement(SerializationStrings.StackTag)) - { - ct = ContainerType.Stack; - } - else if (IsNextElement(SerializationStrings.ListTag)) - { - ct = ContainerType.List; - } - else if (IsNextElement(SerializationStrings.CollectionTag)) - { - ct = ContainerType.Enumerable; - } - else - { - ct = ContainerType.None; - } + if (IsNextElement(SerializationStrings.DictionaryTag)) + { + ct = ContainerType.Dictionary; + } + else if (IsNextElement(SerializationStrings.QueueTag)) + { + ct = ContainerType.Queue; + } + else if (IsNextElement(SerializationStrings.StackTag)) + { + ct = ContainerType.Stack; + } + else if (IsNextElement(SerializationStrings.ListTag)) + { + ct = ContainerType.List; + } + else if (IsNextElement(SerializationStrings.CollectionTag)) + { + ct = ContainerType.Enumerable; + } + else + { + ct = ContainerType.None; + } - return ct != ContainerType.None; - } + return ct != ContainerType.None; + } - private object ReadKnownContainer(ContainerType ct) - { - switch (ct) - { - case ContainerType.Dictionary: - return ReadDictionary(ct); + private object ReadKnownContainer(ContainerType ct) + { + switch (ct) + { + case ContainerType.Dictionary: + return ReadDictionary(ct); - case ContainerType.Enumerable: - case ContainerType.List: - case ContainerType.Queue: - case ContainerType.Stack: - return ReadListContainer(ct); + case ContainerType.Enumerable: + case ContainerType.List: + case ContainerType.Queue: + case ContainerType.Stack: + return ReadListContainer(ct); - default: - Dbg.Assert(false, "Unrecognized ContainerType enum"); - return null; - } - } + default: + Dbg.Assert(false, "Unrecognized ContainerType enum"); + return null; + } + } - /// - /// Read List Containers - /// - /// - private object ReadListContainer(ContainerType ct) - { - Dbg.Assert(ct == ContainerType.Enumerable || - ct == ContainerType.List || - ct == ContainerType.Queue || - ct == ContainerType.Stack, "ct should be queue, stack, enumberable or list"); + /// + /// Read List Containers + /// + /// + private object ReadListContainer(ContainerType ct) + { + Dbg.Assert(ct == ContainerType.Enumerable || + ct == ContainerType.List || + ct == ContainerType.Queue || + ct == ContainerType.Stack, "ct should be queue, stack, enumberable or list"); ArrayList list = new ArrayList(); - if (ReadStartElementAndHandleEmpty(_reader.LocalName)) - { - while (_reader.NodeType == XmlNodeType.Element) - { - list.Add(ReadOneObject()); - } - ReadEndElement(); - } - if (ct == ContainerType.Stack) - { - list.Reverse(); - return new Stack(list); - } - else if (ct == ContainerType.Queue) - { + if (ReadStartElementAndHandleEmpty(_reader.LocalName)) + { + while (_reader.NodeType == XmlNodeType.Element) + { + list.Add(ReadOneObject()); + } + ReadEndElement(); + } + if (ct == ContainerType.Stack) + { + list.Reverse(); + return new Stack(list); + } + else if (ct == ContainerType.Queue) + { return new Queue(list); - } - return list; - } + } + return list; + } - /// - /// Deserialize Dictionary - /// - /// - private object ReadDictionary(ContainerType ct) - { - Dbg.Assert(ct == ContainerType.Dictionary, "Unrecognized ContainerType enum"); + /// + /// Deserialize Dictionary + /// + /// + private object ReadDictionary(ContainerType ct) + { + Dbg.Assert(ct == ContainerType.Dictionary, "Unrecognized ContainerType enum"); - // We assume the hash table is a PowerShell hash table and hence uses - // a case insensitive string comparer. If we discover a key collision, - // we'll revert back to the default comparer. - Hashtable table = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - int keyClashFoundIteration = 0; - if (ReadStartElementAndHandleEmpty(SerializationStrings.DictionaryTag)) - { - while (_reader.NodeType == XmlNodeType.Element) - { - ReadStartElement(SerializationStrings.DictionaryEntryTag); + // We assume the hash table is a PowerShell hash table and hence uses + // a case insensitive string comparer. If we discover a key collision, + // we'll revert back to the default comparer. + Hashtable table = new Hashtable(StringComparer.CurrentCultureIgnoreCase); + int keyClashFoundIteration = 0; + if (ReadStartElementAndHandleEmpty(SerializationStrings.DictionaryTag)) + { + while (_reader.NodeType == XmlNodeType.Element) + { + ReadStartElement(SerializationStrings.DictionaryEntryTag); - //Read Key - if (_reader.NodeType != XmlNodeType.Element) - { - throw NewXmlException(Serialization.DictionaryKeyNotSpecified, null); - } - string name = ReadNameAttribute(); - if (string.Compare(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase) != 0) - { - throw NewXmlException(Serialization.InvalidDictionaryKeyName, null); - } - object key = ReadOneObject(); + //Read Key + if (_reader.NodeType != XmlNodeType.Element) + { + throw NewXmlException(Serialization.DictionaryKeyNotSpecified, null); + } + string name = ReadNameAttribute(); + if (string.Compare(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase) != 0) + { + throw NewXmlException(Serialization.InvalidDictionaryKeyName, null); + } + object key = ReadOneObject(); - if (key == null) - { - throw NewXmlException(Serialization.NullAsDictionaryKey, null); - } - //Read Value - if (_reader.NodeType != XmlNodeType.Element) - { - throw NewXmlException(Serialization.DictionaryValueNotSpecified, null); - } - name = ReadNameAttribute(); - if (string.Compare(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase) != 0) - { - throw NewXmlException(Serialization.InvalidDictionaryValueName, null); - } - object value = ReadOneObject(); + if (key == null) + { + throw NewXmlException(Serialization.NullAsDictionaryKey, null); + } + //Read Value + if (_reader.NodeType != XmlNodeType.Element) + { + throw NewXmlException(Serialization.DictionaryValueNotSpecified, null); + } + name = ReadNameAttribute(); + if (string.Compare(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase) != 0) + { + throw NewXmlException(Serialization.InvalidDictionaryValueName, null); + } + object value = ReadOneObject(); - // On the first collision, copy the hash table to one that uses the default comparer. - if (table.ContainsKey(key) && (keyClashFoundIteration == 0)) - { - keyClashFoundIteration++; - Hashtable newHashTable = new Hashtable(); - foreach (DictionaryEntry entry in table) - { - newHashTable.Add(entry.Key, entry.Value); - } + // On the first collision, copy the hash table to one that uses the default comparer. + if (table.ContainsKey(key) && (keyClashFoundIteration == 0)) + { + keyClashFoundIteration++; + Hashtable newHashTable = new Hashtable(); + foreach (DictionaryEntry entry in table) + { + newHashTable.Add(entry.Key, entry.Value); + } - table = newHashTable; - } + table = newHashTable; + } - // win8: 389060. If there are still collisions even with case-sensitive default comparer, - // use an IEqualityComparer that does object ref equality. - if (table.ContainsKey(key) && (keyClashFoundIteration == 1)) - { - keyClashFoundIteration++; - IEqualityComparer equalityComparer = new ReferenceEqualityComparer(); - Hashtable newHashTable = new Hashtable(equalityComparer); - foreach (DictionaryEntry entry in table) - { - newHashTable.Add(entry.Key, entry.Value); - } + // win8: 389060. If there are still collisions even with case-sensitive default comparer, + // use an IEqualityComparer that does object ref equality. + if (table.ContainsKey(key) && (keyClashFoundIteration == 1)) + { + keyClashFoundIteration++; + IEqualityComparer equalityComparer = new ReferenceEqualityComparer(); + Hashtable newHashTable = new Hashtable(equalityComparer); + foreach (DictionaryEntry entry in table) + { + newHashTable.Add(entry.Key, entry.Value); + } - table = newHashTable; - } + table = newHashTable; + } - try - { - //Add entry to hashtable - table.Add(key, value); - } - catch (ArgumentException e) - { - throw this.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(Hashtable)); - } + try + { + //Add entry to hashtable + table.Add(key, value); + } + catch (ArgumentException e) + { + throw this.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(Hashtable)); + } - ReadEndElement(); - } - ReadEndElement(); - } + ReadEndElement(); + } + ReadEndElement(); + } - return table; - } + return table; + } - #endregion known containers + #endregion known containers - #endregion deserialization + #endregion deserialization - #region Getting XmlReaderSettings + #region Getting XmlReaderSettings - static private readonly XmlReaderSettings xmlReaderSettingsForCliXml = GetXmlReaderSettingsForCliXml(); - static internal XmlReaderSettings XmlReaderSettingsForCliXml - { - get { return xmlReaderSettingsForCliXml; } - } + static private readonly XmlReaderSettings s_xmlReaderSettingsForCliXml = GetXmlReaderSettingsForCliXml(); + static internal XmlReaderSettings XmlReaderSettingsForCliXml + { + get { return s_xmlReaderSettingsForCliXml; } + } - static private XmlReaderSettings GetXmlReaderSettingsForCliXml() - { - XmlReaderSettings xrs = new XmlReaderSettings(); + static private XmlReaderSettings GetXmlReaderSettingsForCliXml() + { + XmlReaderSettings xrs = new XmlReaderSettings(); - xrs.CheckCharacters = false; - xrs.CloseInput = false; + xrs.CheckCharacters = false; + xrs.CloseInput = false; - //The XML data needs to be in conformance to the rules for a well-formed XML 1.0 document. - xrs.ConformanceLevel = ConformanceLevel.Document; - xrs.IgnoreComments = true; - xrs.IgnoreProcessingInstructions = true; - xrs.IgnoreWhitespace = false; - xrs.MaxCharactersFromEntities = 1024; - //xrs.DtdProcessing = DtdProcessing.Prohibit; //because system.management.automation needs to build as 2.0 - //xrs.ProhibitDtd = true; + //The XML data needs to be in conformance to the rules for a well-formed XML 1.0 document. + xrs.ConformanceLevel = ConformanceLevel.Document; + xrs.IgnoreComments = true; + xrs.IgnoreProcessingInstructions = true; + xrs.IgnoreWhitespace = false; + xrs.MaxCharactersFromEntities = 1024; + //xrs.DtdProcessing = DtdProcessing.Prohibit; //because system.management.automation needs to build as 2.0 + //xrs.ProhibitDtd = true; #if !CORECLR // XmlReaderSettings.Schemas/ValidationFlags/ValidationType/XmlResolver Not In CoreCLR - xrs.Schemas = null; - xrs.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; - xrs.ValidationType = ValidationType.None; - xrs.XmlResolver = null; + xrs.Schemas = null; + xrs.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; + xrs.ValidationType = ValidationType.None; + xrs.XmlResolver = null; #endif - return xrs; - } + return xrs; + } - static private readonly XmlReaderSettings xmlReaderSettingsForUntrustedXmlDocument = GetXmlReaderSettingsForUntrustedXmlDocument(); - static internal XmlReaderSettings XmlReaderSettingsForUntrustedXmlDocument - { - get { return xmlReaderSettingsForUntrustedXmlDocument; } - } + static private readonly XmlReaderSettings s_xmlReaderSettingsForUntrustedXmlDocument = GetXmlReaderSettingsForUntrustedXmlDocument(); + static internal XmlReaderSettings XmlReaderSettingsForUntrustedXmlDocument + { + get { return s_xmlReaderSettingsForUntrustedXmlDocument; } + } - static private XmlReaderSettings GetXmlReaderSettingsForUntrustedXmlDocument() - { - XmlReaderSettings settings = new XmlReaderSettings(); + static private XmlReaderSettings GetXmlReaderSettingsForUntrustedXmlDocument() + { + XmlReaderSettings settings = new XmlReaderSettings(); - settings.CheckCharacters = false; - settings.ConformanceLevel = ConformanceLevel.Auto; - settings.IgnoreComments = true; - settings.IgnoreProcessingInstructions = true; - settings.IgnoreWhitespace = true; - settings.MaxCharactersFromEntities = 1024; - settings.MaxCharactersInDocument = 512 * 1024 * 1024; // 512M characters = 1GB + settings.CheckCharacters = false; + settings.ConformanceLevel = ConformanceLevel.Auto; + settings.IgnoreComments = true; + settings.IgnoreProcessingInstructions = true; + settings.IgnoreWhitespace = true; + settings.MaxCharactersFromEntities = 1024; + settings.MaxCharactersInDocument = 512 * 1024 * 1024; // 512M characters = 1GB #if CORECLR // DtdProcessing.Parse Not In CoreCLR settings.DtdProcessing = DtdProcessing.Ignore; #else // XmlReaderSettings.ValidationFlags/ValidationType/XmlResolver Not In CoreCLR settings.DtdProcessing = DtdProcessing.Parse; // Allowing DTD parsing with limits of MaxCharactersFromEntities/MaxCharactersInDocument - settings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; - settings.ValidationType = ValidationType.None; - settings.XmlResolver = null; + settings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; + settings.ValidationType = ValidationType.None; + settings.XmlResolver = null; #endif - return settings; - } + return settings; + } - #endregion + #endregion - #region known type deserialization + #region known type deserialization - internal static object DeserializeBoolean(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - try - { + internal static object DeserializeBoolean(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + try + { return XmlConvert.ToBoolean(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(bool).FullName); - } - } + } + catch (FormatException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(bool).FullName); + } + } - internal static object DeserializeByte(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeByte(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToByte(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(byte).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(byte).FullName); + } - internal static object DeserializeChar(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeChar(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return (Char)XmlConvert.ToUInt16(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(char).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(char).FullName); + } internal static object DeserializeDateTime(InternalDeserializer deserializer) { @@ -4152,1143 +4148,1142 @@ namespace System.Management.Automation } } - internal static object DeserializeDecimal(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeDecimal(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToDecimal(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(decimal).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(decimal).FullName); + } - internal static object DeserializeDouble(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeDouble(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToDouble(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(double).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(double).FullName); + } - internal static object DeserializeGuid(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeGuid(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToGuid(deserializer._reader.ReadElementContentAsString()); - } - // MSDN for XmlConvert.ToGuid doesn't list any exceptions, but - // Reflector shows that this just calls to new Guid(string) - // which MSDN documents can throw Format/OverflowException - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Guid).FullName); - } + } + // MSDN for XmlConvert.ToGuid doesn't list any exceptions, but + // Reflector shows that this just calls to new Guid(string) + // which MSDN documents can throw Format/OverflowException + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Guid).FullName); + } - internal static object DeserializeVersion(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeVersion(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return new Version(deserializer._reader.ReadElementContentAsString()); - } - catch (ArgumentException e) - { - recognizedException = e; - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Version).FullName); - } + } + catch (ArgumentException e) + { + recognizedException = e; + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Version).FullName); + } - internal static object DeserializeInt16(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeInt16(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToInt16(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int16).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int16).FullName); + } - internal static object DeserializeInt32(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeInt32(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToInt32(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int32).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int32).FullName); + } - internal static object DeserializeInt64(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeInt64(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToInt64(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int64).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(Int64).FullName); + } - internal static object DeserializeSByte(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeSByte(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToSByte(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(sbyte).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(sbyte).FullName); + } - internal static object DeserializeSingle(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeSingle(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToSingle(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(float).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(float).FullName); + } - internal static object DeserializeScriptBlock(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - string scriptBlockBody = deserializer.ReadDecodedElementString(SerializationStrings.ScriptBlockTag); - if (DeserializationOptions.DeserializeScriptBlocks == (deserializer._context.options & DeserializationOptions.DeserializeScriptBlocks)) - { - return ScriptBlock.Create(scriptBlockBody); - } - else - { - //Scriptblock is deserialized as string - return scriptBlockBody; - } - } + internal static object DeserializeScriptBlock(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + string scriptBlockBody = deserializer.ReadDecodedElementString(SerializationStrings.ScriptBlockTag); + if (DeserializationOptions.DeserializeScriptBlocks == (deserializer._context.options & DeserializationOptions.DeserializeScriptBlocks)) + { + return ScriptBlock.Create(scriptBlockBody); + } + else + { + //Scriptblock is deserialized as string + return scriptBlockBody; + } + } - internal static object DeserializeString(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - return deserializer.ReadDecodedElementString(SerializationStrings.StringTag); - } + internal static object DeserializeString(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + return deserializer.ReadDecodedElementString(SerializationStrings.StringTag); + } - static internal object DeserializeTimeSpan(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - try - { + static internal object DeserializeTimeSpan(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + try + { return XmlConvert.ToTimeSpan(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(TimeSpan).FullName); - } - } + } + catch (FormatException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(TimeSpan).FullName); + } + } - internal static object DeserializeUInt16(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeUInt16(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToUInt16(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt16).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt16).FullName); + } - internal static object DeserializeUInt32(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeUInt32(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToUInt32(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt32).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt32).FullName); + } - internal static object DeserializeUInt64(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - Exception recognizedException = null; - try - { + internal static object DeserializeUInt64(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Exception recognizedException = null; + try + { return XmlConvert.ToUInt64(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); - } + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); + } - internal static object DeserializeUri(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - try - { - string uriString = deserializer.ReadDecodedElementString(SerializationStrings.AnyUriTag); - return new Uri(uriString, UriKind.RelativeOrAbsolute); - } - catch (UriFormatException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(Uri).FullName); - } - } + internal static object DeserializeUri(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + try + { + string uriString = deserializer.ReadDecodedElementString(SerializationStrings.AnyUriTag); + return new Uri(uriString, UriKind.RelativeOrAbsolute); + } + catch (UriFormatException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(Uri).FullName); + } + } - internal static object DeserializeByteArray(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - try - { + internal static object DeserializeByteArray(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + try + { return Convert.FromBase64String(deserializer._reader.ReadElementContentAsString()); - } - catch (FormatException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(byte[]).FullName); - } - } + } + catch (FormatException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(byte[]).FullName); + } + } - /// - internal static XmlDocument LoadUnsafeXmlDocument(FileInfo xmlPath, bool preserveNonElements, int? maxCharactersInDocument) - { - XmlDocument doc = null; - // same FileStream options as Reflector shows for XmlDocument.Load(path) / XmlDownloadManager.GetStream: - using (Stream stream = new FileStream(xmlPath.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - doc = LoadUnsafeXmlDocument(stream, preserveNonElements, maxCharactersInDocument); - } + /// + internal static XmlDocument LoadUnsafeXmlDocument(FileInfo xmlPath, bool preserveNonElements, int? maxCharactersInDocument) + { + XmlDocument doc = null; + // same FileStream options as Reflector shows for XmlDocument.Load(path) / XmlDownloadManager.GetStream: + using (Stream stream = new FileStream(xmlPath.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + doc = LoadUnsafeXmlDocument(stream, preserveNonElements, maxCharactersInDocument); + } - return doc; - } + return doc; + } - /// - internal static XmlDocument LoadUnsafeXmlDocument(string xmlContents, bool preserveNonElements, int? maxCharactersInDocument) - { - using (TextReader textReader = new StringReader(xmlContents)) - { - return LoadUnsafeXmlDocument(textReader, preserveNonElements, maxCharactersInDocument); - } - } + /// + internal static XmlDocument LoadUnsafeXmlDocument(string xmlContents, bool preserveNonElements, int? maxCharactersInDocument) + { + using (TextReader textReader = new StringReader(xmlContents)) + { + return LoadUnsafeXmlDocument(textReader, preserveNonElements, maxCharactersInDocument); + } + } - /// - internal static XmlDocument LoadUnsafeXmlDocument(Stream stream, bool preserveNonElements, int? maxCharactersInDocument) - { - using (TextReader textReader = new StreamReader(stream)) - { - return LoadUnsafeXmlDocument(textReader, preserveNonElements, maxCharactersInDocument); - } - } + /// + internal static XmlDocument LoadUnsafeXmlDocument(Stream stream, bool preserveNonElements, int? maxCharactersInDocument) + { + using (TextReader textReader = new StreamReader(stream)) + { + return LoadUnsafeXmlDocument(textReader, preserveNonElements, maxCharactersInDocument); + } + } - /// - internal static XmlDocument LoadUnsafeXmlDocument(TextReader textReader, bool preserveNonElements, int? maxCharactersInDocument) - { - XmlReaderSettings settings; - if (maxCharactersInDocument.HasValue || preserveNonElements) - { - settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument.Clone(); - if (maxCharactersInDocument.HasValue) - { - settings.MaxCharactersInDocument = maxCharactersInDocument.Value; - } - if (preserveNonElements) - { - settings.IgnoreWhitespace = false; - settings.IgnoreProcessingInstructions = false; - settings.IgnoreComments = false; - } - } - else - { - settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument; - } + /// + internal static XmlDocument LoadUnsafeXmlDocument(TextReader textReader, bool preserveNonElements, int? maxCharactersInDocument) + { + XmlReaderSettings settings; + if (maxCharactersInDocument.HasValue || preserveNonElements) + { + settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument.Clone(); + if (maxCharactersInDocument.HasValue) + { + settings.MaxCharactersInDocument = maxCharactersInDocument.Value; + } + if (preserveNonElements) + { + settings.IgnoreWhitespace = false; + settings.IgnoreProcessingInstructions = false; + settings.IgnoreComments = false; + } + } + else + { + settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument; + } - try - { - XmlReader xmlReader = XmlReader.Create(textReader, settings); - XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.PreserveWhitespace = preserveNonElements; - xmlDocument.Load(xmlReader); - return xmlDocument; - } - catch (InvalidOperationException invalidOperationException) - { - throw new XmlException(invalidOperationException.Message, invalidOperationException); - } - } + try + { + XmlReader xmlReader = XmlReader.Create(textReader, settings); + XmlDocument xmlDocument = new XmlDocument(); + xmlDocument.PreserveWhitespace = preserveNonElements; + xmlDocument.Load(xmlReader); + return xmlDocument; + } + catch (InvalidOperationException invalidOperationException) + { + throw new XmlException(invalidOperationException.Message, invalidOperationException); + } + } - internal static object DeserializeXmlDocument(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - string docAsString = deserializer.ReadDecodedElementString(SerializationStrings.XmlDocumentTag); + internal static object DeserializeXmlDocument(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + string docAsString = deserializer.ReadDecodedElementString(SerializationStrings.XmlDocumentTag); - try - { - int? maxCharactersInDocument = null; - if (deserializer._context.MaximumAllowedMemory.HasValue) - { - maxCharactersInDocument = deserializer._context.MaximumAllowedMemory.Value / sizeof(char); - } + try + { + int? maxCharactersInDocument = null; + if (deserializer._context.MaximumAllowedMemory.HasValue) + { + maxCharactersInDocument = deserializer._context.MaximumAllowedMemory.Value / sizeof(char); + } - XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( - docAsString, - true, /* preserve whitespace, comments, etc. */ - maxCharactersInDocument); + XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( + docAsString, + true, /* preserve whitespace, comments, etc. */ + maxCharactersInDocument); - deserializer._context.LogExtraMemoryUsage((docAsString.Length - doc.OuterXml.Length) * sizeof(char)); + deserializer._context.LogExtraMemoryUsage((docAsString.Length - doc.OuterXml.Length) * sizeof(char)); - return doc; - } - catch (XmlException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(XmlDocument).FullName); - } - } + return doc; + } + catch (XmlException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(XmlDocument).FullName); + } + } - internal static object DeserializeProgressRecord(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + internal static object DeserializeProgressRecord(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - // - // read deserialized elements of a progress record - // - - deserializer.ReadStartElement(SerializationStrings.ProgressRecord); + // + // read deserialized elements of a progress record + // - string activity = null, currentOperation = null, prt = null, statusDescription = null; - int activityId = 0, parentActivityId = 0, percentComplete = 0, secondsRemaining = 0; + deserializer.ReadStartElement(SerializationStrings.ProgressRecord); - Exception recognizedException = null; - try - { - activity = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivity); - activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); - - object tmp = deserializer.ReadOneObject(); - currentOperation = (tmp == null) ? null : tmp.ToString(); - - parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); - percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); - prt = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordType); - secondsRemaining = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordSecondsRemaining), CultureInfo.InvariantCulture); - statusDescription = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordStatusDescription); - } - catch (FormatException e) - { - recognizedException = e; - } - catch (OverflowException e) - { - recognizedException = e; - } - if (recognizedException != null) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); - } + string activity = null, currentOperation = null, prt = null, statusDescription = null; + int activityId = 0, parentActivityId = 0, percentComplete = 0, secondsRemaining = 0; - deserializer.ReadEndElement(); + Exception recognizedException = null; + try + { + activity = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivity); + activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); - // - // Build the progress record - // + object tmp = deserializer.ReadOneObject(); + currentOperation = (tmp == null) ? null : tmp.ToString(); - ProgressRecordType type; - try - { - type = (ProgressRecordType)Enum.Parse(typeof(ProgressRecordType), prt, true); - } - catch (ArgumentException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(ProgressRecord).FullName); - } + parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); + percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); + prt = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordType); + secondsRemaining = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordSecondsRemaining), CultureInfo.InvariantCulture); + statusDescription = deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordStatusDescription); + } + catch (FormatException e) + { + recognizedException = e; + } + catch (OverflowException e) + { + recognizedException = e; + } + if (recognizedException != null) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); + } - try - { - ProgressRecord record = new ProgressRecord(activityId, activity, statusDescription); + deserializer.ReadEndElement(); - if (!string.IsNullOrEmpty(currentOperation)) - { - record.CurrentOperation = currentOperation; - } + // + // Build the progress record + // - record.ParentActivityId = parentActivityId; - record.PercentComplete = percentComplete; - record.RecordType = type; - record.SecondsRemaining = secondsRemaining; + ProgressRecordType type; + try + { + type = (ProgressRecordType)Enum.Parse(typeof(ProgressRecordType), prt, true); + } + catch (ArgumentException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(ProgressRecord).FullName); + } - return record; - } - catch (ArgumentException e) - { - throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof (ProgressRecord).FullName); - } - } + try + { + ProgressRecord record = new ProgressRecord(activityId, activity, statusDescription); - internal static object DeserializeSecureString(InternalDeserializer deserializer) - { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + if (!string.IsNullOrEmpty(currentOperation)) + { + record.CurrentOperation = currentOperation; + } - // - // read deserialized elements of a Secure String - // - return deserializer.ReadSecureString(); - } + record.ParentActivityId = parentActivityId; + record.PercentComplete = percentComplete; + record.RecordType = type; + record.SecondsRemaining = secondsRemaining; - #endregion known type deserialization + return record; + } + catch (ArgumentException e) + { + throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, e, typeof(ProgressRecord).FullName); + } + } - #region misc + internal static object DeserializeSecureString(InternalDeserializer deserializer) + { + Dbg.Assert(deserializer != null, "Caller should validate the parameter"); - /// - /// Check if LocalName of next element is "tag" - /// - /// - /// - private bool IsNextElement(string tag) - { - Dbg.Assert(!string.IsNullOrEmpty(tag), "Caller should validate the parameter"); - return (_reader.LocalName == tag) && - ((0 != (this._context.options & DeserializationOptions.NoNamespace)) || - (_reader.NamespaceURI == SerializationStrings.MonadNamespace)); - } + // + // read deserialized elements of a Secure String + // + return deserializer.ReadSecureString(); + } - /// - /// Read start element in monad namespace - /// - /// element tag to read - /// true if not an empty element else false - internal bool ReadStartElementAndHandleEmpty(string element) - { - Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); + #endregion known type deserialization - //IsEmpty is set to true when element is of the form - bool isEmpty = _reader.IsEmptyElement; + #region misc - this.ReadStartElement(element); + /// + /// Check if LocalName of next element is "tag" + /// + /// + /// + private bool IsNextElement(string tag) + { + Dbg.Assert(!string.IsNullOrEmpty(tag), "Caller should validate the parameter"); + return (_reader.LocalName == tag) && + ((0 != (_context.options & DeserializationOptions.NoNamespace)) || + (_reader.NamespaceURI == SerializationStrings.MonadNamespace)); + } - //This takes care of the case: or . In - //this case isEmpty is false. - if (isEmpty == false && _reader.NodeType == XmlNodeType.EndElement) - { - ReadEndElement(); - isEmpty = true; - } - return !isEmpty; - } + /// + /// Read start element in monad namespace + /// + /// element tag to read + /// true if not an empty element else false + internal bool ReadStartElementAndHandleEmpty(string element) + { + Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); - private void ReadStartElement(string element) - { - Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); + //IsEmpty is set to true when element is of the form + bool isEmpty = _reader.IsEmptyElement; - if (DeserializationOptions.NoNamespace == (this._context.options & DeserializationOptions.NoNamespace)) - { - _reader.ReadStartElement(element); - } - else - { - _reader.ReadStartElement(element, SerializationStrings.MonadNamespace); - } - _reader.MoveToContent(); - } + this.ReadStartElement(element); - private void ReadEndElement() - { - _reader.ReadEndElement(); - _reader.MoveToContent(); - } + //This takes care of the case: or . In + //this case isEmpty is false. + if (isEmpty == false && _reader.NodeType == XmlNodeType.EndElement) + { + ReadEndElement(); + isEmpty = true; + } + return !isEmpty; + } - private string ReadDecodedElementString(string element) - { - Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); - this.CheckIfStopping(); + private void ReadStartElement(string element) + { + Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); - string temp = null; - if (DeserializationOptions.NoNamespace == (this._context.options & DeserializationOptions.NoNamespace)) - { + if (DeserializationOptions.NoNamespace == (_context.options & DeserializationOptions.NoNamespace)) + { + _reader.ReadStartElement(element); + } + else + { + _reader.ReadStartElement(element, SerializationStrings.MonadNamespace); + } + _reader.MoveToContent(); + } + + private void ReadEndElement() + { + _reader.ReadEndElement(); + _reader.MoveToContent(); + } + + private string ReadDecodedElementString(string element) + { + Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); + this.CheckIfStopping(); + + string temp = null; + if (DeserializationOptions.NoNamespace == (_context.options & DeserializationOptions.NoNamespace)) + { temp = _reader.ReadElementContentAsString(element, string.Empty); - } - else - { - temp = _reader.ReadElementContentAsString(element, SerializationStrings.MonadNamespace); - } - _reader.MoveToContent(); - temp = DecodeString(temp); - return temp; - } + } + else + { + temp = _reader.ReadElementContentAsString(element, SerializationStrings.MonadNamespace); + } + _reader.MoveToContent(); + temp = DecodeString(temp); + return temp; + } - /// - /// Skips an element and all its child elements. - /// Moves cursor to next content Node. - /// - private void Skip() - { - _reader.Skip(); - _reader.MoveToContent(); - } + /// + /// Skips an element and all its child elements. + /// Moves cursor to next content Node. + /// + private void Skip() + { + _reader.Skip(); + _reader.MoveToContent(); + } - /// - /// Reads Primary known type - /// - /// - /// - private object ReadPrimaryKnownType(TypeSerializationInfo pktInfo) - { - Dbg.Assert(pktInfo != null, "Deserializer should be available"); - Dbg.Assert(pktInfo.Deserializer != null, "Deserializer should be available"); - object result = pktInfo.Deserializer(this); - _reader.MoveToContent(); - return result; - } + /// + /// Reads Primary known type + /// + /// + /// + private object ReadPrimaryKnownType(TypeSerializationInfo pktInfo) + { + Dbg.Assert(pktInfo != null, "Deserializer should be available"); + Dbg.Assert(pktInfo.Deserializer != null, "Deserializer should be available"); + object result = pktInfo.Deserializer(this); + _reader.MoveToContent(); + return result; + } - private object ReadSecureString() - { + private object ReadSecureString() + { String encryptedString = _reader.ReadElementContentAsString(); - try - { - object result; - if (_context.cryptoHelper != null) - { - result = _context.cryptoHelper.DecryptSecureString(encryptedString); - } - else - { - result = Microsoft.PowerShell.SecureStringHelper.Unprotect(encryptedString); - } + try + { + object result; + if (_context.cryptoHelper != null) + { + result = _context.cryptoHelper.DecryptSecureString(encryptedString); + } + else + { + result = Microsoft.PowerShell.SecureStringHelper.Unprotect(encryptedString); + } - _reader.MoveToContent(); - return result; - } - catch (PSCryptoException) - { - throw NewXmlException(Serialization.DeserializeSecureStringFailed, null); - } - } + _reader.MoveToContent(); + return result; + } + catch (PSCryptoException) + { + throw NewXmlException(Serialization.DeserializeSecureStringFailed, null); + } + } - /// - /// Helper function for building XmlException - /// - /// - /// resource String - /// - /// - /// - /// params for format string obtained from resourceId - /// - private XmlException NewXmlException - ( - string resourceString, - Exception innerException, - params object[] args - ) - { - Dbg.Assert(!string.IsNullOrEmpty(resourceString), "Caller should validate the parameter"); + /// + /// Helper function for building XmlException + /// + /// + /// resource String + /// + /// + /// + /// params for format string obtained from resourceId + /// + private XmlException NewXmlException + ( + string resourceString, + Exception innerException, + params object[] args + ) + { + Dbg.Assert(!string.IsNullOrEmpty(resourceString), "Caller should validate the parameter"); - string message = StringUtil.Format(resourceString, args); + string message = StringUtil.Format(resourceString, args); - XmlException ex = null; + XmlException ex = null; IXmlLineInfo xmlLineInfo = _reader as IXmlLineInfo; - if (xmlLineInfo != null) - { - if (xmlLineInfo.HasLineInfo()) - { - ex = new XmlException - ( - message, - innerException, - xmlLineInfo.LineNumber, - xmlLineInfo.LinePosition - ); - } - } + if (xmlLineInfo != null) + { + if (xmlLineInfo.HasLineInfo()) + { + ex = new XmlException + ( + message, + innerException, + xmlLineInfo.LineNumber, + xmlLineInfo.LinePosition + ); + } + } - if (ex == null) - { - ex = new XmlException(message, innerException); - } + if (ex == null) + { + ex = new XmlException(message, innerException); + } - return ex; - } + return ex; + } - private string ReadNameAttribute() - { - string encodedName = _reader.GetAttribute(SerializationStrings.NameAttribute); - if (encodedName == null) - { - throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.NameAttribute); - } - return DecodeString(encodedName); - } + private string ReadNameAttribute() + { + string encodedName = _reader.GetAttribute(SerializationStrings.NameAttribute); + if (encodedName == null) + { + throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.NameAttribute); + } + return DecodeString(encodedName); + } - private static string DecodeString(string s) - { - Dbg.Assert(s != null, "Caller should validate the parameter"); - return XmlConvert.DecodeName(s); - } + private static string DecodeString(string s) + { + Dbg.Assert(s != null, "Caller should validate the parameter"); + return XmlConvert.DecodeName(s); + } - #endregion misc + #endregion misc - [TraceSourceAttribute("InternalDeserializer", "InternalDeserializer class")] - private static readonly PSTraceSource _trace = PSTraceSource.GetTracer("InternalDeserializer", "InternalDeserializer class"); - } + [TraceSourceAttribute("InternalDeserializer", "InternalDeserializer class")] + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("InternalDeserializer", "InternalDeserializer class"); + } - /// - /// Helper class for generating reference id. - /// - internal class ReferenceIdHandlerForSerializer where T : class - { - /// - /// Get new reference id. - /// - /// New reference id - private UInt64 GetNewReferenceId() - { - UInt64 refId = seed++; - return refId; - } + /// + /// Helper class for generating reference id. + /// + internal class ReferenceIdHandlerForSerializer where T : class + { + /// + /// Get new reference id. + /// + /// New reference id + private UInt64 GetNewReferenceId() + { + UInt64 refId = _seed++; + return refId; + } - /// - /// Seed is incremented by one after each reference generation - /// - private UInt64 seed; + /// + /// Seed is incremented by one after each reference generation + /// + private UInt64 _seed; - // note: - // any boxed UInt64 takes 16 bytes on the heap - // one-character string (i.e. "7") takes 20 bytes on the heap - private readonly IDictionary object2refId; + // note: + // any boxed UInt64 takes 16 bytes on the heap + // one-character string (i.e. "7") takes 20 bytes on the heap + private readonly IDictionary _object2refId; - internal ReferenceIdHandlerForSerializer(IDictionary dictionary) - { - this.object2refId = dictionary; - } + internal ReferenceIdHandlerForSerializer(IDictionary dictionary) + { + _object2refId = dictionary; + } - /// - /// Assigns a RefId to the given object - /// - /// object to assign a RefId to - /// RefId assigned to the object - internal string SetRefId(T t) - { - if (this.object2refId != null) - { - Dbg.Assert(!this.object2refId.ContainsKey(t), "SetRefId shouldn't be called when the object is already assigned a ref id"); - UInt64 refId = GetNewReferenceId(); - this.object2refId.Add(t, refId); - return refId.ToString(System.Globalization.CultureInfo.InvariantCulture); - } - else - { - return null; - } - } + /// + /// Assigns a RefId to the given object + /// + /// object to assign a RefId to + /// RefId assigned to the object + internal string SetRefId(T t) + { + if (_object2refId != null) + { + Dbg.Assert(!_object2refId.ContainsKey(t), "SetRefId shouldn't be called when the object is already assigned a ref id"); + UInt64 refId = GetNewReferenceId(); + _object2refId.Add(t, refId); + return refId.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + else + { + return null; + } + } - /// - /// Gets a RefId already assigned for the given object or null if there is no associated ref id - /// - /// - /// - internal string GetRefId(T t) - { - UInt64 refId; - if ((this.object2refId != null) && (this.object2refId.TryGetValue(t, out refId))) - { - return refId.ToString(System.Globalization.CultureInfo.InvariantCulture); - } - else - { - return null; - } - } - } + /// + /// Gets a RefId already assigned for the given object or null if there is no associated ref id + /// + /// + /// + internal string GetRefId(T t) + { + UInt64 refId; + if ((_object2refId != null) && (_object2refId.TryGetValue(t, out refId))) + { + return refId.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + else + { + return null; + } + } + } - internal class ReferenceIdHandlerForDeserializer where T : class - { - private readonly Dictionary refId2object = new Dictionary(); + internal class ReferenceIdHandlerForDeserializer where T : class + { + private readonly Dictionary _refId2object = new Dictionary(); - internal void SetRefId(T o, string refId, bool duplicateRefIdsAllowed) - { + internal void SetRefId(T o, string refId, bool duplicateRefIdsAllowed) + { #if DEBUG - if (!duplicateRefIdsAllowed) - { - Dbg.Assert(!this.refId2object.ContainsKey(refId), "You can't change refId association"); - } + if (!duplicateRefIdsAllowed) + { + Dbg.Assert(!_refId2object.ContainsKey(refId), "You can't change refId association"); + } #endif - this.refId2object[refId] = o; - } + _refId2object[refId] = o; + } - internal T GetReferencedObject(string refId) - { - Dbg.Assert(this.refId2object.ContainsKey(refId), "Reference id wasn't seen earlier"); - T t; - if (this.refId2object.TryGetValue(refId, out t)) - { - return t; - } - else - { - return null; - } - } - } + internal T GetReferencedObject(string refId) + { + Dbg.Assert(_refId2object.ContainsKey(refId), "Reference id wasn't seen earlier"); + T t; + if (_refId2object.TryGetValue(refId, out t)) + { + return t; + } + else + { + return null; + } + } + } - /// - /// A delegate for serializing known type - /// - internal delegate void TypeSerializerDelegate(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry); - /// - /// A delegate for deserializing known type - /// - internal delegate object TypeDeserializerDelegate(InternalDeserializer deserializer); + /// + /// A delegate for serializing known type + /// + internal delegate void TypeSerializerDelegate(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry); + /// + /// A delegate for deserializing known type + /// + internal delegate object TypeDeserializerDelegate(InternalDeserializer deserializer); - /// - /// This class contains serialization information about a type. - /// - internal class TypeSerializationInfo - { - /// - /// Constructor - /// - /// Type for which this entry is created - /// ItemTag for the type - /// PropertyTag for the type - /// TypeSerializerDelegate for serializing the type - /// TypeDeserializerDelegate for deserializing the type - internal TypeSerializationInfo(Type type, string itemTag, string propertyTag, TypeSerializerDelegate serializer, TypeDeserializerDelegate deserializer) - { - _type = type; - _serializer = serializer; - _deserializer = deserializer; - _itemTag = itemTag; - _propertyTag = propertyTag; - } + /// + /// This class contains serialization information about a type. + /// + internal class TypeSerializationInfo + { + /// + /// Constructor + /// + /// Type for which this entry is created + /// ItemTag for the type + /// PropertyTag for the type + /// TypeSerializerDelegate for serializing the type + /// TypeDeserializerDelegate for deserializing the type + internal TypeSerializationInfo(Type type, string itemTag, string propertyTag, TypeSerializerDelegate serializer, TypeDeserializerDelegate deserializer) + { + _type = type; + _serializer = serializer; + _deserializer = deserializer; + _itemTag = itemTag; + _propertyTag = propertyTag; + } - #region properties + #region properties - /// - /// Get the type for which this TypeSerializationInfo is created. - /// - internal Type Type - { - get - { - return _type; - } - } + /// + /// Get the type for which this TypeSerializationInfo is created. + /// + internal Type Type + { + get + { + return _type; + } + } - /// - /// Get the item tag for this type - /// - internal string ItemTag - { - get - { - return _itemTag; - } - } + /// + /// Get the item tag for this type + /// + internal string ItemTag + { + get + { + return _itemTag; + } + } - /// - /// Get the Property tag for this type - /// - internal string PropertyTag - { - get - { - return _propertyTag; - } - } - /// - /// Gets the delegate to serialize this type - /// - internal TypeSerializerDelegate Serializer - { - get - { - return _serializer; - } - } - /// - /// Gets the delegate to deserialize this type - /// - internal TypeDeserializerDelegate Deserializer - { - get - { - return _deserializer; - } - } - #endregion properties + /// + /// Get the Property tag for this type + /// + internal string PropertyTag + { + get + { + return _propertyTag; + } + } + /// + /// Gets the delegate to serialize this type + /// + internal TypeSerializerDelegate Serializer + { + get + { + return _serializer; + } + } + /// + /// Gets the delegate to deserialize this type + /// + internal TypeDeserializerDelegate Deserializer + { + get + { + return _deserializer; + } + } + #endregion properties - #region private - /// - /// Type for which this entry is created - /// - private readonly Type _type; - /// - /// ItemTag for the type - /// - private readonly string _itemTag; - /// - /// PropertyTag for the type - /// - private readonly string _propertyTag; - /// - /// TypeSerializerDelegate for serializing the type - /// - private readonly TypeSerializerDelegate _serializer; - /// - /// TypeDeserializerDelegate for deserializing the type - /// - private readonly TypeDeserializerDelegate _deserializer; - #endregion private - } + #region private + /// + /// Type for which this entry is created + /// + private readonly Type _type; + /// + /// ItemTag for the type + /// + private readonly string _itemTag; + /// + /// PropertyTag for the type + /// + private readonly string _propertyTag; + /// + /// TypeSerializerDelegate for serializing the type + /// + private readonly TypeSerializerDelegate _serializer; + /// + /// TypeDeserializerDelegate for deserializing the type + /// + private readonly TypeDeserializerDelegate _deserializer; + #endregion private + } - /// - /// A class for identifying types which are treated as KnownType by Monad. - /// A KnownType is guranteed to be available on machine on which monad is - /// running. - /// - internal static class KnownTypes - { - /// - /// Static constructor - /// - static KnownTypes() - { - for (int i = 0; i < _TypeSerializationInfo.Length; i++) - { - _knownTableKeyType.Add(_TypeSerializationInfo[i].Type.FullName, _TypeSerializationInfo[i]); - _knownTableKeyItemTag.Add(_TypeSerializationInfo[i].ItemTag, _TypeSerializationInfo[i]); - } - } + /// + /// A class for identifying types which are treated as KnownType by Monad. + /// A KnownType is guranteed to be available on machine on which monad is + /// running. + /// + internal static class KnownTypes + { + /// + /// Static constructor + /// + static KnownTypes() + { + for (int i = 0; i < s_typeSerializationInfo.Length; i++) + { + s_knownTableKeyType.Add(s_typeSerializationInfo[i].Type.FullName, s_typeSerializationInfo[i]); + s_knownTableKeyItemTag.Add(s_typeSerializationInfo[i].ItemTag, s_typeSerializationInfo[i]); + } + } - /// - /// Gets the type serialization information about a type - /// - /// Type for which information is retrieved - /// TypeSerializationInfo for the type, null if it doesn't exist - internal static TypeSerializationInfo GetTypeSerializationInfo(Type type) - { - TypeSerializationInfo temp; - if (!_knownTableKeyType.TryGetValue(type.FullName, out temp) && typeof(XmlDocument).IsAssignableFrom(type)) - { - temp = _xdInfo; - } - return temp; - } + /// + /// Gets the type serialization information about a type + /// + /// Type for which information is retrieved + /// TypeSerializationInfo for the type, null if it doesn't exist + internal static TypeSerializationInfo GetTypeSerializationInfo(Type type) + { + TypeSerializationInfo temp; + if (!s_knownTableKeyType.TryGetValue(type.FullName, out temp) && typeof(XmlDocument).IsAssignableFrom(type)) + { + temp = s_xdInfo; + } + return temp; + } - /// - /// Get TypeSerializationInfo using ItemTag as key - /// - /// ItemTag for which TypeSerializationInfo is to be fetched - /// TypeSerializationInfo entry, null if no entry exist for the tag - internal static TypeSerializationInfo GetTypeSerializationInfoFromItemTag(string itemTag) - { - TypeSerializationInfo temp; - _knownTableKeyItemTag.TryGetValue(itemTag, out temp); - return temp; - } + /// + /// Get TypeSerializationInfo using ItemTag as key + /// + /// ItemTag for which TypeSerializationInfo is to be fetched + /// TypeSerializationInfo entry, null if no entry exist for the tag + internal static TypeSerializationInfo GetTypeSerializationInfoFromItemTag(string itemTag) + { + TypeSerializationInfo temp; + s_knownTableKeyItemTag.TryGetValue(itemTag, out temp); + return temp; + } - #region private_fields + #region private_fields - //TypeSerializationInfo for XmlDocument - private static readonly TypeSerializationInfo _xdInfo = - new TypeSerializationInfo(typeof(XmlDocument), - SerializationStrings.XmlDocumentTag, - SerializationStrings.XmlDocumentTag, - InternalSerializer.WriteXmlDocument, - InternalDeserializer.DeserializeXmlDocument); + //TypeSerializationInfo for XmlDocument + private static readonly TypeSerializationInfo s_xdInfo = + new TypeSerializationInfo(typeof(XmlDocument), + SerializationStrings.XmlDocumentTag, + SerializationStrings.XmlDocumentTag, + InternalSerializer.WriteXmlDocument, + InternalDeserializer.DeserializeXmlDocument); - /// - /// Array of known types. - /// - private static readonly TypeSerializationInfo[] _TypeSerializationInfo = new TypeSerializationInfo[] - { - new TypeSerializationInfo(typeof(Boolean), - SerializationStrings.BooleanTag, - SerializationStrings.BooleanTag, - InternalSerializer.WriteBoolean, - InternalDeserializer.DeserializeBoolean), + /// + /// Array of known types. + /// + private static readonly TypeSerializationInfo[] s_typeSerializationInfo = new TypeSerializationInfo[] + { + new TypeSerializationInfo(typeof(Boolean), + SerializationStrings.BooleanTag, + SerializationStrings.BooleanTag, + InternalSerializer.WriteBoolean, + InternalDeserializer.DeserializeBoolean), - new TypeSerializationInfo(typeof(Byte), - SerializationStrings.UnsignedByteTag, - SerializationStrings.UnsignedByteTag, - null, - InternalDeserializer.DeserializeByte), + new TypeSerializationInfo(typeof(Byte), + SerializationStrings.UnsignedByteTag, + SerializationStrings.UnsignedByteTag, + null, + InternalDeserializer.DeserializeByte), - new TypeSerializationInfo(typeof(Char), - SerializationStrings.CharTag, - SerializationStrings.CharTag, - InternalSerializer.WriteChar, - InternalDeserializer.DeserializeChar), + new TypeSerializationInfo(typeof(Char), + SerializationStrings.CharTag, + SerializationStrings.CharTag, + InternalSerializer.WriteChar, + InternalDeserializer.DeserializeChar), - new TypeSerializationInfo(typeof(DateTime), - SerializationStrings.DateTimeTag, - SerializationStrings.DateTimeTag, - InternalSerializer.WriteDateTime, - InternalDeserializer.DeserializeDateTime), + new TypeSerializationInfo(typeof(DateTime), + SerializationStrings.DateTimeTag, + SerializationStrings.DateTimeTag, + InternalSerializer.WriteDateTime, + InternalDeserializer.DeserializeDateTime), - new TypeSerializationInfo(typeof(Decimal), - SerializationStrings.DecimalTag, - SerializationStrings.DecimalTag, - null, - InternalDeserializer.DeserializeDecimal), + new TypeSerializationInfo(typeof(Decimal), + SerializationStrings.DecimalTag, + SerializationStrings.DecimalTag, + null, + InternalDeserializer.DeserializeDecimal), - new TypeSerializationInfo(typeof(Double), - SerializationStrings.DoubleTag, - SerializationStrings.DoubleTag, - InternalSerializer.WriteDouble, - InternalDeserializer.DeserializeDouble), + new TypeSerializationInfo(typeof(Double), + SerializationStrings.DoubleTag, + SerializationStrings.DoubleTag, + InternalSerializer.WriteDouble, + InternalDeserializer.DeserializeDouble), - new TypeSerializationInfo(typeof(Guid), - SerializationStrings.GuidTag, - SerializationStrings.GuidTag, - null, - InternalDeserializer.DeserializeGuid), - new TypeSerializationInfo(typeof(Int16), - SerializationStrings.ShortTag, - SerializationStrings.ShortTag, - null, - InternalDeserializer.DeserializeInt16), + new TypeSerializationInfo(typeof(Guid), + SerializationStrings.GuidTag, + SerializationStrings.GuidTag, + null, + InternalDeserializer.DeserializeGuid), + new TypeSerializationInfo(typeof(Int16), + SerializationStrings.ShortTag, + SerializationStrings.ShortTag, + null, + InternalDeserializer.DeserializeInt16), - new TypeSerializationInfo(typeof(Int32), - SerializationStrings.IntTag, - SerializationStrings.IntTag, - null, - InternalDeserializer.DeserializeInt32), + new TypeSerializationInfo(typeof(Int32), + SerializationStrings.IntTag, + SerializationStrings.IntTag, + null, + InternalDeserializer.DeserializeInt32), - new TypeSerializationInfo(typeof(Int64), - SerializationStrings.LongTag, - SerializationStrings.LongTag, - null, - InternalDeserializer.DeserializeInt64), + new TypeSerializationInfo(typeof(Int64), + SerializationStrings.LongTag, + SerializationStrings.LongTag, + null, + InternalDeserializer.DeserializeInt64), - new TypeSerializationInfo(typeof(SByte), - SerializationStrings.ByteTag, - SerializationStrings.ByteTag, - null, - InternalDeserializer.DeserializeSByte), + new TypeSerializationInfo(typeof(SByte), + SerializationStrings.ByteTag, + SerializationStrings.ByteTag, + null, + InternalDeserializer.DeserializeSByte), - new TypeSerializationInfo(typeof(Single), - SerializationStrings.FloatTag, - SerializationStrings.FloatTag, - InternalSerializer.WriteSingle, - InternalDeserializer.DeserializeSingle), + new TypeSerializationInfo(typeof(Single), + SerializationStrings.FloatTag, + SerializationStrings.FloatTag, + InternalSerializer.WriteSingle, + InternalDeserializer.DeserializeSingle), - new TypeSerializationInfo(typeof(ScriptBlock), - SerializationStrings.ScriptBlockTag, - SerializationStrings.ScriptBlockTag, - InternalSerializer.WriteScriptBlock, - InternalDeserializer.DeserializeScriptBlock), + new TypeSerializationInfo(typeof(ScriptBlock), + SerializationStrings.ScriptBlockTag, + SerializationStrings.ScriptBlockTag, + InternalSerializer.WriteScriptBlock, + InternalDeserializer.DeserializeScriptBlock), - new TypeSerializationInfo(typeof(String), - SerializationStrings.StringTag, - SerializationStrings.StringTag, - InternalSerializer.WriteEncodedString, - InternalDeserializer.DeserializeString), + new TypeSerializationInfo(typeof(String), + SerializationStrings.StringTag, + SerializationStrings.StringTag, + InternalSerializer.WriteEncodedString, + InternalDeserializer.DeserializeString), - new TypeSerializationInfo(typeof(TimeSpan), - SerializationStrings.DurationTag, - SerializationStrings.DurationTag, - InternalSerializer.WriteTimeSpan, - InternalDeserializer.DeserializeTimeSpan), + new TypeSerializationInfo(typeof(TimeSpan), + SerializationStrings.DurationTag, + SerializationStrings.DurationTag, + InternalSerializer.WriteTimeSpan, + InternalDeserializer.DeserializeTimeSpan), - new TypeSerializationInfo(typeof(UInt16), - SerializationStrings.UnsignedShortTag, - SerializationStrings.UnsignedShortTag, - null, - InternalDeserializer.DeserializeUInt16), + new TypeSerializationInfo(typeof(UInt16), + SerializationStrings.UnsignedShortTag, + SerializationStrings.UnsignedShortTag, + null, + InternalDeserializer.DeserializeUInt16), - new TypeSerializationInfo(typeof(UInt32), - SerializationStrings.UnsignedIntTag, - SerializationStrings.UnsignedIntTag, - null, - InternalDeserializer.DeserializeUInt32), + new TypeSerializationInfo(typeof(UInt32), + SerializationStrings.UnsignedIntTag, + SerializationStrings.UnsignedIntTag, + null, + InternalDeserializer.DeserializeUInt32), - new TypeSerializationInfo(typeof(UInt64), - SerializationStrings.UnsignedLongTag, - SerializationStrings.UnsignedLongTag, - null, - InternalDeserializer.DeserializeUInt64), + new TypeSerializationInfo(typeof(UInt64), + SerializationStrings.UnsignedLongTag, + SerializationStrings.UnsignedLongTag, + null, + InternalDeserializer.DeserializeUInt64), - new TypeSerializationInfo(typeof(Uri), - SerializationStrings.AnyUriTag, - SerializationStrings.AnyUriTag, - InternalSerializer.WriteUri, - InternalDeserializer.DeserializeUri), + new TypeSerializationInfo(typeof(Uri), + SerializationStrings.AnyUriTag, + SerializationStrings.AnyUriTag, + InternalSerializer.WriteUri, + InternalDeserializer.DeserializeUri), - new TypeSerializationInfo(typeof(byte[]), - SerializationStrings.Base64BinaryTag, - SerializationStrings.Base64BinaryTag, - InternalSerializer.WriteByteArray, - InternalDeserializer.DeserializeByteArray), + new TypeSerializationInfo(typeof(byte[]), + SerializationStrings.Base64BinaryTag, + SerializationStrings.Base64BinaryTag, + InternalSerializer.WriteByteArray, + InternalDeserializer.DeserializeByteArray), - new TypeSerializationInfo(typeof(System.Version), - SerializationStrings.VersionTag, - SerializationStrings.VersionTag, - InternalSerializer.WriteVersion, - InternalDeserializer.DeserializeVersion), - _xdInfo, + new TypeSerializationInfo(typeof(System.Version), + SerializationStrings.VersionTag, + SerializationStrings.VersionTag, + InternalSerializer.WriteVersion, + InternalDeserializer.DeserializeVersion), + s_xdInfo, - new TypeSerializationInfo(typeof(ProgressRecord), - SerializationStrings.ProgressRecord, - SerializationStrings.ProgressRecord, - InternalSerializer.WriteProgressRecord, - InternalDeserializer.DeserializeProgressRecord), + new TypeSerializationInfo(typeof(ProgressRecord), + SerializationStrings.ProgressRecord, + SerializationStrings.ProgressRecord, + InternalSerializer.WriteProgressRecord, + InternalDeserializer.DeserializeProgressRecord), - new TypeSerializationInfo(typeof(SecureString), - SerializationStrings.SecureStringTag, - SerializationStrings.SecureStringTag, - InternalSerializer.WriteSecureString, - InternalDeserializer.DeserializeSecureString), + new TypeSerializationInfo(typeof(SecureString), + SerializationStrings.SecureStringTag, + SerializationStrings.SecureStringTag, + InternalSerializer.WriteSecureString, + InternalDeserializer.DeserializeSecureString), +}; - }; + /// + /// Hashtable of knowntypes. + /// Key is Type.FullName and value is Type object. + /// + private static readonly Dictionary s_knownTableKeyType = new Dictionary(); - /// - /// Hashtable of knowntypes. - /// Key is Type.FullName and value is Type object. - /// - private static readonly Dictionary _knownTableKeyType = new Dictionary(); + /// + /// Hashtable of knowntypes. Key is ItemTag + /// + private static readonly Dictionary s_knownTableKeyItemTag = new Dictionary(); - /// - /// Hashtable of knowntypes. Key is ItemTag - /// - private static readonly Dictionary _knownTableKeyItemTag = new Dictionary(); + #endregion private_fields + } - #endregion private_fields - } + /// + /// This class contains helper routined for serialization/deserialization + /// + internal static class SerializationUtilities + { + /// + /// Extracts the value of a note property from a PSObject; returns null if the property does not exist + /// + internal static object GetPropertyValue(PSObject psObject, string propertyName) + { + PSNoteProperty property = (PSNoteProperty)psObject.Properties[propertyName]; - /// - /// This class contains helper routined for serialization/deserialization - /// - internal static class SerializationUtilities - { - /// - /// Extracts the value of a note property from a PSObject; returns null if the property does not exist - /// - internal static object GetPropertyValue(PSObject psObject, string propertyName) - { - PSNoteProperty property = (PSNoteProperty)psObject.Properties[propertyName]; + if (property == null) + { + return null; + } - if (property == null) - { - return null; - } + return property.Value; + } - return property.Value; - } + /// + /// Returns the BaseObject of a note property encoded as a PSObject; returns null if the property does not exist + /// + internal static object GetPsObjectPropertyBaseObject(PSObject psObject, string propertyName) + { + PSObject propertyPsObject = (PSObject)GetPropertyValue(psObject, propertyName); - /// - /// Returns the BaseObject of a note property encoded as a PSObject; returns null if the property does not exist - /// - internal static object GetPsObjectPropertyBaseObject(PSObject psObject, string propertyName) - { - PSObject propertyPsObject = (PSObject)GetPropertyValue(psObject, propertyName); + if (propertyPsObject == null) + { + return null; + } - if (propertyPsObject == null) - { - return null; - } - - return propertyPsObject.BaseObject; - } + return propertyPsObject.BaseObject; + } /// /// Checks if source is known container type and returns appropriate @@ -5587,1236 +5582,1236 @@ namespace System.Management.Automation return null; } } - } + } - /// - /// A dictionary from object to T where - /// 1) keys are objects, - /// 2) keys use reference equality, - /// 3) dictionary keeps only weak references to keys - /// - /// type of dictionary values - internal class WeakReferenceDictionary : IDictionary - { - private class WeakReferenceEqualityComparer : IEqualityComparer - { - public bool Equals(WeakReference x, WeakReference y) - { - object tx = x.Target; - if (tx == null) - { - return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) - } + /// + /// A dictionary from object to T where + /// 1) keys are objects, + /// 2) keys use reference equality, + /// 3) dictionary keeps only weak references to keys + /// + /// type of dictionary values + internal class WeakReferenceDictionary : IDictionary + { + private class WeakReferenceEqualityComparer : IEqualityComparer + { + public bool Equals(WeakReference x, WeakReference y) + { + object tx = x.Target; + if (tx == null) + { + return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) + } - object ty = y.Target; - if (ty == null) - { - return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) - } + object ty = y.Target; + if (ty == null) + { + return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) + } - return object.ReferenceEquals(tx, ty); - } + return object.ReferenceEquals(tx, ty); + } - public int GetHashCode(WeakReference obj) - { - object t = obj.Target; - if (t == null) - { - // collected object doesn't have a hash code - // return an arbitrary hashcode here and fall back on Equal method for comparison - return RuntimeHelpers.GetHashCode(obj); // RuntimeHelpers.GetHashCode(null) returns 0 - this would cause many hashtable colisions for WeakReferences to dead objects - } - else - { - return RuntimeHelpers.GetHashCode(t); - } - } - } + public int GetHashCode(WeakReference obj) + { + object t = obj.Target; + if (t == null) + { + // collected object doesn't have a hash code + // return an arbitrary hashcode here and fall back on Equal method for comparison + return RuntimeHelpers.GetHashCode(obj); // RuntimeHelpers.GetHashCode(null) returns 0 - this would cause many hashtable colisions for WeakReferences to dead objects + } + else + { + return RuntimeHelpers.GetHashCode(t); + } + } + } - private readonly IEqualityComparer weakEqualityComparer; - private Dictionary dictionary; + private readonly IEqualityComparer _weakEqualityComparer; + private Dictionary _dictionary; - public WeakReferenceDictionary() - { - this.weakEqualityComparer = new WeakReferenceEqualityComparer(); - this.dictionary = new Dictionary(this.weakEqualityComparer); - } + public WeakReferenceDictionary() + { + _weakEqualityComparer = new WeakReferenceEqualityComparer(); + _dictionary = new Dictionary(_weakEqualityComparer); + } #if DEBUG - private const int initialCleanupTriggerSize = 2; // 2 will stress this code more + private const int initialCleanupTriggerSize = 2; // 2 will stress this code more #else - private const int initialCleanupTriggerSize = 1000; + private const int initialCleanupTriggerSize = 1000; #endif - private int cleanupTriggerSize = initialCleanupTriggerSize; + private int _cleanupTriggerSize = initialCleanupTriggerSize; - private void CleanUp() - { - if (this.Count > this.cleanupTriggerSize) - { - Dictionary alive = new Dictionary(this.weakEqualityComparer); - foreach (KeyValuePair weakKeyValuePair in this.dictionary) - { - object key = weakKeyValuePair.Key.Target; - if (key != null) - { - alive.Add(weakKeyValuePair.Key, weakKeyValuePair.Value); - } - } - this.dictionary = alive; - this.cleanupTriggerSize = initialCleanupTriggerSize + this.Count * 2; - } - } + private void CleanUp() + { + if (this.Count > _cleanupTriggerSize) + { + Dictionary alive = new Dictionary(_weakEqualityComparer); + foreach (KeyValuePair weakKeyValuePair in _dictionary) + { + object key = weakKeyValuePair.Key.Target; + if (key != null) + { + alive.Add(weakKeyValuePair.Key, weakKeyValuePair.Value); + } + } + _dictionary = alive; + _cleanupTriggerSize = initialCleanupTriggerSize + this.Count * 2; + } + } - #region IDictionary Members + #region IDictionary Members - public void Add(object key, T value) - { - this.dictionary.Add(new WeakReference(key), value); - this.CleanUp(); - } + public void Add(object key, T value) + { + _dictionary.Add(new WeakReference(key), value); + this.CleanUp(); + } - public bool ContainsKey(object key) - { - return this.dictionary.ContainsKey(new WeakReference(key)); - } + public bool ContainsKey(object key) + { + return _dictionary.ContainsKey(new WeakReference(key)); + } - public ICollection Keys - { - get - { - List keys = new List(this.dictionary.Keys.Count); - foreach (WeakReference weakKey in this.dictionary.Keys) - { - object key = weakKey.Target; - if (key != null) - { - keys.Add(key); - } - } - return keys; - } - } + public ICollection Keys + { + get + { + List keys = new List(_dictionary.Keys.Count); + foreach (WeakReference weakKey in _dictionary.Keys) + { + object key = weakKey.Target; + if (key != null) + { + keys.Add(key); + } + } + return keys; + } + } - public bool Remove(object key) - { - return this.dictionary.Remove(new WeakReference(key)); - } + public bool Remove(object key) + { + return _dictionary.Remove(new WeakReference(key)); + } - public bool TryGetValue(object key, out T value) - { - WeakReference weakKey = new WeakReference(key); - return this.dictionary.TryGetValue(weakKey, out value); - } + public bool TryGetValue(object key, out T value) + { + WeakReference weakKey = new WeakReference(key); + return _dictionary.TryGetValue(weakKey, out value); + } - public ICollection Values - { - get - { - return this.dictionary.Values; - } - } + public ICollection Values + { + get + { + return _dictionary.Values; + } + } - public T this[object key] - { - get - { - return this.dictionary[new WeakReference(key)]; - } - set - { - this.dictionary[new WeakReference(key)] = value; - this.CleanUp(); - } - } + public T this[object key] + { + get + { + return _dictionary[new WeakReference(key)]; + } + set + { + _dictionary[new WeakReference(key)] = value; + this.CleanUp(); + } + } - #endregion + #endregion - #region ICollection> Members + #region ICollection> Members - private ICollection> WeakCollection - { - get - { - return this.dictionary; - } - } + private ICollection> WeakCollection + { + get + { + return _dictionary; + } + } - static private KeyValuePair WeakKeyValuePair(KeyValuePair publicKeyValuePair) - { - return new KeyValuePair(new WeakReference(publicKeyValuePair.Key), publicKeyValuePair.Value); - } + static private KeyValuePair WeakKeyValuePair(KeyValuePair publicKeyValuePair) + { + return new KeyValuePair(new WeakReference(publicKeyValuePair.Key), publicKeyValuePair.Value); + } - public void Add(KeyValuePair item) - { - this.WeakCollection.Add(WeakKeyValuePair(item)); - this.CleanUp(); - } + public void Add(KeyValuePair item) + { + this.WeakCollection.Add(WeakKeyValuePair(item)); + this.CleanUp(); + } - public void Clear() - { - this.WeakCollection.Clear(); - } + public void Clear() + { + this.WeakCollection.Clear(); + } - public bool Contains(KeyValuePair item) - { - return this.WeakCollection.Contains(WeakKeyValuePair(item)); - } + public bool Contains(KeyValuePair item) + { + return this.WeakCollection.Contains(WeakKeyValuePair(item)); + } - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - List> rawList = new List>(this.WeakCollection.Count); - foreach (KeyValuePair keyValuePair in this) - { - rawList.Add(keyValuePair); - } - rawList.CopyTo(array, arrayIndex); - } + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + List> rawList = new List>(this.WeakCollection.Count); + foreach (KeyValuePair keyValuePair in this) + { + rawList.Add(keyValuePair); + } + rawList.CopyTo(array, arrayIndex); + } - public int Count - { - get - { - return this.WeakCollection.Count; - } - } + public int Count + { + get + { + return this.WeakCollection.Count; + } + } - public bool IsReadOnly - { - get - { - return this.WeakCollection.IsReadOnly; - } - } + public bool IsReadOnly + { + get + { + return this.WeakCollection.IsReadOnly; + } + } - public bool Remove(KeyValuePair item) - { - return this.WeakCollection.Remove(WeakKeyValuePair(item)); - } + public bool Remove(KeyValuePair item) + { + return this.WeakCollection.Remove(WeakKeyValuePair(item)); + } - #endregion + #endregion - #region IEnumerable> Members + #region IEnumerable> Members - public IEnumerator> GetEnumerator() - { - foreach (KeyValuePair weakKeyValuePair in this.WeakCollection) - { - object key = weakKeyValuePair.Key.Target; - if (key != null) - { - yield return new KeyValuePair(key, weakKeyValuePair.Value); - } - } - } + public IEnumerator> GetEnumerator() + { + foreach (KeyValuePair weakKeyValuePair in this.WeakCollection) + { + object key = weakKeyValuePair.Key.Target; + if (key != null) + { + yield return new KeyValuePair(key, weakKeyValuePair.Value); + } + } + } - #endregion + #endregion - #region IEnumerable Members + #region IEnumerable Members - IEnumerator IEnumerable.GetEnumerator() - { - IEnumerable> enumerable = this; - IEnumerator> enumerator = enumerable.GetEnumerator(); - return enumerator; - } + IEnumerator IEnumerable.GetEnumerator() + { + IEnumerable> enumerable = this; + IEnumerator> enumerator = enumerable.GetEnumerator(); + return enumerator; + } - #endregion - } + #endregion + } - /// - /// is a that is limited to - /// 1) case-insensitive strings as keys and - /// 2) values that can be serialized and deserialized during PowerShell remoting handshake - /// (in major-version compatible versions of PowerShell remoting) - /// - [Serializable] - public sealed class PSPrimitiveDictionary : Hashtable - { - #region Constructors + /// + /// is a that is limited to + /// 1) case-insensitive strings as keys and + /// 2) values that can be serialized and deserialized during PowerShell remoting handshake + /// (in major-version compatible versions of PowerShell remoting) + /// + [Serializable] + public sealed class PSPrimitiveDictionary : Hashtable + { + #region Constructors - /// - /// Initializes a new empty instance of the class - /// - public PSPrimitiveDictionary() - : base(StringComparer.OrdinalIgnoreCase) - { - } + /// + /// Initializes a new empty instance of the class + /// + public PSPrimitiveDictionary() + : base(StringComparer.OrdinalIgnoreCase) + { + } - /// - /// Initializes a new instance of the class with contents - /// copied from the hashtable. - /// - /// hashtable to copy into the new instance of - /// - /// This constructor will throw if the hashtable contains keys that are not a strings - /// or values that are not one of primitive types that will work during PowerShell remoting handshake. - /// - [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The class is sealed")] - public PSPrimitiveDictionary(Hashtable other) - : base(StringComparer.OrdinalIgnoreCase) - { - if (other == null) - { - throw new ArgumentNullException("other"); - } + /// + /// Initializes a new instance of the class with contents + /// copied from the hashtable. + /// + /// hashtable to copy into the new instance of + /// + /// This constructor will throw if the hashtable contains keys that are not a strings + /// or values that are not one of primitive types that will work during PowerShell remoting handshake. + /// + [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "The class is sealed")] + public PSPrimitiveDictionary(Hashtable other) + : base(StringComparer.OrdinalIgnoreCase) + { + if (other == null) + { + throw new ArgumentNullException("other"); + } - foreach (DictionaryEntry entry in other) - { - Hashtable valueAsHashtable = PSObject.Base(entry.Value) as Hashtable; - if (valueAsHashtable != null) - { - this.Add(entry.Key, new PSPrimitiveDictionary(valueAsHashtable)); - } - else - { - this.Add(entry.Key, entry.Value); - } - } - } + foreach (DictionaryEntry entry in other) + { + Hashtable valueAsHashtable = PSObject.Base(entry.Value) as Hashtable; + if (valueAsHashtable != null) + { + this.Add(entry.Key, new PSPrimitiveDictionary(valueAsHashtable)); + } + else + { + this.Add(entry.Key, entry.Value); + } + } + } #if !CORECLR // No .NET Serialization In CoreCLR - /// - /// Support for .NET serialization - /// - private PSPrimitiveDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } + /// + /// Support for .NET serialization + /// + private PSPrimitiveDictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) + : base(info, context) + { + } #endif - #endregion + #endregion - #region Plumbing to make Hashtable reject all non-primitive types + #region Plumbing to make Hashtable reject all non-primitive types - private string VerifyKey(object key) - { - key = PSObject.Base(key); - string keyAsString = key as string; - if (keyAsString == null) - { - string message = StringUtil.Format(Serialization.PrimitiveHashtableInvalidKey, - key.GetType().FullName); - throw new ArgumentException(message); - } - else - { - return keyAsString; - } - } + private string VerifyKey(object key) + { + key = PSObject.Base(key); + string keyAsString = key as string; + if (keyAsString == null) + { + string message = StringUtil.Format(Serialization.PrimitiveHashtableInvalidKey, + key.GetType().FullName); + throw new ArgumentException(message); + } + else + { + return keyAsString; + } + } - private static readonly Type[] handshakeFriendlyTypes = new Type[] { - typeof(Boolean), - typeof(Byte), - typeof(Char), - typeof(DateTime), - typeof(Decimal), - typeof(Double), - typeof(Guid), - typeof(Int32), - typeof(Int64), - typeof(SByte), - typeof(Single), + private static readonly Type[] s_handshakeFriendlyTypes = new Type[] { + typeof(Boolean), + typeof(Byte), + typeof(Char), + typeof(DateTime), + typeof(Decimal), + typeof(Double), + typeof(Guid), + typeof(Int32), + typeof(Int64), + typeof(SByte), + typeof(Single), // typeof(ScriptBlock) - don't want ScriptBlocks, because they are deserialized into strings typeof(String), - typeof(TimeSpan), - typeof(UInt16), - typeof(UInt32), - typeof(UInt64), - typeof(Uri), - typeof(byte[]), - typeof(Version), - typeof(ProgressRecord), - typeof(XmlDocument), + typeof(TimeSpan), + typeof(UInt16), + typeof(UInt32), + typeof(UInt64), + typeof(Uri), + typeof(byte[]), + typeof(Version), + typeof(ProgressRecord), + typeof(XmlDocument), - typeof(PSPrimitiveDictionary) - }; + typeof(PSPrimitiveDictionary) + }; - private void VerifyValue(object value) - { - // null is a primitive type - if (value == null) - { - return; - } + private void VerifyValue(object value) + { + // null is a primitive type + if (value == null) + { + return; + } - value = PSObject.Base(value); + value = PSObject.Base(value); - // this list is based on the list inside KnownTypes - // it is copied here to make sure that a list of "handshake friendly types" - // won't change even if we add new primitive types in v.next + // this list is based on the list inside KnownTypes + // it is copied here to make sure that a list of "handshake friendly types" + // won't change even if we add new primitive types in v.next - Type valueType = value.GetType(); + Type valueType = value.GetType(); - // if "value" is a "primitiveType" then we are good - foreach (Type goodType in handshakeFriendlyTypes) - { - if (valueType == goodType) - { - return; - } - } + // if "value" is a "primitiveType" then we are good + foreach (Type goodType in s_handshakeFriendlyTypes) + { + if (valueType == goodType) + { + return; + } + } - // if "value" is an array of "primitiveType" items then we are good - // (note: we could have used IEnumerable<> or ICollection<> (covariance/contravariance concerns), - // but it is safer to limit the types to arrays. - // (one concern is that in v.next we might allow overriding SerializationMethod for - // types [i.e. check SerializationMethod *before* HandleKnownContainerTypes) + // if "value" is an array of "primitiveType" items then we are good + // (note: we could have used IEnumerable<> or ICollection<> (covariance/contravariance concerns), + // but it is safer to limit the types to arrays. + // (one concern is that in v.next we might allow overriding SerializationMethod for + // types [i.e. check SerializationMethod *before* HandleKnownContainerTypes) if ((valueType.IsArray) || valueType == typeof(ArrayList)) - { - foreach (object o in (IEnumerable)value) - { - VerifyValue(o); - } - return; - } + { + foreach (object o in (IEnumerable)value) + { + VerifyValue(o); + } + return; + } - string message = StringUtil.Format(Serialization.PrimitiveHashtableInvalidValue, - value.GetType().FullName); - throw new ArgumentException(message); - } + string message = StringUtil.Format(Serialization.PrimitiveHashtableInvalidValue, + value.GetType().FullName); + throw new ArgumentException(message); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - /// - /// This method will throw if the is not a string and the - /// is not one of primitive types that will work during PowerShell remoting handshake. - /// Use of strongly-typed overloads of this method is suggested if throwing an exception is not acceptable. - /// - public override void Add(object key, object value) - { - string keyAsString = this.VerifyKey(key); - this.VerifyValue(value); - base.Add(keyAsString, value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + /// + /// This method will throw if the is not a string and the + /// is not one of primitive types that will work during PowerShell remoting handshake. + /// Use of strongly-typed overloads of this method is suggested if throwing an exception is not acceptable. + /// + public override void Add(object key, object value) + { + string keyAsString = this.VerifyKey(key); + this.VerifyValue(value); + base.Add(keyAsString, value); + } - /// - /// Gets or sets the value associated with the specified key. - /// - /// The key whose value to get or set - /// The value associated with the specified key. - /// - /// If the specified key is not found, attempting to get it returns null - /// and attempting to set it creates a new element using the specified key. - /// - /// - /// The setter will throw if the is not a string and the value - /// is not one of primitive types that will work during PowerShell remoting handshake. - /// Use of strongly-typed overloads of Add method is suggested if throwing an exception is not acceptable. - /// - public override object this[object key] - { - get - { - return base[key]; - } - set - { - string keyAsString = this.VerifyKey(key); - this.VerifyValue(value); - base[keyAsString] = value; - } - } + /// + /// Gets or sets the value associated with the specified key. + /// + /// The key whose value to get or set + /// The value associated with the specified key. + /// + /// If the specified key is not found, attempting to get it returns null + /// and attempting to set it creates a new element using the specified key. + /// + /// + /// The setter will throw if the is not a string and the value + /// is not one of primitive types that will work during PowerShell remoting handshake. + /// Use of strongly-typed overloads of Add method is suggested if throwing an exception is not acceptable. + /// + public override object this[object key] + { + get + { + return base[key]; + } + set + { + string keyAsString = this.VerifyKey(key); + this.VerifyValue(value); + base[keyAsString] = value; + } + } - /// - /// Gets or sets the value associated with the specified key. - /// - /// The key whose value to get or set - /// The value associated with the specified key. - /// - /// If the specified key is not found, attempting to get it returns null - /// and attempting to set it creates a new element using the specified key. - /// - /// - /// The setter will throw if the value - /// is not one of primitive types that will work during PowerShell remoting handshake. - /// Use of strongly-typed overloads of Add method is suggested if throwing an exception is not acceptable. - /// - public object this[string key] - { - get - { - return base[key]; - } - set - { - this.VerifyValue(value); - base[key] = value; - } - } + /// + /// Gets or sets the value associated with the specified key. + /// + /// The key whose value to get or set + /// The value associated with the specified key. + /// + /// If the specified key is not found, attempting to get it returns null + /// and attempting to set it creates a new element using the specified key. + /// + /// + /// The setter will throw if the value + /// is not one of primitive types that will work during PowerShell remoting handshake. + /// Use of strongly-typed overloads of Add method is suggested if throwing an exception is not acceptable. + /// + public object this[string key] + { + get + { + return base[key]; + } + set + { + this.VerifyValue(value); + base[key] = value; + } + } - #endregion + #endregion - #region Helper methods + #region Helper methods - /// - /// Creates a new instance by doing a shallow copy of the current instance. - /// - /// - public override object Clone() - { - return new PSPrimitiveDictionary(this); - } + /// + /// Creates a new instance by doing a shallow copy of the current instance. + /// + /// + public override object Clone() + { + return new PSPrimitiveDictionary(this); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Boolean value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Boolean value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Boolean[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Boolean[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Byte value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Byte value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, byte[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, byte[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Char value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Char value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Char[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Char[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, DateTime value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, DateTime value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, DateTime[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, DateTime[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Decimal value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Decimal value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Decimal[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Decimal[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Double value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Double value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Double[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Double[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Guid value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Guid value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Guid[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Guid[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Int32 value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Int32 value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Int32[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Int32[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Int64 value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Int64 value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Int64[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Int64[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, SByte value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, SByte value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, SByte[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, SByte[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Single value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Single value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Single[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Single[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, String value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, String value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, String[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, String[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, TimeSpan value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, TimeSpan value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, TimeSpan[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, TimeSpan[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt16 value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt16 value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt16[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt16[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt32 value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt32 value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt32[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt32[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt64 value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt64 value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, UInt64[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, UInt64[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Uri value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Uri value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Uri[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Uri[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Version value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Version value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, Version[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, Version[] value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, PSPrimitiveDictionary value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, PSPrimitiveDictionary value) + { + this.Add((object)key, (object)value); + } - /// - /// Adds an element with the specified key and value into the Hashtable - /// - /// The key of the element to add - /// The value of the element to add - public void Add(string key, PSPrimitiveDictionary[] value) - { - this.Add((object)key, (object)value); - } + /// + /// Adds an element with the specified key and value into the Hashtable + /// + /// The key of the element to add + /// The value of the element to add + public void Add(string key, PSPrimitiveDictionary[] value) + { + this.Add((object)key, (object)value); + } - #endregion + #endregion - #region Internal Methods + #region Internal Methods - /// - /// If originalHash contains PSVersionTable, then just returns the Cloned copy of - /// the original hash. Othewise, creates a clone copy and add PSVersionInfo.GetPSVersionTable - /// to the clone and returns. - /// - /// - /// - internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDictionary originalHash) - { - if ((null != originalHash) && - (originalHash.ContainsKey(PSVersionInfo.PSVersionTableName))) - { - return (PSPrimitiveDictionary) originalHash.Clone(); - } + /// + /// If originalHash contains PSVersionTable, then just returns the Cloned copy of + /// the original hash. Othewise, creates a clone copy and add PSVersionInfo.GetPSVersionTable + /// to the clone and returns. + /// + /// + /// + internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDictionary originalHash) + { + if ((null != originalHash) && + (originalHash.ContainsKey(PSVersionInfo.PSVersionTableName))) + { + return (PSPrimitiveDictionary)originalHash.Clone(); + } - PSPrimitiveDictionary result = originalHash; - if (null != originalHash) - { - result = (PSPrimitiveDictionary)originalHash.Clone(); - } - else - { - result = new PSPrimitiveDictionary(); - } - PSPrimitiveDictionary versionTable = new PSPrimitiveDictionary(PSVersionInfo.GetPSVersionTable()); - result.Add(PSVersionInfo.PSVersionTableName, versionTable); + PSPrimitiveDictionary result = originalHash; + if (null != originalHash) + { + result = (PSPrimitiveDictionary)originalHash.Clone(); + } + else + { + result = new PSPrimitiveDictionary(); + } + PSPrimitiveDictionary versionTable = new PSPrimitiveDictionary(PSVersionInfo.GetPSVersionTable()); + result.Add(PSVersionInfo.PSVersionTableName, versionTable); - return result; - } + return result; + } - /// - /// Tries to get a value that might be present in a chain of nested PSPrimitiveDictionaries. - /// For example to get $sessionInfo.ApplicationPrivateData.ImplicitRemoting.Hash you could call - /// TryPathGet<string>($sessionInfo.ApplicationPrivateData, out myHash, "ImplicitRemoting", "Hash"). - /// - /// Expected type of the value - /// The root dictionary - /// - /// A chain of keys leading from the root dictionary () to the value - /// true if the value was found and was of the correct type; false otherwise - static internal bool TryPathGet(IDictionary data, out T result, params string[] keys) - { - Dbg.Assert(keys != null, "Caller should verify that keys != null"); - Dbg.Assert(keys.Length >= 1, "Caller should verify that keys.Length >= 1"); - Dbg.Assert(keys[0] != null, "Caller should verify that keys[i] != null"); + /// + /// Tries to get a value that might be present in a chain of nested PSPrimitiveDictionaries. + /// For example to get $sessionInfo.ApplicationPrivateData.ImplicitRemoting.Hash you could call + /// TryPathGet<string>($sessionInfo.ApplicationPrivateData, out myHash, "ImplicitRemoting", "Hash"). + /// + /// Expected type of the value + /// The root dictionary + /// + /// A chain of keys leading from the root dictionary () to the value + /// true if the value was found and was of the correct type; false otherwise + static internal bool TryPathGet(IDictionary data, out T result, params string[] keys) + { + Dbg.Assert(keys != null, "Caller should verify that keys != null"); + Dbg.Assert(keys.Length >= 1, "Caller should verify that keys.Length >= 1"); + Dbg.Assert(keys[0] != null, "Caller should verify that keys[i] != null"); - if (data == null || !data.Contains(keys[0])) - { - result = default(T); - return false; - } + if (data == null || !data.Contains(keys[0])) + { + result = default(T); + return false; + } - if (keys.Length == 1) - { - return LanguagePrimitives.TryConvertTo(data[keys[0]], out result); - } - else - { - IDictionary subData; - if (LanguagePrimitives.TryConvertTo(data[keys[0]], out subData) - && subData != null) - { - string[] subKeys = new string[keys.Length - 1]; - Array.Copy(keys, 1, subKeys, 0, subKeys.Length); - return TryPathGet(subData, out result, subKeys); - } - else - { - result = default(T); - return false; - } - } - } + if (keys.Length == 1) + { + return LanguagePrimitives.TryConvertTo(data[keys[0]], out result); + } + else + { + IDictionary subData; + if (LanguagePrimitives.TryConvertTo(data[keys[0]], out subData) + && subData != null) + { + string[] subKeys = new string[keys.Length - 1]; + Array.Copy(keys, 1, subKeys, 0, subKeys.Length); + return TryPathGet(subData, out result, subKeys); + } + else + { + result = default(T); + return false; + } + } + } - #endregion - } + #endregion + } } namespace Microsoft.PowerShell { - using System.Management.Automation; - using System.Security.Principal; + using System.Management.Automation; + using System.Security.Principal; - /// - /// Rehydrating type converter used during deserialization. - /// It takes results of serializing some common types - /// and rehydrates them back from property bags into live objects. - /// - /// - public sealed class DeserializingTypeConverter : PSTypeConverter - { + /// + /// Rehydrating type converter used during deserialization. + /// It takes results of serializing some common types + /// and rehydrates them back from property bags into live objects. + /// + /// + public sealed class DeserializingTypeConverter : PSTypeConverter + { #region Infrastructure - private static readonly Dictionary> converter; + private static readonly Dictionary> s_converter; static DeserializingTypeConverter() { - converter = new Dictionary>(); + s_converter = new Dictionary>(); - converter.Add(typeof(PSPrimitiveDictionary), RehydratePrimitiveHashtable); + s_converter.Add(typeof(PSPrimitiveDictionary), RehydratePrimitiveHashtable); - converter.Add(typeof(SwitchParameter), RehydrateSwitchParameter); - converter.Add(typeof(PSListModifier), RehydratePSListModifier); - converter.Add(typeof(PSCredential), RehydratePSCredential); - converter.Add(typeof(PSSenderInfo), RehydratePSSenderInfo); - converter.Add(typeof(CultureInfo), RehydrateCultureInfo); - converter.Add(typeof(ParameterSetMetadata), RehydrateParameterSetMetadata); + s_converter.Add(typeof(SwitchParameter), RehydrateSwitchParameter); + s_converter.Add(typeof(PSListModifier), RehydratePSListModifier); + s_converter.Add(typeof(PSCredential), RehydratePSCredential); + s_converter.Add(typeof(PSSenderInfo), RehydratePSSenderInfo); + s_converter.Add(typeof(CultureInfo), RehydrateCultureInfo); + s_converter.Add(typeof(ParameterSetMetadata), RehydrateParameterSetMetadata); - converter.Add(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2), RehydrateX509Certificate2); - converter.Add(typeof(System.Security.Cryptography.X509Certificates.X500DistinguishedName), RehydrateX500DistinguishedName); - converter.Add(typeof(System.Net.IPAddress), RehydrateIPAddress); + s_converter.Add(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2), RehydrateX509Certificate2); + s_converter.Add(typeof(System.Security.Cryptography.X509Certificates.X500DistinguishedName), RehydrateX500DistinguishedName); + s_converter.Add(typeof(System.Net.IPAddress), RehydrateIPAddress); - converter.Add(typeof(MailAddress), RehydrateMailAddress); + s_converter.Add(typeof(MailAddress), RehydrateMailAddress); - converter.Add(typeof(System.Security.AccessControl.DirectorySecurity), RehydrateObjectSecurity); - converter.Add(typeof(System.Security.AccessControl.FileSecurity), RehydrateObjectSecurity); - converter.Add(typeof(System.Security.AccessControl.RegistrySecurity), RehydrateObjectSecurity); + s_converter.Add(typeof(System.Security.AccessControl.DirectorySecurity), RehydrateObjectSecurity); + s_converter.Add(typeof(System.Security.AccessControl.FileSecurity), RehydrateObjectSecurity); + s_converter.Add(typeof(System.Security.AccessControl.RegistrySecurity), RehydrateObjectSecurity); - converter.Add(typeof(ExtendedTypeDefinition), RehydrateExtendedTypeDefinition); - converter.Add(typeof(FormatViewDefinition), RehydrateFormatViewDefinition); - converter.Add(typeof(PSControl), RehydratePSControl); - converter.Add(typeof(PSControlGroupBy), RehydrateGroupBy); - converter.Add(typeof(DisplayEntry), RehydrateDisplayEntry); - converter.Add(typeof(EntrySelectedBy), RehydrateEntrySelectedBy); - converter.Add(typeof(TableControlColumnHeader), RehydrateTableControlColumnHeader); - converter.Add(typeof(TableControlRow), RehydrateTableControlRow); - converter.Add(typeof(TableControlColumn), RehydrateTableControlColumn); - converter.Add(typeof(ListControlEntry), RehydrateListControlEntry); - converter.Add(typeof(ListControlEntryItem), RehydrateListControlEntryItem); - converter.Add(typeof(WideControlEntryItem), RehydrateWideControlEntryItem); - converter.Add(typeof(CustomControlEntry), RehydrateCustomControlEntry); - converter.Add(typeof(CustomItemBase), RehydrateCustomItemBase); + s_converter.Add(typeof(ExtendedTypeDefinition), RehydrateExtendedTypeDefinition); + s_converter.Add(typeof(FormatViewDefinition), RehydrateFormatViewDefinition); + s_converter.Add(typeof(PSControl), RehydratePSControl); + s_converter.Add(typeof(PSControlGroupBy), RehydrateGroupBy); + s_converter.Add(typeof(DisplayEntry), RehydrateDisplayEntry); + s_converter.Add(typeof(EntrySelectedBy), RehydrateEntrySelectedBy); + s_converter.Add(typeof(TableControlColumnHeader), RehydrateTableControlColumnHeader); + s_converter.Add(typeof(TableControlRow), RehydrateTableControlRow); + s_converter.Add(typeof(TableControlColumn), RehydrateTableControlColumn); + s_converter.Add(typeof(ListControlEntry), RehydrateListControlEntry); + s_converter.Add(typeof(ListControlEntryItem), RehydrateListControlEntryItem); + s_converter.Add(typeof(WideControlEntryItem), RehydrateWideControlEntryItem); + s_converter.Add(typeof(CustomControlEntry), RehydrateCustomControlEntry); + s_converter.Add(typeof(CustomItemBase), RehydrateCustomItemBase); - converter.Add(typeof(CompletionResult), RehydrateCompletionResult); - converter.Add(typeof(ModuleSpecification), RehydrateModuleSpecification); - converter.Add(typeof(CommandCompletion), RehydrateCommandCompletion); - converter.Add(typeof(JobStateInfo), RehydrateJobStateInfo); - converter.Add(typeof(JobStateEventArgs), RehydrateJobStateEventArgs); - converter.Add(typeof(PSSessionOption), RehydratePSSessionOption); - converter.Add(typeof(LineBreakpoint), RehydrateLineBreakpoint); - converter.Add(typeof(CommandBreakpoint), RehydrateCommandBreakpoint); - converter.Add(typeof(VariableBreakpoint), RehydrateVariableBreakpoint); - converter.Add(typeof(BreakpointUpdatedEventArgs), RehydrateBreakpointUpdatedEventArgs); - converter.Add(typeof(DebuggerCommand), RehydrateDebuggerCommand); - converter.Add(typeof(DebuggerCommandResults), RehydrateDebuggerCommandResults); - converter.Add(typeof(DebuggerStopEventArgs), RehydrateDebuggerStopEventArgs); + s_converter.Add(typeof(CompletionResult), RehydrateCompletionResult); + s_converter.Add(typeof(ModuleSpecification), RehydrateModuleSpecification); + s_converter.Add(typeof(CommandCompletion), RehydrateCommandCompletion); + s_converter.Add(typeof(JobStateInfo), RehydrateJobStateInfo); + s_converter.Add(typeof(JobStateEventArgs), RehydrateJobStateEventArgs); + s_converter.Add(typeof(PSSessionOption), RehydratePSSessionOption); + s_converter.Add(typeof(LineBreakpoint), RehydrateLineBreakpoint); + s_converter.Add(typeof(CommandBreakpoint), RehydrateCommandBreakpoint); + s_converter.Add(typeof(VariableBreakpoint), RehydrateVariableBreakpoint); + s_converter.Add(typeof(BreakpointUpdatedEventArgs), RehydrateBreakpointUpdatedEventArgs); + s_converter.Add(typeof(DebuggerCommand), RehydrateDebuggerCommand); + s_converter.Add(typeof(DebuggerCommandResults), RehydrateDebuggerCommandResults); + s_converter.Add(typeof(DebuggerStopEventArgs), RehydrateDebuggerStopEventArgs); } - /// - /// Determines if the converter can convert the parameter to the parameter. - /// - /// The value to convert from - /// The type to convert to - /// True if the converter can convert the parameter to the parameter, otherwise false. - public override bool CanConvertFrom(PSObject sourceValue, Type destinationType) - { - foreach (Type type in converter.Keys) - { - if (Deserializer.IsDeserializedInstanceOfType(sourceValue, type)) - { - return true; - } - } + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// The value to convert from + /// The type to convert to + /// True if the converter can convert the parameter to the parameter, otherwise false. + public override bool CanConvertFrom(PSObject sourceValue, Type destinationType) + { + foreach (Type type in s_converter.Keys) + { + if (Deserializer.IsDeserializedInstanceOfType(sourceValue, type)) + { + return true; + } + } - return false; - } + return false; + } - /// - /// Converts the parameter to the parameter using formatProvider and ignoreCase - /// - /// The value to convert from - /// The type to convert to - /// The format provider to use like in IFormatable's ToString - /// true if case should be ignored - /// the parameter converted to the parameter using formatProvider and ignoreCase - /// if no conversion was possible - public override object ConvertFrom(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - if (destinationType == null) - { - throw PSTraceSource.NewArgumentNullException("destinationType"); - } + /// + /// Converts the parameter to the parameter using formatProvider and ignoreCase + /// + /// The value to convert from + /// The type to convert to + /// The format provider to use like in IFormatable's ToString + /// true if case should be ignored + /// the parameter converted to the parameter using formatProvider and ignoreCase + /// if no conversion was possible + public override object ConvertFrom(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) + { + if (destinationType == null) + { + throw PSTraceSource.NewArgumentNullException("destinationType"); + } - if (sourceValue == null) - { - throw new PSInvalidCastException( - "InvalidCastWhenRehydratingFromNull", - PSTraceSource.NewArgumentNullException("sourceValue"), - ExtendedTypeSystem.InvalidCastFromNull, - destinationType.ToString()); - } + if (sourceValue == null) + { + throw new PSInvalidCastException( + "InvalidCastWhenRehydratingFromNull", + PSTraceSource.NewArgumentNullException("sourceValue"), + ExtendedTypeSystem.InvalidCastFromNull, + destinationType.ToString()); + } - foreach (KeyValuePair> item in converter) - { - Type type = item.Key; - Func typeConverter = item.Value; - if (Deserializer.IsDeserializedInstanceOfType(sourceValue, type)) - { - return ConvertFrom(sourceValue, typeConverter); - } - } + foreach (KeyValuePair> item in s_converter) + { + Type type = item.Key; + Func typeConverter = item.Value; + if (Deserializer.IsDeserializedInstanceOfType(sourceValue, type)) + { + return ConvertFrom(sourceValue, typeConverter); + } + } - throw new PSInvalidCastException( - "InvalidCastEnumFromTypeNotAString", - null, - ExtendedTypeSystem.InvalidCastException, - sourceValue, - destinationType); - } + throw new PSInvalidCastException( + "InvalidCastEnumFromTypeNotAString", + null, + ExtendedTypeSystem.InvalidCastException, + sourceValue, + destinationType); + } - private static object ConvertFrom(PSObject o, Func converter) - { - // rehydrate - PSObject dso = o; - object rehydratedObject = converter(dso); + private static object ConvertFrom(PSObject o, Func converter) + { + // rehydrate + PSObject dso = o; + object rehydratedObject = converter(dso); - // re-add instance properties - // (dso.InstanceMembers includes both instance and *type table* properties; - // therefore this will also re-add type table properties if they are not present when the deserializer runs; - // this is ok) - bool returnPSObject = false; - PSObject rehydratedPSObject = PSObject.AsPSObject(rehydratedObject); - foreach (PSMemberInfo member in dso.InstanceMembers) - { - if (member.MemberType == (member.MemberType & (PSMemberTypes.Properties | PSMemberTypes.MemberSet | PSMemberTypes.PropertySet))) - { - if (rehydratedPSObject.Members[member.Name] == null) - { - rehydratedPSObject.InstanceMembers.Add(member); - returnPSObject = true; - } - } - } + // re-add instance properties + // (dso.InstanceMembers includes both instance and *type table* properties; + // therefore this will also re-add type table properties if they are not present when the deserializer runs; + // this is ok) + bool returnPSObject = false; + PSObject rehydratedPSObject = PSObject.AsPSObject(rehydratedObject); + foreach (PSMemberInfo member in dso.InstanceMembers) + { + if (member.MemberType == (member.MemberType & (PSMemberTypes.Properties | PSMemberTypes.MemberSet | PSMemberTypes.PropertySet))) + { + if (rehydratedPSObject.Members[member.Name] == null) + { + rehydratedPSObject.InstanceMembers.Add(member); + returnPSObject = true; + } + } + } - if (returnPSObject) - { - return rehydratedPSObject; - } - else - { - return rehydratedObject; - } - } + if (returnPSObject) + { + return rehydratedPSObject; + } + else + { + return rehydratedObject; + } + } - /// - /// Returns true if the converter can convert the parameter to the parameter - /// - /// The value to convert from - /// The type to convert to - /// True if the converter can convert the parameter to the parameter, otherwise false. - public override bool CanConvertTo(object sourceValue, Type destinationType) - { - return false; - } + /// + /// Returns true if the converter can convert the parameter to the parameter + /// + /// The value to convert from + /// The type to convert to + /// True if the converter can convert the parameter to the parameter, otherwise false. + public override bool CanConvertTo(object sourceValue, Type destinationType) + { + return false; + } - /// - /// Converts the parameter to the parameter using formatProvider and ignoreCase - /// - /// The value to convert from - /// The type to convert to - /// The format provider to use like in IFormatable's ToString - /// true if case should be ignored - /// sourceValue converted to the parameter using formatProvider and ignoreCase - /// if no conversion was possible - public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - throw PSTraceSource.NewNotSupportedException(); - } + /// + /// Converts the parameter to the parameter using formatProvider and ignoreCase + /// + /// The value to convert from + /// The type to convert to + /// The format provider to use like in IFormatable's ToString + /// true if case should be ignored + /// sourceValue converted to the parameter using formatProvider and ignoreCase + /// if no conversion was possible + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) + { + throw PSTraceSource.NewNotSupportedException(); + } - /// - /// This method is not implemented - an overload taking a PSObject is implemented instead - /// - public override bool CanConvertFrom(object sourceValue, Type destinationType) - { - throw new NotImplementedException(); - } + /// + /// This method is not implemented - an overload taking a PSObject is implemented instead + /// + public override bool CanConvertFrom(object sourceValue, Type destinationType) + { + throw new NotImplementedException(); + } - /// - /// This method is not implemented - an overload taking a PSObject is implemented instead - /// - public override bool CanConvertTo(PSObject sourceValue, Type destinationType) - { - throw new NotImplementedException(); - } + /// + /// This method is not implemented - an overload taking a PSObject is implemented instead + /// + public override bool CanConvertTo(PSObject sourceValue, Type destinationType) + { + throw new NotImplementedException(); + } - /// - /// This method is not implemented - an overload taking a PSObject is implemented instead - /// - public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - throw new NotImplementedException(); - } + /// + /// This method is not implemented - an overload taking a PSObject is implemented instead + /// + public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) + { + throw new NotImplementedException(); + } - /// - /// This method is not implemented - an overload taking a PSObject is implemented instead - /// - public override object ConvertTo(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - throw new NotImplementedException(); - } + /// + /// This method is not implemented - an overload taking a PSObject is implemented instead + /// + public override object ConvertTo(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) + { + throw new NotImplementedException(); + } - #endregion + #endregion - #region Rehydration helpers + #region Rehydration helpers - [Flags] - internal enum RehydrationFlags - { - NullValueBad = 0, - NullValueOk = 0x1, - NullValueMeansEmptyList = 0x3, + [Flags] + internal enum RehydrationFlags + { + NullValueBad = 0, + NullValueOk = 0x1, + NullValueMeansEmptyList = 0x3, - MissingPropertyBad = 0, - MissingPropertyOk = 0x4, - } + MissingPropertyBad = 0, + MissingPropertyOk = 0x4, + } - /// - /// Gets value of a property (has to be present, value has to be non-null). - /// Can throw any exception (which is ok - LanguagePrimitives.ConvertTo will catch that). - /// - /// Expected type of the property - /// Deserialized object - /// Property name - /// - private static T GetPropertyValue(PSObject pso, string propertyName) - { - return GetPropertyValue(pso, propertyName, RehydrationFlags.NullValueBad | RehydrationFlags.MissingPropertyBad); - } + /// + /// Gets value of a property (has to be present, value has to be non-null). + /// Can throw any exception (which is ok - LanguagePrimitives.ConvertTo will catch that). + /// + /// Expected type of the property + /// Deserialized object + /// Property name + /// + private static T GetPropertyValue(PSObject pso, string propertyName) + { + return GetPropertyValue(pso, propertyName, RehydrationFlags.NullValueBad | RehydrationFlags.MissingPropertyBad); + } - /// - /// Gets value of a property. Can throw any exception (which is ok - LanguagePrimitives.ConvertTo will catch that). - /// - /// Expected type of the property - /// Deserialized object - /// Property name - /// - /// - internal static T GetPropertyValue(PSObject pso, string propertyName, RehydrationFlags flags) - { - Dbg.Assert(pso != null, "Caller should verify pso != null"); - Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName != null"); + /// + /// Gets value of a property. Can throw any exception (which is ok - LanguagePrimitives.ConvertTo will catch that). + /// + /// Expected type of the property + /// Deserialized object + /// Property name + /// + /// + internal static T GetPropertyValue(PSObject pso, string propertyName, RehydrationFlags flags) + { + Dbg.Assert(pso != null, "Caller should verify pso != null"); + Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName != null"); - PSPropertyInfo property = pso.Properties[propertyName]; - if ((property == null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) - { - return default(T); - } - else - { - object propertyValue = property.Value; - if ((propertyValue == null) && (RehydrationFlags.NullValueOk == (flags & RehydrationFlags.NullValueOk))) - { - return default(T); - } - else - { - T t = (T)LanguagePrimitives.ConvertTo(propertyValue, typeof(T), CultureInfo.InvariantCulture); - return t; - } - } - } + PSPropertyInfo property = pso.Properties[propertyName]; + if ((property == null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) + { + return default(T); + } + else + { + object propertyValue = property.Value; + if ((propertyValue == null) && (RehydrationFlags.NullValueOk == (flags & RehydrationFlags.NullValueOk))) + { + return default(T); + } + else + { + T t = (T)LanguagePrimitives.ConvertTo(propertyValue, typeof(T), CultureInfo.InvariantCulture); + return t; + } + } + } private static ListType RehydrateList(PSObject pso, string propertyName, RehydrationFlags flags) where ListType : IList, new() @@ -6845,178 +6840,179 @@ namespace Microsoft.PowerShell } } - #endregion + #endregion - #region Rehydration of miscellaneous types + #region Rehydration of miscellaneous types - private static object RehydratePrimitiveHashtable(PSObject pso) - { - Hashtable hashtable = (Hashtable)LanguagePrimitives.ConvertTo(pso, typeof(Hashtable), CultureInfo.InvariantCulture); - return new PSPrimitiveDictionary(hashtable); - } + private static object RehydratePrimitiveHashtable(PSObject pso) + { + Hashtable hashtable = (Hashtable)LanguagePrimitives.ConvertTo(pso, typeof(Hashtable), CultureInfo.InvariantCulture); + return new PSPrimitiveDictionary(hashtable); + } - private static object RehydrateSwitchParameter(PSObject pso) - { - return GetPropertyValue(pso, "IsPresent"); - } + private static object RehydrateSwitchParameter(PSObject pso) + { + return GetPropertyValue(pso, "IsPresent"); + } - private static CultureInfo RehydrateCultureInfo(PSObject pso) - { - string s = pso.ToString(); - return new CultureInfo(s); - } + private static CultureInfo RehydrateCultureInfo(PSObject pso) + { + string s = pso.ToString(); + return new CultureInfo(s); + } - private static PSListModifier RehydratePSListModifier(PSObject pso) - { - Hashtable h = new Hashtable(); + private static PSListModifier RehydratePSListModifier(PSObject pso) + { + Hashtable h = new Hashtable(); - PSPropertyInfo addProperty = pso.Properties[PSListModifier.AddKey]; - if ((addProperty != null) && (addProperty.Value != null)) - { - h.Add(PSListModifier.AddKey, addProperty.Value); - } + PSPropertyInfo addProperty = pso.Properties[PSListModifier.AddKey]; + if ((addProperty != null) && (addProperty.Value != null)) + { + h.Add(PSListModifier.AddKey, addProperty.Value); + } - PSPropertyInfo removeProperty = pso.Properties[PSListModifier.RemoveKey]; - if ((removeProperty != null) && (removeProperty.Value != null)) - { - h.Add(PSListModifier.RemoveKey, removeProperty.Value); - } + PSPropertyInfo removeProperty = pso.Properties[PSListModifier.RemoveKey]; + if ((removeProperty != null) && (removeProperty.Value != null)) + { + h.Add(PSListModifier.RemoveKey, removeProperty.Value); + } - PSPropertyInfo replaceProperty = pso.Properties[PSListModifier.ReplaceKey]; - if ((replaceProperty != null) && (replaceProperty.Value != null)) - { - h.Add(PSListModifier.ReplaceKey, replaceProperty.Value); - } + PSPropertyInfo replaceProperty = pso.Properties[PSListModifier.ReplaceKey]; + if ((replaceProperty != null) && (replaceProperty.Value != null)) + { + h.Add(PSListModifier.ReplaceKey, replaceProperty.Value); + } - return new PSListModifier(h); - } + return new PSListModifier(h); + } - private static CompletionResult RehydrateCompletionResult(PSObject pso) - { - string completionText = GetPropertyValue(pso, "CompletionText"); - string listItemText = GetPropertyValue(pso, "ListItemText"); - string toolTip = GetPropertyValue(pso, "ToolTip"); - CompletionResultType resultType = GetPropertyValue(pso, "ResultType"); + private static CompletionResult RehydrateCompletionResult(PSObject pso) + { + string completionText = GetPropertyValue(pso, "CompletionText"); + string listItemText = GetPropertyValue(pso, "ListItemText"); + string toolTip = GetPropertyValue(pso, "ToolTip"); + CompletionResultType resultType = GetPropertyValue(pso, "ResultType"); - return new CompletionResult(completionText, listItemText, resultType, toolTip); - } + return new CompletionResult(completionText, listItemText, resultType, toolTip); + } - private static ModuleSpecification RehydrateModuleSpecification(PSObject pso) - { - return new ModuleSpecification { - Name = GetPropertyValue(pso, "Name"), - Guid = GetPropertyValue(pso, "Guid"), - Version = GetPropertyValue(pso, "Version"), - MaximumVersion = GetPropertyValue(pso, "MaximumVersion"), - RequiredVersion = + private static ModuleSpecification RehydrateModuleSpecification(PSObject pso) + { + return new ModuleSpecification + { + Name = GetPropertyValue(pso, "Name"), + Guid = GetPropertyValue(pso, "Guid"), + Version = GetPropertyValue(pso, "Version"), + MaximumVersion = GetPropertyValue(pso, "MaximumVersion"), + RequiredVersion = GetPropertyValue(pso, "RequiredVersion") - }; - } - - private static CommandCompletion RehydrateCommandCompletion(PSObject pso) - { - var completions = new Collection(); + }; + } + + private static CommandCompletion RehydrateCommandCompletion(PSObject pso) + { + var completions = new Collection(); foreach (var match in GetPropertyValue(pso, "CompletionMatches")) - { - completions.Add((CompletionResult)match); - } - var currentMatchIndex = GetPropertyValue(pso, "CurrentMatchIndex"); - var replacementIndex = GetPropertyValue(pso, "ReplacementIndex"); - var replacementLength = GetPropertyValue(pso, "ReplacementLength"); - return new CommandCompletion(completions, currentMatchIndex, replacementIndex, replacementLength); - } + { + completions.Add((CompletionResult)match); + } + var currentMatchIndex = GetPropertyValue(pso, "CurrentMatchIndex"); + var replacementIndex = GetPropertyValue(pso, "ReplacementIndex"); + var replacementLength = GetPropertyValue(pso, "ReplacementLength"); + return new CommandCompletion(completions, currentMatchIndex, replacementIndex, replacementLength); + } - private static JobStateInfo RehydrateJobStateInfo(PSObject pso) - { - var jobState = GetPropertyValue(pso, "State"); - - Exception reason = null; - object propertyValue = null; - PSPropertyInfo property = pso.Properties["Reason"]; - string message = string.Empty; + private static JobStateInfo RehydrateJobStateInfo(PSObject pso) + { + var jobState = GetPropertyValue(pso, "State"); - if (property != null) - { - propertyValue = property.Value; - } + Exception reason = null; + object propertyValue = null; + PSPropertyInfo property = pso.Properties["Reason"]; + string message = string.Empty; - if (propertyValue != null) - { - if (Deserializer.IsDeserializedInstanceOfType(propertyValue, typeof(Exception))) - { - // if we have a deserialized remote or any other exception, use its message to construct - // an exception - message = PSObject.AsPSObject(propertyValue).Properties["Message"].Value as string; - } - else if (propertyValue is Exception) - { - reason = (Exception) propertyValue; - } - else - { - message = propertyValue.ToString(); - } + if (property != null) + { + propertyValue = property.Value; + } - if (!string.IsNullOrEmpty(message)) - { - try - { - reason = (Exception)LanguagePrimitives.ConvertTo(message, typeof(Exception), CultureInfo.InvariantCulture); - } - catch (Exception) - { - // it is ok to eat this exception since we do not want - // rehydration to fail - reason = null; - } - } - } + if (propertyValue != null) + { + if (Deserializer.IsDeserializedInstanceOfType(propertyValue, typeof(Exception))) + { + // if we have a deserialized remote or any other exception, use its message to construct + // an exception + message = PSObject.AsPSObject(propertyValue).Properties["Message"].Value as string; + } + else if (propertyValue is Exception) + { + reason = (Exception)propertyValue; + } + else + { + message = propertyValue.ToString(); + } - return new JobStateInfo(jobState, reason); - } + if (!string.IsNullOrEmpty(message)) + { + try + { + reason = (Exception)LanguagePrimitives.ConvertTo(message, typeof(Exception), CultureInfo.InvariantCulture); + } + catch (Exception) + { + // it is ok to eat this exception since we do not want + // rehydration to fail + reason = null; + } + } + } - internal static JobStateEventArgs RehydrateJobStateEventArgs(PSObject pso) - { - var jobStateInfo = RehydrateJobStateInfo(PSObject.AsPSObject(pso.Properties["JobStateInfo"].Value)); - JobStateInfo previousJobStateInfo = null; - var previousJobStateInfoProperty = pso.Properties["PreviousJobStateInfo"]; + return new JobStateInfo(jobState, reason); + } - if (previousJobStateInfoProperty != null && previousJobStateInfoProperty.Value != null) - { - previousJobStateInfo = RehydrateJobStateInfo(PSObject.AsPSObject(previousJobStateInfoProperty.Value)); - } + internal static JobStateEventArgs RehydrateJobStateEventArgs(PSObject pso) + { + var jobStateInfo = RehydrateJobStateInfo(PSObject.AsPSObject(pso.Properties["JobStateInfo"].Value)); + JobStateInfo previousJobStateInfo = null; + var previousJobStateInfoProperty = pso.Properties["PreviousJobStateInfo"]; - return new JobStateEventArgs(jobStateInfo, previousJobStateInfo); - } + if (previousJobStateInfoProperty != null && previousJobStateInfoProperty.Value != null) + { + previousJobStateInfo = RehydrateJobStateInfo(PSObject.AsPSObject(previousJobStateInfoProperty.Value)); + } + + return new JobStateEventArgs(jobStateInfo, previousJobStateInfo); + } internal static PSSessionOption RehydratePSSessionOption(PSObject pso) { PSSessionOption option = new PSSessionOption(); - + option.ApplicationArguments = GetPropertyValue(pso, "ApplicationArguments"); - option.CancelTimeout = GetPropertyValue(pso,"CancelTimeout"); - option.Culture = GetPropertyValue(pso,"Culture"); - option.IdleTimeout = GetPropertyValue(pso,"IdleTimeout"); + option.CancelTimeout = GetPropertyValue(pso, "CancelTimeout"); + option.Culture = GetPropertyValue(pso, "Culture"); + option.IdleTimeout = GetPropertyValue(pso, "IdleTimeout"); option.MaximumConnectionRedirectionCount = GetPropertyValue(pso, "MaximumConnectionRedirectionCount"); option.MaximumReceivedDataSizePerCommand = GetPropertyValue>(pso, "MaximumReceivedDataSizePerCommand"); - option.MaximumReceivedObjectSize = GetPropertyValue>(pso,"MaximumReceivedObjectSize"); + option.MaximumReceivedObjectSize = GetPropertyValue>(pso, "MaximumReceivedObjectSize"); option.NoCompression = GetPropertyValue(pso, "NoCompression"); option.NoEncryption = GetPropertyValue(pso, "NoEncryption"); - option.NoMachineProfile = GetPropertyValue(pso,"NoMachineProfile"); - option.OpenTimeout = GetPropertyValue(pso,"OpenTimeout"); - option.OperationTimeout = GetPropertyValue(pso,"OperationTimeout"); - option.OutputBufferingMode = GetPropertyValue(pso,"OutputBufferingMode"); + option.NoMachineProfile = GetPropertyValue(pso, "NoMachineProfile"); + option.OpenTimeout = GetPropertyValue(pso, "OpenTimeout"); + option.OperationTimeout = GetPropertyValue(pso, "OperationTimeout"); + option.OutputBufferingMode = GetPropertyValue(pso, "OutputBufferingMode"); option.MaxConnectionRetryCount = GetPropertyValue(pso, "MaxConnectionRetryCount"); option.ProxyAccessType = GetPropertyValue(pso, "ProxyAccessType"); option.ProxyAuthentication = GetPropertyValue(pso, "ProxyAuthentication"); option.ProxyCredential = GetPropertyValue(pso, "ProxyCredential"); - option.SkipCACheck = GetPropertyValue(pso,"SkipCACheck"); - option.SkipCNCheck = GetPropertyValue(pso,"SkipCNCheck"); - option.SkipRevocationCheck = GetPropertyValue(pso,"SkipRevocationCheck"); - option.UICulture = GetPropertyValue(pso,"UICulture"); - option.UseUTF16 = GetPropertyValue(pso,"UseUTF16"); + option.SkipCACheck = GetPropertyValue(pso, "SkipCACheck"); + option.SkipCNCheck = GetPropertyValue(pso, "SkipCNCheck"); + option.SkipRevocationCheck = GetPropertyValue(pso, "SkipRevocationCheck"); + option.UICulture = GetPropertyValue(pso, "UICulture"); + option.UseUTF16 = GetPropertyValue(pso, "UseUTF16"); option.IncludePortInSPN = GetPropertyValue(pso, "IncludePortInSPN"); - + return option; } @@ -7122,49 +7118,49 @@ namespace Microsoft.PowerShell #endregion - #region Rehydration of security-related types + #region Rehydration of security-related types - private static PSCredential RehydratePSCredential(PSObject pso) - { - string userName = GetPropertyValue(pso, "UserName"); - System.Security.SecureString password = GetPropertyValue(pso, "Password"); + private static PSCredential RehydratePSCredential(PSObject pso) + { + string userName = GetPropertyValue(pso, "UserName"); + System.Security.SecureString password = GetPropertyValue(pso, "Password"); - if (String.IsNullOrEmpty(userName)) - { - return PSCredential.Empty; - } - else - { - return new PSCredential(userName, password); - } - } + if (String.IsNullOrEmpty(userName)) + { + return PSCredential.Empty; + } + else + { + return new PSCredential(userName, password); + } + } - internal static PSSenderInfo RehydratePSSenderInfo(PSObject pso) - { - PSObject userInfo = GetPropertyValue(pso, "UserInfo"); - PSObject userIdentity = GetPropertyValue(userInfo, "Identity"); - PSObject certDetails = GetPropertyValue(userIdentity, "CertificateDetails"); - - PSCertificateDetails psCertDetails = certDetails == null ? null : new PSCertificateDetails( - GetPropertyValue(certDetails, "Subject"), - GetPropertyValue(certDetails, "IssuerName"), - GetPropertyValue(certDetails, "IssuerThumbprint")); - PSIdentity psIdentity = new PSIdentity( - GetPropertyValue(userIdentity, "AuthenticationType"), - GetPropertyValue(userIdentity, "IsAuthenticated"), - GetPropertyValue(userIdentity, "Name"), - psCertDetails); - PSPrincipal psPrincipal = new PSPrincipal(psIdentity, WindowsIdentity.GetCurrent()); + internal static PSSenderInfo RehydratePSSenderInfo(PSObject pso) + { + PSObject userInfo = GetPropertyValue(pso, "UserInfo"); + PSObject userIdentity = GetPropertyValue(userInfo, "Identity"); + PSObject certDetails = GetPropertyValue(userIdentity, "CertificateDetails"); - PSSenderInfo senderInfo = new PSSenderInfo(psPrincipal, GetPropertyValue(pso, "ConnectionString")); + PSCertificateDetails psCertDetails = certDetails == null ? null : new PSCertificateDetails( + GetPropertyValue(certDetails, "Subject"), + GetPropertyValue(certDetails, "IssuerName"), + GetPropertyValue(certDetails, "IssuerThumbprint")); + PSIdentity psIdentity = new PSIdentity( + GetPropertyValue(userIdentity, "AuthenticationType"), + GetPropertyValue(userIdentity, "IsAuthenticated"), + GetPropertyValue(userIdentity, "Name"), + psCertDetails); + PSPrincipal psPrincipal = new PSPrincipal(psIdentity, WindowsIdentity.GetCurrent()); + + PSSenderInfo senderInfo = new PSSenderInfo(psPrincipal, GetPropertyValue(pso, "ConnectionString")); #if !CORECLR // TimeZone Not In CoreCLR senderInfo.ClientTimeZone = TimeZone.CurrentTimeZone; #endif - senderInfo.ApplicationArguments = GetPropertyValue(pso, "ApplicationArguments"); + senderInfo.ApplicationArguments = GetPropertyValue(pso, "ApplicationArguments"); - return senderInfo; - } + return senderInfo; + } private static System.Security.Cryptography.X509Certificates.X509Certificate2 RehydrateX509Certificate2(PSObject pso) { @@ -7190,44 +7186,44 @@ namespace Microsoft.PowerShell return new MailAddress(s); } - private static T RehydrateObjectSecurity(PSObject pso) - where T : System.Security.AccessControl.ObjectSecurity, new() - { - string sddl = GetPropertyValue(pso, "SDDL"); + private static T RehydrateObjectSecurity(PSObject pso) + where T : System.Security.AccessControl.ObjectSecurity, new() + { + string sddl = GetPropertyValue(pso, "SDDL"); - T t = new T(); - t.SetSecurityDescriptorSddlForm(sddl); - return t; - } + T t = new T(); + t.SetSecurityDescriptorSddlForm(sddl); + return t; + } - #endregion + #endregion - #region Rehydration of types needed by implicit remoting + #region Rehydration of types needed by implicit remoting - /// - /// Gets the boolean properties of ParameterSetMetadata object encoded as an integer - /// - /// - /// The PSObject for which to obtain the flags - /// - /// - /// Boolean properties of ParameterSetMetadata object encoded as an integer - /// - public static UInt32 GetParameterSetMetadataFlags(PSObject instance) - { - if(instance == null) - { - throw PSTraceSource.NewArgumentNullException("instance"); - } + /// + /// Gets the boolean properties of ParameterSetMetadata object encoded as an integer + /// + /// + /// The PSObject for which to obtain the flags + /// + /// + /// Boolean properties of ParameterSetMetadata object encoded as an integer + /// + public static UInt32 GetParameterSetMetadataFlags(PSObject instance) + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException("instance"); + } - ParameterSetMetadata parameterSetMetadata = instance.BaseObject as ParameterSetMetadata; - if(parameterSetMetadata == null) - { - throw PSTraceSource.NewArgumentNullException("instance"); - } + ParameterSetMetadata parameterSetMetadata = instance.BaseObject as ParameterSetMetadata; + if (parameterSetMetadata == null) + { + throw PSTraceSource.NewArgumentNullException("instance"); + } - return (UInt32)(parameterSetMetadata.Flags); - } + return (UInt32)(parameterSetMetadata.Flags); + } /// /// Gets the full remoting serialized PSObject for the InvocationInfo property @@ -7266,224 +7262,224 @@ namespace Microsoft.PowerShell return new ParameterSetMetadata(position, (ParameterSetMetadata.ParameterFlags)flags, helpMessage); } - private static DisplayEntry RehydrateDisplayEntry(PSObject deserializedDisplayEntry) - { - var result = new DisplayEntry - { - Value = GetPropertyValue(deserializedDisplayEntry, "Value"), - ValueType = GetPropertyValue(deserializedDisplayEntry, "ValueType") - }; - return result; - } + private static DisplayEntry RehydrateDisplayEntry(PSObject deserializedDisplayEntry) + { + var result = new DisplayEntry + { + Value = GetPropertyValue(deserializedDisplayEntry, "Value"), + ValueType = GetPropertyValue(deserializedDisplayEntry, "ValueType") + }; + return result; + } - private static EntrySelectedBy RehydrateEntrySelectedBy(PSObject deserializedEsb) - { - var result = new EntrySelectedBy - { - TypeNames = RehydrateList, string>(deserializedEsb, "TypeNames", RehydrationFlags.MissingPropertyOk), - SelectionCondition = RehydrateList, DisplayEntry>(deserializedEsb, "SelectionCondition", RehydrationFlags.MissingPropertyOk) - }; - return result; - } + private static EntrySelectedBy RehydrateEntrySelectedBy(PSObject deserializedEsb) + { + var result = new EntrySelectedBy + { + TypeNames = RehydrateList, string>(deserializedEsb, "TypeNames", RehydrationFlags.MissingPropertyOk), + SelectionCondition = RehydrateList, DisplayEntry>(deserializedEsb, "SelectionCondition", RehydrationFlags.MissingPropertyOk) + }; + return result; + } - private static WideControlEntryItem RehydrateWideControlEntryItem(PSObject deserializedEntryItem) - { - var entrySelectedBy = GetPropertyValue(deserializedEntryItem, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); - if (entrySelectedBy == null) - { - var selectedBy = RehydrateList, string>(deserializedEntryItem, "SelectedBy", RehydrationFlags.MissingPropertyOk); + private static WideControlEntryItem RehydrateWideControlEntryItem(PSObject deserializedEntryItem) + { + var entrySelectedBy = GetPropertyValue(deserializedEntryItem, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); + if (entrySelectedBy == null) + { + var selectedBy = RehydrateList, string>(deserializedEntryItem, "SelectedBy", RehydrationFlags.MissingPropertyOk); entrySelectedBy = EntrySelectedBy.Get(selectedBy, null); } - var result = new WideControlEntryItem - { - DisplayEntry = GetPropertyValue(deserializedEntryItem, "DisplayEntry"), - EntrySelectedBy = entrySelectedBy, + var result = new WideControlEntryItem + { + DisplayEntry = GetPropertyValue(deserializedEntryItem, "DisplayEntry"), + EntrySelectedBy = entrySelectedBy, FormatString = GetPropertyValue(deserializedEntryItem, "FormatString", RehydrationFlags.MissingPropertyOk), - }; - return result; - } + }; + return result; + } - private static ListControlEntryItem RehydrateListControlEntryItem(PSObject deserializedEntryItem) - { - var result = new ListControlEntryItem - { - DisplayEntry = GetPropertyValue(deserializedEntryItem, "DisplayEntry"), + private static ListControlEntryItem RehydrateListControlEntryItem(PSObject deserializedEntryItem) + { + var result = new ListControlEntryItem + { + DisplayEntry = GetPropertyValue(deserializedEntryItem, "DisplayEntry"), ItemSelectionCondition = GetPropertyValue(deserializedEntryItem, "ItemSelectionCondition", RehydrationFlags.MissingPropertyOk), FormatString = GetPropertyValue(deserializedEntryItem, "FormatString", RehydrationFlags.MissingPropertyOk), - Label = GetPropertyValue(deserializedEntryItem, "Label", RehydrationFlags.NullValueOk) - }; - return result; - } + Label = GetPropertyValue(deserializedEntryItem, "Label", RehydrationFlags.NullValueOk) + }; + return result; + } - private static ListControlEntry RehydrateListControlEntry(PSObject deserializedEntry) - { - var entrySelectedBy = GetPropertyValue(deserializedEntry, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); - if (entrySelectedBy == null) - { - var selectedBy = RehydrateList, string>(deserializedEntry, "SelectedBy", RehydrationFlags.MissingPropertyOk); + private static ListControlEntry RehydrateListControlEntry(PSObject deserializedEntry) + { + var entrySelectedBy = GetPropertyValue(deserializedEntry, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); + if (entrySelectedBy == null) + { + var selectedBy = RehydrateList, string>(deserializedEntry, "SelectedBy", RehydrationFlags.MissingPropertyOk); entrySelectedBy = EntrySelectedBy.Get(selectedBy, null); } - var result = new ListControlEntry - { - Items = RehydrateList, ListControlEntryItem>(deserializedEntry, "Items", RehydrationFlags.NullValueBad), - EntrySelectedBy = entrySelectedBy - }; - return result; - } + var result = new ListControlEntry + { + Items = RehydrateList, ListControlEntryItem>(deserializedEntry, "Items", RehydrationFlags.NullValueBad), + EntrySelectedBy = entrySelectedBy + }; + return result; + } - private static TableControlColumnHeader RehydrateTableControlColumnHeader(PSObject deserializedHeader) - { - var result = new TableControlColumnHeader - { - Alignment = GetPropertyValue(deserializedHeader, "Alignment"), - Label = GetPropertyValue(deserializedHeader, "Label", RehydrationFlags.NullValueOk), - Width = GetPropertyValue(deserializedHeader, "Width") - }; - return result; - } + private static TableControlColumnHeader RehydrateTableControlColumnHeader(PSObject deserializedHeader) + { + var result = new TableControlColumnHeader + { + Alignment = GetPropertyValue(deserializedHeader, "Alignment"), + Label = GetPropertyValue(deserializedHeader, "Label", RehydrationFlags.NullValueOk), + Width = GetPropertyValue(deserializedHeader, "Width") + }; + return result; + } - private static TableControlColumn RehydrateTableControlColumn(PSObject deserializedColumn) - { - var result = new TableControlColumn - { - Alignment = GetPropertyValue(deserializedColumn, "Alignment"), - DisplayEntry = GetPropertyValue(deserializedColumn, "DisplayEntry"), - FormatString = GetPropertyValue(deserializedColumn, "FormatString", RehydrationFlags.MissingPropertyOk) - }; - return result; - } + private static TableControlColumn RehydrateTableControlColumn(PSObject deserializedColumn) + { + var result = new TableControlColumn + { + Alignment = GetPropertyValue(deserializedColumn, "Alignment"), + DisplayEntry = GetPropertyValue(deserializedColumn, "DisplayEntry"), + FormatString = GetPropertyValue(deserializedColumn, "FormatString", RehydrationFlags.MissingPropertyOk) + }; + return result; + } - private static TableControlRow RehydrateTableControlRow(PSObject deserializedRow) - { - var result = new TableControlRow - { - Wrap = GetPropertyValue(deserializedRow, "Wrap", RehydrationFlags.MissingPropertyOk), + private static TableControlRow RehydrateTableControlRow(PSObject deserializedRow) + { + var result = new TableControlRow + { + Wrap = GetPropertyValue(deserializedRow, "Wrap", RehydrationFlags.MissingPropertyOk), SelectedBy = GetPropertyValue(deserializedRow, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk), - Columns = RehydrateList, TableControlColumn>(deserializedRow, "Columns", RehydrationFlags.NullValueBad) - }; - return result; - } + Columns = RehydrateList, TableControlColumn>(deserializedRow, "Columns", RehydrationFlags.NullValueBad) + }; + return result; + } - private static CustomControlEntry RehydrateCustomControlEntry(PSObject deserializedEntry) - { - var result = new CustomControlEntry - { - CustomItems = RehydrateList, CustomItemBase>(deserializedEntry, "CustomItems", RehydrationFlags.MissingPropertyBad), + private static CustomControlEntry RehydrateCustomControlEntry(PSObject deserializedEntry) + { + var result = new CustomControlEntry + { + CustomItems = RehydrateList, CustomItemBase>(deserializedEntry, "CustomItems", RehydrationFlags.MissingPropertyBad), SelectedBy = GetPropertyValue(deserializedEntry, "SelectedBy", RehydrationFlags.MissingPropertyOk) - }; - return result; - } + }; + return result; + } - private static CustomItemBase RehydrateCustomItemBase(PSObject deserializedItem) - { - CustomItemBase result; + private static CustomItemBase RehydrateCustomItemBase(PSObject deserializedItem) + { + CustomItemBase result; - if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemNewline))) - { - result = new CustomItemNewline - { - Count = GetPropertyValue(deserializedItem, "Count", RehydrationFlags.MissingPropertyBad) - }; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemText))) - { - result = new CustomItemText - { - Text = GetPropertyValue(deserializedItem, "Text", RehydrationFlags.MissingPropertyBad) - }; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemFrame))) - { - result = new CustomItemFrame - { + if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemNewline))) + { + result = new CustomItemNewline + { + Count = GetPropertyValue(deserializedItem, "Count", RehydrationFlags.MissingPropertyBad) + }; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemText))) + { + result = new CustomItemText + { + Text = GetPropertyValue(deserializedItem, "Text", RehydrationFlags.MissingPropertyBad) + }; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemFrame))) + { + result = new CustomItemFrame + { FirstLineHanging = GetPropertyValue(deserializedItem, "FirstLineHanging"), FirstLineIndent = GetPropertyValue(deserializedItem, "FirstLineIndent"), RightIndent = GetPropertyValue(deserializedItem, "RightIndent"), LeftIndent = GetPropertyValue(deserializedItem, "LeftIndent"), CustomItems = RehydrateList, CustomItemBase>(deserializedItem, "CustomItems", RehydrationFlags.MissingPropertyBad) - }; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemExpression))) - { - result = new CustomItemExpression - { + }; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedItem, typeof(CustomItemExpression))) + { + result = new CustomItemExpression + { EnumerateCollection = GetPropertyValue(deserializedItem, "EnumerateCollection"), CustomControl = GetPropertyValue(deserializedItem, "CustomControl", RehydrationFlags.MissingPropertyOk), Expression = GetPropertyValue(deserializedItem, "Expression", RehydrationFlags.MissingPropertyOk), ItemSelectionCondition = GetPropertyValue(deserializedItem, "ItemSelectionCondition", RehydrationFlags.MissingPropertyOk) - }; - } - else - { - throw PSTraceSource.NewArgumentException("deserializedItem"); - } - return result; - } + }; + } + else + { + throw PSTraceSource.NewArgumentException("deserializedItem"); + } + return result; + } - private static PSControl RehydratePSControl(PSObject deserializedControl) - { + private static PSControl RehydratePSControl(PSObject deserializedControl) + { // Earlier versions of PowerShell did not have all of the possible properties in a control, so we must // use MisingPropertyOk to allow for connections to those older endpoints. - PSControl result; - if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(TableControl))) - { - var tableControl = new TableControl - { - AutoSize = GetPropertyValue(deserializedControl, "AutoSize", RehydrationFlags.MissingPropertyOk), + PSControl result; + if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(TableControl))) + { + var tableControl = new TableControl + { + AutoSize = GetPropertyValue(deserializedControl, "AutoSize", RehydrationFlags.MissingPropertyOk), HideTableHeaders = GetPropertyValue(deserializedControl, "HideTableHeaders", RehydrationFlags.MissingPropertyOk), - Headers = RehydrateList, TableControlColumnHeader>(deserializedControl, "Headers", RehydrationFlags.NullValueBad), - Rows = RehydrateList, TableControlRow>(deserializedControl, "Rows", RehydrationFlags.NullValueBad) - }; - result = tableControl; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(ListControl))) - { - var listControl = new ListControl - { - Entries = RehydrateList, ListControlEntry>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) - }; - result = listControl; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(WideControl))) - { - var wideControl = new WideControl - { - AutoSize = GetPropertyValue(deserializedControl, "Alignment", RehydrationFlags.MissingPropertyOk), - Columns = GetPropertyValue(deserializedControl, "Columns"), - Entries = RehydrateList, WideControlEntryItem>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) - }; - result = wideControl; - } - else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(CustomControl))) - { - var customControl = new CustomControl - { - Entries = RehydrateList, CustomControlEntry>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) - }; - result = customControl; - } - else - { - throw PSTraceSource.NewArgumentException("pso"); - } + Headers = RehydrateList, TableControlColumnHeader>(deserializedControl, "Headers", RehydrationFlags.NullValueBad), + Rows = RehydrateList, TableControlRow>(deserializedControl, "Rows", RehydrationFlags.NullValueBad) + }; + result = tableControl; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(ListControl))) + { + var listControl = new ListControl + { + Entries = RehydrateList, ListControlEntry>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) + }; + result = listControl; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(WideControl))) + { + var wideControl = new WideControl + { + AutoSize = GetPropertyValue(deserializedControl, "Alignment", RehydrationFlags.MissingPropertyOk), + Columns = GetPropertyValue(deserializedControl, "Columns"), + Entries = RehydrateList, WideControlEntryItem>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) + }; + result = wideControl; + } + else if (Deserializer.IsDeserializedInstanceOfType(deserializedControl, typeof(CustomControl))) + { + var customControl = new CustomControl + { + Entries = RehydrateList, CustomControlEntry>(deserializedControl, "Entries", RehydrationFlags.NullValueBad) + }; + result = customControl; + } + else + { + throw PSTraceSource.NewArgumentException("pso"); + } - result.GroupBy = GetPropertyValue(deserializedControl, "GroupBy", RehydrationFlags.MissingPropertyOk); - result.OutOfBand = GetPropertyValue(deserializedControl, "OutOfBand", RehydrationFlags.MissingPropertyOk); - return result; - } + result.GroupBy = GetPropertyValue(deserializedControl, "GroupBy", RehydrationFlags.MissingPropertyOk); + result.OutOfBand = GetPropertyValue(deserializedControl, "OutOfBand", RehydrationFlags.MissingPropertyOk); + return result; + } - private static PSControlGroupBy RehydrateGroupBy(PSObject deserializedGroupBy) - { - var result = new PSControlGroupBy - { - CustomControl = GetPropertyValue(deserializedGroupBy, "CustomControl", RehydrationFlags.MissingPropertyOk), - Expression = GetPropertyValue(deserializedGroupBy, "Expression", RehydrationFlags.MissingPropertyOk), - Label = GetPropertyValue(deserializedGroupBy, "Label", RehydrationFlags.NullValueOk) - }; - return result; - } + private static PSControlGroupBy RehydrateGroupBy(PSObject deserializedGroupBy) + { + var result = new PSControlGroupBy + { + CustomControl = GetPropertyValue(deserializedGroupBy, "CustomControl", RehydrationFlags.MissingPropertyOk), + Expression = GetPropertyValue(deserializedGroupBy, "Expression", RehydrationFlags.MissingPropertyOk), + Label = GetPropertyValue(deserializedGroupBy, "Label", RehydrationFlags.NullValueOk) + }; + return result; + } /// /// Gets the boolean properties of ParameterSetMetadata object encoded as an integer @@ -7495,62 +7491,62 @@ namespace Microsoft.PowerShell /// Boolean properties of ParameterSetMetadata object encoded as an integer /// public static Guid GetFormatViewDefinitionInstanceId(PSObject instance) - { - if(instance == null) - { - throw PSTraceSource.NewArgumentNullException("instance"); - } + { + if (instance == null) + { + throw PSTraceSource.NewArgumentNullException("instance"); + } - FormatViewDefinition formatViewDefinition = instance.BaseObject as FormatViewDefinition; - if(formatViewDefinition == null) - { - throw PSTraceSource.NewArgumentNullException("instance"); - } + FormatViewDefinition formatViewDefinition = instance.BaseObject as FormatViewDefinition; + if (formatViewDefinition == null) + { + throw PSTraceSource.NewArgumentNullException("instance"); + } - return formatViewDefinition.InstanceId; - } + return formatViewDefinition.InstanceId; + } - private static FormatViewDefinition RehydrateFormatViewDefinition(PSObject deserializedViewDefinition) - { - string name = GetPropertyValue(deserializedViewDefinition, "Name"); - Guid instanceId = GetPropertyValue(deserializedViewDefinition, "InstanceId"); - PSControl control = GetPropertyValue(deserializedViewDefinition, "Control"); + private static FormatViewDefinition RehydrateFormatViewDefinition(PSObject deserializedViewDefinition) + { + string name = GetPropertyValue(deserializedViewDefinition, "Name"); + Guid instanceId = GetPropertyValue(deserializedViewDefinition, "InstanceId"); + PSControl control = GetPropertyValue(deserializedViewDefinition, "Control"); - return new FormatViewDefinition(name, control, instanceId); - } + return new FormatViewDefinition(name, control, instanceId); + } - private static ExtendedTypeDefinition RehydrateExtendedTypeDefinition(PSObject deserializedTypeDefinition) - { + private static ExtendedTypeDefinition RehydrateExtendedTypeDefinition(PSObject deserializedTypeDefinition) + { // Prefer TypeNames to TypeName - as it was incorrect to create multiple ExtendedTypeDefinitions for a group of types. // But if a new PowerShell connects to an old endpoint, TypeNames will be missing, so fall back to TypeName in that case. - string typeName; - var typeNames = RehydrateList, string>(deserializedTypeDefinition, "TypeNames", RehydrationFlags.MissingPropertyOk); - if (typeNames == null || typeNames.Count == 0) - { + string typeName; + var typeNames = RehydrateList, string>(deserializedTypeDefinition, "TypeNames", RehydrationFlags.MissingPropertyOk); + if (typeNames == null || typeNames.Count == 0) + { typeName = GetPropertyValue(deserializedTypeDefinition, "TypeName"); - } + } else - { + { typeName = typeNames[0]; - } + } - List viewDefinitions = RehydrateList, FormatViewDefinition>( - deserializedTypeDefinition, - "FormatViewDefinition", - RehydrationFlags.NullValueBad); + List viewDefinitions = RehydrateList, FormatViewDefinition>( + deserializedTypeDefinition, + "FormatViewDefinition", + RehydrationFlags.NullValueBad); - var result = new ExtendedTypeDefinition(typeName, viewDefinitions); - if (typeNames != null && typeNames.Count > 1) - { - for (var i = 1; i < typeNames.Count; i++) - { - result.TypeNames.Add(typeNames[i]); - } - } - return result; - } + var result = new ExtendedTypeDefinition(typeName, viewDefinitions); + if (typeNames != null && typeNames.Count > 1) + { + for (var i = 1; i < typeNames.Count; i++) + { + result.TypeNames.Add(typeNames[i]); + } + } + return result; + } - #endregion - } + #endregion + } } diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index f138d820a..e7643f3c7 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Diagnostics.CodeAnalysis; // for fxcop namespace System.Management.Automation @@ -18,7 +19,7 @@ namespace System.Management.Automation /// The constructor is private. The only way to create an /// AliasHelpInfo object is through static method /// - [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] private AliasHelpInfo(AliasInfo aliasInfo) { _fullHelpObject = new PSObject(); diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index d8d18dbf8..c5d527257 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Management.Automation.Internal; @@ -19,7 +20,7 @@ namespace System.Management.Automation /// The real information for alias is stored in command help. To retrieve the real /// help information, help forwarding is needed. /// - internal class AliasHelpProvider: HelpProvider + internal class AliasHelpProvider : HelpProvider { /// /// Initializes a new instance of AliasHelpProvider class. @@ -99,7 +100,7 @@ namespace System.Management.Automation try { - commandInfo = this._commandDiscovery.LookupCommandInfo(helpRequest.Target); + commandInfo = _commandDiscovery.LookupCommandInfo(helpRequest.Target); } catch (CommandNotFoundException) { @@ -265,7 +266,7 @@ namespace System.Management.Automation if (0 == (helpRequest.HelpCategory & helpInfo.HelpCategory)) { return false; - } + } if (!Match(helpInfo.Component, helpRequest.Component)) { diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 7ecc41c1b..4f416df4a 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.Linq; using System.Management.Automation.Runspaces; @@ -17,7 +18,7 @@ namespace System.Management.Automation /// internal abstract class BaseCommandHelpInfo : HelpInfo { - internal BaseCommandHelpInfo(HelpCategory helpCategory) + internal BaseCommandHelpInfo(HelpCategory helpCategory) : base() { _helpCategory = helpCategory; @@ -91,23 +92,23 @@ namespace System.Management.Automation } object[] synopsisItems = (object[])LanguagePrimitives.ConvertTo( - commandDetails.Properties["Description"].Value, + commandDetails.Properties["Description"].Value, typeof(object[]), CultureInfo.InvariantCulture); - if (synopsisItems == null || synopsisItems.Length == 0) - { + if (synopsisItems == null || synopsisItems.Length == 0) + { return ""; - } - - PSObject firstSynopsisItem = synopsisItems[0] == null ? null : PSObject.AsPSObject(synopsisItems[0]); - if (firstSynopsisItem == null || - firstSynopsisItem.Properties["Text"] == null || - firstSynopsisItem.Properties["Text"].Value == null) - { - return ""; } - string synopsis = firstSynopsisItem.Properties["Text"].Value.ToString(); + PSObject firstSynopsisItem = synopsisItems[0] == null ? null : PSObject.AsPSObject(synopsisItems[0]); + if (firstSynopsisItem == null || + firstSynopsisItem.Properties["Text"] == null || + firstSynopsisItem.Properties["Text"].Value == null) + { + return ""; + } + + string synopsis = firstSynopsisItem.Properties["Text"].Value.ToString(); if (synopsis == null) { return ""; @@ -177,7 +178,7 @@ namespace System.Management.Automation internal Uri LookupUriFromCommandInfo() { CommandTypes cmdTypesToLookFor = CommandTypes.Cmdlet; - switch(this.HelpCategory) + switch (this.HelpCategory) { case Automation.HelpCategory.Cmdlet: cmdTypesToLookFor = CommandTypes.Cmdlet; @@ -206,7 +207,7 @@ namespace System.Management.Automation default: return null; } - + string commandName = this.Name; string moduleName = string.Empty; if (this.FullHelp.Properties["ModuleName"] != null) @@ -244,7 +245,7 @@ namespace System.Management.Automation { cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault(); } - + if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null)) { return null; @@ -252,7 +253,7 @@ namespace System.Management.Automation string uriString = cmdInfo.CommandMetadata.HelpUri; if (!string.IsNullOrEmpty(uriString)) - { + { if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute)) { // WinBlue: 545315 Online help links are broken with localized help @@ -276,9 +277,8 @@ namespace System.Management.Automation } } } - catch(CommandNotFoundException) + catch (CommandNotFoundException) { - } return null; @@ -303,7 +303,7 @@ namespace System.Management.Automation } object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo( - relatedLinks.Properties["navigationLink"].Value, + relatedLinks.Properties["navigationLink"].Value, typeof(object[]), CultureInfo.InvariantCulture); foreach (object navigationLinkAsObject in navigationLinks) @@ -361,7 +361,7 @@ namespace System.Management.Automation internal override bool MatchPatternInContent(WildcardPattern pattern) { Dbg.Assert(null != pattern, "pattern cannot be null"); - + string synopsis = Synopsis; string detailedDescription = DetailedDescription; @@ -387,7 +387,7 @@ namespace System.Management.Automation { // this object knows Maml format... // So retrieve parameter information as per the format.. - if ((this.FullHelp == null) || + if ((this.FullHelp == null) || (this.FullHelp.Properties["parameters"] == null) || (this.FullHelp.Properties["parameters"].Value == null)) { @@ -403,7 +403,7 @@ namespace System.Management.Automation } PSObject[] prmtArray = (PSObject[])LanguagePrimitives.ConvertTo( - prmts.Properties["parameter"].Value, + prmts.Properties["parameter"].Value, typeof(PSObject[]), CultureInfo.InvariantCulture); @@ -452,7 +452,7 @@ namespace System.Management.Automation } object[] descriptionItems = (object[])LanguagePrimitives.ConvertTo( - this.FullHelp.Properties["Description"].Value, + this.FullHelp.Properties["Description"].Value, typeof(object[]), CultureInfo.InvariantCulture); if (descriptionItems == null || descriptionItems.Length == 0) diff --git a/src/System.Management.Automation/help/CabinetAPI.cs b/src/System.Management.Automation/help/CabinetAPI.cs index a1a28f8a2..59360aabb 100644 --- a/src/System.Management.Automation/help/CabinetAPI.cs +++ b/src/System.Management.Automation/help/CabinetAPI.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Internal @@ -29,7 +30,7 @@ namespace System.Management.Automation.Internal /// /// Flag: Has Dispose already been called? /// - private bool disposed = false; + private bool _disposed = false; /// /// Disposes the instance, callable by consumers. @@ -42,7 +43,7 @@ namespace System.Management.Automation.Internal protected virtual void Dispose(bool disposing) { - if (disposed) + if (_disposed) { // Nothing to do since the resource has already been disposed. return; @@ -52,7 +53,7 @@ namespace System.Management.Automation.Internal // Free managed objects if disposing == true; // Free unmanaged objects regardless. - disposed = true; + _disposed = true; } ~ICabinetExtractor() @@ -81,7 +82,7 @@ namespace System.Management.Automation.Internal /// internal class CabinetExtractorFactory { - private static ICabinetExtractorLoader cabinetLoader; + private static ICabinetExtractorLoader s_cabinetLoader; internal static ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); /// @@ -90,7 +91,7 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] static CabinetExtractorFactory() { - cabinetLoader = CabinetExtractorLoader.GetInstance(); + s_cabinetLoader = CabinetExtractorLoader.GetInstance(); } /// @@ -99,9 +100,9 @@ namespace System.Management.Automation.Internal /// Tracer instance internal static ICabinetExtractor GetCabinetExtractor() { - if (cabinetLoader != null) + if (s_cabinetLoader != null) { - return cabinetLoader.GetCabinetExtractor(); + return s_cabinetLoader.GetCabinetExtractor(); } else { diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 7edbc9e8b..f9bfe5680 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; @@ -16,40 +17,40 @@ namespace System.Management.Automation.Internal /// /// GC handle which prevents garbage collector from collecting this delegate. /// - private CabinetNativeApi.FdiAllocDelegate allocDelegate; - private GCHandle fdiAllocHandle; - private CabinetNativeApi.FdiFreeDelegate freeDelegate; - private GCHandle fdiFreeHandle; - private CabinetNativeApi.FdiOpenDelegate openDelegate; - private GCHandle fdiOpenHandle; - private CabinetNativeApi.FdiReadDelegate readDelegate; - private GCHandle fdiReadHandle; - private CabinetNativeApi.FdiWriteDelegate writeDelegate; - private GCHandle fdiWriteHandle; - private CabinetNativeApi.FdiCloseDelegate closeDelegate; - private GCHandle fdiCloseHandle; - private CabinetNativeApi.FdiSeekDelegate seekDelegate; - private GCHandle fdiSeekHandle; - private CabinetNativeApi.FdiNotifyDelegate notifyDelegate; - private GCHandle fdiNotifyHandle; + private CabinetNativeApi.FdiAllocDelegate _allocDelegate; + private GCHandle _fdiAllocHandle; + private CabinetNativeApi.FdiFreeDelegate _freeDelegate; + private GCHandle _fdiFreeHandle; + private CabinetNativeApi.FdiOpenDelegate _openDelegate; + private GCHandle _fdiOpenHandle; + private CabinetNativeApi.FdiReadDelegate _readDelegate; + private GCHandle _fdiReadHandle; + private CabinetNativeApi.FdiWriteDelegate _writeDelegate; + private GCHandle _fdiWriteHandle; + private CabinetNativeApi.FdiCloseDelegate _closeDelegate; + private GCHandle _fdiCloseHandle; + private CabinetNativeApi.FdiSeekDelegate _seekDelegate; + private GCHandle _fdiSeekHandle; + private CabinetNativeApi.FdiNotifyDelegate _notifyDelegate; + private GCHandle _fdiNotifyHandle; internal CabinetNativeApi.FdiContextHandle fdiContext; // HFDI internal CabinetExtractor() { CabinetNativeApi.FdiERF err = new CabinetNativeApi.FdiERF(); - + populateDelegates(); // marshal the delegate to a unmanaged function pointer so that AppDomain reference is stored correctly. fdiContext = CabinetNativeApi.FDICreate( - Marshal.GetFunctionPointerForDelegate(allocDelegate), - Marshal.GetFunctionPointerForDelegate(freeDelegate), - Marshal.GetFunctionPointerForDelegate(openDelegate), - Marshal.GetFunctionPointerForDelegate(readDelegate), - Marshal.GetFunctionPointerForDelegate(writeDelegate), - Marshal.GetFunctionPointerForDelegate(closeDelegate), - Marshal.GetFunctionPointerForDelegate(seekDelegate), + Marshal.GetFunctionPointerForDelegate(_allocDelegate), + Marshal.GetFunctionPointerForDelegate(_freeDelegate), + Marshal.GetFunctionPointerForDelegate(_openDelegate), + Marshal.GetFunctionPointerForDelegate(_readDelegate), + Marshal.GetFunctionPointerForDelegate(_writeDelegate), + Marshal.GetFunctionPointerForDelegate(_closeDelegate), + Marshal.GetFunctionPointerForDelegate(_seekDelegate), CabinetNativeApi.FdiCreateCpuType.Cpu80386, err); } @@ -59,7 +60,7 @@ namespace System.Management.Automation.Internal /// /// Flag: Has Dispose already been called? /// - private bool disposed = false; + private bool _disposed = false; /// /// Protected implementation of Dispose pattern. @@ -67,7 +68,7 @@ namespace System.Management.Automation.Internal /// protected override void Dispose(bool disposing) { - if (disposed) + if (_disposed) { return; } @@ -80,7 +81,7 @@ namespace System.Management.Automation.Internal // Free unmanaged objects here this.CleanUpDelegates(); - disposed = true; + _disposed = true; // Call base class implementation in case it has resources to release base.Dispose(disposing); @@ -103,9 +104,9 @@ namespace System.Management.Automation.Internal bool result = CabinetNativeApi.FDICopy( fdiContext, cabinetName, - srcPath, + srcPath, 0, // Not used - Marshal.GetFunctionPointerForDelegate(notifyDelegate), + Marshal.GetFunctionPointerForDelegate(_notifyDelegate), IntPtr.Zero, nativeDestPath); @@ -124,29 +125,29 @@ namespace System.Management.Automation.Internal // to the delegate, allowing relocation of the delegate, but preventing // disposal. Using GCHandle without pinning reduces fragmentation potential // of the managed heap. - allocDelegate = new CabinetNativeApi.FdiAllocDelegate(CabinetNativeApi.FdiAlloc); - this.fdiAllocHandle = GCHandle.Alloc(allocDelegate); + _allocDelegate = new CabinetNativeApi.FdiAllocDelegate(CabinetNativeApi.FdiAlloc); + _fdiAllocHandle = GCHandle.Alloc(_allocDelegate); - freeDelegate = new CabinetNativeApi.FdiFreeDelegate(CabinetNativeApi.FdiFree); - this.fdiFreeHandle = GCHandle.Alloc(freeDelegate); + _freeDelegate = new CabinetNativeApi.FdiFreeDelegate(CabinetNativeApi.FdiFree); + _fdiFreeHandle = GCHandle.Alloc(_freeDelegate); - openDelegate = new CabinetNativeApi.FdiOpenDelegate(CabinetNativeApi.FdiOpen); - this.fdiOpenHandle = GCHandle.Alloc(openDelegate); + _openDelegate = new CabinetNativeApi.FdiOpenDelegate(CabinetNativeApi.FdiOpen); + _fdiOpenHandle = GCHandle.Alloc(_openDelegate); - readDelegate = new CabinetNativeApi.FdiReadDelegate(CabinetNativeApi.FdiRead); - this.fdiReadHandle = GCHandle.Alloc(readDelegate); + _readDelegate = new CabinetNativeApi.FdiReadDelegate(CabinetNativeApi.FdiRead); + _fdiReadHandle = GCHandle.Alloc(_readDelegate); - writeDelegate = new CabinetNativeApi.FdiWriteDelegate(CabinetNativeApi.FdiWrite); - this.fdiWriteHandle = GCHandle.Alloc(writeDelegate); + _writeDelegate = new CabinetNativeApi.FdiWriteDelegate(CabinetNativeApi.FdiWrite); + _fdiWriteHandle = GCHandle.Alloc(_writeDelegate); - closeDelegate = new CabinetNativeApi.FdiCloseDelegate(CabinetNativeApi.FdiClose); - this.fdiCloseHandle = GCHandle.Alloc(closeDelegate); + _closeDelegate = new CabinetNativeApi.FdiCloseDelegate(CabinetNativeApi.FdiClose); + _fdiCloseHandle = GCHandle.Alloc(_closeDelegate); - seekDelegate = new CabinetNativeApi.FdiSeekDelegate(CabinetNativeApi.FdiSeek); - this.fdiSeekHandle = GCHandle.Alloc(seekDelegate); + _seekDelegate = new CabinetNativeApi.FdiSeekDelegate(CabinetNativeApi.FdiSeek); + _fdiSeekHandle = GCHandle.Alloc(_seekDelegate); - notifyDelegate = new CabinetNativeApi.FdiNotifyDelegate(CabinetNativeApi.FdiNotify); - this.fdiNotifyHandle = GCHandle.Alloc(notifyDelegate); + _notifyDelegate = new CabinetNativeApi.FdiNotifyDelegate(CabinetNativeApi.FdiNotify); + _fdiNotifyHandle = GCHandle.Alloc(_notifyDelegate); } /// @@ -155,41 +156,41 @@ namespace System.Management.Automation.Internal private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (null != this.fdiAllocHandle) + if (null != _fdiAllocHandle) { - this.fdiAllocHandle.Free(); - this.fdiFreeHandle.Free(); - this.fdiOpenHandle.Free(); - this.fdiReadHandle.Free(); - this.fdiWriteHandle.Free(); - this.fdiCloseHandle.Free(); - this.fdiSeekHandle.Free(); - this.fdiNotifyHandle.Free(); + _fdiAllocHandle.Free(); + _fdiFreeHandle.Free(); + _fdiOpenHandle.Free(); + _fdiReadHandle.Free(); + _fdiWriteHandle.Free(); + _fdiCloseHandle.Free(); + _fdiSeekHandle.Free(); + _fdiNotifyHandle.Free(); } - } + } }; // CabinetExtractor loader implementation internal class CabinetExtractorLoader : ICabinetExtractorLoader { - private static CabinetExtractor extractorInstance; - private static CabinetExtractorLoader instance; - private static double created = 0; + private static CabinetExtractor s_extractorInstance; + private static CabinetExtractorLoader s_instance; + private static double s_created = 0; internal static CabinetExtractorLoader GetInstance() { - if (0 == System.Threading.Interlocked.CompareExchange(ref created, 1, 0)) + if (0 == System.Threading.Interlocked.CompareExchange(ref s_created, 1, 0)) { - instance = new CabinetExtractorLoader(); - extractorInstance = new CabinetExtractor(); + s_instance = new CabinetExtractorLoader(); + s_extractorInstance = new CabinetExtractor(); } - return instance; + return s_instance; } internal override ICabinetExtractor GetCabinetExtractor() { - return extractorInstance; + return s_extractorInstance; } }; @@ -222,8 +223,8 @@ namespace System.Management.Automation.Internal [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr FdiOpenDelegate( - [MarshalAs(UnmanagedType.LPStr)] string filename, - int oflag, + [MarshalAs(UnmanagedType.LPStr)] string filename, + int oflag, int pmode); internal static IntPtr FdiOpen(string filename, int oflag, int pmode) @@ -248,11 +249,11 @@ namespace System.Management.Automation.Internal return new IntPtr(-1); } } - + [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiReadDelegate( IntPtr fp, - [In, Out] + [In, Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int count); @@ -267,12 +268,12 @@ namespace System.Management.Automation.Internal { numCharactersRead = stream.Read(buffer, 0, count); } - catch(ArgumentNullException) { numCharactersRead = -1; } - catch(ArgumentOutOfRangeException) { numCharactersRead = -1; } - catch(NotSupportedException) { numCharactersRead = -1; } - catch(IOException) { numCharactersRead = -1; } - catch(ArgumentException) { numCharactersRead = -1; } - catch(ObjectDisposedException) { numCharactersRead = -1; } + catch (ArgumentNullException) { numCharactersRead = -1; } + catch (ArgumentOutOfRangeException) { numCharactersRead = -1; } + catch (NotSupportedException) { numCharactersRead = -1; } + catch (IOException) { numCharactersRead = -1; } + catch (ArgumentException) { numCharactersRead = -1; } + catch (ObjectDisposedException) { numCharactersRead = -1; } return numCharactersRead; } @@ -280,8 +281,8 @@ namespace System.Management.Automation.Internal [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiWriteDelegate( IntPtr fp, - [In] - [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] + [In] + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int count); @@ -296,12 +297,12 @@ namespace System.Management.Automation.Internal stream.Write(buffer, 0, count); numCharactersWritten = count; // Write doesn't return the number of bytes written. Per MSDN, if it succeeds, it will have written count bytes. } - catch(ArgumentNullException) { numCharactersWritten = -1; } - catch(ArgumentOutOfRangeException) { numCharactersWritten = -1; } - catch(NotSupportedException) { numCharactersWritten = -1; } - catch(IOException) { numCharactersWritten = -1; } - catch(ArgumentException) { numCharactersWritten = -1; } - catch(ObjectDisposedException) { numCharactersWritten = -1; } + catch (ArgumentNullException) { numCharactersWritten = -1; } + catch (ArgumentOutOfRangeException) { numCharactersWritten = -1; } + catch (NotSupportedException) { numCharactersWritten = -1; } + catch (IOException) { numCharactersWritten = -1; } + catch (ArgumentException) { numCharactersWritten = -1; } + catch (ObjectDisposedException) { numCharactersWritten = -1; } return numCharactersWritten; } @@ -339,10 +340,10 @@ namespace System.Management.Automation.Internal { status = stream.Seek(offset, seekOrigin); } - catch(NotSupportedException) { status = -1; } - catch(IOException) { status = -1; } - catch(ArgumentException) { status = -1; } - catch(ObjectDisposedException) { status = -1; } + catch (NotSupportedException) { status = -1; } + catch (IOException) { status = -1; } + catch (ArgumentException) { status = -1; } + catch (ObjectDisposedException) { status = -1; } return (int)status; } @@ -353,7 +354,7 @@ namespace System.Management.Automation.Internal // Handles FDI notification internal static IntPtr FdiNotify(FdiNotificationType fdint, FdiNotification fdin) { - switch(fdint) + switch (fdint) { case FdiNotificationType.FdintCOPY_FILE: { @@ -407,7 +408,7 @@ namespace System.Management.Automation.Internal } PlatformInvokes.SetFileAttributesW( - absoluteFilePath, + absoluteFilePath, (PlatformInvokes.FileAttributes)fdin.attribs & (PlatformInvokes.FileAttributes.ReadOnly | PlatformInvokes.FileAttributes.Hidden | PlatformInvokes.FileAttributes.System | PlatformInvokes.FileAttributes.Archive)); // Call notification function @@ -428,7 +429,7 @@ namespace System.Management.Automation.Internal /// The appropriate System.IO.SeekOrigin value. internal static SeekOrigin ConvertOriginToSeekOrigin(int origin) { - switch(origin) + switch (origin) { case 0x0: // SEEK_SET return SeekOrigin.Begin; @@ -466,7 +467,7 @@ namespace System.Management.Automation.Internal { return FileMode.Create; } - else if (0 != (oflag & (int)OpFlags.RdWr)) + else if (0 != (oflag & (int)OpFlags.RdWr)) { return FileMode.Open; } @@ -479,7 +480,7 @@ namespace System.Management.Automation.Internal return FileMode.OpenOrCreate; // This seemed the safest way to handled unrecognized types } } - + /// /// Converts an unmanaged define into a known managed type. /// @@ -585,20 +586,20 @@ namespace System.Management.Automation.Internal internal enum FdiNotificationType : int { - FdintCABINET_INFO = 0x0, - FdintPARTIAL_FILE = 0x1, - FdintCOPY_FILE = 0x2, - FdintCLOSE_FILE_INFO = 0x3, - FdintNEXT_CABINET = 0x4, - FdintENUMERATE = 0x5 + FdintCABINET_INFO = 0x0, + FdintPARTIAL_FILE = 0x1, + FdintCOPY_FILE = 0x2, + FdintCLOSE_FILE_INFO = 0x3, + FdintNEXT_CABINET = 0x4, + FdintENUMERATE = 0x5 } [StructLayout(LayoutKind.Sequential)] - internal class FdiERF + internal class FdiERF { - internal int erfOper; - internal int erfType; - internal bool fError; + internal int erfOper; + internal int erfType; + internal bool fError; }; internal sealed class FdiContextHandle : SafeHandleZeroOrMinusOneIsInvalid @@ -657,7 +658,7 @@ namespace System.Management.Automation.Internal [DllImport("cabinet.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, SetLastError = true, BestFitMapping = false)] internal static extern bool FDICopy( FdiContextHandle hfdi, - [MarshalAs(UnmanagedType.LPStr)] string pszCabinet, + [MarshalAs(UnmanagedType.LPStr)] string pszCabinet, [MarshalAs(UnmanagedType.LPStr)] string pszCabPath, int flags, IntPtr pfnfdin, diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 8d3c8b666..1534b1049 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -27,7 +27,7 @@ namespace System.Management.Automation /// Command Help information are stored in 'help.xml' files. Location of these files /// can be found from through the engine execution context. /// - internal class CommandHelpProvider: HelpProviderWithCache + internal class CommandHelpProvider : HelpProviderWithCache { /// /// Constructor for CommandHelpProvider @@ -42,16 +42,16 @@ namespace System.Management.Automation /// static CommandHelpProvider() { - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Core", "System.Management.Automation.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security.dll-Help.xml"); - engineModuleHelpFileCache.Add("Microsoft.WSMan.Management", "Microsoft.Wsman.Management.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Core", "System.Management.Automation.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security.dll-Help.xml"); + s_engineModuleHelpFileCache.Add("Microsoft.WSMan.Management", "Microsoft.Wsman.Management.dll-Help.xml"); } - private static Dictionary engineModuleHelpFileCache = new Dictionary(); + private static Dictionary s_engineModuleHelpFileCache = new Dictionary(); private readonly ExecutionContext _context; @@ -77,7 +77,7 @@ namespace System.Management.Automation { get { - return + return HelpCategory.Alias | HelpCategory.Cmdlet; } @@ -111,23 +111,23 @@ namespace System.Management.Automation testWithoutPrefix = true; cmdNameWithoutPrefix = Microsoft.PowerShell.Commands.ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix); } - + if (commandInfo.Module.NestedModules != null) { foreach (PSModuleInfo nestedModule in commandInfo.Module.NestedModules) { - if ( cmdletInfo != null && - ( nestedModule.ExportedCmdlets.ContainsKey(commandInfo.Name) || - ( testWithoutPrefix && nestedModule.ExportedCmdlets.ContainsKey(cmdNameWithoutPrefix) ) ) ) + if (cmdletInfo != null && + (nestedModule.ExportedCmdlets.ContainsKey(commandInfo.Name) || + (testWithoutPrefix && nestedModule.ExportedCmdlets.ContainsKey(cmdNameWithoutPrefix)))) { nestedModulePath = nestedModule.Path; break; } - else if ( scriptCommandInfo != null && - ( nestedModule.ExportedFunctions.ContainsKey(commandInfo.Name) || - nestedModule.ExportedWorkflows.ContainsKey(commandInfo.Name) || - ( testWithoutPrefix && nestedModule.ExportedFunctions.ContainsKey(cmdNameWithoutPrefix) ) || - ( testWithoutPrefix && nestedModule.ExportedWorkflows.ContainsKey(cmdNameWithoutPrefix) ) ) ) + else if (scriptCommandInfo != null && + (nestedModule.ExportedFunctions.ContainsKey(commandInfo.Name) || + nestedModule.ExportedWorkflows.ContainsKey(commandInfo.Name) || + (testWithoutPrefix && nestedModule.ExportedFunctions.ContainsKey(cmdNameWithoutPrefix)) || + (testWithoutPrefix && nestedModule.ExportedWorkflows.ContainsKey(cmdNameWithoutPrefix)))) { nestedModulePath = nestedModule.Path; break; @@ -265,7 +265,7 @@ namespace System.Management.Automation // want to download the content from the remote machine. Reason: In Exchange scenario there // are ~700 proxy commands, downloading help for all the commands and searching in that // content takes a lot of time (in the order of 30 minutes) for their scenarios. - result = sb.GetHelpInfo(this._context, commandInfo, searchOnlyContent, HelpSystem.ScriptBlockTokenCache, + result = sb.GetHelpInfo(_context, commandInfo, searchOnlyContent, HelpSystem.ScriptBlockTokenCache, out helpFile, out helpUriFromDotLink); if (!String.IsNullOrEmpty(helpUriFromDotLink)) @@ -529,7 +529,7 @@ namespace System.Management.Automation // like "get-command -syntax" if (String.IsNullOrEmpty(location)) { - tracer.WriteLine("Unable to load file {0}", helpFileToLoad); + s_tracer.WriteLine("Unable to load file {0}", helpFileToLoad); } return location; @@ -556,7 +556,7 @@ namespace System.Management.Automation { if (InitialSessionState.IsEngineModule(cmdletInfo.Module.Name)) { - return System.IO.Path.Combine(cmdletInfo.Module.ModuleBase, CultureInfo.CurrentCulture.Name, engineModuleHelpFileCache[cmdletInfo.Module.Name]); + return System.IO.Path.Combine(cmdletInfo.Module.ModuleBase, CultureInfo.CurrentCulture.Name, s_engineModuleHelpFileCache[cmdletInfo.Module.Name]); } } @@ -640,7 +640,7 @@ namespace System.Management.Automation { e = invalidOperationException; } - + if (reportErrors && (e != null)) { ReportHelpFileError(e, commandName, helpFile); @@ -684,7 +684,7 @@ namespace System.Management.Automation if (helpItemsNode == null) { - tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); + s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; } @@ -836,7 +836,6 @@ namespace System.Management.Automation if (newMamlHelpInfo.FullHelp.Properties["Details"] != null && newMamlHelpInfo.FullHelp.Properties["Details"].Value != null) { - PSObject commandDetails = PSObject.AsPSObject(newMamlHelpInfo.FullHelp.Properties["Details"].Value); if (commandDetails.Properties["Noun"] != null) { @@ -912,7 +911,7 @@ namespace System.Management.Automation } } - return result; + return result; } /// @@ -939,7 +938,7 @@ namespace System.Management.Automation helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, "MamlCommandHelpInfo#{0}", mshSnapInId)); } - + AddCache(key, helpInfo); } @@ -975,7 +974,7 @@ namespace System.Management.Automation } return false; - } + } /// /// Search help for a specific target. @@ -1014,7 +1013,6 @@ namespace System.Management.Automation else { patternList.Add(target); - } } else @@ -1049,7 +1047,7 @@ namespace System.Management.Automation HelpInfo helpInfo = GetHelpInfo(current, !decoratedSearch, searchOnlyContent); string helpName = GetHelpName(current); - + if (helpInfo != null && !String.IsNullOrEmpty(helpName)) { if (!SessionState.IsVisible(helpRequest.CommandOrigin, current)) @@ -1179,10 +1177,10 @@ namespace System.Management.Automation static private bool Match(string target, string pattern) { - if(String.IsNullOrEmpty(pattern)) + if (String.IsNullOrEmpty(pattern)) return true; - if(String.IsNullOrEmpty(target)) + if (String.IsNullOrEmpty(target)) target = ""; WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); @@ -1210,7 +1208,7 @@ namespace System.Management.Automation foreach (string pattern in patterns) { - if ( Match(target, pattern) ) + if (Match(target, pattern)) { // we have a match so return true return true; @@ -1250,7 +1248,7 @@ namespace System.Management.Automation { try { - CommandInfo targetCommand = this._context.CommandDiscovery.LookupCommandInfo(commandHelpRequest.Target); + CommandInfo targetCommand = _context.CommandDiscovery.LookupCommandInfo(commandHelpRequest.Target); commandHelpRequest.HelpCategory = targetCommand.HelpCategory; } catch (CommandNotFoundException) @@ -1296,7 +1294,7 @@ namespace System.Management.Automation internal virtual CommandSearcher GetCommandSearcherForExactMatch(string commandName, ExecutionContext context) { CommandSearcher searcher = new CommandSearcher( - commandName, + commandName, SearchResolutionOptions.None, CommandTypes.Cmdlet, context); @@ -1328,7 +1326,7 @@ namespace System.Management.Automation #region tracer [TraceSource("CommandHelpProvider", "CommandHelpProvider")] - static private readonly PSTraceSource tracer = PSTraceSource.GetTracer("CommandHelpProvider", "CommandHelpProvider"); + static private readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandHelpProvider", "CommandHelpProvider"); #endregion tracer } @@ -1368,7 +1366,7 @@ namespace System.Management.Automation static internal UserDefinedHelpData Load(XmlNode dataNode) { - if(dataNode == null) + if (dataNode == null) return null; UserDefinedHelpData userDefinedHelpData = new UserDefinedHelpData(); diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index e80af72de..ccdc89426 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Globalization; @@ -162,18 +163,18 @@ namespace System.Management.Automation.Help /// command verb /// type name for help /// synopsis - static internal void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp, + static internal void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp, string synopsis = null) { PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#details", typeNameForHelp)); + mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp)); mshObject.Properties.Add(new PSNoteProperty("name", name)); mshObject.Properties.Add(new PSNoteProperty("noun", noun)); mshObject.Properties.Add(new PSNoteProperty("verb", verb)); - + // add synopsis if (!string.IsNullOrEmpty(synopsis)) { @@ -226,7 +227,7 @@ namespace System.Management.Automation.Help PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#syntaxItem", typeNameForHelp)); + mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp)); mshObject.Properties.Add(new PSNoteProperty("name", cmdletName)); mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common)); @@ -358,7 +359,7 @@ namespace System.Management.Automation.Help PSObject paramValueGroup = new PSObject(); paramValueGroup.TypeNames.Clear(); - paramValueGroup.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + paramValueGroup.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); ArrayList paramValue = new ArrayList(values); @@ -379,7 +380,7 @@ namespace System.Management.Automation.Help PSObject paramsObject = new PSObject(); paramsObject.TypeNames.Clear(); - paramsObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#parameters",typeNameForHelp)); + paramsObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameters", typeNameForHelp)); ArrayList paramObjects = new ArrayList(); @@ -410,7 +411,7 @@ namespace System.Management.Automation.Help PSObject paramObject = new PSObject(); paramObject.TypeNames.Clear(); - paramObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + paramObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); AddParameterProperties(paramObject, parameter, parameters[parameter].Aliases, parameters[parameter].IsDynamic, parameters[parameter].ParameterType, parameters[parameter].Attributes); @@ -605,7 +606,7 @@ namespace System.Management.Automation.Help { Collection attribs = GetParameterAttribute(parameter.Value.Attributes); - foreach(ParameterAttribute attrib in attribs) + foreach (ParameterAttribute attrib in attribs) { if (attrib.ValueFromPipeline || attrib.ValueFromPipelineByPropertyName || @@ -635,7 +636,7 @@ namespace System.Management.Automation.Help PSObject inputTypesObj = new PSObject(); inputTypesObj.TypeNames.Clear(); - inputTypesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + inputTypesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject inputTypeObj = new PSObject(); @@ -663,7 +664,7 @@ namespace System.Management.Automation.Help PSObject returnValuesObj = new PSObject(); returnValuesObj.TypeNames.Clear(); - returnValuesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture,"{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + returnValuesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject returnValueObj = new PSObject(); @@ -750,7 +751,7 @@ namespace System.Management.Automation.Help /// static internal void AddRelatedLinksProperties(PSObject obj, string relatedLink) { - if(!String.IsNullOrEmpty(relatedLink)) + if (!String.IsNullOrEmpty(relatedLink)) { PSObject navigationLinkObj = new PSObject(); diff --git a/src/System.Management.Automation/help/DefaultHelpProvider.cs b/src/System.Management.Automation/help/DefaultHelpProvider.cs index b20242953..96160384d 100644 --- a/src/System.Management.Automation/help/DefaultHelpProvider.cs +++ b/src/System.Management.Automation/help/DefaultHelpProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index 57d54ff0c..6b959a8e9 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -38,7 +38,7 @@ namespace System.Management.Automation private readonly Hashtable _helpFiles = new Hashtable(); [TraceSource("DscResourceHelpProvider", "DscResourceHelpProvider")] - static private readonly PSTraceSource tracer = PSTraceSource.GetTracer("DscResourceHelpProvider", "DscResourceHelpProvider"); + static private readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DscResourceHelpProvider", "DscResourceHelpProvider"); #region common properties @@ -72,7 +72,7 @@ namespace System.Management.Automation string target = helpRequest.Target; Collection patternList = new Collection(); - + bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target); if (decoratedSearch) @@ -86,7 +86,7 @@ namespace System.Management.Automation { DscResourceSearcher searcher = new DscResourceSearcher(pattern, _context); - foreach(var helpInfo in GetHelpInfo(searcher)) + foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) yield return helpInfo; @@ -103,7 +103,7 @@ namespace System.Management.Automation { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); - if((helpRequest.HelpCategory & Automation.HelpCategory.DscResource) == 0) + if ((helpRequest.HelpCategory & Automation.HelpCategory.DscResource) == 0) { yield return null; } @@ -128,26 +128,26 @@ namespace System.Management.Automation /// Next HelpInfo object. private IEnumerable GetHelpInfo(DscResourceSearcher searcher) { - while(searcher.MoveNext()) + while (searcher.MoveNext()) { DscResourceInfo current = ((IEnumerator)searcher).Current; string moduleName = null; string moduleDir = current.ParentPath; - + // for binary modules, current.Module is empty. // in such cases use the leaf folder of ParentPath as filename. if (current.Module != null) { moduleName = current.Module.Name; } - else if(!String.IsNullOrEmpty(moduleDir)) + else if (!String.IsNullOrEmpty(moduleDir)) { string[] splitPath = moduleDir.Split(Utils.Separators.Backslash); moduleName = splitPath[splitPath.Length - 1]; } - if(!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleDir)) + if (!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleDir)) { string helpFileToFind = moduleName + "-Help.xml"; @@ -203,7 +203,7 @@ namespace System.Management.Automation } #region private methods - + private HelpInfo GetHelpInfoFromHelpFile(DscResourceInfo resourceInfo, string helpFileToFind, Collection searchPaths, bool reportErrors, out string helpFile) { Dbg.Assert(resourceInfo != null, "Caller should verify that resourceInfo != null"); @@ -220,10 +220,10 @@ namespace System.Management.Automation { //Load the help file only once. Then use it from the cache. if (!_helpFiles.Contains(helpFile)) - { + { LoadHelpFile(helpFile, helpFile, resourceInfo.Name, reportErrors); } - + result = GetFromResourceHelpCache(helpFile, Automation.HelpCategory.DscResource); } @@ -284,7 +284,7 @@ namespace System.Management.Automation } if (e != null) - tracer.WriteLine("Error occured in DscResourceHelpProvider {0}", e.Message); + s_tracer.WriteLine("Error occured in DscResourceHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { @@ -332,7 +332,7 @@ namespace System.Management.Automation if (helpItemsNode == null) { - tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); + s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; } @@ -372,7 +372,5 @@ namespace System.Management.Automation } #endregion - - } } \ No newline at end of file diff --git a/src/System.Management.Automation/help/FaqHelpInfo.cs b/src/System.Management.Automation/help/FaqHelpInfo.cs index 7d3474a43..6ba33173a 100644 --- a/src/System.Management.Automation/help/FaqHelpInfo.cs +++ b/src/System.Management.Automation/help/FaqHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Xml; using System.Diagnostics.CodeAnalysis; // for fxcop @@ -32,11 +33,11 @@ namespace System.Management.Automation _fullHelpObject = mamlNode.PSObject; this.Errors = mamlNode.Errors; - this._fullHelpObject.TypeNames.Clear(); - this._fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, - "FaqHelpInfo#{0}",Name)); - this._fullHelpObject.TypeNames.Add("FaqHelpInfo"); - this._fullHelpObject.TypeNames.Add("HelpInfo"); + _fullHelpObject.TypeNames.Clear(); + _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, + "FaqHelpInfo#{0}", Name)); + _fullHelpObject.TypeNames.Add("FaqHelpInfo"); + _fullHelpObject.TypeNames.Add("HelpInfo"); } #region Basic Help Properties / Methods diff --git a/src/System.Management.Automation/help/FaqHelpProvider.cs b/src/System.Management.Automation/help/FaqHelpProvider.cs index 84bb8612a..d2d71e959 100644 --- a/src/System.Management.Automation/help/FaqHelpProvider.cs +++ b/src/System.Management.Automation/help/FaqHelpProvider.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// located in the Monad / CustomShell Path as well as in the Application Base /// of PSSnapIns /// - internal class FaqHelpProvider: HelpProviderWithFullCache + internal class FaqHelpProvider : HelpProviderWithFullCache { /// /// Constructor for FaqHelpProvider diff --git a/src/System.Management.Automation/help/GeneralHelpInfo.cs b/src/System.Management.Automation/help/GeneralHelpInfo.cs index a89bf098a..275eca588 100644 --- a/src/System.Management.Automation/help/GeneralHelpInfo.cs +++ b/src/System.Management.Automation/help/GeneralHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Xml; using System.Diagnostics.CodeAnalysis; // for fxcop @@ -31,11 +32,11 @@ namespace System.Management.Automation _fullHelpObject = mamlNode.PSObject; this.Errors = mamlNode.Errors; - this._fullHelpObject.TypeNames.Clear(); - this._fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, + _fullHelpObject.TypeNames.Clear(); + _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, "GeneralHelpInfo#{0}", Name)); - this._fullHelpObject.TypeNames.Add("GeneralHelpInfo"); - this._fullHelpObject.TypeNames.Add("HelpInfo"); + _fullHelpObject.TypeNames.Add("GeneralHelpInfo"); + _fullHelpObject.TypeNames.Add("HelpInfo"); } #region Basic Help Properties diff --git a/src/System.Management.Automation/help/GeneralHelpProvider.cs b/src/System.Management.Automation/help/GeneralHelpProvider.cs index e7b62be01..b5574fec4 100644 --- a/src/System.Management.Automation/help/GeneralHelpProvider.cs +++ b/src/System.Management.Automation/help/GeneralHelpProvider.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// located in the Monad / CustomShell Path as well as in the Application Base /// of PSSnapIns /// - internal class GeneralHelpProvider: HelpProviderWithFullCache + internal class GeneralHelpProvider : HelpProviderWithFullCache { /// /// Constructor for GeneralHelpProvider @@ -63,7 +63,7 @@ namespace System.Management.Automation /// internal sealed override void LoadCache() { - Collection files = MUIFileSearcher.SearchFiles("*.concept.xml",GetSearchPaths()); + Collection files = MUIFileSearcher.SearchFiles("*.concept.xml", GetSearchPaths()); if (files == null) return; diff --git a/src/System.Management.Automation/help/GlossaryHelpInfo.cs b/src/System.Management.Automation/help/GlossaryHelpInfo.cs index 9545c1d0e..228274e28 100644 --- a/src/System.Management.Automation/help/GlossaryHelpInfo.cs +++ b/src/System.Management.Automation/help/GlossaryHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Xml; using System.Text; using System.Diagnostics.CodeAnalysis; @@ -34,11 +35,11 @@ namespace System.Management.Automation _name = GetTerm(); - this._fullHelpObject.TypeNames.Clear(); - this._fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, + _fullHelpObject.TypeNames.Clear(); + _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, "GlossaryHelpInfo#{0}", Name)); - this._fullHelpObject.TypeNames.Add("GlossaryHelpInfo"); - this._fullHelpObject.TypeNames.Add("HelpInfo"); + _fullHelpObject.TypeNames.Add("GlossaryHelpInfo"); + _fullHelpObject.TypeNames.Add("HelpInfo"); } #region Basic Help Properties @@ -67,12 +68,12 @@ namespace System.Management.Automation if (_fullHelpObject.Properties["Terms"].Value == null) return ""; - PSObject terms = (PSObject) _fullHelpObject.Properties["Terms"].Value; + PSObject terms = (PSObject)_fullHelpObject.Properties["Terms"].Value; - if(terms.Properties["Term"] == null) + if (terms.Properties["Term"] == null) return ""; - if(terms.Properties["Term"].Value == null) + if (terms.Properties["Term"].Value == null) return ""; if (terms.Properties["Term"].Value.GetType().Equals(typeof(PSObject))) @@ -95,7 +96,7 @@ namespace System.Management.Automation str = str.Trim(); - if(String.IsNullOrEmpty(str)) + if (String.IsNullOrEmpty(str)) continue; if (result.Length > 0) diff --git a/src/System.Management.Automation/help/GlossaryHelpProvider.cs b/src/System.Management.Automation/help/GlossaryHelpProvider.cs index 37f6de0f0..63aa68b8f 100644 --- a/src/System.Management.Automation/help/GlossaryHelpProvider.cs +++ b/src/System.Management.Automation/help/GlossaryHelpProvider.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// located in the Monad / CustomShell Path as well as in the Application Base /// of PSSnapIns /// - internal class GlossaryHelpProvider: HelpProviderWithFullCache + internal class GlossaryHelpProvider : HelpProviderWithFullCache { /// /// Constructor for GlossaryHelpProvider @@ -78,7 +78,7 @@ namespace System.Management.Automation /// protected sealed override bool CustomMatch(string target, string key) { - if(String.IsNullOrEmpty(target) || String.IsNullOrEmpty(key)) + if (String.IsNullOrEmpty(target) || String.IsNullOrEmpty(key)) return false; string[] terms = key.Split(Utils.Separators.Comma); @@ -103,7 +103,7 @@ namespace System.Management.Automation if (files == null) return; - + foreach (string file in files) { if (!_helpFiles.ContainsKey(file)) @@ -113,7 +113,7 @@ namespace System.Management.Automation _helpFiles[file] = 0; } } - } + } /// /// Load help file for HelpInfo objects. The HelpInfo objects will be @@ -136,7 +136,7 @@ namespace System.Management.Automation try { doc = InternalDeserializer.LoadUnsafeXmlDocument( - new FileInfo(helpFile), + new FileInfo(helpFile), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ } diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index 8dbf5ac8c..24f3828cc 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -30,7 +30,7 @@ namespace Microsoft.PowerShell.Commands /// Initializes a new instance of the HelpCategoryInvalidException class. /// /// The name of help category that is invalid. - public HelpCategoryInvalidException (string helpCategory) : base() + public HelpCategoryInvalidException(string helpCategory) : base() { _helpCategory = helpCategory; CreateErrorRecord(); @@ -39,7 +39,7 @@ namespace Microsoft.PowerShell.Commands /// /// Initializes a new instance of the HelpCategoryInvalidException class. /// - public HelpCategoryInvalidException () : base() + public HelpCategoryInvalidException() : base() { CreateErrorRecord(); } @@ -49,8 +49,8 @@ namespace Microsoft.PowerShell.Commands /// /// The name of help category that is invalid. /// The inner exception of this exception - public HelpCategoryInvalidException (string helpCategory, Exception innerException) : - base ((innerException != null) ? innerException.Message : string.Empty, innerException) + public HelpCategoryInvalidException(string helpCategory, Exception innerException) : + base((innerException != null) ? innerException.Message : string.Empty, innerException) { _helpCategory = helpCategory; CreateErrorRecord(); diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index a78657c2b..1a432b740 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -27,10 +28,10 @@ namespace Microsoft.PowerShell.Commands /// internal enum HelpView { - Default = 0x00, // Default View + Default = 0x00, // Default View DetailedView = 0x01, - FullView = 0x02, - ExamplesView = 0x03 + FullView = 0x02, + ExamplesView = 0x03 } /// @@ -265,20 +266,20 @@ namespace Microsoft.PowerShell.Commands { set { - showOnlineHelp = value; - if (showOnlineHelp) + _showOnlineHelp = value; + if (_showOnlineHelp) { VerifyParameterForbiddenInRemoteRunspace(this, "Online"); } } get { - return showOnlineHelp; + return _showOnlineHelp; } } - private bool showOnlineHelp; + private bool _showOnlineHelp; - private bool showWindow; + private bool _showWindow; /// /// Gets and sets a value indicatuing whether the help should be displayed in a separate window /// @@ -287,13 +288,13 @@ namespace Microsoft.PowerShell.Commands { get { - return showWindow; + return _showWindow; } set { - showWindow = value; - if (showWindow) + _showWindow = value; + if (_showWindow) { VerifyParameterForbiddenInRemoteRunspace(this, "ShowWindow"); } @@ -323,12 +324,12 @@ namespace Microsoft.PowerShell.Commands if (!Online.IsPresent && UpdatableHelpSystem.ShouldPromptToUpdateHelp() && HostUtilities.IsProcessInteractive(MyInvocation) && HasInternetConnection()) { - if(ShouldContinue(HelpDisplayStrings.UpdateHelpPromptBody, HelpDisplayStrings.UpdateHelpPromptTitle)) + if (ShouldContinue(HelpDisplayStrings.UpdateHelpPromptBody, HelpDisplayStrings.UpdateHelpPromptTitle)) { System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Update-Help").Invoke(); _updatedHelp = true; } - + UpdatableHelpSystem.SetDisablePromptToUpdateHelp(); } } @@ -341,7 +342,7 @@ namespace Microsoft.PowerShell.Commands try { #if !CORECLR - if(this.ShowWindow) + if (this.ShowWindow) { this.graphicalHostReflectionWrapper = GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(this, "Microsoft.PowerShell.Commands.Internal.HelpWindowHelper"); } @@ -349,7 +350,7 @@ namespace Microsoft.PowerShell.Commands this.Context.HelpSystem.OnProgress += new HelpSystem.HelpProgressHandler(HelpSystem_OnProgress); bool failed = false; - HelpCategory helpCategory = ToHelpCategory(this._category, ref failed); + HelpCategory helpCategory = ToHelpCategory(_category, ref failed); if (failed) return; @@ -359,10 +360,10 @@ namespace Microsoft.PowerShell.Commands HelpRequest helpRequest = new HelpRequest(this.Name, helpCategory); - helpRequest.Provider = this._provider; - helpRequest.Component = this._component; - helpRequest.Role = this._role; - helpRequest.Functionality = this._functionality; + helpRequest.Provider = _provider; + helpRequest.Component = _component; + helpRequest.Role = _role; + helpRequest.Functionality = _functionality; helpRequest.ProviderContext = new ProviderContext( this.Path, this.Context.Engine.Context, @@ -414,7 +415,7 @@ namespace Microsoft.PowerShell.Commands { WriteObjectsOrShowOnlineHelp(firstHelpInfoObject, true); } - else if (showOnlineHelp && (countOfHelpInfos > 1)) + else if (_showOnlineHelp && (countOfHelpInfos > 1)) { throw PSTraceSource.NewInvalidOperationException(HelpErrors.MultipleOnlineTopicsNotSupported, "Online"); } @@ -489,7 +490,7 @@ namespace Microsoft.PowerShell.Commands if (_viewTokenToAdd == HelpView.Default) { - tracer.WriteLine("Detailed, Full, Examples are not selected. Constructing default view."); + s_tracer.WriteLine("Detailed, Full, Examples are not selected. Constructing default view."); return originalHelpObject; } @@ -519,14 +520,14 @@ namespace Microsoft.PowerShell.Commands } string typeToAdd = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", typeName, tokenToAdd); - tracer.WriteLine("Adding type {0}", typeToAdd); + s_tracer.WriteLine("Adding type {0}", typeToAdd); objectToReturn.TypeNames.Add(typeToAdd); } // Existing typenames at the bottom.. foreach (string typeName in originalHelpObject.TypeNames) { - tracer.WriteLine("Adding type {0}", typeName); + s_tracer.WriteLine("Adding type {0}", typeName); objectToReturn.TypeNames.Add(typeName); } } @@ -542,14 +543,14 @@ namespace Microsoft.PowerShell.Commands /// HelpInfo Object to look for the parameter. private void GetAndWriteParameterInfo(HelpInfo helpInfo) { - tracer.WriteLine("Searching parameters for {0}", helpInfo.Name); - PSObject[] pInfos = helpInfo.GetParameter(this._parameter); + s_tracer.WriteLine("Searching parameters for {0}", helpInfo.Name); + PSObject[] pInfos = helpInfo.GetParameter(_parameter); if ((pInfos == null) || (pInfos.Length == 0)) { Exception innerException = PSTraceSource.NewArgumentException("Parameter", - HelpErrors.NoParmsFound, this._parameter); - WriteError(new ErrorRecord(innerException,"NoParmsFound", ErrorCategory.InvalidArgument, helpInfo)); + HelpErrors.NoParmsFound, _parameter); + WriteError(new ErrorRecord(innerException, "NoParmsFound", ErrorCategory.InvalidArgument, helpInfo)); } else { @@ -575,31 +576,31 @@ namespace Microsoft.PowerShell.Commands } // categories that support -Parameter, -Role, -Functionality, -Component parameters - HelpCategory supportedCategories = - HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | + HelpCategory supportedCategories = + HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand | HelpCategory.Workflow; if ((cat & supportedCategories) == 0) { - if (!string.IsNullOrEmpty(this._parameter)) + if (!string.IsNullOrEmpty(_parameter)) { throw PSTraceSource.NewArgumentException("Parameter", HelpErrors.ParamNotSupported, "-Parameter"); } - if (this._component != null) + if (_component != null) { throw PSTraceSource.NewArgumentException("Component", HelpErrors.ParamNotSupported, "-Component"); } - if (this._role != null) + if (_role != null) { throw PSTraceSource.NewArgumentException("Role", HelpErrors.ParamNotSupported, "-Role"); } - if (this._functionality != null) + if (_functionality != null) { throw PSTraceSource.NewArgumentException("Functionality", HelpErrors.ParamNotSupported, "-Functionality"); @@ -619,11 +620,11 @@ namespace Microsoft.PowerShell.Commands // online help can be showed only if showFullHelp is true.. // showFullHelp will be false when the help tries to display multiple help topics.. // -Online should not work when multiple help topics are displayed. - if (showFullHelp && showOnlineHelp) + if (showFullHelp && _showOnlineHelp) { bool onlineUriFound = false; // show online help - tracer.WriteLine("Preparing to show help online."); + s_tracer.WriteLine("Preparing to show help online."); Uri onlineUri = helpInfo.GetUriForOnlineHelp(); if (null != onlineUri) { @@ -634,7 +635,7 @@ namespace Microsoft.PowerShell.Commands if (!onlineUriFound) { - throw PSTraceSource.NewInvalidOperationException(HelpErrors.NoURIFound); + throw PSTraceSource.NewInvalidOperationException(HelpErrors.NoURIFound); } } else if (showFullHelp && ShowWindow) @@ -728,7 +729,7 @@ namespace Microsoft.PowerShell.Commands #endregion - void HelpSystem_OnProgress(object sender, HelpProgressInfo arg) + private void HelpSystem_OnProgress(object sender, HelpProgressInfo arg) { ProgressRecord record = new ProgressRecord(0, this.CommandInfo.Name, arg.Activity); @@ -739,7 +740,7 @@ namespace Microsoft.PowerShell.Commands #if !CORECLR [DllImport("wininet.dll")] - static extern bool InternetGetConnectedState(out int desc, int reserved) ; + private static extern bool InternetGetConnectedState(out int desc, int reserved); #endif /// /// Checks if we can connect to the internet @@ -751,7 +752,7 @@ namespace Microsoft.PowerShell.Commands return true; // TODO:CORECLR wininet.dll is not present on NanoServer #else int unused; - return InternetGetConnectedState(out unused, 0 ); + return InternetGetConnectedState(out unused, 0); #endif } @@ -775,7 +776,7 @@ namespace Microsoft.PowerShell.Commands #region trace [TraceSourceAttribute("GetHelpCommand ", "GetHelpCommand ")] - static private PSTraceSource tracer = PSTraceSource.GetTracer("GetHelpCommand ", "GetHelpCommand "); + static private PSTraceSource s_tracer = PSTraceSource.GetTracer("GetHelpCommand ", "GetHelpCommand "); #endregion } @@ -791,7 +792,6 @@ namespace Microsoft.PowerShell.Commands /// private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() { - InitialSessionState iss = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InitialSessionState; if (iss != null) @@ -807,7 +807,7 @@ namespace Microsoft.PowerShell.Commands foreach (SessionStateCommandEntry getHelpEntry in publicGetHelpEntries) { SessionStateCmdletEntry getHelpCmdlet = getHelpEntry as SessionStateCmdletEntry; - if ((null != getHelpCmdlet) && (getHelpCmdlet.ImplementingType.Equals(typeof (GetHelpCommand)))) + if ((null != getHelpCmdlet) && (getHelpCmdlet.ImplementingType.Equals(typeof(GetHelpCommand)))) { return true; } @@ -845,7 +845,7 @@ namespace Microsoft.PowerShell.Commands // The type checking is needed to avoid a try..catch exception block as // the CommandInfo.CommandMetadata throws an InvalidOperationException // instead of returning null. - if ((cmdInfo is CmdletInfo) || (cmdInfo is FunctionInfo) || + if ((cmdInfo is CmdletInfo) || (cmdInfo is FunctionInfo) || (cmdInfo is ExternalScriptInfo) || (cmdInfo is ScriptInfo)) { if (!string.IsNullOrEmpty(cmdInfo.CommandMetadata.HelpUri)) @@ -855,7 +855,7 @@ namespace Microsoft.PowerShell.Commands } AliasInfo aliasInfo = cmdInfo as AliasInfo; - if ((null != aliasInfo) && + if ((null != aliasInfo) && (null != aliasInfo.ExternalCommandMetadata) && (!string.IsNullOrEmpty(aliasInfo.ExternalCommandMetadata.HelpUri))) { diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 4cc9e18d9..b63e8a95e 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; using System.Collections; using System.Collections.Generic; @@ -28,7 +29,7 @@ namespace System.Management.Automation private HelpCommentsParser(List parameterDescriptions) { - this.parameterDescriptions = parameterDescriptions; + _parameterDescriptions = parameterDescriptions; } private HelpCommentsParser(CommandInfo commandInfo, List parameterDescriptions) @@ -36,20 +37,20 @@ namespace System.Management.Automation FunctionInfo fi = commandInfo as FunctionInfo; if (fi != null) { - this.scriptBlock = fi.ScriptBlock; - this.commandName = fi.Name; + _scriptBlock = fi.ScriptBlock; + _commandName = fi.Name; } else { ExternalScriptInfo si = commandInfo as ExternalScriptInfo; if (si != null) { - this.scriptBlock = si.ScriptBlock; - this.commandName = si.Path; + _scriptBlock = si.ScriptBlock; + _commandName = si.Path; } } - this.commandMetadata = commandInfo.CommandMetadata; - this.parameterDescriptions = parameterDescriptions; + _commandMetadata = commandInfo.CommandMetadata; + _parameterDescriptions = parameterDescriptions; } private readonly Language.CommentHelpInfo _sections = new Language.CommentHelpInfo(); @@ -60,30 +61,30 @@ namespace System.Management.Automation private readonly List _links = new List(); internal bool isExternalHelpSet = false; - ScriptBlock scriptBlock; - CommandMetadata commandMetadata; - string commandName; - List parameterDescriptions; - XmlDocument doc; + private ScriptBlock _scriptBlock; + private CommandMetadata _commandMetadata; + private string _commandName; + private List _parameterDescriptions; + private XmlDocument _doc; internal static readonly string mamlURI = "http://schemas.microsoft.com/maml/2004/10"; internal static readonly string commandURI = "http://schemas.microsoft.com/maml/dev/command/2004/10"; internal static readonly string devURI = "http://schemas.microsoft.com/maml/dev/2004/10"; - const string directive = @"^\s*\.(\w+)(\s+(\S.*))?\s*$"; - const string blankline = @"^\s*$"; + private const string directive = @"^\s*\.(\w+)(\s+(\S.*))?\s*$"; + private const string blankline = @"^\s*$"; internal static readonly string ProviderHelpCommandXPath = "/helpItems/providerHelp/CmdletHelpPaths/CmdletHelpPath{0}/command:command[command:details/command:verb='{1}' and command:details/command:noun='{2}']"; private void DetermineParameterDescriptions() { int i = 0; - foreach (string parameterName in commandMetadata.StaticCommandParameterMetadata.BindableParameters.Keys) + foreach (string parameterName in _commandMetadata.StaticCommandParameterMetadata.BindableParameters.Keys) { string description; if (!_parameters.TryGetValue(parameterName.ToUpperInvariant(), out description)) { - if (i < parameterDescriptions.Count) + if (i < _parameterDescriptions.Count) { - _parameters.Add(parameterName.ToUpperInvariant(), parameterDescriptions[i]); + _parameters.Add(parameterName.ToUpperInvariant(), _parameterDescriptions[i]); } } ++i; @@ -111,7 +112,7 @@ namespace System.Management.Automation string defaultValue, bool forSyntax) { - XmlElement command_parameter = doc.CreateElement("command:parameter", commandURI); + XmlElement command_parameter = _doc.CreateElement("command:parameter", commandURI); command_parameter.SetAttribute("required", isMandatory ? "true" : "false"); //command_parameter.SetAttribute("variableLength", "unknown"); command_parameter.SetAttribute("globbing", supportsWildcards ? "true" : "false"); @@ -135,14 +136,14 @@ namespace System.Management.Automation command_parameter.SetAttribute("pipelineInput", fromPipeline); command_parameter.SetAttribute("position", position); - XmlElement name = doc.CreateElement("maml:name", mamlURI); - XmlText name_text = doc.CreateTextNode(parameterName); + XmlElement name = _doc.CreateElement("maml:name", mamlURI); + XmlText name_text = _doc.CreateTextNode(parameterName); command_parameter.AppendChild(name).AppendChild(name_text); if (!string.IsNullOrEmpty(description)) { - XmlElement maml_description = doc.CreateElement("maml:description", mamlURI); - XmlElement maml_para = doc.CreateElement("maml:para", mamlURI); - XmlText maml_para_text = doc.CreateTextNode(description); + XmlElement maml_description = _doc.CreateElement("maml:description", mamlURI); + XmlElement maml_para = _doc.CreateElement("maml:para", mamlURI); + XmlText maml_para_text = _doc.CreateTextNode(description); command_parameter.AppendChild(maml_description).AppendChild(maml_para).AppendChild(maml_para_text); } @@ -154,12 +155,12 @@ namespace System.Management.Automation if (elementType.GetTypeInfo().IsEnum) { - XmlElement parameterValueGroup = doc.CreateElement("command:parameterValueGroup", commandURI); + XmlElement parameterValueGroup = _doc.CreateElement("command:parameterValueGroup", commandURI); foreach (string valueName in Enum.GetNames(elementType)) { - XmlElement parameterValue = doc.CreateElement("command:parameterValue", commandURI); + XmlElement parameterValue = _doc.CreateElement("command:parameterValue", commandURI); parameterValue.SetAttribute("required", "false"); - XmlText parameterValue_text = doc.CreateTextNode(valueName); + XmlText parameterValue_text = _doc.CreateTextNode(valueName); parameterValueGroup.AppendChild(parameterValue).AppendChild(parameterValue_text); } command_parameter.AppendChild(parameterValueGroup); @@ -169,23 +170,23 @@ namespace System.Management.Automation bool isSwitchParameter = elementType == typeof(SwitchParameter); if (!forSyntax || !isSwitchParameter) { - XmlElement parameterValue = doc.CreateElement("command:parameterValue", commandURI); + XmlElement parameterValue = _doc.CreateElement("command:parameterValue", commandURI); parameterValue.SetAttribute("required", isSwitchParameter ? "false" : "true"); //parameterValue.SetAttribute("variableLength", "unknown"); - XmlText parameterValue_text = doc.CreateTextNode(type.Name); + XmlText parameterValue_text = _doc.CreateTextNode(type.Name); command_parameter.AppendChild(parameterValue).AppendChild(parameterValue_text); } } if (!forSyntax) { - XmlElement devType = doc.CreateElement("dev:type", devURI); - XmlElement typeName = doc.CreateElement("maml:name", mamlURI); - XmlText typeName_text = doc.CreateTextNode(type.Name); + XmlElement devType = _doc.CreateElement("dev:type", devURI); + XmlElement typeName = _doc.CreateElement("maml:name", mamlURI); + XmlText typeName_text = _doc.CreateTextNode(type.Name); command_parameter.AppendChild(devType).AppendChild(typeName).AppendChild(typeName_text); - XmlElement defaultValueElement = doc.CreateElement("dev:defaultValue", devURI); - XmlText defaultValue_text = doc.CreateTextNode(defaultValue); + XmlElement defaultValueElement = _doc.CreateElement("dev:defaultValue", devURI); + XmlText defaultValue_text = _doc.CreateTextNode(defaultValue); command_parameter.AppendChild(defaultValueElement).AppendChild(defaultValue_text); } @@ -198,27 +199,27 @@ namespace System.Management.Automation /// The xml node for the command constructed internal XmlDocument BuildXmlFromComments() { - Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "Name can never be null"); + Diagnostics.Assert(!string.IsNullOrEmpty(_commandName), "Name can never be null"); - doc = new XmlDocument(); - XmlElement command = doc.CreateElement("command:command", commandURI); + _doc = new XmlDocument(); + XmlElement command = _doc.CreateElement("command:command", commandURI); command.SetAttribute("xmlns:maml", mamlURI); command.SetAttribute("xmlns:command", commandURI); command.SetAttribute("xmlns:dev", devURI); - doc.AppendChild(command); + _doc.AppendChild(command); - XmlElement details = doc.CreateElement("command:details", commandURI); + XmlElement details = _doc.CreateElement("command:details", commandURI); command.AppendChild(details); - XmlElement name = doc.CreateElement("command:name", commandURI); - XmlText name_text = doc.CreateTextNode(commandName); + XmlElement name = _doc.CreateElement("command:name", commandURI); + XmlText name_text = _doc.CreateTextNode(_commandName); details.AppendChild(name).AppendChild(name_text); if (!string.IsNullOrEmpty(_sections.Synopsis)) { - XmlElement synopsis = doc.CreateElement("maml:description", mamlURI); - XmlElement synopsis_para = doc.CreateElement("maml:para", mamlURI); - XmlText synopsis_text = doc.CreateTextNode(_sections.Synopsis); + XmlElement synopsis = _doc.CreateElement("maml:description", mamlURI); + XmlElement synopsis_para = _doc.CreateElement("maml:para", mamlURI); + XmlText synopsis_text = _doc.CreateTextNode(_sections.Synopsis); details.AppendChild(synopsis).AppendChild(synopsis_para).AppendChild(synopsis_text); } @@ -227,8 +228,8 @@ namespace System.Management.Automation // The syntax is automatically generated from parameter metadata DetermineParameterDescriptions(); - XmlElement syntax = doc.CreateElement("command:syntax", commandURI); - MergedCommandParameterMetadata parameterMetadata = this.commandMetadata.StaticCommandParameterMetadata; + XmlElement syntax = _doc.CreateElement("command:syntax", commandURI); + MergedCommandParameterMetadata parameterMetadata = _commandMetadata.StaticCommandParameterMetadata; if (parameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < parameterMetadata.ParameterSetCount; ++i) @@ -245,7 +246,7 @@ namespace System.Management.Automation #region Parameters - XmlElement commandParameters = doc.CreateElement("command:parameters", commandURI); + XmlElement commandParameters = _doc.CreateElement("command:parameters", commandURI); foreach (KeyValuePair pair in parameterMetadata.BindableParameters) { MergedCompiledCommandParameter mergedParameter = pair.Value; @@ -297,7 +298,7 @@ namespace System.Management.Automation if (defaultValue == null) { RuntimeDefinedParameter rdp; - if (scriptBlock.RuntimeDefinedParameters.TryGetValue(parameterName, out rdp)) + if (_scriptBlock.RuntimeDefinedParameters.TryGetValue(parameterName, out rdp)) { defaultValue = rdp.Value; } @@ -325,33 +326,33 @@ namespace System.Management.Automation if (!string.IsNullOrEmpty(_sections.Description)) { - XmlElement description = doc.CreateElement("maml:description", mamlURI); - XmlElement description_para = doc.CreateElement("maml:para", mamlURI); - XmlText description_text = doc.CreateTextNode(_sections.Description); + XmlElement description = _doc.CreateElement("maml:description", mamlURI); + XmlElement description_para = _doc.CreateElement("maml:para", mamlURI); + XmlText description_text = _doc.CreateTextNode(_sections.Description); command.AppendChild(description).AppendChild(description_para).AppendChild(description_text); } if (!string.IsNullOrEmpty(_sections.Notes)) { - XmlElement alertSet = doc.CreateElement("maml:alertSet", mamlURI); - XmlElement alert = doc.CreateElement("maml:alert", mamlURI); - XmlElement alert_para = doc.CreateElement("maml:para", mamlURI); - XmlText alert_para_text = doc.CreateTextNode(_sections.Notes); + XmlElement alertSet = _doc.CreateElement("maml:alertSet", mamlURI); + XmlElement alert = _doc.CreateElement("maml:alert", mamlURI); + XmlElement alert_para = _doc.CreateElement("maml:para", mamlURI); + XmlText alert_para_text = _doc.CreateTextNode(_sections.Notes); command.AppendChild(alertSet).AppendChild(alert).AppendChild(alert_para).AppendChild(alert_para_text); } if (_examples.Count > 0) { - XmlElement examples = doc.CreateElement("command:examples", commandURI); + XmlElement examples = _doc.CreateElement("command:examples", commandURI); int count = 1; foreach (string example in _examples) - { - XmlElement example_node = doc.CreateElement("command:example", commandURI); + { + XmlElement example_node = _doc.CreateElement("command:example", commandURI); // The title is automatically generated - XmlElement title = doc.CreateElement("maml:title", mamlURI); + XmlElement title = _doc.CreateElement("maml:title", mamlURI); string titleStr = string.Format(CultureInfo.InvariantCulture, " -------------------------- {0} {1} --------------------------", HelpDisplayStrings.ExampleUpperCase, count++); - XmlText title_text = doc.CreateTextNode(titleStr); + XmlText title_text = _doc.CreateTextNode(titleStr); example_node.AppendChild(title).AppendChild(title_text); string prompt_str; @@ -360,25 +361,25 @@ namespace System.Management.Automation GetExampleSections(example, out prompt_str, out code_str, out remarks_str); // Introduction (usually the prompt) - XmlElement introduction = doc.CreateElement("maml:introduction", mamlURI); - XmlElement introduction_para = doc.CreateElement("maml:para", mamlURI); - XmlText introduction_para_text = doc.CreateTextNode(prompt_str); + XmlElement introduction = _doc.CreateElement("maml:introduction", mamlURI); + XmlElement introduction_para = _doc.CreateElement("maml:para", mamlURI); + XmlText introduction_para_text = _doc.CreateTextNode(prompt_str); example_node.AppendChild(introduction).AppendChild(introduction_para).AppendChild(introduction_para_text); // Example code - XmlElement code = doc.CreateElement("dev:code", devURI); - XmlText code_text = doc.CreateTextNode(code_str); + XmlElement code = _doc.CreateElement("dev:code", devURI); + XmlText code_text = _doc.CreateTextNode(code_str); example_node.AppendChild(code).AppendChild(code_text); // Remarks are comments on the example - XmlElement remarks = doc.CreateElement("dev:remarks", devURI); - XmlElement remarks_para = doc.CreateElement("maml:para", mamlURI); - XmlText remarks_para_text = doc.CreateTextNode(remarks_str); + XmlElement remarks = _doc.CreateElement("dev:remarks", devURI); + XmlElement remarks_para = _doc.CreateElement("maml:para", mamlURI); + XmlText remarks_para_text = _doc.CreateTextNode(remarks_str); example_node.AppendChild(remarks).AppendChild(remarks_para).AppendChild(remarks_para_text); // The convention is to have 4 blank paras after the example for spacing for (int i = 0; i < 4; i++) { - remarks.AppendChild(doc.CreateElement("maml:para", mamlURI)); + remarks.AppendChild(_doc.CreateElement("maml:para", mamlURI)); } examples.AppendChild(example_node); } @@ -386,13 +387,13 @@ namespace System.Management.Automation } if (_inputs.Count > 0) { - XmlElement inputTypes = doc.CreateElement("command:inputTypes", commandURI); + XmlElement inputTypes = _doc.CreateElement("command:inputTypes", commandURI); foreach (string inputStr in _inputs) { - XmlElement inputType = doc.CreateElement("command:inputType", commandURI); - XmlElement type = doc.CreateElement("dev:type", devURI); - XmlElement maml_name = doc.CreateElement("maml:name", mamlURI); - XmlText maml_name_text = doc.CreateTextNode(inputStr); + XmlElement inputType = _doc.CreateElement("command:inputType", commandURI); + XmlElement type = _doc.CreateElement("dev:type", devURI); + XmlElement maml_name = _doc.CreateElement("maml:name", mamlURI); + XmlText maml_name_text = _doc.CreateTextNode(inputStr); inputTypes.AppendChild(inputType).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } command.AppendChild(inputTypes); @@ -404,47 +405,47 @@ namespace System.Management.Automation { outputs = _outputs; } - else if (scriptBlock.OutputType.Count > 0) + else if (_scriptBlock.OutputType.Count > 0) { - outputs = scriptBlock.OutputType; + outputs = _scriptBlock.OutputType; } if (outputs != null) { - XmlElement returnValues = doc.CreateElement("command:returnValues", commandURI); + XmlElement returnValues = _doc.CreateElement("command:returnValues", commandURI); foreach (object output in outputs) { - XmlElement returnValue = doc.CreateElement("command:returnValue", commandURI); - XmlElement type = doc.CreateElement("dev:type", devURI); - XmlElement maml_name = doc.CreateElement("maml:name", mamlURI); + XmlElement returnValue = _doc.CreateElement("command:returnValue", commandURI); + XmlElement type = _doc.CreateElement("dev:type", devURI); + XmlElement maml_name = _doc.CreateElement("maml:name", mamlURI); string returnValueStr = output as string ?? ((PSTypeName)output).Name; - XmlText maml_name_text = doc.CreateTextNode(returnValueStr); + XmlText maml_name_text = _doc.CreateTextNode(returnValueStr); returnValues.AppendChild(returnValue).AppendChild(type).AppendChild(maml_name).AppendChild(maml_name_text); } command.AppendChild(returnValues); } if (_links.Count > 0) { - XmlElement links = doc.CreateElement("maml:relatedLinks", mamlURI); + XmlElement links = _doc.CreateElement("maml:relatedLinks", mamlURI); foreach (string link in _links) { - XmlElement navigationLink = doc.CreateElement("maml:navigationLink", mamlURI); + XmlElement navigationLink = _doc.CreateElement("maml:navigationLink", mamlURI); bool isOnlineHelp = Uri.IsWellFormedUriString(Uri.EscapeUriString(link), UriKind.Absolute); string nodeName = isOnlineHelp ? "maml:uri" : "maml:linkText"; - XmlElement linkText = doc.CreateElement(nodeName, mamlURI); - XmlText linkText_text = doc.CreateTextNode(link); + XmlElement linkText = _doc.CreateElement(nodeName, mamlURI); + XmlText linkText_text = _doc.CreateTextNode(link); links.AppendChild(navigationLink).AppendChild(linkText).AppendChild(linkText_text); } command.AppendChild(links); } - return doc; + return _doc; } private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, MergedCommandParameterMetadata parameterMetadata, int i) { - XmlElement syntaxItem = doc.CreateElement("command:syntaxItem", commandURI); - XmlElement syntaxItemName = doc.CreateElement("maml:name", mamlURI); - XmlText syntaxItemName_text = doc.CreateTextNode(commandName); + XmlElement syntaxItem = _doc.CreateElement("command:syntaxItem", commandURI); + XmlElement syntaxItemName = _doc.CreateElement("maml:name", mamlURI); + XmlText syntaxItemName_text = _doc.CreateTextNode(_commandName); syntaxItem.AppendChild(syntaxItemName).AppendChild(syntaxItemName_text); @@ -659,7 +660,7 @@ namespace System.Management.Automation SessionState sessionState = scriptCommandInfo.ScriptBlock.SessionState; object runspaceInfoAsObject = sessionState.PSVariable.GetValue(_sections.RemoteHelpRunspace); PSSession runspaceInfo; - if (runspaceInfoAsObject == null || + if (runspaceInfoAsObject == null || !LanguagePrimitives.TryConvertTo(runspaceInfoAsObject, out runspaceInfo)) { string errorMessage = HelpErrors.RemoteRunspaceNotAvailable; @@ -667,10 +668,10 @@ namespace System.Management.Automation } return new RemoteHelpInfo( - context, + context, (RemoteRunspace)runspaceInfo.Runspace, commandInfo.Name, - _sections.ForwardHelpTargetName, + _sections.ForwardHelpTargetName, _sections.ForwardHelpCategory, commandInfo.HelpCategory); } @@ -715,7 +716,8 @@ namespace System.Management.Automation { string param = match.Groups[3].Value.ToUpperInvariant().Trim(); string section = GetSection(commentLines, ref i); - if (!_parameters.ContainsKey(param)) { + if (!_parameters.ContainsKey(param)) + { _parameters.Add(param, section); } break; @@ -776,7 +778,7 @@ namespace System.Management.Automation } } } - else if (! Regex.IsMatch(commentLines[i], blankline)) + else if (!Regex.IsMatch(commentLines[i], blankline)) { return false; } @@ -807,7 +809,7 @@ namespace System.Management.Automation _sections.Functionality, _sections.Role); } - + internal static CommentHelpInfo GetHelpContents(List comments, List parameterDescriptions) { HelpCommentsParser helpCommentsParser = new HelpCommentsParser(parameterDescriptions); @@ -915,15 +917,15 @@ namespace System.Management.Automation localHelpInfo.FullHelp.Properties.Add(new PSNoteProperty("CommonParameters", common)); localHelpInfo.FullHelp.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow)); - DefaultCommandHelpObjectBuilder.AddDetailsProperties(obj:localHelpInfo.FullHelp, name:workflowInfo.Name, - noun: workflowInfo.Noun, verb: workflowInfo.Verb, + DefaultCommandHelpObjectBuilder.AddDetailsProperties(obj: localHelpInfo.FullHelp, name: workflowInfo.Name, + noun: workflowInfo.Noun, verb: workflowInfo.Verb, typeNameForHelp: "MamlCommandHelpInfo", synopsis: localHelpInfo.Synopsis); DefaultCommandHelpObjectBuilder.AddSyntaxProperties(localHelpInfo.FullHelp, workflowInfo.Name, workflowInfo.ParameterSets, common, commonWorkflow, "MamlCommandHelpInfo"); } - + // Add HelpUri if necessary - if(localHelpInfo.GetUriForOnlineHelp() == null) + if (localHelpInfo.GetUriForOnlineHelp() == null) { DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(localHelpInfo.FullHelp, commandInfo.CommandMetadata.HelpUri); } @@ -1093,7 +1095,7 @@ namespace System.Management.Automation Dictionary scriptBlockTokenCache) { Diagnostics.Assert(scriptBlockTokenCache != null, "scriptBlockTokenCache cannot be null"); - var ast = (Ast) ipmp; + var ast = (Ast)ipmp; var rootAst = ast; Ast configAst = null; @@ -1174,7 +1176,6 @@ namespace System.Management.Automation "Unexpected first token in script block"); Diagnostics.Assert(tokens[lastTokenIndex].Kind == TokenKind.RCurly, "Unexpected last token in script block"); - } while (true) @@ -1221,5 +1222,5 @@ namespace System.Management.Automation } #endregion Collect comments from AST - } + } } diff --git a/src/System.Management.Automation/help/HelpErrorTracer.cs b/src/System.Management.Automation/help/HelpErrorTracer.cs index d49cd1962..9373df51c 100644 --- a/src/System.Management.Automation/help/HelpErrorTracer.cs +++ b/src/System.Management.Automation/help/HelpErrorTracer.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.ObjectModel; using System.Reflection; @@ -136,7 +137,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("HelpSystem"); } - this._helpSystem = helpSystem; + _helpSystem = helpSystem; } /// diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index 6fec30063..c79f45b5f 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index e46fb2812..7c79bb95b 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; using System.Collections; using System.Collections.Generic; @@ -20,7 +21,7 @@ namespace System.Management.Automation /// of PSSnapIns /// /// - internal class HelpFileHelpProvider: HelpProviderWithCache + internal class HelpFileHelpProvider : HelpProviderWithCache { /// /// Constructor for HelpProvider @@ -64,7 +65,7 @@ namespace System.Management.Automation int countHelpInfosFound = 0; string helpFileName = helpRequest.Target + ".help.txt"; Collection filesMatched = MUIFileSearcher.SearchFiles(helpFileName, GetExtendedSearchPaths()); - + Diagnostics.Assert(filesMatched != null, "Files collection should not be null."); var matchedFilesToRemove = FilterToLatestModuleVersion(filesMatched); @@ -105,12 +106,12 @@ namespace System.Management.Automation private Collection FilterToLatestModuleVersion(Collection filesMatched) { - Collection matchedFilesToRemove = new Collection(); - + Collection matchedFilesToRemove = new Collection(); + if (filesMatched.Count > 1) { //Dictionary<, > - Dictionary, Tuple> modulesAndVersion = new Dictionary, Tuple>(); + Dictionary, Tuple> modulesAndVersion = new Dictionary, Tuple>(); HashSet filesProcessed = new HashSet(); var allPSModulePaths = ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext); @@ -154,12 +155,12 @@ namespace System.Management.Automation else { //Add the module to the dictionary as it was not processes earlier. - modulesAndVersion.Add(new Tuple(moduleName,fileName), + modulesAndVersion.Add(new Tuple(moduleName, fileName), new Tuple(fileFullName, moduleVersionFromPath)); } } } - + filesProcessed.Add(fileName); } } @@ -186,7 +187,7 @@ namespace System.Management.Automation if (searchOnlyContent) { string searchTarget = helpRequest.Target; - if(!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) + if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) { searchTarget = "*" + searchTarget + "*"; } @@ -287,7 +288,7 @@ namespace System.Management.Automation if (!path.EndsWith(".help.txt", StringComparison.OrdinalIgnoreCase)) return null; - string name = fileName.Substring(0, fileName.Length - 9 /* ".help.txt".Length */); + string name = fileName.Substring(0, fileName.Length - 9 /* ".help.txt".Length */); if (String.IsNullOrEmpty(name)) return null; @@ -320,7 +321,7 @@ namespace System.Management.Automation internal Collection GetExtendedSearchPaths() { Collection searchPaths = GetSearchPaths(); - + // Add $pshome at the top of the list String defaultShellSearchPath = GetDefaultShellSearchPath(); int index = searchPaths.IndexOf(defaultShellSearchPath); @@ -346,7 +347,7 @@ namespace System.Management.Automation string[] directories = Directory.GetDirectories(psModulePath, "*", SearchOption.AllDirectories); var possibleModuleDirectories = directories.Where(directory => ModuleUtils.IsPossibleModuleDirectory(directory)); - + foreach (string directory in possibleModuleDirectories) { // Add only directories that are not empty diff --git a/src/System.Management.Automation/help/HelpInfo.cs b/src/System.Management.Automation/help/HelpInfo.cs index 9e2fedbd5..d3fe5c13f 100644 --- a/src/System.Management.Automation/help/HelpInfo.cs +++ b/src/System.Management.Automation/help/HelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.ObjectModel; namespace System.Management.Automation @@ -273,13 +274,13 @@ namespace System.Management.Automation this.FullHelp.Properties.Remove("Component"); this.FullHelp.Properties.Add(new PSNoteProperty("Component", this.Component)); - + this.FullHelp.Properties.Remove("Role"); this.FullHelp.Properties.Add(new PSNoteProperty("Role", this.Role)); - + this.FullHelp.Properties.Remove("Functionality"); this.FullHelp.Properties.Add(new PSNoteProperty("Functionality", this.Functionality)); - } + } #region Error handling diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index 3cf3a2b19..6f118f4fd 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -29,7 +29,7 @@ namespace Microsoft.PowerShell.Commands /// Initializes a new instance of the HelpNotFoundException class with the give help topic. /// /// The help topic for which help is not found. - public HelpNotFoundException (string helpTopic) : base() + public HelpNotFoundException(string helpTopic) : base() { _helpTopic = helpTopic; CreateErrorRecord(); @@ -38,7 +38,7 @@ namespace Microsoft.PowerShell.Commands /// /// Initializes a new instance of the HelpNotFoundException class. /// - public HelpNotFoundException () : base() + public HelpNotFoundException() : base() { CreateErrorRecord(); } @@ -49,8 +49,8 @@ namespace Microsoft.PowerShell.Commands /// /// The help topic for which help is not found. /// The inner exception. - public HelpNotFoundException (string helpTopic, Exception innerException) : - base ((innerException != null) ? innerException.Message : string.Empty, innerException) + public HelpNotFoundException(string helpTopic, Exception innerException) : + base((innerException != null) ? innerException.Message : string.Empty, innerException) { _helpTopic = helpTopic; CreateErrorRecord(); diff --git a/src/System.Management.Automation/help/HelpProvider.cs b/src/System.Management.Automation/help/HelpProvider.cs index 5a131ef1c..25cf42b13 100644 --- a/src/System.Management.Automation/help/HelpProvider.cs +++ b/src/System.Management.Automation/help/HelpProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -49,7 +50,7 @@ namespace System.Management.Automation /// internal HelpProvider(HelpSystem helpSystem) { - this._helpSystem = helpSystem; + _helpSystem = helpSystem; } private HelpSystem _helpSystem; @@ -255,7 +256,7 @@ namespace System.Management.Automation /// true if supported,false otherwise. internal bool AreSnapInsSupported() { - RunspaceConfigForSingleShell runspace = this._helpSystem.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; + RunspaceConfigForSingleShell runspace = _helpSystem.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; return (null == runspace ? false : true); } @@ -268,15 +269,15 @@ namespace System.Management.Automation internal Collection GetSearchPaths() { Collection searchPaths = this.HelpSystem.GetSearchPaths(); - + Diagnostics.Assert(searchPaths != null, "HelpSystem returned an null search path"); - + searchPaths.Add(GetDefaultShellSearchPath()); return searchPaths; } - + #endregion } } diff --git a/src/System.Management.Automation/help/HelpProviderWithCache.cs b/src/System.Management.Automation/help/HelpProviderWithCache.cs index 39947287a..45316486e 100644 --- a/src/System.Management.Automation/help/HelpProviderWithCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithCache.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; @@ -148,7 +149,7 @@ namespace System.Management.Automation int countOfHelpInfoObjectsFound = 0; WildcardPattern helpMatchter = WildcardPattern.Get(wildcardpattern, WildcardOptions.IgnoreCase); foreach (string key in _helpCache.Keys) - { + { if ((!searchOnlyContent && helpMatchter.IsMatch(key)) || (searchOnlyContent && ((HelpInfo)_helpCache[key]).MatchPatternInContent(helpMatchter))) { diff --git a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs index 6915c948d..b5b4740d1 100644 --- a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; namespace System.Management.Automation @@ -71,7 +72,7 @@ namespace System.Management.Automation // If the current invocation is a singleshell based // then we have to constantly update the cache as // snapins might get added / removed. - if (!this.CacheFullyLoaded || AreSnapInsSupported()) + if (!this.CacheFullyLoaded || AreSnapInsSupported()) { LoadCache(); } diff --git a/src/System.Management.Automation/help/HelpRequest.cs b/src/System.Management.Automation/help/HelpRequest.cs index 95306dec4..809f0a6a4 100644 --- a/src/System.Management.Automation/help/HelpRequest.cs +++ b/src/System.Management.Automation/help/HelpRequest.cs @@ -56,7 +56,7 @@ namespace System.Management.Automation /// /// Defines which provider the user seeking help is curious about. /// - internal ProviderContext ProviderContext + internal ProviderContext ProviderContext { get { return _providerContext; } set { _providerContext = value; } diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index ca87f9c15..be0244a56 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -98,7 +99,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("ExecutionContext"); } - this._executionContext = context; + _executionContext = context; Initialize(); } @@ -137,9 +138,9 @@ namespace System.Management.Automation /// internal void Initialize() { - this._verboseHelpErrors = LanguagePrimitives.IsTrue( + _verboseHelpErrors = LanguagePrimitives.IsTrue( _executionContext.GetVariableValue(SpecialVariables.VerboseHelpErrorsVarPath, false)); - this._helpErrorTracer = new HelpErrorTracer(this); + _helpErrorTracer = new HelpErrorTracer(this); InitializeHelpProviders(); } @@ -236,7 +237,7 @@ namespace System.Management.Automation // Cache of search paths that are currently active. // This will save a lot time when help providers do their searching - Collection _searchPaths = null; + private Collection _searchPaths = null; /// /// Gets the search paths for external snapins/modules that are currently loaded. @@ -302,11 +303,11 @@ namespace System.Management.Automation /// An array of HelpInfo object private IEnumerable DoGetHelp(HelpRequest helpRequest) { - this._lastErrors.Clear(); + _lastErrors.Clear(); // Reset SearchPaths _searchPaths = null; - this._lastHelpCategory = helpRequest.HelpCategory; + _lastHelpCategory = helpRequest.HelpCategory; if (String.IsNullOrEmpty(helpRequest.Target)) { @@ -486,7 +487,7 @@ namespace System.Management.Automation HelpProgressInfo progress = new HelpProgressInfo(); - progress.Activity = StringUtil.Format(HelpDisplayStrings.SearchingForHelpContent, helpRequest.Target) ; + progress.Activity = StringUtil.Format(HelpDisplayStrings.SearchingForHelpContent, helpRequest.Target); progress.Completed = false; progress.PercentComplete = 0; @@ -546,7 +547,6 @@ namespace System.Management.Automation progress.PercentComplete += (100 / this.HelpProviders.Count); OnProgress(this, progress); } - } while (!shouldBreak); } finally @@ -556,7 +556,6 @@ namespace System.Management.Automation OnProgress(this, progress); } - } #endregion Help Engine @@ -576,7 +575,7 @@ namespace System.Management.Automation return _helpProviders; } } - + /// /// Initialize help providers. /// @@ -604,12 +603,12 @@ namespace System.Management.Automation helpProvider = new PSClassHelpProvider(this); _helpProviders.Add(helpProvider); -/* TH Bug#3141590 - Disable DscResourceHelp for ClientRTM due to perf issue. -#if !CORECLR // TODO:CORECLR Add this back in once we support Get-DscResource - helpProvider = new DscResourceHelpProvider(this); - _helpProviders.Add(helpProvider); -#endif -*/ + /* TH Bug#3141590 - Disable DscResourceHelp for ClientRTM due to perf issue. + #if !CORECLR // TODO:CORECLR Add this back in once we support Get-DscResource + helpProvider = new DscResourceHelpProvider(this); + _helpProviders.Add(helpProvider); + #endif + */ helpProvider = new HelpFileHelpProvider(this); _helpProviders.Add(helpProvider); @@ -797,10 +796,10 @@ namespace System.Management.Automation /// internal void ResetHelpProviders() { - if(this._helpProviders == null) + if (_helpProviders == null) return; - for (int i = 0; i < this._helpProviders.Count; i++) + for (int i = 0; i < _helpProviders.Count; i++) { HelpProvider helpProvider = (HelpProvider)_helpProviders[i]; @@ -814,22 +813,21 @@ namespace System.Management.Automation #region ScriptBlock Parse Tokens Caching/Clearing Functionality - private readonly Lazy> scriptBlockTokenCache = new Lazy>(isThreadSafe: true); + private readonly Lazy> _scriptBlockTokenCache = new Lazy>(isThreadSafe: true); internal Dictionary ScriptBlockTokenCache { - get { return scriptBlockTokenCache.Value; } + get { return _scriptBlockTokenCache.Value; } } internal void ClearScriptBlockTokenCache() { - if (scriptBlockTokenCache.IsValueCreated) + if (_scriptBlockTokenCache.IsValueCreated) { - scriptBlockTokenCache.Value.Clear(); + _scriptBlockTokenCache.Value.Clear(); } } - #endregion } diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index fe475f129..61d53fb26 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -20,11 +20,11 @@ namespace System.Management.Automation /// /// private MUIFileSearcher(string target, Collection searchPaths, SearchMode searchMode) - { + { _target = target; _searchPaths = searchPaths; _searchMode = searchMode; - } + } /// /// A constructor to make searchMode optional. @@ -38,7 +38,7 @@ namespace System.Management.Automation #region Basic Properties - private string _target = null; + private string _target = null; /// /// Search target. It can be @@ -130,7 +130,7 @@ namespace System.Management.Automation { SearchForFiles(pattern, directory); - if(this.SearchMode == SearchMode.First && this.Result.Count > 0) + if (this.SearchMode == SearchMode.First && this.Result.Count > 0) { return; } @@ -272,7 +272,7 @@ namespace System.Management.Automation // step 3: locate the file in the default PowerShell installation directory. string defaultPSPath = GetMshDefaultInstallationPath(); - if (defaultPSPath != null && + if (defaultPSPath != null && !result.Contains(defaultPSPath) && Directory.Exists(defaultPSPath)) { @@ -302,8 +302,8 @@ namespace System.Management.Automation // returnValue can be null. return returnValue; } - - #endregion + + #endregion #region Static API's diff --git a/src/System.Management.Automation/help/MamlClassHelpInfo.cs b/src/System.Management.Automation/help/MamlClassHelpInfo.cs index 78d29b192..b27c8c122 100644 --- a/src/System.Management.Automation/help/MamlClassHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlClassHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Xml; namespace System.Management.Automation @@ -11,8 +12,8 @@ namespace System.Management.Automation /// class help provider. /// /// - internal class MamlClassHelpInfo : HelpInfo - { + internal class MamlClassHelpInfo : HelpInfo + { /// /// Constructor for custom HelpInfo object creation. /// @@ -37,8 +38,8 @@ namespace System.Management.Automation _fullHelpObject = mamlNode.PSObject; this.Errors = mamlNode.Errors; - this._fullHelpObject.TypeNames.Clear(); - this._fullHelpObject.TypeNames.Add("PSClassHelpInfo"); + _fullHelpObject.TypeNames.Clear(); + _fullHelpObject.TypeNames.Add("PSClassHelpInfo"); } /// @@ -50,7 +51,7 @@ namespace System.Management.Automation /// PSObject representation on help. /// private PSObject _fullHelpObject; - + #region Load /// @@ -81,7 +82,7 @@ namespace System.Management.Automation /// MamlClassHelpInfo object. internal MamlClassHelpInfo Copy() { - MamlClassHelpInfo result = new MamlClassHelpInfo(this._fullHelpObject.Copy(), this.HelpCategory); + MamlClassHelpInfo result = new MamlClassHelpInfo(_fullHelpObject.Copy(), this.HelpCategory); return result; } @@ -92,46 +93,46 @@ namespace System.Management.Automation /// MamlClassHelpInfo internal MamlClassHelpInfo Copy(HelpCategory newCategoryToUse) { - MamlClassHelpInfo result = new MamlClassHelpInfo(this._fullHelpObject.Copy(), newCategoryToUse); + MamlClassHelpInfo result = new MamlClassHelpInfo(_fullHelpObject.Copy(), newCategoryToUse); result.FullHelp.Properties["Category"].Value = newCategoryToUse; return result; } internal override string Name { - get + get { string tempName = string.Empty; - var title = this._fullHelpObject.Properties["title"]; + var title = _fullHelpObject.Properties["title"]; if (title != null && title.Value != null) { tempName = title.Value.ToString(); } - return tempName; + return tempName; } } internal override string Synopsis { - get + get { string tempSynopsis = string.Empty; - var intro = this._fullHelpObject.Properties["introduction"]; + var intro = _fullHelpObject.Properties["introduction"]; - if(intro != null && intro.Value != null) + if (intro != null && intro.Value != null) { tempSynopsis = intro.Value.ToString(); } - return tempSynopsis; + return tempSynopsis; } } internal override HelpCategory HelpCategory { - get + get { return _helpCategory; } @@ -139,7 +140,7 @@ namespace System.Management.Automation internal override PSObject FullHelp { - get + get { return _fullHelpObject; } diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index 75d7bb93b..57b414638 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Globalization; using System.Xml; using System.Text; @@ -34,15 +35,15 @@ namespace System.Management.Automation // set user defined data if (helpObject.Properties["Component"] != null) { - this._component = helpObject.Properties["Component"].Value as string; + _component = helpObject.Properties["Component"].Value as string; } if (helpObject.Properties["Role"] != null) { - this._role = helpObject.Properties["Role"].Value as string; + _role = helpObject.Properties["Role"].Value as string; } if (helpObject.Properties["Functionality"] != null) { - this._functionality = helpObject.Properties["Functionality"].Value as string; + _functionality = helpObject.Properties["Functionality"].Value as string; } } @@ -60,24 +61,24 @@ namespace System.Management.Automation { MamlNode mamlNode = new MamlNode(xmlNode); _fullHelpObject = mamlNode.PSObject; - + this.Errors = mamlNode.Errors; // The type name hierarchy for mshObject doesn't necessary // reflect the hierarchy in source code. From display's point of // view MamlCommandHelpInfo is derived from HelpInfo. - this._fullHelpObject.TypeNames.Clear(); + _fullHelpObject.TypeNames.Clear(); if (helpCategory == HelpCategory.DscResource) { - this._fullHelpObject.TypeNames.Add("DscResourceHelpInfo"); + _fullHelpObject.TypeNames.Add("DscResourceHelpInfo"); } else { - this._fullHelpObject.TypeNames.Add("MamlCommandHelpInfo"); - this._fullHelpObject.TypeNames.Add("HelpInfo"); + _fullHelpObject.TypeNames.Add("MamlCommandHelpInfo"); + _fullHelpObject.TypeNames.Add("HelpInfo"); } - + this.ForwardHelpCategory = HelpCategory.Provider; } @@ -87,13 +88,13 @@ namespace System.Management.Automation internal void OverrideProviderSpecificHelpWithGenericHelp(HelpInfo genericHelpInfo) { PSObject genericHelpMaml = genericHelpInfo.FullHelp; - MamlUtil.OverrideName(this._fullHelpObject, genericHelpMaml); - MamlUtil.OverridePSTypeNames(this._fullHelpObject, genericHelpMaml); - MamlUtil.PrependSyntax(this._fullHelpObject, genericHelpMaml); - MamlUtil.PrependDetailedDescription(this._fullHelpObject, genericHelpMaml); - MamlUtil.OverrideParameters(this._fullHelpObject, genericHelpMaml); - MamlUtil.PrependNotes(this._fullHelpObject, genericHelpMaml); - MamlUtil.AddCommonProperties(this._fullHelpObject, genericHelpMaml); + MamlUtil.OverrideName(_fullHelpObject, genericHelpMaml); + MamlUtil.OverridePSTypeNames(_fullHelpObject, genericHelpMaml); + MamlUtil.PrependSyntax(_fullHelpObject, genericHelpMaml); + MamlUtil.PrependDetailedDescription(_fullHelpObject, genericHelpMaml); + MamlUtil.OverrideParameters(_fullHelpObject, genericHelpMaml); + MamlUtil.PrependNotes(_fullHelpObject, genericHelpMaml); + MamlUtil.AddCommonProperties(_fullHelpObject, genericHelpMaml); } #region Basic Help Properties @@ -206,9 +207,9 @@ namespace System.Management.Automation internal void SetAdditionalDataFromHelpComment(string component, string functionality, string role) { - this._component = component; - this._functionality = functionality; - this._role = role; + _component = component; + _functionality = functionality; + _role = role; // component,role,functionality is part of common help.. // Update these properties as we have new data now.. @@ -227,17 +228,17 @@ namespace System.Management.Automation string propertyValue; if (userDefinedData.Properties.TryGetValue("component", out propertyValue)) { - this._component = propertyValue; + _component = propertyValue; } if (userDefinedData.Properties.TryGetValue("role", out propertyValue)) { - this._role = propertyValue; + _role = propertyValue; } if (userDefinedData.Properties.TryGetValue("functionality", out propertyValue)) { - this._functionality = propertyValue; + _functionality = propertyValue; } // component,role,functionality is part of common help.. @@ -327,9 +328,9 @@ namespace System.Management.Automation return string.Empty; } - return ExtractText(PSObject.AsPSObject(psObject.Properties[propertyName].Value)); + return ExtractText(PSObject.AsPSObject(psObject.Properties[propertyName].Value)); } - + /// /// Given a PSObject, this method will traverse through the objects properties, /// extracts content from properities that are of type System.String, appends them @@ -434,13 +435,13 @@ namespace System.Management.Automation internal MamlCommandHelpInfo Copy() { - MamlCommandHelpInfo result = new MamlCommandHelpInfo(this._fullHelpObject.Copy(), this.HelpCategory); + MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), this.HelpCategory); return result; } internal MamlCommandHelpInfo Copy(HelpCategory newCategoryToUse) { - MamlCommandHelpInfo result = new MamlCommandHelpInfo(this._fullHelpObject.Copy(), newCategoryToUse); + MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), newCategoryToUse); result.FullHelp.Properties["Category"].Value = newCategoryToUse; return result; } diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 661e0877f..3a4400900 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Collections.ObjectModel; using System.Globalization; @@ -78,7 +79,7 @@ namespace System.Management.Automation } private XmlNode _xmlNode; - + /// /// Underline xmlNode for this MamlNode object /// @@ -217,14 +218,14 @@ namespace System.Management.Automation // the ouput is readable. This is done only for complex nodes. mshObject.TypeNames.Clear(); - if(xmlNode.Attributes["type"] != null) + if (xmlNode.Attributes["type"] != null) { if (String.Compare(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase) == 0) mshObject.TypeNames.Add("MamlPSClassHelpInfo#field"); else if (String.Compare(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase) == 0) - mshObject.TypeNames.Add("MamlPSClassHelpInfo#method"); + mshObject.TypeNames.Add("MamlPSClassHelpInfo#method"); } - + mshObject.TypeNames.Add("MamlCommandHelpInfo#" + xmlNode.LocalName); } @@ -235,7 +236,7 @@ namespace System.Management.Automation mshObject.Properties.Add(new PSNoteProperty(attribute.Name, attribute.Value)); } } - + return mshObject; } @@ -312,7 +313,7 @@ namespace System.Management.Automation if (xmlNode.ChildNodes != null) { foreach (XmlNode childNode in xmlNode.ChildNodes) - { + { AddProperty(properties, childNode.LocalName, GetPSObject(childNode)); } } @@ -384,7 +385,7 @@ namespace System.Management.Automation /// property value static private void AddProperty(Hashtable properties, string name, PSObject mshObject) { - ArrayList propertyValues = (ArrayList) properties[name]; + ArrayList propertyValues = (ArrayList)properties[name]; if (propertyValues == null) { @@ -402,9 +403,9 @@ namespace System.Management.Automation return; } - PSObject[] mshObjects = (PSObject[]) mshObject.BaseObject; + PSObject[] mshObjects = (PSObject[])mshObject.BaseObject; - for(int i = 0; i < mshObjects.Length; i++) + for (int i = 0; i < mshObjects.Length; i++) { propertyValues.Add(mshObjects[i]); } @@ -431,16 +432,16 @@ namespace System.Management.Automation Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator enumerator = properties.GetEnumerator(); - while(enumerator.MoveNext()) + while (enumerator.MoveNext()) { - ArrayList propertyValues = (ArrayList) enumerator.Value; + ArrayList propertyValues = (ArrayList)enumerator.Value; - if(propertyValues == null || propertyValues.Count == 0) + if (propertyValues == null || propertyValues.Count == 0) continue; - if(propertyValues.Count == 1) + if (propertyValues.Count == 1) { - if(!IsMamlFormattingPSObject((PSObject)propertyValues[0])) + if (!IsMamlFormattingPSObject((PSObject)propertyValues[0])) { PSObject mshObject = (PSObject)propertyValues[0]; @@ -530,7 +531,7 @@ namespace System.Management.Automation return true; if (xmlNode.LocalName.Equals("definitionList", StringComparison.OrdinalIgnoreCase)) - return true; + return true; return false; } @@ -613,7 +614,7 @@ namespace System.Management.Automation { ++count; PSObject paraPSObject = GetParaPSObject(childNode, count != paraNodes); - if(paraPSObject != null) + if (paraPSObject != null) mshObjects.Add(paraPSObject); continue; } @@ -640,13 +641,13 @@ namespace System.Management.Automation } continue; - } + } // If we get here, there is some tags that is not supported by maml. WriteMamlInvalidChildNodeError(xmlNode, childNode); } - return (PSObject[]) mshObjects.ToArray(typeof(PSObject)); + return (PSObject[])mshObjects.ToArray(typeof(PSObject)); } /// @@ -1058,7 +1059,7 @@ namespace System.Management.Automation WriteMamlInvalidChildNodeCountError(xmlNode, "para", 1); } - string text = ""; + string text = ""; foreach (XmlNode childNode in xmlNode.ChildNodes) { @@ -1163,7 +1164,7 @@ namespace System.Management.Automation int start = i; - if(start == lines.Length) + if (start == lines.Length) return null; for (i = lines.Length - 1; i >= start; i--) @@ -1194,7 +1195,7 @@ namespace System.Management.Automation for (int i = 0; i < lines.Length; i++) { - if(IsEmptyLine(lines[i])) + if (IsEmptyLine(lines[i])) continue; int indentation = GetIndentation(lines[i]); diff --git a/src/System.Management.Automation/help/MamlUtil.cs b/src/System.Management.Automation/help/MamlUtil.cs index d0ef2dc8c..bafa177a9 100644 --- a/src/System.Management.Automation/help/MamlUtil.cs +++ b/src/System.Management.Automation/help/MamlUtil.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Management.Automation.Help; using System.Collections.Generic; @@ -127,13 +128,13 @@ namespace System.Management.Automation } // copy parameters from maml2 that are not present in maml1 - for(int index = 0; index < maml2items.Count; index++) + for (int index = 0; index < maml2items.Count; index++) { PSObject m2paramObj = PSObject.AsPSObject(maml2items[index]); string param2Name = ""; PSPropertyInfo m2propertyInfo = m2paramObj.Properties["Name"]; - if(null != m2propertyInfo) + if (null != m2propertyInfo) { if (!LanguagePrimitives.TryConvertTo(m2propertyInfo.Value, out param2Name)) { @@ -175,7 +176,7 @@ namespace System.Management.Automation else if (maml1items.Count >= 2) { propertyInfo1.Value = maml1items.ToArray(); - } + } } /// @@ -196,7 +197,7 @@ namespace System.Management.Automation return null; } - for (int i = 0 ; i < path.Length ; ++i) + for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; @@ -210,7 +211,7 @@ namespace System.Management.Automation return null; } - psObject = (PSObject) propertyInfo.Value; + psObject = (PSObject)propertyInfo.Value; } // We will never reach this line but the compiler needs some reassurance. @@ -295,7 +296,7 @@ namespace System.Management.Automation } // Walk the path and extend it if necessary. - for (int i = 0 ; i < path.Length ; ++i) + for (int i = 0; i < path.Length; ++i) { string propertyName = path[i]; PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; @@ -322,7 +323,7 @@ namespace System.Management.Automation } // Now move one step further along the path. - psObject = (PSObject) propertyInfo.Value; + psObject = (PSObject)propertyInfo.Value; } } } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index a14016348..e87810a07 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -21,7 +21,7 @@ namespace System.Management.Automation internal PSClassHelpProvider(HelpSystem helpSystem) : base(helpSystem) { - _context = helpSystem.ExecutionContext; + _context = helpSystem.ExecutionContext; } /// @@ -38,7 +38,7 @@ namespace System.Management.Automation private readonly Hashtable _helpFiles = new Hashtable(); [TraceSource("PSClassHelpProvider", "PSClassHelpProvider")] - static private readonly PSTraceSource tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider"); + static private readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSClassHelpProvider", "PSClassHelpProvider"); #region common properties @@ -68,11 +68,11 @@ namespace System.Management.Automation /// override internal IEnumerable SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { - Debug.Assert(helpRequest != null, "helpRequest cannot be null."); + Debug.Assert(helpRequest != null, "helpRequest cannot be null."); string target = helpRequest.Target; Collection patternList = new Collection(); - + bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(helpRequest.Target); if (decoratedSearch) @@ -88,7 +88,7 @@ namespace System.Management.Automation { PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context); - foreach(var helpInfo in GetHelpInfo(searcher)) + foreach (var helpInfo in GetHelpInfo(searcher)) { if (helpInfo != null) yield return helpInfo; @@ -105,7 +105,7 @@ namespace System.Management.Automation { Debug.Assert(helpRequest != null, "helpRequest cannot be null."); - if((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0) + if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0) { yield return null; } @@ -131,14 +131,14 @@ namespace System.Management.Automation /// Next HelpInfo object. private IEnumerable GetHelpInfo(PSClassSearcher searcher) { - while(searcher.MoveNext()) + while (searcher.MoveNext()) { PSClassInfo current = ((IEnumerator)searcher).Current; string moduleName = current.Module.Name; string moduleDir = current.Module.ModuleBase; - if(!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleDir)) + if (!String.IsNullOrEmpty(moduleName) && !String.IsNullOrEmpty(moduleDir)) { string helpFileToFind = moduleName + "-Help.xml"; @@ -208,7 +208,7 @@ namespace System.Management.Automation } #region private methods - + private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection searchPaths, bool reportErrors, out string helpFile) { Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null"); @@ -217,7 +217,7 @@ namespace System.Management.Automation HelpInfo result = null; helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths); - + if (!File.Exists(helpFile)) return result; @@ -289,7 +289,7 @@ namespace System.Management.Automation } if (e != null) - tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); + s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { @@ -337,7 +337,7 @@ namespace System.Management.Automation if (helpItemsNode == null) { - tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); + s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; } @@ -377,7 +377,5 @@ namespace System.Management.Automation } #endregion - - } } \ No newline at end of file diff --git a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs index 18674841d..a78c2c64b 100644 --- a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index 991fbd27a..1f70d93d4 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -41,11 +41,11 @@ namespace System.Management.Automation PathIntrinsics pathIntrinsics) { Dbg.Assert(null != executionContext, "ExecutionContext cannot be null."); - this._requestedPath = requestedPath; - this._executionContext = executionContext; - this._pathIntrinsics = pathIntrinsics; + _requestedPath = requestedPath; + _executionContext = executionContext; + _pathIntrinsics = pathIntrinsics; } - + /// /// Get provider specific help info. /// @@ -111,7 +111,7 @@ namespace System.Management.Automation { throw new ItemNotFoundException(_requestedPath, "PathNotFound", SessionStateStrings.PathNotFound); } - + // ok we have path and valid provider that supplys content..intialize the provider // and get the help content for the path. cmdletProvider.Start(providerInfo, cmdletProviderContext); diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index 7e4672a97..5d3826b07 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections; using System.Xml; @@ -38,20 +39,20 @@ namespace System.Management.Automation { get { - if (_fullHelpObject == null) - return ""; + if (_fullHelpObject == null) + return ""; - if (_fullHelpObject.Properties["Name"] == null) - return ""; + if (_fullHelpObject.Properties["Name"] == null) + return ""; - if (_fullHelpObject.Properties["Name"].Value == null) - return ""; + if (_fullHelpObject.Properties["Name"].Value == null) + return ""; - string name = _fullHelpObject.Properties["Name"].Value.ToString(); - if (name == null) - return ""; + string name = _fullHelpObject.Properties["Name"].Value.ToString(); + if (name == null) + return ""; - return name.Trim(); + return name.Trim(); } } diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 85828b109..b177da848 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation /// Provider Help information are stored in 'help.xml' files. Location of these files /// can be found from CommandDiscovery. /// - internal class ProviderHelpProvider: HelpProviderWithCache + internal class ProviderHelpProvider : HelpProviderWithCache { /// /// Constructor for HelpProvider @@ -71,7 +71,7 @@ namespace System.Management.Automation try { - matchingProviders = this._sessionState.Provider.Get(helpRequest.Target); + matchingProviders = _sessionState.Provider.Get(helpRequest.Target); } catch (ProviderNotFoundException e) { @@ -85,7 +85,7 @@ namespace System.Management.Automation ErrorRecord errorRecord = new ErrorRecord(e, "ProviderLoadError", ErrorCategory.ResourceUnavailable, null); errorRecord.ErrorDetails = new ErrorDetails(typeof(ProviderHelpProvider).GetTypeInfo().Assembly, "HelpErrors", "ProviderLoadError", helpRequest.Target, e.Message); this.HelpSystem.LastErrors.Add(errorRecord); - } + } } if (matchingProviders != null) @@ -119,7 +119,7 @@ namespace System.Management.Automation } } - + static private string GetProviderAssemblyPath(ProviderInfo providerInfo) { if (providerInfo == null) @@ -198,7 +198,7 @@ namespace System.Management.Automation throw new FileNotFoundException(helpFile); XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( - new FileInfo(location), + new FileInfo(location), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ @@ -248,7 +248,7 @@ namespace System.Management.Automation helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, "ProviderHelpInfo#{0}", providerInfo.PSSnapInName)); } - AddCache(providerInfo.PSSnapInName+"\\"+helpInfo.Name, helpInfo); + AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); } } } @@ -305,7 +305,7 @@ namespace System.Management.Automation yield break; } - foreach (ProviderInfo providerInfo in this._sessionState.Provider.GetAll()) + foreach (ProviderInfo providerInfo in _sessionState.Provider.GetAll()) { if (providerInfo.IsMatch(pattern)) { @@ -356,7 +356,6 @@ namespace System.Management.Automation yield break; } } - } } diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index e38ed1dca..8f619b487 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.ObjectModel; using Dbg = System.Management.Automation.Diagnostics; @@ -14,10 +15,10 @@ namespace System.Management.Automation /// internal class RemoteHelpInfo : BaseCommandHelpInfo { - private PSObject deserializedRemoteHelp; + private PSObject _deserializedRemoteHelp; internal RemoteHelpInfo( - ExecutionContext context, + ExecutionContext context, RemoteRunspace remoteRunspace, string localCommandName, string remoteHelpTopic, @@ -47,20 +48,20 @@ namespace System.Management.Automation throw new Microsoft.PowerShell.Commands.HelpNotFoundException(remoteHelpTopic); } - Dbg.Assert(helpResults.Count == 1, "Remote help should return exactly one result"); - this.deserializedRemoteHelp = helpResults[0]; - this.deserializedRemoteHelp.Methods.Remove("ToString"); + Dbg.Assert(helpResults.Count == 1, "Remote help should return exactly one result"); + _deserializedRemoteHelp = helpResults[0]; + _deserializedRemoteHelp.Methods.Remove("ToString"); // Win8: bug9457: Remote proxy command's name can be changed locally using -Prefix // parameter of the Import-PSSession cmdlet. To give better user expereience for // get-help (on par with get-command), it was decided to use the local command name // for the help content. - PSPropertyInfo nameInfo = this.deserializedRemoteHelp.Properties["Name"]; - if (nameInfo!= null) + PSPropertyInfo nameInfo = _deserializedRemoteHelp.Properties["Name"]; + if (nameInfo != null) { nameInfo.Value = localCommandName; } PSObject commandDetails = this.Details; - if (commandDetails != null) + if (commandDetails != null) { nameInfo = commandDetails.Properties["Name"]; if (nameInfo != null) @@ -72,21 +73,20 @@ namespace System.Management.Automation commandDetails.InstanceMembers.Add(new PSNoteProperty("Name", localCommandName)); } } - } } internal override PSObject FullHelp { - get + get { - return this.deserializedRemoteHelp; + return _deserializedRemoteHelp; } } private string GetHelpProperty(string propertyName) { - PSPropertyInfo property = this.deserializedRemoteHelp.Properties[propertyName]; + PSPropertyInfo property = _deserializedRemoteHelp.Properties[propertyName]; if (property == null) { return null; diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 734d20a58..bb61eae84 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Management.Automation; @@ -32,7 +33,7 @@ namespace Microsoft.PowerShell.Commands #endregion - private bool alreadyCheckedOncePerDayPerModule = false; + private bool _alreadyCheckedOncePerDayPerModule = false; #region Parameters @@ -71,10 +72,10 @@ namespace Microsoft.PowerShell.Commands set { _path = value; - isLiteralPath = true; + _isLiteralPath = true; } } - bool isLiteralPath = false; + private bool _isLiteralPath = false; /// /// Specifies the modules to update @@ -86,7 +87,7 @@ namespace Microsoft.PowerShell.Commands [ArgumentToModuleTransformationAttribute()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSModuleInfo[] Module { get; set; } - + /// /// Specifies the Module Specifications to update /// @@ -146,7 +147,7 @@ namespace Microsoft.PowerShell.Commands base.Process(moduleInfos); } finally - { + { ProgressRecord progress = new ProgressRecord(activityId, HelpDisplayStrings.SaveProgressActivityForModule, HelpDisplayStrings.UpdateProgressInstalling); progress.PercentComplete = 100; @@ -225,7 +226,7 @@ namespace Microsoft.PowerShell.Commands } } - if (isLiteralPath) + if (_isLiteralPath) { string destinationPath = GetUnresolvedProviderPathFromPSPath(destPath); if (!Directory.Exists(destinationPath)) @@ -289,18 +290,18 @@ namespace Microsoft.PowerShell.Commands { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. - currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, - currentCulture: null, pathOverride: null, verbose: false, - shouldResolveUri:false, ignoreValidationException: false); + currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, + currentCulture: null, pathOverride: null, verbose: false, + shouldResolveUri: false, ignoreValidationException: false); } // Don't update too frequently - if (!alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, path, module.GetHelpInfoName(), DateTime.UtcNow, _force)) + if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, path, module.GetHelpInfoName(), DateTime.UtcNow, _force)) { return true; } - alreadyCheckedOncePerDayPerModule = true; + _alreadyCheckedOncePerDayPerModule = true; // Form the actual HelpInfo.xml uri helpInfoUri = _helpSystem.GetHelpInfoUri(module, null).ResolvedUri; @@ -444,7 +445,7 @@ namespace Microsoft.PowerShell.Commands { int elemtCount = iListArg.Count; int targetIndex = 0; - var target = Array.CreateInstance(typeof (object), elemtCount); + var target = Array.CreateInstance(typeof(object), elemtCount); foreach (object elemt in iListArg) { diff --git a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs index 04ea256ac..f28a71de6 100644 --- a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs +++ b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs @@ -42,7 +42,7 @@ namespace System.Management.Automation HelpCategory.Workflow; } } - + /// /// Gets a command searcher used for ExactMatch help lookup. /// @@ -52,7 +52,7 @@ namespace System.Management.Automation internal override CommandSearcher GetCommandSearcherForExactMatch(string commandName, ExecutionContext context) { CommandSearcher searcher = new CommandSearcher( - commandName, + commandName, SearchResolutionOptions.None, CommandTypes.Filter | CommandTypes.Function | CommandTypes.ExternalScript | CommandTypes.Configuration, context); diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 83fad44b1..91865ea24 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Linq; using System.Management.Automation; @@ -31,7 +32,7 @@ namespace Microsoft.PowerShell.Commands internal bool _stopping; internal int activityId; - private Dictionary exceptions; + private Dictionary _exceptions; #region Parameters @@ -49,7 +50,7 @@ namespace Microsoft.PowerShell.Commands if (_language != null) { result = new CultureInfo[_language.Length]; - for(int index = 0; index < _language.Length; index++) + for (int index = 0; index < _language.Length; index++) { result[index] = new CultureInfo(_language[index]); } @@ -60,7 +61,7 @@ namespace Microsoft.PowerShell.Commands { if (value == null) return; _language = new string[value.Length]; - for(int index = 0; index < value.Length; index++) + for (int index = 0; index < value.Length; index++) { _language[index] = value[index].Name; } @@ -143,7 +144,7 @@ namespace Microsoft.PowerShell.Commands #region Constructor - private static Dictionary metadataCache; + private static Dictionary s_metadataCache; /// /// Static constructor @@ -154,17 +155,17 @@ namespace Microsoft.PowerShell.Commands /// static UpdatableHelpCommandBase() { - metadataCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + s_metadataCache = new Dictionary(StringComparer.OrdinalIgnoreCase); // TODO: assign real TechNet addresses - metadataCache.Add("Microsoft.PowerShell.Diagnostics", "http://go.microsoft.com/fwlink/?linkid=390783"); - metadataCache.Add("Microsoft.PowerShell.Core", "http://go.microsoft.com/fwlink/?linkid=390782"); - metadataCache.Add("Microsoft.PowerShell.Utility", "http://go.microsoft.com/fwlink/?linkid=390787"); - metadataCache.Add("Microsoft.PowerShell.Host", "http://go.microsoft.com/fwlink/?linkid=390784"); - metadataCache.Add("Microsoft.PowerShell.Management", " http://go.microsoft.com/fwlink/?linkid=390785"); - metadataCache.Add("Microsoft.PowerShell.Security", " http://go.microsoft.com/fwlink/?linkid=390786"); - metadataCache.Add("Microsoft.WSMan.Management", "http://go.microsoft.com/fwlink/?linkid=390788"); + s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "http://go.microsoft.com/fwlink/?linkid=390783"); + s_metadataCache.Add("Microsoft.PowerShell.Core", "http://go.microsoft.com/fwlink/?linkid=390782"); + s_metadataCache.Add("Microsoft.PowerShell.Utility", "http://go.microsoft.com/fwlink/?linkid=390787"); + s_metadataCache.Add("Microsoft.PowerShell.Host", "http://go.microsoft.com/fwlink/?linkid=390784"); + s_metadataCache.Add("Microsoft.PowerShell.Management", " http://go.microsoft.com/fwlink/?linkid=390785"); + s_metadataCache.Add("Microsoft.PowerShell.Security", " http://go.microsoft.com/fwlink/?linkid=390786"); + s_metadataCache.Add("Microsoft.WSMan.Management", "http://go.microsoft.com/fwlink/?linkid=390788"); } /// @@ -175,7 +176,7 @@ namespace Microsoft.PowerShell.Commands /// true if system module, false if not internal static bool IsSystemModule(string module) { - return metadataCache.ContainsKey(module); + return s_metadataCache.ContainsKey(module); } /// @@ -186,7 +187,7 @@ namespace Microsoft.PowerShell.Commands { _commandType = commandType; _helpSystem = new UpdatableHelpSystem(this, _useDefaultCredentials); - exceptions = new Dictionary(); + _exceptions = new Dictionary(); _helpSystem.OnProgressChanged += new EventHandler(HandleProgressChanged); Random rand = new Random(); @@ -208,7 +209,7 @@ namespace Microsoft.PowerShell.Commands if (!helpModules.ContainsKey(keyTuple)) { helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, module.Guid, - Utils.GetApplicationBase(context.ShellID), metadataCache[module.Name])); + Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name])); } return; @@ -282,8 +283,8 @@ namespace Microsoft.PowerShell.Commands // Match wildcards WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); - - foreach (KeyValuePair name in metadataCache) + + foreach (KeyValuePair name in s_metadataCache) { if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true)) { @@ -304,7 +305,7 @@ namespace Microsoft.PowerShell.Commands WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid)); helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, - module.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[module.Name])); + module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name])); } } } @@ -341,13 +342,13 @@ namespace Microsoft.PowerShell.Commands /// protected override void EndProcessing() { - foreach (UpdatableHelpExceptionContext exception in exceptions.Values) + foreach (UpdatableHelpExceptionContext exception in _exceptions.Values) { UpdatableHelpExceptionContext e = exception; if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") && ((exception.Cultures != null && exception.Cultures.Count > 1) || - (exception.Modules != null && exception.Modules.Count > 1) )) + (exception.Modules != null && exception.Modules.Count > 1))) { // Win8: 744749 Rewriting the error message only in the case where either // multiple cultures or multiple modules are involved. @@ -366,8 +367,8 @@ namespace Microsoft.PowerShell.Commands context.Severity = "Error"; PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline, - context, e.GetExceptionMessage(_commandType)); - } + context, e.GetExceptionMessage(_commandType)); + } } /// @@ -479,7 +480,7 @@ namespace Microsoft.PowerShell.Commands if (this is UpdateHelpCommand && !Directory.Exists(module.ModuleBase)) { - ProcessException(module.ModuleName, null, + ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("ModuleBaseMustExist", StringUtil.Format(HelpDisplayStrings.ModuleBaseMustExist), ErrorCategory.InvalidOperation, null, null)); @@ -605,9 +606,9 @@ namespace Microsoft.PowerShell.Commands { Dictionary, UpdatableHelpModuleInfo> modules = GetModuleInfo(Context, pattern, fullyQualifiedName, noErrors); - if (modules.Count == 0 && exceptions.Count == 0 && !noErrors) + if (modules.Count == 0 && _exceptions.Count == 0 && !noErrors) { - var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName) + var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName) : StringUtil.Format(HelpDisplayStrings.CannotMatchModulePattern, pattern); ErrorRecord errorRecord = new ErrorRecord(new Exception(errorMessage), @@ -647,7 +648,7 @@ namespace Microsoft.PowerShell.Commands StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, culture.Name, newHelpInfo.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null); } - + // Version check if (!force && currentHelpInfo != null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture)) { @@ -669,7 +670,7 @@ namespace Microsoft.PowerShell.Commands internal bool CheckOncePerDayPerModule(string moduleName, string path, string filename, DateTime time, bool force) { // Update if -Force is specified - if(force) + if (force) { return true; } @@ -720,7 +721,7 @@ namespace Microsoft.PowerShell.Commands if (!Directory.Exists(newPath)) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", - StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, + StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, null, new ItemNotFoundException()); } @@ -839,7 +840,7 @@ namespace Microsoft.PowerShell.Commands except = (UpdatableHelpSystemException)e; } #if !CORECLR - else if(e is WebException) + else if (e is WebException) { except = new UpdatableHelpSystemException("UnableToConnect", StringUtil.Format(HelpDisplayStrings.UnableToConnect), ErrorCategory.InvalidOperation, null, e); @@ -856,16 +857,16 @@ namespace Microsoft.PowerShell.Commands e.Message, ErrorCategory.InvalidOperation, null, e); } - if (!exceptions.ContainsKey(except.FullyQualifiedErrorId)) + if (!_exceptions.ContainsKey(except.FullyQualifiedErrorId)) { - exceptions.Add(except.FullyQualifiedErrorId, new UpdatableHelpExceptionContext(except)); + _exceptions.Add(except.FullyQualifiedErrorId, new UpdatableHelpExceptionContext(except)); } - exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName); + _exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName); if (culture != null) { - exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture); + _exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture); } } diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index 20ceed398..d60802436 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Management.Automation.Internal; using System.Globalization; using System.Diagnostics; @@ -89,7 +90,7 @@ namespace System.Management.Automation.Help { return _unresolvedUri; } - } + } private string _unresolvedUri; /// @@ -136,7 +137,7 @@ namespace System.Management.Automation.Help return true; } - return v1 > v2;; + return v1 > v2; ; } /// @@ -150,7 +151,7 @@ namespace System.Management.Automation.Help foreach (CultureSpecificUpdatableHelp updatableHelpItem in _updatableHelpItems) { - if (String.Compare(updatableHelpItem.Culture.Name, culture.Name, + if (String.Compare(updatableHelpItem.Culture.Name, culture.Name, StringComparison.OrdinalIgnoreCase) == 0) { return true; diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index 276ca979d..08d100794 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Globalization; using System.Diagnostics; diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index ffc3ce6f9..a7e264e2b 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Globalization; using System.Collections.ObjectModel; using System.Net; @@ -63,7 +64,6 @@ namespace System.Management.Automation.Help protected UpdatableHelpSystemException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { - } #endif @@ -451,7 +451,7 @@ namespace System.Management.Automation.Help { client.Timeout = _defaultTimeout; Task responseBody = client.GetStringAsync(uri); - xml = responseBody.Result; + xml = responseBody.Result; if (responseBody.Exception != null) { return null; @@ -461,9 +461,9 @@ namespace System.Management.Automation.Help #else string xml = _webClient.DownloadString(uri); #endif - UpdatableHelpInfo helpInfo = CreateHelpInfo(xml, moduleName, moduleGuid, - currentCulture: culture, pathOverride: null, verbose: true, - shouldResolveUri:true, ignoreValidationException: false); + UpdatableHelpInfo helpInfo = CreateHelpInfo(xml, moduleName, moduleGuid, + currentCulture: culture, pathOverride: null, verbose: true, + shouldResolveUri: true, ignoreValidationException: false); return helpInfo; } @@ -621,7 +621,7 @@ namespace System.Management.Automation.Help return uri; } } - else if(response.StatusCode == HttpStatusCode.OK) + else if (response.StatusCode == HttpStatusCode.OK) { if (uri.EndsWith("/", StringComparison.OrdinalIgnoreCase)) { @@ -702,9 +702,9 @@ namespace System.Management.Automation.Help XmlDocument document = null; try { - document = CreateValidXmlDocument(xml, HelpInfoXmlNamespace,HelpInfoXmlSchema, + document = CreateValidXmlDocument(xml, HelpInfoXmlNamespace, HelpInfoXmlSchema, #if !CORECLR - new ValidationEventHandler(HelpInfoValidationHandler), + new ValidationEventHandler(HelpInfoValidationHandler), #endif true); } @@ -736,7 +736,7 @@ namespace System.Management.Automation.Help } else { - uri = unresolvedUri; + uri = unresolvedUri; } } @@ -799,7 +799,7 @@ namespace System.Management.Automation.Help { document.Load(reader); } - catch(XmlException e) + catch (XmlException e) { if (helpInfo) { @@ -1157,8 +1157,8 @@ namespace System.Management.Automation.Help { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. - oldHelpInfo = CreateHelpInfo(xml, moduleName, moduleGuid, currentCulture: null, pathOverride: null, - verbose: false, shouldResolveUri:false, ignoreValidationException: force); + oldHelpInfo = CreateHelpInfo(xml, moduleName, moduleGuid, currentCulture: null, pathOverride: null, + verbose: false, shouldResolveUri: false, ignoreValidationException: force); } using (FileStream file = new FileStream(destHelpInfo, FileMode.Create, FileAccess.Write)) @@ -1252,7 +1252,7 @@ namespace System.Management.Automation.Help { FileAttributes attributes = File.GetAttributes(path); - if((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { attributes = (attributes & ~FileAttributes.ReadOnly); File.SetAttributes(path, attributes); @@ -1334,9 +1334,9 @@ namespace System.Management.Automation.Help Directory.Delete(tempPath); } } - catch (IOException) {} + catch (IOException) { } catch (UnauthorizedAccessException) { } - catch (ArgumentException ) {} + catch (ArgumentException) { } } } @@ -1398,23 +1398,23 @@ namespace System.Management.Automation.Help } } catch (FileNotFoundException) - {} + { } catch (DirectoryNotFoundException) - {} + { } catch (UnauthorizedAccessException) - {} + { } catch (System.Security.SecurityException) - {} + { } catch (ArgumentNullException) - {} + { } catch (ArgumentException) - {} + { } catch (PathTooLongException) - {} + { } catch (NotSupportedException) - {} + { } catch (IOException) - {} + { } } } } @@ -1473,7 +1473,7 @@ namespace System.Management.Automation.Help { if (xsd == null) { - throw new ItemNotFoundException(StringUtil.Format(HelpDisplayStrings.HelpContentXsdNotFound, xsdPath)); + throw new ItemNotFoundException(StringUtil.Format(HelpDisplayStrings.HelpContentXsdNotFound, xsdPath)); } else { @@ -1493,7 +1493,7 @@ namespace System.Management.Automation.Help XmlNode helpItemsNode = null; - if(contentDocument.DocumentElement != null && + if (contentDocument.DocumentElement != null && contentDocument.DocumentElement.LocalName.Equals("providerHelp", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = contentDocument; @@ -1535,7 +1535,7 @@ namespace System.Management.Automation.Help foreach (XmlNode node in helpItemsNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element) - { + { if (!node.LocalName.Equals("providerHelp", StringComparison.OrdinalIgnoreCase)) { if (node.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) @@ -1551,9 +1551,9 @@ namespace System.Management.Automation.Help continue; } } - + if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/command/2004/10", StringComparison.OrdinalIgnoreCase) && - !node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase) ) + !node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, @@ -1561,9 +1561,9 @@ namespace System.Management.Automation.Help } } - CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd, + CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd, #if !CORECLR - new ValidationEventHandler(HelpContentValidationHandler), + new ValidationEventHandler(HelpContentValidationHandler), #endif false); } @@ -1587,7 +1587,6 @@ namespace System.Management.Automation.Help StringUtil.Format(HelpDisplayStrings.HelpContentContainsInvalidFiles), ErrorCategory.InvalidData, null, null); } - } } @@ -1740,7 +1739,7 @@ namespace System.Management.Automation.Help // Ignore AccessDenied related exceptions } } - + /// /// Checks if it is necessary to prompt to update help /// diff --git a/src/System.Management.Automation/help/UpdatableHelpUri.cs b/src/System.Management.Automation/help/UpdatableHelpUri.cs index e4577c08d..26b5a1b9f 100644 --- a/src/System.Management.Automation/help/UpdatableHelpUri.cs +++ b/src/System.Management.Automation/help/UpdatableHelpUri.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Globalization; using System.Diagnostics; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 6545c3bbd..431e1ca6e 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Management.Automation.Internal; @@ -32,7 +33,7 @@ namespace Microsoft.PowerShell.Commands #endregion - private bool alreadyCheckedOncePerDayPerModule = false; + private bool _alreadyCheckedOncePerDayPerModule = false; #region Parameters @@ -126,7 +127,7 @@ namespace Microsoft.PowerShell.Commands #endregion - private bool isInitialized = false; + private bool _isInitialized = false; #region Implementation @@ -166,14 +167,14 @@ namespace Microsoft.PowerShell.Commands ThrowTerminatingError(error); } - if (!isInitialized) + if (!_isInitialized) { if (_path == null && Recurse.IsPresent) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); } - isInitialized = true; + _isInitialized = true; } base.Process(_module, FullyQualifiedModule); @@ -222,20 +223,20 @@ namespace Microsoft.PowerShell.Commands { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. - currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, - currentCulture: null, pathOverride: null, verbose: false, - shouldResolveUri: false, + currentHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, + currentCulture: null, pathOverride: null, verbose: false, + shouldResolveUri: false, // ignore validation exception if _force is true ignoreValidationException: _force); } // Don't update too frequently - if (!alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force)) + if (!_alreadyCheckedOncePerDayPerModule && !CheckOncePerDayPerModule(module.ModuleName, module.ModuleBase, module.GetHelpInfoName(), DateTime.UtcNow, _force)) { return true; } - alreadyCheckedOncePerDayPerModule = true; + _alreadyCheckedOncePerDayPerModule = true; if (_path != null) { @@ -294,7 +295,7 @@ namespace Microsoft.PowerShell.Commands if (xml != null) { - newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath, + newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath, verbose: false, shouldResolveUri: true, ignoreValidationException: false); helpInfoUri = resolvedPath; break; @@ -341,8 +342,8 @@ namespace Microsoft.PowerShell.Commands string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, - (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0", - newHelpInfo.GetCultureVersion(contentUri.Culture), + (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0", + newHelpInfo.GetCultureVersion(contentUri.Culture), contentUri.Culture); if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help")) { @@ -350,7 +351,7 @@ namespace Microsoft.PowerShell.Commands } if (Utils.IsUnderProductFolder(module.ModuleBase) && (!Utils.IsAdministrator())) - { + { string message = StringUtil.Format(HelpErrors.UpdatableHelpRequiresElevation); ProcessException(module.ModuleName, null, new UpdatableHelpSystemException("UpdatableHelpSystemRequiresElevation", message, ErrorCategory.InvalidOperation, null, null)); @@ -428,7 +429,7 @@ namespace Microsoft.PowerShell.Commands { _helpSystem.InstallHelpContent(UpdatableHelpCommandType.UpdateHelpCommand, Context, helpContentUri, destPaths, module.GetHelpContentName(contentUri.Culture), - Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), + Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())), contentUri.Culture, xsdPath, out filesInstalled); } } diff --git a/src/System.Management.Automation/logging/LogContext.cs b/src/System.Management.Automation/logging/LogContext.cs index 3fbd0b31b..61a603330 100644 --- a/src/System.Management.Automation/logging/LogContext.cs +++ b/src/System.Management.Automation/logging/LogContext.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Collections.Generic; diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index 1afa570f2..47fe2770e 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Collections.Generic; @@ -51,7 +52,7 @@ namespace System.Management.Automation /// /// /// - abstract internal void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary additionalInfo); + abstract internal void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary additionalInfo); /// /// Provider interface function for logging engine lifecycle event diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 52279d855..53c39c40f 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -61,21 +62,21 @@ namespace System.Management.Automation /// The value of this dictionary is never empty. A value of type DummyProvider means /// no logging. /// - private static ConcurrentDictionary> _logProviders = + private static ConcurrentDictionary> s_logProviders = new ConcurrentDictionary>(); private const string _crimsonLogProviderAssemblyName = "MshCrimsonLog"; private const string _crimsonLogProviderTypeName = "System.Management.Automation.Logging.CrimsonLogProvider"; - private static Collection ignoredCommands = new Collection(); + private static Collection s_ignoredCommands = new Collection(); /// /// Static constructor /// static MshLog() { - ignoredCommands.Add("Out-Lineoutput"); - ignoredCommands.Add("Format-Default"); + s_ignoredCommands.Add("Out-Lineoutput"); + s_ignoredCommands.Add("Format-Default"); } /// @@ -91,7 +92,7 @@ namespace System.Management.Automation /// static private IEnumerable GetLogProvider(string shellId) { - return _logProviders.GetOrAdd(shellId, CreateLogProvider); + return s_logProviders.GetOrAdd(shellId, CreateLogProvider); } /// @@ -210,13 +211,13 @@ namespace System.Management.Automation static internal void SetDummyLog(string shellId) { Collection providers = new Collection { new DummyLogProvider() }; - _logProviders.AddOrUpdate(shellId, providers, (key, value) => providers); + s_logProviders.AddOrUpdate(shellId, providers, (key, value) => providers); } #endregion #region Engine Health Event Logging Api - + /// /// LogEngineHealthEvent: Log an engine health event. If engine state is changed, a engine /// lifecycle event will be logged also. @@ -232,11 +233,11 @@ namespace System.Management.Automation /// Severity of this event /// Additional information for this event /// New engine state - static internal void LogEngineHealthEvent(ExecutionContext executionContext, - int eventId, + static internal void LogEngineHealthEvent(ExecutionContext executionContext, + int eventId, Exception exception, Severity severity, - Dictionary additionalInfo, + Dictionary additionalInfo, EngineState newEngineState) { if (executionContext == null) @@ -295,7 +296,7 @@ namespace System.Management.Automation /// /// static internal void LogEngineHealthEvent(ExecutionContext executionContext, - Exception exception, + Exception exception, Severity severity) { LogEngineHealthEvent(executionContext, 100, exception, severity, null); @@ -495,7 +496,7 @@ namespace System.Management.Automation return; } - if (ignoredCommands.Contains(invocationInfo.MyCommand.Name)) + if (s_ignoredCommands.Contains(invocationInfo.MyCommand.Name)) { return; } @@ -706,7 +707,7 @@ namespace System.Management.Automation /// Previous value for the variable /// Invocation data for the command that is currently running static internal void LogSettingsEvent(ExecutionContext executionContext, - string variableName, + string variableName, string newValue, string previousValue, InvocationInfo invocationInfo) @@ -793,7 +794,7 @@ namespace System.Management.Automation /// /// /// - static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) + private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) { if (executionContext == null) return null; @@ -815,7 +816,7 @@ namespace System.Management.Automation logContext.HostApplication = String.Join(" ", Environment.GetCommandLineArgs()); - if(executionContext.CurrentRunspace != null) + if (executionContext.CurrentRunspace != null) { logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString(); logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString(); @@ -846,9 +847,9 @@ namespace System.Management.Automation logContext.User = Logging.UnknownUserName; } - System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = + System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; - if(psSenderInfo != null) + if (psSenderInfo != null) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } @@ -857,7 +858,7 @@ namespace System.Management.Automation if (invocationInfo == null) return logContext; - + logContext.ScriptName = invocationInfo.ScriptName; logContext.CommandLine = invocationInfo.Line; @@ -876,7 +877,7 @@ namespace System.Management.Automation break; } } - + return logContext; } @@ -1045,7 +1046,7 @@ namespace System.Management.Automation #region Sequence Id Generator - private static int _nextSequenceNumber = 0; + private static int s_nextSequenceNumber = 0; /// /// generate next sequence id to be attached to current event. @@ -1055,17 +1056,17 @@ namespace System.Management.Automation { get { - return Convert.ToString(Interlocked.Increment(ref _nextSequenceNumber), CultureInfo.CurrentCulture); + return Convert.ToString(Interlocked.Increment(ref s_nextSequenceNumber), CultureInfo.CurrentCulture); } } #endregion #region EventId Constants - + //General health issues. internal const int EVENT_ID_GENERAL_HEALTH_ISSUE = 100; - + // Dependency. resource not available internal const int EVENT_ID_RESOURCE_NOT_AVAILABLE = 101; //Connectivity. network connection failure @@ -1075,7 +1076,7 @@ namespace System.Management.Automation //Performance. system is experiencing some performance issues internal const int EVENT_ID_PERFORMANCE_ISSUE = 104; //Security: system is experiencing some security issues - internal const int EVENT_ID_SECURITY_ISSUE=105; + internal const int EVENT_ID_SECURITY_ISSUE = 105; //Workload. system is overloaded. internal const int EVENT_ID_SYSTEM_OVERLOADED = 106; @@ -1090,17 +1091,17 @@ namespace System.Management.Automation /// internal class LogContextCache { - private string user = null; + private string _user = null; internal string User { get { - return user; + return _user; } set { - user = value; + _user = value; } } } @@ -1115,7 +1116,7 @@ namespace System.Management.Automation /// /// Undefined severity. /// - None, + None, /// /// Critical event causing engine not to work. /// diff --git a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs index 90ffa6e21..f0fb1495e 100644 --- a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs +++ b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Management.Automation; using System.Collections; @@ -27,7 +28,7 @@ namespace System.Management.Automation /// always be available. /// /// - internal class EventLogLogProvider: LogProvider + internal class EventLogLogProvider : LogProvider { /// /// Constructor. @@ -45,7 +46,7 @@ namespace System.Management.Automation internal string SetupEventSource(string shellId) { - string source; + string source; // In case shellId == null, use the "Default" source. if (String.IsNullOrEmpty(shellId)) @@ -63,7 +64,7 @@ namespace System.Management.Automation // There may be a situation where ShellId ends with a '.'. // In that case, use the default source. - if(String.IsNullOrEmpty(source)) + if (String.IsNullOrEmpty(source)) source = "Default"; } @@ -80,7 +81,7 @@ namespace System.Management.Automation /// This represent a handle to EventLog /// private EventLog _eventLog; - private ResourceManager _resourceManager; + private ResourceManager _resourceManager; #region Log Provider Api @@ -194,7 +195,7 @@ namespace System.Management.Automation /// private static int GetEngineLifecycleEventId(EngineState engineState) { - switch(engineState) + switch (engineState) { case EngineState.None: return _invalidEventId; @@ -330,7 +331,7 @@ namespace System.Management.Automation } } - const int MaxLength = 16000; + private const int MaxLength = 16000; private List GroupMessages(List messages) { @@ -410,7 +411,7 @@ namespace System.Management.Automation mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - if ( icer.ErrorRecord.ErrorDetails != null + if (icer.ErrorRecord.ErrorDetails != null && !String.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message)) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; @@ -670,7 +671,7 @@ namespace System.Management.Automation } message.Append(messageTemplate.Substring(cursor, startIndex - cursor)); - cursor = startIndex; + cursor = startIndex; string placeHolder = messageTemplate.Substring(startIndex + 1, endIndex - startIndex - 1); diff --git a/src/System.Management.Automation/minishell/api/FormatAndTypeDataHelper.cs b/src/System.Management.Automation/minishell/api/FormatAndTypeDataHelper.cs index fa2e385a3..0f3fa0a78 100644 --- a/src/System.Management.Automation/minishell/api/FormatAndTypeDataHelper.cs +++ b/src/System.Management.Automation/minishell/api/FormatAndTypeDataHelper.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -17,52 +18,52 @@ namespace System.Management.Automation.Runspaces { public string psSnapinName; // only one of fullPath or formatTable or typeData or typeDefinition should be specified.. - private string fullPath; - private FormatTable formatTable; + private string _fullPath; + private FormatTable _formatTable; // typeData and isRemove should be used together - private TypeData typeData; - private bool isRemove; - private ExtendedTypeDefinition typeDefinition; - private ConcurrentBag errors; + private TypeData _typeData; + private bool _isRemove; + private ExtendedTypeDefinition _typeDefinition; + private ConcurrentBag _errors; internal PSSnapInTypeAndFormatErrors(string psSnapinName, string fullPath) { this.psSnapinName = psSnapinName; - this.fullPath = fullPath; - this.errors = new ConcurrentBag(); + _fullPath = fullPath; + _errors = new ConcurrentBag(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, FormatTable formatTable) { this.psSnapinName = psSnapinName; - this.formatTable = formatTable; - this.errors = new ConcurrentBag(); + _formatTable = formatTable; + _errors = new ConcurrentBag(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, TypeData typeData, bool isRemove) { this.psSnapinName = psSnapinName; - this.typeData = typeData; - this.isRemove = isRemove; - this.errors = new ConcurrentBag(); + _typeData = typeData; + _isRemove = isRemove; + _errors = new ConcurrentBag(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, ExtendedTypeDefinition typeDefinition) { this.psSnapinName = psSnapinName; - this.typeDefinition = typeDefinition; - this.errors = new ConcurrentBag(); + _typeDefinition = typeDefinition; + _errors = new ConcurrentBag(); } - internal ExtendedTypeDefinition FormatData { get { return typeDefinition; } } - internal TypeData TypeData { get { return typeData; } } - internal bool IsRemove { get { return isRemove; } } - internal string FullPath { get { return fullPath; } } - internal FormatTable FormatTable { get { return formatTable; } } - internal ConcurrentBag Errors - { - get { return errors; } - set { errors = value; } + internal ExtendedTypeDefinition FormatData { get { return _typeDefinition; } } + internal TypeData TypeData { get { return _typeData; } } + internal bool IsRemove { get { return _isRemove; } } + internal string FullPath { get { return _fullPath; } } + internal FormatTable FormatTable { get { return _formatTable; } } + internal ConcurrentBag Errors + { + get { return _errors; } + set { _errors = value; } } internal string PSSnapinName { get { return psSnapinName; } } internal bool FailToLoadFile; @@ -78,7 +79,7 @@ namespace System.Management.Automation.Runspaces internal const string ValidationException = "ValidationException"; private static string GetBaseFolder( - RunspaceConfiguration runspaceConfiguration, + RunspaceConfiguration runspaceConfiguration, Collection independentErrors) { string returnValue = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId); @@ -117,7 +118,7 @@ namespace System.Management.Automation.Runspaces HashSet fullFileNameSet = new HashSet(StringComparer.OrdinalIgnoreCase); int index = -1; - foreach (var configurationEntry in configurationEntryCollection) + foreach (var configurationEntry in configurationEntryCollection) { string fileName; string psSnapinName = configurationEntry.PSSnapIn == null ? runspaceConfiguration.ShellId : configurationEntry.PSSnapIn.Name; @@ -127,7 +128,7 @@ namespace System.Management.Automation.Runspaces { fileName = typeEntry.FileName; - if(fileName == null) + if (fileName == null) { returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, typeEntry.TypeData, typeEntry.IsRemove)); continue; @@ -138,7 +139,7 @@ namespace System.Management.Automation.Runspaces FormatConfigurationEntry formatEntry = (FormatConfigurationEntry)configurationEntry; fileName = formatEntry.FileName; - if(fileName == null) + if (fileName == null) { returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, formatEntry.FormatData)); continue; @@ -156,18 +157,18 @@ namespace System.Management.Automation.Runspaces } continue; } - + returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, fullFileName)); } return returnValue; } private static string GetAndCheckFullFileName( - string psSnapinName, - HashSet fullFileNameSet, - string baseFolder, - string baseFileName, - Collection independentErrors, + string psSnapinName, + HashSet fullFileNameSet, + string baseFolder, + string baseFileName, + Collection independentErrors, ref bool needToRemoveEntry, bool checkFileExists) { @@ -200,9 +201,9 @@ namespace System.Management.Automation.Runspaces } internal static void ThrowExceptionOnError( - string errorId, + string errorId, Collection independentErrors, - Collection PSSnapinFilesCollection, + Collection PSSnapinFilesCollection, RunspaceConfigurationCategory category) { Collection errors = new Collection(); @@ -252,8 +253,8 @@ namespace System.Management.Automation.Runspaces } internal static void ThrowExceptionOnError( - string errorId, - ConcurrentBag errors, + string errorId, + ConcurrentBag errors, RunspaceConfigurationCategory category) { if (errors.Count == 0) diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfiguration.cs b/src/System.Management.Automation/minishell/api/RunspaceConfiguration.cs index 8ebc0bfd7..85845f918 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfiguration.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfiguration.cs @@ -3,6 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; @@ -110,7 +111,7 @@ namespace System.Management.Automation.Runspaces #endif abstract class RunspaceConfiguration { -#region RunspaceConfiguration Factory + #region RunspaceConfiguration Factory #if V2 @@ -163,7 +164,7 @@ namespace System.Management.Automation.Runspaces // If this assembly can't be loaded, Assembly.Load will throw an exception. // Just let the exception bubble up. - + Assembly assembly = null; foreach (Assembly asm in ClrFacade.GetAssemblies()) { @@ -286,9 +287,9 @@ namespace System.Management.Automation.Runspaces return (RunspaceConfiguration)method.Invoke(null, null); } -#endregion RunspaceConfiguration Factory + #endregion RunspaceConfiguration Factory -#region Shell Id + #region Shell Id /// /// Gets the shell id for current runspace configuration. @@ -298,9 +299,9 @@ namespace System.Management.Automation.Runspaces get; } -#endregion + #endregion -#region PSSnapin Api's + #region PSSnapin Api's /// /// Add a PSSnapin to runspace configuration. @@ -345,9 +346,9 @@ namespace System.Management.Automation.Runspaces throw PSTraceSource.NewNotSupportedException(); } -#endregion + #endregion -#region Cmdlet, Provider, Relationship + #region Cmdlet, Provider, Relationship private RunspaceConfigurationEntryCollection _cmdlets; @@ -401,9 +402,9 @@ namespace System.Management.Automation.Runspaces } */ -#endregion + #endregion -#region Types and Formats + #region Types and Formats /// /// types.ps1xml information @@ -413,12 +414,12 @@ namespace System.Management.Automation.Runspaces { get { - if (typeTable == null) - typeTable = new TypeTable(); - return typeTable; + if (_typeTable == null) + _typeTable = new TypeTable(); + return _typeTable; } } - private TypeTable typeTable; + private TypeTable _typeTable; private RunspaceConfigurationEntryCollection _types; @@ -463,16 +464,16 @@ namespace System.Management.Automation.Runspaces return _formats; } } - private TypeInfoDataBaseManager formatDBManger = new TypeInfoDataBaseManager(); + private TypeInfoDataBaseManager _formatDBManger = new TypeInfoDataBaseManager(); internal TypeInfoDataBaseManager FormatDBManager { - get { return formatDBManger; } + get { return _formatDBManger; } } - -#endregion -#region Script Data + #endregion + + #region Script Data private RunspaceConfigurationEntryCollection _scripts; @@ -496,9 +497,9 @@ namespace System.Management.Automation.Runspaces } } -#endregion + #endregion -#region Profile configuration + #region Profile configuration private RunspaceConfigurationEntryCollection _initializationScripts; @@ -522,9 +523,9 @@ namespace System.Management.Automation.Runspaces } } -#endregion + #endregion -#region Assemblies + #region Assemblies private RunspaceConfigurationEntryCollection _assemblies; @@ -548,9 +549,9 @@ namespace System.Management.Automation.Runspaces } } -#endregion + #endregion -#region Security Manager + #region Security Manager private AuthorizationManager _authorizationManager = null; @@ -565,18 +566,18 @@ namespace System.Management.Automation.Runspaces { get { - if(_authorizationManager == null) + if (_authorizationManager == null) { _authorizationManager = new Microsoft.PowerShell.PSAuthorizationManager(this.ShellId); } - return _authorizationManager; + return _authorizationManager; } } -#endregion + #endregion -#region Configuration Update + #region Configuration Update private PSHost _host = null; internal void Bind(ExecutionContext executionContext) @@ -587,14 +588,14 @@ namespace System.Management.Automation.Runspaces this.Assemblies.OnUpdate += executionContext.UpdateAssemblyCache; - runspaceInitTracer.WriteLine("initializing assembly list"); + s_runspaceInitTracer.WriteLine("initializing assembly list"); try { this.Assemblies.Update(true); } catch (RuntimeException e) { - runspaceInitTracer.WriteLine("assembly list initialization failed"); + s_runspaceInitTracer.WriteLine("assembly list initialization failed"); MshLog.LogEngineHealthEvent( executionContext, MshLog.EVENT_ID_CONFIGURATION_FAILURE, @@ -610,14 +611,14 @@ namespace System.Management.Automation.Runspaces this.Cmdlets.OnUpdate += executionContext.CommandDiscovery.UpdateCmdletCache; // Force an update here so that cmdlet cache is updated in engine. - runspaceInitTracer.WriteLine("initializing cmdlet list"); + s_runspaceInitTracer.WriteLine("initializing cmdlet list"); try { this.Cmdlets.Update(true); } catch (PSNotSupportedException e) { - runspaceInitTracer.WriteLine("cmdlet list initialization failed"); + s_runspaceInitTracer.WriteLine("cmdlet list initialization failed"); MshLog.LogEngineHealthEvent( executionContext, MshLog.EVENT_ID_CONFIGURATION_FAILURE, @@ -631,16 +632,16 @@ namespace System.Management.Automation.Runspaces if (executionContext.EngineSessionState != null) { this.Providers.OnUpdate += executionContext.EngineSessionState.UpdateProviders; - + // Force an update here so that provider cache is updated in engine. - runspaceInitTracer.WriteLine("initializing provider list"); + s_runspaceInitTracer.WriteLine("initializing provider list"); try { this.Providers.Update(true); } catch (PSNotSupportedException e) { - runspaceInitTracer.WriteLine("provider list initialization failed"); + s_runspaceInitTracer.WriteLine("provider list initialization failed"); MshLog.LogEngineHealthEvent( executionContext, MshLog.EVENT_ID_CONFIGURATION_FAILURE, @@ -671,7 +672,7 @@ namespace System.Management.Automation.Runspaces } private bool _initialized = false; - Object _syncObject = new Object(); + private Object _syncObject = new Object(); internal void Initialize(ExecutionContext executionContext) { #pragma warning disable 56517 @@ -685,14 +686,14 @@ namespace System.Management.Automation.Runspaces this.Types.OnUpdate += this.UpdateTypes; this.Formats.OnUpdate += this.UpdateFormats; - runspaceInitTracer.WriteLine("initializing types information"); + s_runspaceInitTracer.WriteLine("initializing types information"); try { this.UpdateTypes(); } catch (RuntimeException e) { - runspaceInitTracer.WriteLine("type information initialization failed"); + s_runspaceInitTracer.WriteLine("type information initialization failed"); MshLog.LogEngineHealthEvent( executionContext, MshLog.EVENT_ID_CONFIGURATION_FAILURE, @@ -701,14 +702,14 @@ namespace System.Management.Automation.Runspaces executionContext.ReportEngineStartupError(e.Message); } - runspaceInitTracer.WriteLine("initializing format information"); + s_runspaceInitTracer.WriteLine("initializing format information"); try { this.UpdateFormats(true); } catch (RuntimeException e) { - runspaceInitTracer.WriteLine("format information initialization failed"); + s_runspaceInitTracer.WriteLine("format information initialization failed"); MshLog.LogEngineHealthEvent( executionContext, MshLog.EVENT_ID_CONFIGURATION_FAILURE, @@ -728,8 +729,8 @@ namespace System.Management.Automation.Runspaces Collection entryIndicesToRemove = new Collection(); Collection PSSnapinFiles = FormatAndTypeDataHelper.GetFormatAndTypesErrors( this, - this._host, - this.Types, + _host, + this.Types, independentErrors, entryIndicesToRemove); @@ -738,10 +739,10 @@ namespace System.Management.Automation.Runspaces RemoveNeedlessEntries(RunspaceConfigurationCategory.Types, entryIndicesToRemove); } - this.TypeTable.Update(PSSnapinFiles, this._authorizationManager, this._host); + this.TypeTable.Update(PSSnapinFiles, _authorizationManager, _host); FormatAndTypeDataHelper.ThrowExceptionOnError( - "ErrorsUpdatingTypes", - independentErrors, + "ErrorsUpdatingTypes", + independentErrors, PSSnapinFiles, RunspaceConfigurationCategory.Types); } @@ -757,8 +758,8 @@ namespace System.Management.Automation.Runspaces Collection entryIndicesToRemove = new Collection(); Collection PSSnapinFiles = FormatAndTypeDataHelper.GetFormatAndTypesErrors( this, - this._host, - this.Formats, + _host, + this.Formats, independentErrors, entryIndicesToRemove); @@ -767,10 +768,10 @@ namespace System.Management.Automation.Runspaces RemoveNeedlessEntries(RunspaceConfigurationCategory.Formats, entryIndicesToRemove); } - this.FormatDBManager.UpdateDataBase(PSSnapinFiles, this.AuthorizationManager, this._host, preValidated); + this.FormatDBManager.UpdateDataBase(PSSnapinFiles, this.AuthorizationManager, _host, preValidated); FormatAndTypeDataHelper.ThrowExceptionOnError( - "ErrorsUpdatingFormats", - independentErrors, + "ErrorsUpdatingFormats", + independentErrors, PSSnapinFiles, RunspaceConfigurationCategory.Formats); } @@ -795,11 +796,10 @@ namespace System.Management.Automation.Runspaces } } -#endregion + #endregion [TraceSource("RunspaceInit", "Initialization code for Runspace")] - static private PSTraceSource runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); - + static private PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); } /// @@ -844,7 +844,7 @@ namespace System.Management.Automation.Runspaces /// /// Formats /// - Formats, + Formats, } #if V2 diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs index 0de682d70..3a25c32f3 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationAttributeException.cs @@ -35,7 +35,7 @@ namespace System.Management.Automation.Runspaces /// /// Error detail for the exception /// Assembly on which runspace configuration attribute is defined or should be defined. - internal RunspaceConfigurationAttributeException (string error, string assemblyName) : base() + internal RunspaceConfigurationAttributeException(string error, string assemblyName) : base() { _error = error; _assemblyName = assemblyName; @@ -45,7 +45,7 @@ namespace System.Management.Automation.Runspaces /// /// Initiate an instance of RunspaceConfigurationAttributeException. /// - public RunspaceConfigurationAttributeException () : base() + public RunspaceConfigurationAttributeException() : base() { } @@ -74,7 +74,7 @@ namespace System.Management.Automation.Runspaces /// Error detail /// Assembly on which runspace configuration attribute is defined or should be defined. /// The inner exception of this exception - internal RunspaceConfigurationAttributeException (string error, string assemblyName, Exception innerException) : base (innerException.Message, innerException) + internal RunspaceConfigurationAttributeException(string error, string assemblyName, Exception innerException) : base(innerException.Message, innerException) { _error = error; _assemblyName = assemblyName; @@ -190,8 +190,8 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); - info.AddValue("Error", this._error); - info.AddValue("AssemblyName", this._assemblyName); + info.AddValue("Error", _error); + info.AddValue("AssemblyName", _assemblyName); } #endregion Serialization diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntry.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntry.cs index 0a1878c01..78a5e6b4a 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntry.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntry.cs @@ -4,6 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. #pragma warning disable 1634, 1691 #pragma warning disable 56506 + using System; using System.IO; using System.Collections; @@ -31,7 +32,7 @@ namespace System.Management.Automation.Runspaces #else public #endif - abstract class RunspaceConfigurationEntry + abstract class RunspaceConfigurationEntry { /// /// Initiate an instance of runspace configuration entry. @@ -159,10 +160,10 @@ namespace System.Management.Automation.Runspaces /// /// TypeData instance /// Specify the operation with the typedata - public TypeConfigurationEntry(TypeData typeData, bool isRemove) + public TypeConfigurationEntry(TypeData typeData, bool isRemove) : base("*") { - if(typeData == null) + if (typeData == null) { throw PSTraceSource.NewArgumentException("typeData"); } @@ -400,10 +401,8 @@ namespace System.Management.Automation.Runspaces { _helpFileName = helpFileName; } + } - - } - private Type _type; /// diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntryCollection.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntryCollection.cs index 2960a0d5b..be91c207d 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntryCollection.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationEntryCollection.cs @@ -232,7 +232,7 @@ namespace System.Management.Automation.Runspaces lock (_syncObject) { - int i = 0; + int i = 0; foreach (T t in items) { RecordAdd(t); @@ -422,7 +422,7 @@ namespace System.Management.Automation.Runspaces } //object to use for locking - object _syncObject = new object(); + private object _syncObject = new object(); /// /// OnUpdate handler should lock the object itself. diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationHelper.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationHelper.cs index 28fce4cf0..ca68286de 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationHelper.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationHelper.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation.Runspaces { /// diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeAttribute.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeAttribute.cs index 3d736bfe0..34cb300e0 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeAttribute.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeAttribute.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.IO; using System.Collections; @@ -28,7 +29,7 @@ namespace System.Management.Automation.Runspaces #else public #endif - sealed class RunspaceConfigurationTypeAttribute: Attribute + sealed class RunspaceConfigurationTypeAttribute : Attribute { /// /// Initiate an instance of RunspaceConfigurationTypeAttribute. diff --git a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs index b0173a0cb..f65b92b34 100644 --- a/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs +++ b/src/System.Management.Automation/minishell/api/RunspaceConfigurationTypeException.cs @@ -38,7 +38,7 @@ namespace System.Management.Automation.Runspaces /// /// Name of the assembly where is defined. /// Runspace configuration type - internal RunspaceConfigurationTypeException (string assemblyName, string typeName) : base() + internal RunspaceConfigurationTypeException(string assemblyName, string typeName) : base() { _assemblyName = assemblyName; _typeName = typeName; @@ -48,7 +48,7 @@ namespace System.Management.Automation.Runspaces /// /// Initiate an instance for RunspaceConfigurationTypeException /// - public RunspaceConfigurationTypeException () : base() + public RunspaceConfigurationTypeException() : base() { } @@ -58,7 +58,7 @@ namespace System.Management.Automation.Runspaces /// Name of the assembly where is defined. /// Runspace configuration type defined in /// Inner exception of this exception - internal RunspaceConfigurationTypeException(string assemblyName, string typeName, Exception innerException) : base (innerException.Message, innerException) + internal RunspaceConfigurationTypeException(string assemblyName, string typeName, Exception innerException) : base(innerException.Message, innerException) { _assemblyName = assemblyName; _typeName = typeName; @@ -182,8 +182,8 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); - info.AddValue("TypeName", this._typeName); - info.AddValue("AssemblyName", this._assemblyName); + info.AddValue("TypeName", _typeName); + info.AddValue("AssemblyName", _assemblyName); } #endregion Serialization diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index d99c9aa1a..6b79f7246 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -14,7 +14,6 @@ using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { - /// /// This provider is the data accessor for shell aliases. It uses /// the SessionStateProviderBase as the base class to produce a view on @@ -32,15 +31,15 @@ namespace Microsoft.PowerShell.Commands /// Gets the name of the provider /// public const string ProviderName = "Alias"; - + #region Constructor /// /// The constructor for the provider that exposes variables to the user /// as drives. /// - public AliasProvider () - { + public AliasProvider() + { } // constructor #endregion Constructor @@ -55,11 +54,11 @@ namespace Microsoft.PowerShell.Commands /// An array of a single PSDriveInfo object representing the alias drive. /// /// - protected override Collection InitializeDefaultDrives () + protected override Collection InitializeDefaultDrives() { string description = SessionStateStrings.AliasDriveDescription; - PSDriveInfo aliasDrive = + PSDriveInfo aliasDrive = new PSDriveInfo( DriveNames.AliasDrive, ProviderInfo, @@ -148,7 +147,7 @@ namespace Microsoft.PowerShell.Commands "The caller should verify this parameter"); AliasInfo value = SessionState.Internal.GetAlias(name, Context.Origin); - + return value; } // GetSessionStateItem @@ -287,7 +286,7 @@ namespace Microsoft.PowerShell.Commands /// The name of the alias to remove from session state. /// /// - internal override void RemoveSessionStateItem (string name) + internal override void RemoveSessionStateItem(string name) { Dbg.Diagnostics.Assert( !String.IsNullOrEmpty(name), @@ -305,7 +304,7 @@ namespace Microsoft.PowerShell.Commands /// session state. /// /// - internal override IDictionary GetSessionStateTable () + internal override IDictionary GetSessionStateTable() { return (IDictionary)SessionState.Internal.GetAliasTable(); } // GetSessionStateTable @@ -364,14 +363,14 @@ namespace Microsoft.PowerShell.Commands [Parameter] public ScopedItemOptions Options { - get { return options; } + get { return _options; } set { - optionsSet = true; - options = value; + _optionsSet = true; + _options = value; } } - private ScopedItemOptions options; + private ScopedItemOptions _options; /// @@ -380,9 +379,9 @@ namespace Microsoft.PowerShell.Commands /// internal bool OptionsSet { - get { return optionsSet; } + get { return _optionsSet; } } - private bool optionsSet = false; + private bool _optionsSet = false; } } diff --git a/src/System.Management.Automation/namespaces/Buffer.cs b/src/System.Management.Automation/namespaces/Buffer.cs index 0beb14462..ad09610cb 100644 --- a/src/System.Management.Automation/namespaces/Buffer.cs +++ b/src/System.Management.Automation/namespaces/Buffer.cs @@ -1,11 +1,6 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // // NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\System\buffer.cs. // Namespace: System // @@ -13,7 +8,6 @@ using BCLDebug = System.Diagnostics.Debug; namespace Microsoft.PowerShell.Commands.Internal { - //Only contains static methods. Does not require serialization #if CORECLR @@ -26,7 +20,6 @@ namespace Microsoft.PowerShell.Commands.Internal [System.Runtime.InteropServices.ComVisible(true)] internal static class Buffer { - // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit @@ -87,7 +80,6 @@ namespace Microsoft.PowerShell.Commands.Internal count -= 4; pByte += 4; - } // Catch any bytes that might be left at the tail of the buffer @@ -132,10 +124,11 @@ namespace Microsoft.PowerShell.Commands.Internal BCLDebug.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. - if (len==0) + if (len == 0) return; - fixed(byte* pSrc = src) { - memcpyimpl(pSrc+srcIndex, pDest+destIndex, len); + fixed (byte* pSrc = src) + { + memcpyimpl(pSrc + srcIndex, pDest + destIndex, len); } } @@ -143,13 +136,13 @@ namespace Microsoft.PowerShell.Commands.Internal internal unsafe static void memcpy(char* pSrc, int srcIndex, char* pDest, int destIndex, int len) { BCLDebug.Assert((srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); - + // No boundary check for buffer overruns - dangerous - if (len==0) + if (len == 0) return; - memcpyimpl((byte*)(char*)(pSrc+srcIndex), (byte*)(char*)(pDest+destIndex), len*2); + memcpyimpl((byte*)(char*)(pSrc + srcIndex), (byte*)(char*)(pDest + destIndex), len * 2); } - + // Note - using a long instead of an int for the length parameter // slows this method down by ~18%. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] @@ -255,9 +248,9 @@ namespace Microsoft.PowerShell.Commands.Internal // (You read that correctly.) // This is 3x faster than a simple while loop copying byte by byte, // for large copies. - if (len >= 16) + if (len >= 16) { - do + do { #if AMD64 ((long*)dest)[0] = ((long*)src)[0]; @@ -272,9 +265,9 @@ namespace Microsoft.PowerShell.Commands.Internal src += 16; } while ((len -= 16) >= 16); } - if(len > 0) // protection against negative len and optimization for len==16*N + if (len > 0) // protection against negative len and optimization for len==16*N { - if ((len & 8) != 0) + if ((len & 8) != 0) { #if AMD64 ((long*)dest)[0] = ((long*)src)[0]; @@ -284,24 +277,24 @@ namespace Microsoft.PowerShell.Commands.Internal #endif dest += 8; src += 8; - } - if ((len & 4) != 0) - { + } + if ((len & 4) != 0) + { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; - } - if ((len & 2) != 0) - { + } + if ((len & 2) != 0) + { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; - } - if ((len & 1) != 0) + } + if ((len & 1) != 0) *dest++ = *src++; } #endif // IA64 } - } + } } diff --git a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs index 2554c8e13..402fba457 100644 --- a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs @@ -309,8 +309,8 @@ namespace System.Management.Automation.Provider Context = context; return RenameItemDynamicParameters(path, newName); } // RenameItemDynamicParameters - - + + /// /// Internal wrapper for the New protected method. It is called instead /// of the protected method that is overridden by derived classes so that the @@ -389,7 +389,7 @@ namespace System.Management.Automation.Provider Context = context; return NewItemDynamicParameters(path, type, newItemValue); } // NewItemDynamicParameters - + /// /// Internal wrapper for the Remove protected method. It is called instead /// of the protected method that is overridden by derived classes so that the @@ -455,7 +455,7 @@ namespace System.Management.Automation.Provider Context = context; return RemoveItemDynamicParameters(path, recurse); } // RemoveItemDynamicParameters - + /// /// Internal wrapper for the HasChildItems protected method. It is called instead @@ -568,7 +568,7 @@ namespace System.Management.Automation.Provider Context = context; return CopyItemDynamicParameters(path, destination, recurse); } // CopyItemDynamicParameters - + #endregion Internal members #region Protected methods @@ -999,8 +999,8 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// protected virtual object NewItemDynamicParameters( - string path, - string itemTypeName, + string path, + string itemTypeName, object newItemValue) { using (PSTransactionManager.GetEngineProtectionScope()) @@ -1209,8 +1209,8 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// protected virtual object CopyItemDynamicParameters( - string path, - string destination, + string path, + string destination, bool recurse) { using (PSTransactionManager.GetEngineProtectionScope()) @@ -1220,10 +1220,8 @@ namespace System.Management.Automation.Provider } // CopyItemDynamicParameters #endregion Protected members - } // ContainerCmdletProvider #endregion ContainerCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index ed09a1662..93038ee32 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Collections.Generic; @@ -10,7 +11,7 @@ using System.Globalization; using System.Management.Automation; using System.Management.Automation.Host; using System.Text; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -37,10 +38,10 @@ namespace System.Management.Automation /// using "CmdletProviderContext" as the category. /// [Dbg.TraceSourceAttribute( - "CmdletProviderContext", + "CmdletProviderContext", "The context under which a core command is being run.")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("CmdletProviderContext", + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("CmdletProviderContext", "The context under which a core command is being run."); #endregion Trace object @@ -64,18 +65,17 @@ namespace System.Management.Automation { if (executionContext == null) { - throw PSTraceSource.NewArgumentNullException ("executionContext"); + throw PSTraceSource.NewArgumentNullException("executionContext"); } - this.executionContext = executionContext; - this._origin = CommandOrigin.Internal; - this.drive = executionContext.EngineSessionState.CurrentDrive; + _executionContext = executionContext; + _origin = CommandOrigin.Internal; + _drive = executionContext.EngineSessionState.CurrentDrive; if ((executionContext.CurrentCommandProcessor != null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet)) { - this.command = (Cmdlet) executionContext.CurrentCommandProcessor.Command; + _command = (Cmdlet)executionContext.CurrentCommandProcessor.Command; } - } // CmdletProviderContext constructor /// @@ -102,9 +102,8 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("executionContext"); } - this.executionContext = executionContext; - this._origin = origin; - + _executionContext = executionContext; + _origin = origin; } // CmdletProviderContext constructor /// @@ -143,15 +142,15 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("command"); } - this.command = command; - this._origin = command.CommandOrigin; - + _command = command; + _origin = command.CommandOrigin; + if (credentials != null) { - this.credentials = credentials; + _credentials = credentials; } - this.drive = drive; + _drive = drive; if (command.Host == null) { @@ -162,12 +161,12 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentException("command.Context"); } - this.executionContext = command.Context; + _executionContext = command.Context; // Stream will default to true because command methods will be used. - this.streamObjects = true; - this.streamErrors = true; + _streamObjects = true; + _streamErrors = true; } // CmdletProviderContext constructor /// @@ -201,12 +200,12 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("command"); } - this.command = command; - this._origin = command.CommandOrigin; - + _command = command; + _origin = command.CommandOrigin; + if (credentials != null) { - this.credentials = credentials; + _credentials = credentials; } if (command.Host == null) @@ -216,14 +215,14 @@ namespace System.Management.Automation if (command.Context == null) { - throw PSTraceSource.NewArgumentException ("command.Context"); + throw PSTraceSource.NewArgumentException("command.Context"); } - this.executionContext = command.Context; + _executionContext = command.Context; // Stream will default to true because command methods will be used. - this.streamObjects = true; - this.streamErrors = true; + _streamObjects = true; + _streamErrors = true; } // CmdletProviderContext constructor /// @@ -252,19 +251,19 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("command"); } - this.command = command; - this._origin = command.CommandOrigin; + _command = command; + _origin = command.CommandOrigin; if (command.Context == null) { - throw PSTraceSource.NewArgumentException ("command.Context"); + throw PSTraceSource.NewArgumentException("command.Context"); } - this.executionContext = command.Context; + _executionContext = command.Context; // Stream will default to true because command methods will be used. - this.streamObjects = true; - this.streamErrors = true; + _streamObjects = true; + _streamErrors = true; } // CmdletProviderContext constructor /// @@ -289,32 +288,32 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("contextToCopyFrom"); } - this.executionContext = contextToCopyFrom.ExecutionContext; + _executionContext = contextToCopyFrom.ExecutionContext; - this.command = contextToCopyFrom.command; + _command = contextToCopyFrom._command; if (contextToCopyFrom.Credential != null) { - this.credentials = contextToCopyFrom.Credential; + _credentials = contextToCopyFrom.Credential; } - this.drive = contextToCopyFrom.Drive; - this.force = contextToCopyFrom.Force; + _drive = contextToCopyFrom.Drive; + _force = contextToCopyFrom.Force; this.CopyFilters(contextToCopyFrom); - this.suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion; - this.dynamicParameters = contextToCopyFrom.DynamicParameters; - this._origin = contextToCopyFrom._origin; + _suppressWildcardExpansion = contextToCopyFrom.SuppressWildcardExpansion; + _dynamicParameters = contextToCopyFrom.DynamicParameters; + _origin = contextToCopyFrom._origin; // Copy the stopping state incase the source context // has already been signaled for stopping - this.stopping = contextToCopyFrom.Stopping; + _stopping = contextToCopyFrom.Stopping; // add this context to the stop referral on the copied // context contextToCopyFrom.StopReferrals.Add(this); - this.copiedContext = contextToCopyFrom; + _copiedContext = contextToCopyFrom; } // CmdletProviderContext constructor #endregion Constructor @@ -325,29 +324,29 @@ namespace System.Management.Automation /// If the constructor that takes a context to copy is /// called, this will be set to the context being copied. /// - private CmdletProviderContext copiedContext; + private CmdletProviderContext _copiedContext; /// /// The execution context of the engine. /// - private ExecutionContext executionContext; + private ExecutionContext _executionContext; /// /// The credentials under which the operation should run. /// - private PSCredential credentials = PSCredential.Empty; + private PSCredential _credentials = PSCredential.Empty; /// /// The drive under which this context is operating. /// - private PSDriveInfo drive; + private PSDriveInfo _drive; /// /// The force parameter gives guidance to providers on how vigorously they /// should try to perform an operation. /// /// - private bool force; + private bool _force; /// /// The provider specific filter used to determine which items to act upon. @@ -358,7 +357,7 @@ namespace System.Management.Automation /// A glob string used to include items upon which to act. /// private Collection _include; - + /// /// A glob string used to exclude items upon which to act. /// @@ -367,7 +366,7 @@ namespace System.Management.Automation /// /// A flag that determines if the provider should glob the paths or not /// - private bool suppressWildcardExpansion; + private bool _suppressWildcardExpansion; /// @@ -375,7 +374,7 @@ namespace System.Management.Automation /// made visible to anyone and should only be set through the /// constructor. /// - private Cmdlet command; + private Cmdlet _command; /// /// This makes the origin of the provider request visible to the internals @@ -387,7 +386,7 @@ namespace System.Management.Automation return _origin; } } - CommandOrigin _origin = CommandOrigin.Internal; + private CommandOrigin _origin = CommandOrigin.Internal; /// @@ -399,7 +398,7 @@ namespace System.Management.Automation /// If it is false, the objects will be accumulated until the /// GetObjects method is called. /// - private bool streamObjects; + private bool _streamObjects; /// /// This defines the default behavior for the WriteError method. @@ -409,29 +408,29 @@ namespace System.Management.Automation /// If it is false, the objects will be accumulated until the /// GetErrorObjects method is called. /// - private bool streamErrors; + private bool _streamErrors; /// /// A collection in which objects that are written using the WriteObject(s) - /// methods are accumulated if is false. + /// methods are accumulated if is false. /// - private Collection accumulatedObjects = new Collection(); + private Collection _accumulatedObjects = new Collection(); /// /// A collection in which objects that are written using the WriteError - /// method are accumulated if is false. + /// method are accumulated if is false. /// - private Collection accumulatedErrorObjects = new Collection(); + private Collection _accumulatedErrorObjects = new Collection(); /// /// The instance of the provider that is currently executing in this context. /// - private System.Management.Automation.Provider.CmdletProvider providerInstance; + private System.Management.Automation.Provider.CmdletProvider _providerInstance; /// /// The dynamic parameters for the provider that is currently executing in this context. /// - private object dynamicParameters; + private object _dynamicParameters; #endregion private properties @@ -445,7 +444,7 @@ namespace System.Management.Automation { get { - return executionContext; + return _executionContext; } } // ExecutionContext @@ -458,14 +457,13 @@ namespace System.Management.Automation { get { - return providerInstance; + return _providerInstance; } // get set { - providerInstance = value; + _providerInstance = value; } // set - } // ProviderInstance /// @@ -490,9 +488,9 @@ namespace System.Management.Automation internal void RemoveStopReferral() { - if (copiedContext != null) + if (_copiedContext != null) { - copiedContext.StopReferrals.Remove(this); + _copiedContext.StopReferrals.Remove(this); } } #endregion Internal properties @@ -507,12 +505,12 @@ namespace System.Management.Automation { get { - return dynamicParameters; + return _dynamicParameters; } // get set { - dynamicParameters = value; + _dynamicParameters = value; } // set } // DynamicParameters @@ -523,9 +521,9 @@ namespace System.Management.Automation { get { - if (command != null) + if (_command != null) { - return command.MyInvocation; + return _command.MyInvocation; } else { @@ -543,12 +541,12 @@ namespace System.Management.Automation { get { - return streamObjects; + return _streamObjects; } // get set { - streamObjects = value; + _streamObjects = value; } // set } // PassThru @@ -564,12 +562,12 @@ namespace System.Management.Automation { get { - return drive; + return _drive; } // get set { - this.drive = value; + _drive = value; } // set } // Drive @@ -580,15 +578,15 @@ namespace System.Management.Automation { get { - PSCredential result = credentials; + PSCredential result = _credentials; // If the username wasn't specified, use the drive credentials - if (credentials == null && drive != null) + if (_credentials == null && _drive != null) { - result = drive.Credential; + result = _drive.Credential; } - + return result; } } // Credential @@ -602,11 +600,11 @@ namespace System.Management.Automation { get { - if((this.command != null) && (this.command.CommandRuntime != null)) + if ((_command != null) && (_command.CommandRuntime != null)) { - MshCommandRuntime mshRuntime = this.command.CommandRuntime as MshCommandRuntime; + MshCommandRuntime mshRuntime = _command.CommandRuntime as MshCommandRuntime; - if(mshRuntime != null) + if (mshRuntime != null) { return mshRuntime.UseTransaction; } @@ -621,9 +619,9 @@ namespace System.Management.Automation /// public bool TransactionAvailable() { - if(this.command != null) + if (_command != null) { - return this.command.TransactionAvailable(); + return _command.TransactionAvailable(); } return false; @@ -637,9 +635,9 @@ namespace System.Management.Automation { get { - if(this.command != null) + if (_command != null) { - return this.command.CurrentPSTransaction; + return _command.CurrentPSTransaction; } return null; @@ -656,12 +654,12 @@ namespace System.Management.Automation { get { - return force; + return _force; } // get set { - force = value; + _force = value; } // set } // Force @@ -694,7 +692,6 @@ namespace System.Management.Automation { return _include; } // get - } // Include /// @@ -708,7 +705,6 @@ namespace System.Management.Automation { return _exclude; } // get - } // Exclude /// @@ -722,12 +718,12 @@ namespace System.Management.Automation { get { - return (bool) suppressWildcardExpansion; + return (bool)_suppressWildcardExpansion; } // get internal set { - suppressWildcardExpansion = value; + _suppressWildcardExpansion = value; } // set } // SuppressWildcardExpansion @@ -750,9 +746,9 @@ namespace System.Management.Automation string target) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldProcess(target); + result = _command.ShouldProcess(target); } return result; @@ -773,13 +769,13 @@ namespace System.Management.Automation /// Also, this occurs if the pipeline was already stopped. /// internal bool ShouldProcess( - string target, + string target, string action) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldProcess(target, action); + result = _command.ShouldProcess(target, action); } return result; @@ -817,9 +813,9 @@ namespace System.Management.Automation string caption) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldProcess( + result = _command.ShouldProcess( verboseDescription, verboseWarning, caption); @@ -867,9 +863,9 @@ namespace System.Management.Automation out ShouldProcessReason shouldProcessReason) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldProcess( + result = _command.ShouldProcess( verboseDescription, verboseWarning, caption, @@ -906,9 +902,9 @@ namespace System.Management.Automation string caption) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldContinue(query, caption); + result = _command.ShouldContinue(query, caption); } return result; @@ -947,9 +943,9 @@ namespace System.Management.Automation ref bool noToAll) { bool result = true; - if (command != null) + if (_command != null) { - result = command.ShouldContinue( + result = _command.ShouldContinue( query, caption, ref yesToAll, ref noToAll); } else @@ -971,9 +967,9 @@ namespace System.Management.Automation /// internal void WriteVerbose(string text) { - if (command != null) + if (_command != null) { - command.WriteVerbose(text); + _command.WriteVerbose(text); } } // WriteVerbose @@ -987,17 +983,17 @@ namespace System.Management.Automation /// internal void WriteWarning(string text) { - if (command != null) + if (_command != null) { - command.WriteWarning(text); + _command.WriteWarning(text); } } // WriteWarning internal void WriteProgress(ProgressRecord record) { - if (command != null) + if (_command != null) { - command.WriteProgress(record); + _command.WriteProgress(record); } } // WriteProgress @@ -1011,25 +1007,25 @@ namespace System.Management.Automation /// internal void WriteDebug(string text) { - if (command != null) + if (_command != null) { - command.WriteDebug(text); + _command.WriteDebug(text); } } // WriteDebug internal void WriteInformation(InformationRecord record) { - if (command != null) + if (_command != null) { - command.WriteInformation(record); + _command.WriteInformation(record); } } // WriteInformation internal void WriteInformation(Object messageData, string[] tags) { - if (command != null) + if (_command != null) { - command.WriteInformation(messageData, tags); + _command.WriteInformation(messageData, tags); } } // WriteInformation @@ -1078,8 +1074,8 @@ namespace System.Management.Automation { // Get the contents as an array - Collection results = accumulatedObjects; - accumulatedObjects = new Collection(); + Collection results = _accumulatedObjects; + _accumulatedObjects = new Collection(); // Return the array @@ -1100,8 +1096,8 @@ namespace System.Management.Automation { // Get the contents as an array - Collection results = accumulatedErrorObjects; - accumulatedErrorObjects = new Collection (); + Collection results = _accumulatedErrorObjects; + _accumulatedErrorObjects = new Collection(); // Return the array @@ -1119,7 +1115,7 @@ namespace System.Management.Automation /// internal void ThrowFirstErrorOrDoNothing() { - ThrowFirstErrorOrDoNothing (true); + ThrowFirstErrorOrDoNothing(true); } /// @@ -1162,7 +1158,7 @@ namespace System.Management.Automation } ProviderInvocationException e = - new ProviderInvocationException ( + new ProviderInvocationException( providerInfo, errors[0]); @@ -1181,9 +1177,9 @@ namespace System.Management.Automation throw errors[0].Exception; } } - } + } } - + /// /// Writes all the accumulated errors to the specified context using WriteError /// @@ -1207,7 +1203,7 @@ namespace System.Management.Automation { foreach (ErrorRecord errorRecord in GetAccumulatedErrorObjects()) { - errorContext.WriteError (errorRecord); + errorContext.WriteError(errorRecord); } } } @@ -1253,16 +1249,16 @@ namespace System.Management.Automation throw stopPipeline; } - if (streamObjects) + if (_streamObjects) { - if (command != null) + if (_command != null) { - tracer.WriteLine("Writing to command pipeline"); + s_tracer.WriteLine("Writing to command pipeline"); // Since there was no writeObject handler use // the command WriteObject method. - command.WriteObject(obj); + _command.WriteObject(obj); } else { @@ -1277,7 +1273,7 @@ namespace System.Management.Automation } else { - tracer.WriteLine("Writing to accumulated objects"); + s_tracer.WriteLine("Writing to accumulated objects"); // Convert the object to a PSObject if it's not already // one. @@ -1286,7 +1282,7 @@ namespace System.Management.Automation // Since we are not streaming, just add the object to the accumulatedObjects - accumulatedObjects.Add(newObj); + _accumulatedObjects.Add(newObj); } } // WriteObject @@ -1322,14 +1318,14 @@ namespace System.Management.Automation throw stopPipeline; } - - if (streamErrors) - { - if (command != null) - { - tracer.WriteLine("Writing error package to command error pipe"); - command.WriteError(errorRecord); + if (_streamErrors) + { + if (_command != null) + { + s_tracer.WriteLine("Writing error package to command error pipe"); + + _command.WriteError(errorRecord); } else { @@ -1342,9 +1338,9 @@ namespace System.Management.Automation else { // Since we are not streaming, just add the object to the accumulatedErrorObjects - accumulatedErrorObjects.Add(errorRecord); + _accumulatedErrorObjects.Add(errorRecord); - if ( null != errorRecord.ErrorDetails + if (null != errorRecord.ErrorDetails && null != errorRecord.ErrorDetails.TextLookupError) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; @@ -1369,8 +1365,7 @@ namespace System.Management.Automation /// internal bool HasErrors() { - return accumulatedErrorObjects != null && accumulatedErrorObjects.Count > 0; - + return _accumulatedErrorObjects != null && _accumulatedErrorObjects.Count > 0; } // HasErrors /// @@ -1381,16 +1376,15 @@ namespace System.Management.Automation /// internal void StopProcessing() { - stopping = true; + _stopping = true; - if (providerInstance != null) + if (_providerInstance != null) { - // We don't need to catch any of the exceptions here because // we are terminating the pipeline and any exception will // be caught by the engine. - providerInstance.StopProcessing(); + _providerInstance.StopProcessing(); } // Call the stop referrals if any @@ -1405,10 +1399,10 @@ namespace System.Management.Automation { get { - return stopping; + return _stopping; } } - private bool stopping; + private bool _stopping; /// /// The list of contexts to which the StopProcessing calls @@ -1417,9 +1411,9 @@ namespace System.Management.Automation /// internal Collection StopReferrals { - get { return stopReferrals; } + get { return _stopReferrals; } } - private Collection stopReferrals = + private Collection _stopReferrals = new Collection(); internal bool HasIncludeOrExclude @@ -1432,9 +1426,7 @@ namespace System.Management.Automation } #endregion Public methods - } // CmdletProviderContext - } - + diff --git a/src/System.Management.Automation/namespaces/DriveProviderBase.cs b/src/System.Management.Automation/namespaces/DriveProviderBase.cs index e489c08bb..88dcb1cee 100644 --- a/src/System.Management.Automation/namespaces/DriveProviderBase.cs +++ b/src/System.Management.Automation/namespaces/DriveProviderBase.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.ObjectModel; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Management.Automation.Internal; namespace System.Management.Automation.Provider @@ -260,7 +260,6 @@ namespace System.Management.Automation.Provider } // InitializeDefaultDrives #endregion Public methods - } // DriveCmdletProvider #endregion DriveCmdletProvider diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index 7ad67c3b3..9e6c3d872 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -39,8 +39,8 @@ namespace Microsoft.PowerShell.Commands /// The constructor for the provider that exposes environment variables to the user /// as drives. /// - public EnvironmentProvider () - { + public EnvironmentProvider() + { } // constructor #endregion Constructor @@ -55,11 +55,11 @@ namespace Microsoft.PowerShell.Commands /// An array of a single PSDriveInfo object representing the alias drive. /// /// - protected override Collection InitializeDefaultDrives () + protected override Collection InitializeDefaultDrives() { string description = SessionStateStrings.EnvironmentDriveDescription; - PSDriveInfo envDrive = + PSDriveInfo envDrive = new PSDriveInfo( DriveNames.EnvironmentDrive, ProviderInfo, @@ -170,7 +170,7 @@ namespace Microsoft.PowerShell.Commands /// The name of the environment variable to remove from session state. /// /// - internal override void RemoveSessionStateItem (string name) + internal override void RemoveSessionStateItem(string name) { Dbg.Diagnostics.Assert( !String.IsNullOrEmpty(name), @@ -188,7 +188,7 @@ namespace Microsoft.PowerShell.Commands /// session state. /// /// - internal override IDictionary GetSessionStateTable () + internal override IDictionary GetSessionStateTable() { // Environment variables are case-sensitive on Unix and // case-insensitive on Windows @@ -226,7 +226,7 @@ namespace Microsoft.PowerShell.Commands /// The value of the item. /// /// - internal override object GetValueOfItem (object item) + internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( item != null, @@ -242,7 +242,6 @@ namespace Microsoft.PowerShell.Commands } // GetValueOfItem #endregion protected members - } // EnvironmentProvider } diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 8539cb77e..d2192c30a 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -13,7 +13,7 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Provider; using System.Threading.Tasks; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { @@ -37,41 +37,41 @@ namespace Microsoft.PowerShell.Commands /// using "FileSystemContentStream" as the category. /// [Dbg.TraceSourceAttribute( - "FileSystemContentStream", + "FileSystemContentStream", "The provider content reader and writer for the file system")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("FileSystemContentStream", + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("FileSystemContentStream", "The provider content reader and writer for the file system"); #endregion tracer - private string path; - private string streamName; - private FileMode mode; - private FileAccess access; - private FileShare share; - private Encoding encoding; - private CmdletProvider provider; + private string _path; + private string _streamName; + private FileMode _mode; + private FileAccess _access; + private FileShare _share; + private Encoding _encoding; + private CmdletProvider _provider; - private FileStream stream; - private StreamReader reader; - private StreamWriter writer; - private bool usingByteEncoding; - private string delimiter = "\n"; - private bool usingDelimiter; - private bool waitForChanges; - private bool isRawStream; - private long fileOffset; + private FileStream _stream; + private StreamReader _reader; + private StreamWriter _writer; + private bool _usingByteEncoding; + private string _delimiter = "\n"; + private bool _usingDelimiter; + private bool _waitForChanges; + private bool _isRawStream; + private long _fileOffset; - private FileAttributes oldAttributes; - private bool haveOldAttributes; + private FileAttributes _oldAttributes; + private bool _haveOldAttributes; // The reader to read file content backward private FileStreamBackReader _backReader; private bool _alreadyDetectEncoding = false; // False to add a newline to the end of the output string, true if not. - private bool suppressNewline = false; + private bool _suppressNewline = false; /// /// Constructor for the content stream @@ -117,7 +117,7 @@ namespace Microsoft.PowerShell.Commands public FileSystemContentReaderWriter( string path, FileMode mode, FileAccess access, FileShare share, Encoding encoding, bool usingByteEncoding, - bool waitForChanges, CmdletProvider provider, bool isRawStream) : + bool waitForChanges, CmdletProvider provider, bool isRawStream) : this(path, null, mode, access, share, encoding, usingByteEncoding, waitForChanges, provider, isRawStream) { } @@ -178,23 +178,23 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentNullException("path"); } - if (tracer.IsEnabled) + if (s_tracer.IsEnabled) { - tracer.WriteLine("path = {0}", path); - tracer.WriteLine("mode = {0}", mode); - tracer.WriteLine("access = {0}", access); + s_tracer.WriteLine("path = {0}", path); + s_tracer.WriteLine("mode = {0}", mode); + s_tracer.WriteLine("access = {0}", access); } - this.path = path; - this.streamName = streamName; - this.mode = mode; - this.access = access; - this.share = share; - this.encoding = encoding; - this.usingByteEncoding = usingByteEncoding; - this.waitForChanges = waitForChanges; - this.provider = provider; - this.isRawStream = isRawStream; + _path = path; + _streamName = streamName; + _mode = mode; + _access = access; + _share = share; + _encoding = encoding; + _usingByteEncoding = usingByteEncoding; + _waitForChanges = waitForChanges; + _provider = provider; + _isRawStream = isRawStream; CreateStreams(path, streamName, mode, access, share, encoding); } @@ -255,7 +255,7 @@ namespace Microsoft.PowerShell.Commands bool isRawStream, bool suppressNewline) : this(path, streamName, mode, access, share, encoding, usingByteEncoding, waitForChanges, provider, isRawStream) { - this.suppressNewline = suppressNewline; + _suppressNewline = suppressNewline; } /// @@ -300,11 +300,11 @@ namespace Microsoft.PowerShell.Commands /// /// public FileSystemContentReaderWriter( - string path, - FileMode mode, + string path, + FileMode mode, FileAccess access, - FileShare share, - string delimiter, + FileShare share, + string delimiter, Encoding encoding, bool waitForChanges, CmdletProvider provider, @@ -371,8 +371,8 @@ namespace Microsoft.PowerShell.Commands bool isRawStream) : this(path, streamName, mode, access, share, encoding, false, waitForChanges, provider, isRawStream) { - this.delimiter = delimiter; - this.usingDelimiter = true; + _delimiter = delimiter; + _usingDelimiter = true; } @@ -393,26 +393,26 @@ namespace Microsoft.PowerShell.Commands /// public IList Read(long readCount) { - if (isRawStream && waitForChanges) + if (_isRawStream && _waitForChanges) { throw PSTraceSource.NewInvalidOperationException(FileSystemProviderStrings.RawAndWaitCannotCoexist); } - bool waitChanges = this.waitForChanges; + bool waitChanges = _waitForChanges; - tracer.WriteLine("blocks requested = {0}", readCount); + s_tracer.WriteLine("blocks requested = {0}", readCount); ArrayList blocks = new ArrayList(); bool readToEnd = (readCount <= 0); - if (_alreadyDetectEncoding && reader.BaseStream.Position == 0) + if (_alreadyDetectEncoding && _reader.BaseStream.Position == 0) { - Encoding curEncoding = reader.CurrentEncoding; + Encoding curEncoding = _reader.CurrentEncoding; // Close the stream, and reopen the stream to make the BOM correctly processed. // The reader has already detected encoding, so if we don't reopen the stream, the BOM (if there is any) // will be treated as a regular character. - stream.Dispose(); - CreateStreams(this.path, null, this.mode, this.access, this.share, curEncoding); + _stream.Dispose(); + CreateStreams(_path, null, _mode, _access, _share, curEncoding); _alreadyDetectEncoding = false; } @@ -420,19 +420,19 @@ namespace Microsoft.PowerShell.Commands { for (long currentBlock = 0; (currentBlock < readCount) || (readToEnd); ++currentBlock) { - if (waitChanges && provider.Stopping) + if (waitChanges && _provider.Stopping) waitChanges = false; - - if (usingByteEncoding) + + if (_usingByteEncoding) { if (!ReadByteEncoded(waitChanges, blocks, false)) break; } else { - if (usingDelimiter || isRawStream) + if (_usingDelimiter || _isRawStream) { - if (!ReadDelimited(waitChanges, blocks, false, delimiter)) + if (!ReadDelimited(waitChanges, blocks, false, _delimiter)) break; } else @@ -443,7 +443,7 @@ namespace Microsoft.PowerShell.Commands } } - tracer.WriteLine("blocks read = {0}", blocks.Count); + s_tracer.WriteLine("blocks read = {0}", blocks.Count); } catch (Exception e) { @@ -454,7 +454,7 @@ namespace Microsoft.PowerShell.Commands (e is ArgumentNullException)) { //Exception contains specific message about the error occured and so no need for errordetails. - this.provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, path)); + _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, _path)); return null; } else @@ -471,15 +471,15 @@ namespace Microsoft.PowerShell.Commands /// internal IList ReadWithoutWaitingChanges(long readCount) { - bool oldWaitChanges = this.waitForChanges; - this.waitForChanges = false; + bool oldWaitChanges = _waitForChanges; + _waitForChanges = false; try { return Read(readCount); } finally { - this.waitForChanges = oldWaitChanges; + _waitForChanges = oldWaitChanges; } } @@ -496,19 +496,19 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentException("backCount"); } - if (isRawStream && waitForChanges) + if (_isRawStream && _waitForChanges) { throw PSTraceSource.NewInvalidOperationException(FileSystemProviderStrings.RawAndWaitCannotCoexist); } - tracer.WriteLine("blocks seek backwards = {0}", backCount); + s_tracer.WriteLine("blocks seek backwards = {0}", backCount); ArrayList blocks = new ArrayList(); - if (reader != null) + if (_reader != null) { // Make the reader automatically detect the encoding Seek(0, SeekOrigin.Begin); - reader.Peek(); + _reader.Peek(); _alreadyDetectEncoding = true; } Seek(0, SeekOrigin.End); @@ -521,7 +521,7 @@ namespace Microsoft.PowerShell.Commands } StringBuilder builder = new StringBuilder(); - foreach (char character in delimiter) + foreach (char character in _delimiter) { builder.Insert(0, character); } @@ -531,7 +531,7 @@ namespace Microsoft.PowerShell.Commands try { - if (isRawStream) + if (_isRawStream) { // We always read to the end for the raw data. // If it's indicated as RawStream, we move the pointer to the @@ -542,14 +542,14 @@ namespace Microsoft.PowerShell.Commands for (; currentBlock < backCount; ++currentBlock) { - if (usingByteEncoding) + if (_usingByteEncoding) { if (!ReadByteEncoded(false, blocks, true)) break; } else { - if (usingDelimiter) + if (_usingDelimiter) { if (!ReadDelimited(false, blocks, true, actualDelimiter)) break; @@ -558,7 +558,7 @@ namespace Microsoft.PowerShell.Commands // ua123ua456ua -- -Tail 1 // If we read backward only once, we get 'ua', and cannot get to the rigth position // So we read one more time, get 'ua456ua', and then we can get the right position - lastDelimiterMatch = (string) blocks[0]; + lastDelimiterMatch = (string)blocks[0]; if (currentBlock == 0 && lastDelimiterMatch.Equals(actualDelimiter, StringComparison.Ordinal)) backCount++; } @@ -573,17 +573,17 @@ namespace Microsoft.PowerShell.Commands } // If usingByteEncoding is true, we don't create the reader and _backReader - if (!usingByteEncoding) + if (!_usingByteEncoding) { long curStreamPosition = _backReader.GetCurrentPosition(); - if (usingDelimiter) + if (_usingDelimiter) { if (currentBlock == backCount) { Dbg.Diagnostics.Assert(lastDelimiterMatch != null, "lastDelimiterMatch should not be null when currentBlock == backCount"); if (lastDelimiterMatch.EndsWith(actualDelimiter, StringComparison.Ordinal)) { - curStreamPosition += _backReader.GetByteCount(this.delimiter); + curStreamPosition += _backReader.GetByteCount(_delimiter); } } } @@ -591,7 +591,7 @@ namespace Microsoft.PowerShell.Commands Seek(curStreamPosition, SeekOrigin.Begin); } - tracer.WriteLine("blocks seek position = {0}", stream.Position); + s_tracer.WriteLine("blocks seek position = {0}", _stream.Position); } catch (Exception e) { @@ -602,7 +602,7 @@ namespace Microsoft.PowerShell.Commands (e is ArgumentNullException)) { //Exception contains specific message about the error occured and so no need for errordetails. - this.provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, path)); + _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, _path)); } else throw; @@ -612,7 +612,7 @@ namespace Microsoft.PowerShell.Commands private bool ReadByLine(bool waitChanges, ArrayList blocks, bool readBackward) { // Reading lines as strings - string line = readBackward ? _backReader.ReadLine() : reader.ReadLine(); + string line = readBackward ? _backReader.ReadLine() : _reader.ReadLine(); if (line == null) { @@ -621,16 +621,16 @@ namespace Microsoft.PowerShell.Commands // We only wait for changes when read forwards. So here we use reader, instead of 'localReader' do { - WaitForChanges(this.path, this.mode, this.access, this.share, reader.CurrentEncoding); - line = reader.ReadLine(); - } while ((line == null) && (!provider.Stopping)); + WaitForChanges(_path, _mode, _access, _share, _reader.CurrentEncoding); + line = _reader.ReadLine(); + } while ((line == null) && (!_provider.Stopping)); } } if (line != null) blocks.Add(line); - int peekResult = readBackward ? _backReader.Peek() : reader.Peek(); + int peekResult = readBackward ? _backReader.Peek() : _reader.Peek(); if (peekResult == -1) return false; else @@ -663,11 +663,11 @@ namespace Microsoft.PowerShell.Commands do { - if (isRawStream) + if (_isRawStream) { // when -Raw is used we want to anyway read the whole thing // so avoiding the while loop by reading the entire content. - string contentRead = reader.ReadToEnd(); + string contentRead = _reader.ReadToEnd(); numRead = contentRead.Length; content.Append(contentRead); } @@ -677,7 +677,7 @@ namespace Microsoft.PowerShell.Commands var readBuffer = new char[currentOffset]; numRead = readBackward ? _backReader.Read(readBuffer, 0, currentOffset) - : reader.Read(readBuffer, 0, currentOffset); + : _reader.Read(readBuffer, 0, currentOffset); // If we want to wait for changes, then we'll keep on attempting to read // until we fill the buffer. @@ -686,13 +686,13 @@ namespace Microsoft.PowerShell.Commands if (waitChanges) { // But stop reading if the provider is stopping - while ((numRead < currentOffset) && (!provider.Stopping)) + while ((numRead < currentOffset) && (!_provider.Stopping)) { // Get the change, and try to read more characters // We only wait for changes when read forwards, so here we don't need to check if 'readBackward' is // true or false, we only use 'reader'. The member 'reader' will be updated by WaitForChanges. - WaitForChanges(this.path, this.mode, this.access, this.share, reader.CurrentEncoding); - numRead += reader.Read(readBuffer, 0, (currentOffset - numRead)); + WaitForChanges(_path, _mode, _access, _share, _reader.CurrentEncoding); + numRead += _reader.Read(readBuffer, 0, (currentOffset - numRead)); } } } @@ -720,14 +720,14 @@ namespace Microsoft.PowerShell.Commands // Two cases where we want to keep reading: // 1. Raw stream and we haven't hit the end of file // 2. Delimiter not found and we haven't hit the end of file - } while ((isRawStream && (numRead != 0)) || + } while ((_isRawStream && (numRead != 0)) || ((content.ToString().IndexOf(actualDelimiter, StringComparison.Ordinal) < 0) && (numRead != 0))); // We've reached the end of file or end of line. if (content.Length > 0) blocks.Add(content.ToString()); - int peekResult = readBackward ? _backReader.Peek() : reader.Peek(); + int peekResult = readBackward ? _backReader.Peek() : _reader.Peek(); if (peekResult != -1) return true; else @@ -742,17 +742,17 @@ namespace Microsoft.PowerShell.Commands private bool ReadByteEncoded(bool waitChanges, ArrayList blocks, bool readBack) { - if (isRawStream) + if (_isRawStream) { // if RawSteam, read all bytes and return. When RawStream is used, we dont // support -first, -last - byte[] bytes = new byte[stream.Length]; - int numBytesToRead = (int)stream.Length; + byte[] bytes = new byte[_stream.Length]; + int numBytesToRead = (int)_stream.Length; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. - int n = stream.Read(bytes, numBytesRead, numBytesToRead); + int n = _stream.Read(bytes, numBytesRead, numBytesToRead); // Break when the end of the file is reached. if (n == 0) @@ -775,19 +775,19 @@ namespace Microsoft.PowerShell.Commands if (readBack) { - if (stream.Position == 0) + if (_stream.Position == 0) { return false; } - stream.Position--; - blocks.Add((byte)stream.ReadByte()); - stream.Position--; + _stream.Position--; + blocks.Add((byte)_stream.ReadByte()); + _stream.Position--; return true; } // Reading bytes not strings - int byteRead = stream.ReadByte(); + int byteRead = _stream.ReadByte(); // We've found the end of the file. if (byteRead == -1) @@ -796,8 +796,8 @@ namespace Microsoft.PowerShell.Commands // the changes if (waitChanges) { - WaitForChanges(this.path, this.mode, this.access, this.share, ClrFacade.GetDefaultEncoding()); - byteRead = stream.ReadByte(); + WaitForChanges(_path, _mode, _access, _share, ClrFacade.GetDefaultEncoding()); + byteRead = _stream.ReadByte(); } } @@ -815,12 +815,12 @@ namespace Microsoft.PowerShell.Commands { // Try to mask off the ReadOnly, and Hidden attributes // if they've specified Force. - if (File.Exists(filePath) && provider.Force) + if (File.Exists(filePath) && _provider.Force) { // Store the old attributes so that we can recover them // in the Close(); - oldAttributes = File.GetAttributes(filePath); - haveOldAttributes = true; + _oldAttributes = File.GetAttributes(filePath); + _haveOldAttributes = true; // Clear the hidden attribute, and if we're writing, also clear readonly. var attributesToClear = FileAttributes.Hidden; @@ -828,7 +828,7 @@ namespace Microsoft.PowerShell.Commands { attributesToClear |= FileAttributes.ReadOnly; } - File.SetAttributes(path, (File.GetAttributes(filePath) & ~attributesToClear)); + File.SetAttributes(_path, (File.GetAttributes(filePath) & ~attributesToClear)); } // If we want to write to the stream, attempt to open it for reading as well @@ -843,46 +843,46 @@ namespace Microsoft.PowerShell.Commands { if (!String.IsNullOrEmpty(streamName)) { - stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, fileAccess, fileShare); + _stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, fileAccess, fileShare); } else { - stream = new FileStream(filePath, fileMode, fileAccess, fileShare); + _stream = new FileStream(filePath, fileMode, fileAccess, fileShare); } } - catch(IOException) + catch (IOException) { if (!String.IsNullOrEmpty(streamName)) { - stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, requestedAccess, fileShare); + _stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, requestedAccess, fileShare); } else { - stream = new FileStream(filePath, fileMode, requestedAccess, fileShare); + _stream = new FileStream(filePath, fileMode, requestedAccess, fileShare); } } - if (!usingByteEncoding) + if (!_usingByteEncoding) { // Open the reader stream if ((fileAccess & (FileAccess.Read)) != 0) { - reader = new StreamReader(stream, fileEncoding); - _backReader = new FileStreamBackReader(stream, fileEncoding); + _reader = new StreamReader(_stream, fileEncoding); + _backReader = new FileStreamBackReader(_stream, fileEncoding); } - + // Open the writer stream if ((fileAccess & (FileAccess.Write)) != 0) { // Ensure we are using the proper encoding - if ((reader != null) && + if ((_reader != null) && ((fileAccess & (FileAccess.Read)) != 0)) { - reader.Peek(); - fileEncoding = reader.CurrentEncoding; + _reader.Peek(); + fileEncoding = _reader.CurrentEncoding; } - writer = new StreamWriter(stream, fileEncoding); + _writer = new StreamWriter(_stream, fileEncoding); } } } @@ -900,10 +900,10 @@ namespace Microsoft.PowerShell.Commands private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, Encoding fileEncoding) { // Close the old stream, and store our current position. - if (stream != null) + if (_stream != null) { - fileOffset = stream.Position; - stream.Dispose(); + _fileOffset = _stream.Position; + _stream.Dispose(); } // Watch for changes, as a blocking call. @@ -933,7 +933,7 @@ namespace Microsoft.PowerShell.Commands { watcher.EnableRaisingEvents = true; - while (!provider.Stopping) + while (!_provider.Stopping) { bool isTaskCompleted = tcs.Task.Wait(500); @@ -977,13 +977,13 @@ namespace Microsoft.PowerShell.Commands // If the file has been shortened, restart from zero. // That will let us catch log roll-overs. - if (fileOffset > stream.Length) - fileOffset = 0; + if (_fileOffset > _stream.Length) + _fileOffset = 0; // Seek to the place we last left off. - stream.Seek(fileOffset, SeekOrigin.Begin); - if(reader != null) { reader.DiscardBufferedData(); } - if(_backReader != null) { _backReader.DiscardBufferedData(); } + _stream.Seek(_fileOffset, SeekOrigin.Begin); + if (_reader != null) { _reader.DiscardBufferedData(); } + if (_backReader != null) { _backReader.DiscardBufferedData(); } } /// @@ -1000,13 +1000,13 @@ namespace Microsoft.PowerShell.Commands /// public void Seek(long offset, SeekOrigin origin) { - if(writer != null) { writer.Flush(); } + if (_writer != null) { _writer.Flush(); } - stream.Seek(offset, origin); + _stream.Seek(offset, origin); - if(writer != null) { writer.Flush(); } - if(reader != null) { reader.DiscardBufferedData(); } - if(_backReader != null) { _backReader.DiscardBufferedData(); } + if (_writer != null) { _writer.Flush(); } + if (_reader != null) { _reader.DiscardBufferedData(); } + if (_backReader != null) { _backReader.DiscardBufferedData(); } } // Seek /// @@ -1016,12 +1016,12 @@ namespace Microsoft.PowerShell.Commands { bool streamClosed = false; - if (writer != null) + if (_writer != null) { try { - writer.Flush(); - writer.Dispose(); + _writer.Flush(); + _writer.Dispose(); } finally { @@ -1029,9 +1029,9 @@ namespace Microsoft.PowerShell.Commands } } - if (reader != null) + if (_reader != null) { - reader.Dispose(); + _reader.Dispose(); streamClosed = true; } @@ -1043,14 +1043,14 @@ namespace Microsoft.PowerShell.Commands if (!streamClosed) { - stream.Flush(); - stream.Dispose(); + _stream.Flush(); + _stream.Dispose(); } // Reset the attributes - if (haveOldAttributes && provider.Force) + if (_haveOldAttributes && _provider.Force) { - File.SetAttributes(path, oldAttributes); + File.SetAttributes(_path, _oldAttributes); } } // Close @@ -1070,7 +1070,7 @@ namespace Microsoft.PowerShell.Commands { foreach (object line in content) { - object[] contentArray = line as object[]; + object[] contentArray = line as object[]; if (contentArray != null) { foreach (object obj in contentArray) @@ -1085,7 +1085,7 @@ namespace Microsoft.PowerShell.Commands } return content; } // Write - + private void WriteObject(object content) { if (content == null) @@ -1093,13 +1093,13 @@ namespace Microsoft.PowerShell.Commands return; } - if (usingByteEncoding) + if (_usingByteEncoding) { try { byte byteToWrite = (byte)content; - stream.WriteByte(byteToWrite); + _stream.WriteByte(byteToWrite); } catch (InvalidCastException) { @@ -1108,13 +1108,13 @@ namespace Microsoft.PowerShell.Commands } else { - if (this.suppressNewline) + if (_suppressNewline) { - writer.Write(content.ToString()); + _writer.Write(content.ToString()); } else { - writer.WriteLine(content.ToString()); + _writer.WriteLine(content.ToString()); } } } // WriteObject @@ -1130,19 +1130,18 @@ namespace Microsoft.PowerShell.Commands internal void Dispose(bool isDisposing) { - if(isDisposing) + if (isDisposing) { - if(stream != null) - stream.Dispose(); - if(reader != null) - reader.Dispose(); + if (_stream != null) + _stream.Dispose(); + if (_reader != null) + _reader.Dispose(); if (_backReader != null) - _backReader.Dispose(); - if (writer != null) - writer.Dispose(); + _backReader.Dispose(); + if (_writer != null) + _writer.Dispose(); } } - } // class FileSystemContentStream internal sealed class FileStreamBackReader : StreamReader @@ -1180,7 +1179,7 @@ namespace Microsoft.PowerShell.Commands private bool? _singleByteCharSet = null; private const byte BothTopBitsSet = 0xC0; - private const byte TopBitUnset = 0x80; + private const byte TopBitUnset = 0x80; /// /// If the given encoding is OEM or Default, check to see if the code page @@ -1336,7 +1335,6 @@ namespace Microsoft.PowerShell.Commands { buffer[index++] = _charBuff[--_charCount]; } - } while (count > 0); return charRead; @@ -1533,7 +1531,7 @@ namespace Microsoft.PowerShell.Commands internal sealed class BackReaderEncodingNotSupportedException : NotSupportedException { internal BackReaderEncodingNotSupportedException(string message, string encodingName) - : base (message) + : base(message) { _encodingName = encodingName; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 9b8120510..1f87e0c09 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -67,15 +67,15 @@ namespace Microsoft.PowerShell.Commands /// An instance of the PSTraceSource class used for trace output /// using "FileSystemProvider" as the category. /// - [Dbg.TraceSourceAttribute("FileSystemProvider","The namespace navigation provider for the file system")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("FileSystemProvider", "The namespace navigation provider for the file system"); + [Dbg.TraceSourceAttribute("FileSystemProvider", "The namespace navigation provider for the file system")] + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("FileSystemProvider", "The namespace navigation provider for the file system"); /// /// Gets the name of the provider /// public const string ProviderName = "FileSystem"; - + /// /// Initializes a new instance of the FileSystemProvider class. Since this /// object needs to be stateless, the constructor does nothing. @@ -84,7 +84,7 @@ namespace Microsoft.PowerShell.Commands { } - private Collection excludeMatcher = null; + private Collection _excludeMatcher = null; /// /// Converts all / in the path to \ @@ -346,7 +346,7 @@ namespace Microsoft.PowerShell.Commands /// /// The updated ProviderInfo object that holds the provider's configuration. /// - protected override ProviderInfo Start (ProviderInfo providerInfo) + protected override ProviderInfo Start(ProviderInfo providerInfo) { // Set the home folder for the user if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) @@ -358,11 +358,11 @@ namespace Microsoft.PowerShell.Commands { if (Directory.Exists(homeDirectory)) { - tracer.WriteLine("Home = {0}", homeDirectory); + s_tracer.WriteLine("Home = {0}", homeDirectory); providerInfo.Home = homeDirectory; } else - tracer.WriteLine("Not setting home directory {0} - does not exist", homeDirectory); + s_tracer.WriteLine("Not setting home directory {0} - does not exist", homeDirectory); } } return providerInfo; @@ -442,7 +442,6 @@ namespace Microsoft.PowerShell.Commands { drive.IsNetworkDrive = true; } - } catch (ArgumentException) // swallow ArgumentException incl. ArgumentNullException { @@ -474,7 +473,7 @@ namespace Microsoft.PowerShell.Commands else { String error = StringUtil.Format(FileSystemProviderStrings.DriveRootError, drive.Root); - Exception e = new IOException (error); + Exception e = new IOException(error); WriteError(new ErrorRecord(e, "DriveRootError", ErrorCategory.ReadError, drive)); } @@ -1034,7 +1033,7 @@ namespace Microsoft.PowerShell.Commands /// /// True if the path is valid, false otherwise. /// - protected override bool IsValidPath (string path) + protected override bool IsValidPath(string path) { //Path passed should be fully qualified path. if (String.IsNullOrEmpty(path)) @@ -1171,7 +1170,7 @@ namespace Microsoft.PowerShell.Commands foundStream = true; } - if ((! WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) + if ((!WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) { string errorMessage = StringUtil.Format( FileSystemProviderStrings.AlternateDataStreamNotFound, desiredStream, result.FullName); @@ -1207,7 +1206,7 @@ namespace Microsoft.PowerShell.Commands { //IOException contains specific message about the error occured and so no need for errordetails. ErrorRecord er = new ErrorRecord(ioError, "GetItemIOError", ErrorCategory.ReadError, path); - WriteError (er); + WriteError(er); } catch (UnauthorizedAccessException accessException) { @@ -1257,11 +1256,10 @@ namespace Microsoft.PowerShell.Commands FileInfo fileObj = new FileInfo(path); result = fileObj; - tracer.WriteLine("Got FileInfo: {0}", fileObj); + s_tracer.WriteLine("Got FileInfo: {0}", fileObj); } else { - // if its not a file, maybe its a directory DirectoryInfo directoryObj = @@ -1290,7 +1288,7 @@ namespace Microsoft.PowerShell.Commands result = directoryObj; isContainer = true; - tracer.WriteLine("Got DirectoryInfo: {0}", directoryObj); + s_tracer.WriteLine("Got DirectoryInfo: {0}", directoryObj); } } return result; @@ -1443,7 +1441,7 @@ namespace Microsoft.PowerShell.Commands { // Don't handle full paths, paths that the user is already trying to // filter, or paths they are trying to escape. - if ((! String.IsNullOrEmpty(filter)) || + if ((!String.IsNullOrEmpty(filter)) || (path.Contains(StringLiterals.DefaultPathSeparatorString)) || (path.Contains(StringLiterals.AlternatePathSeparatorString)) || (path.Contains(StringLiterals.EscapeCharacter))) @@ -1478,9 +1476,9 @@ namespace Microsoft.PowerShell.Commands private void GetPathItems( string path, - bool recurse, - uint depth, - bool nameOnly, + bool recurse, + uint depth, + bool nameOnly, ReturnContainers returnContainers) { // Verify parameters @@ -1644,7 +1642,7 @@ namespace Microsoft.PowerShell.Commands // On some systems, this is already sorted. For consistency, always sort again. IEnumerable sortedChildList = childList.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase); - foreach(FileSystemInfo filesystemInfo in sortedChildList) + foreach (FileSystemInfo filesystemInfo in sortedChildList) { // Making sure to obey the StopProcessing. if (Stopping) @@ -1682,7 +1680,7 @@ namespace Microsoft.PowerShell.Commands if (attributeSatisfy && (filterHidden || switchFilterHidden || Force || !hidden)) { - if(nameOnly) + if (nameOnly) { WriteItemObject( filesystemInfo.Name, @@ -1691,7 +1689,7 @@ namespace Microsoft.PowerShell.Commands } else { - if(filesystemInfo is FileInfo) + if (filesystemInfo is FileInfo) WriteItemObject(filesystemInfo, filesystemInfo.FullName, false); else WriteItemObject(filesystemInfo, filesystemInfo.FullName, true); @@ -1750,7 +1748,7 @@ namespace Microsoft.PowerShell.Commands catch (IOException e) { // 2004/10/13-JonN removed ResourceActionFailedException wrapper - WriteError (new ErrorRecord (e, "DirIOError", ErrorCategory.ReadError, directory.FullName)); + WriteError(new ErrorRecord(e, "DirIOError", ErrorCategory.ReadError, directory.FullName)); } catch (UnauthorizedAccessException uae) { @@ -1816,7 +1814,7 @@ namespace Microsoft.PowerShell.Commands if (instance == null) return String.Empty; - FileSystemInfo fileInfo = (FileSystemInfo) instance.BaseObject; + FileSystemInfo fileInfo = (FileSystemInfo)instance.BaseObject; if (fileInfo == null) return String.Empty; @@ -1872,7 +1870,7 @@ namespace Microsoft.PowerShell.Commands path = NormalizePath(path); if (String.IsNullOrEmpty(newName)) - + { throw PSTraceSource.NewArgumentException("newName"); } @@ -1880,7 +1878,7 @@ namespace Microsoft.PowerShell.Commands // Clean up "newname" to fix some common usability problems: // Rename .\foo.txt .\bar.txt // Rename c:\temp\foo.txt c:\temp\bar.txt - if(newName.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || + if (newName.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || newName.StartsWith("./", StringComparison.OrdinalIgnoreCase)) { newName = newName.Remove(0, 2); @@ -1925,16 +1923,15 @@ namespace Microsoft.PowerShell.Commands string action = FileSystemProviderStrings.RenameItemActionDirectory; - string resource = StringUtil.Format(FileSystemProviderStrings.RenameItemResourceFileTemplate,dir.FullName,newPath); + string resource = StringUtil.Format(FileSystemProviderStrings.RenameItemResourceFileTemplate, dir.FullName, newPath); if (ShouldProcess(resource, action)) { - // Now move the file dir.MoveTo(newPath); result = dir; - WriteItemObject (result, result.FullName, isContainer); + WriteItemObject(result, result.FullName, isContainer); } } else @@ -1963,7 +1960,6 @@ namespace Microsoft.PowerShell.Commands WriteItemObject(result, result.FullName, isContainer); } } - } catch (ArgumentException argException) { @@ -1978,7 +1974,6 @@ namespace Microsoft.PowerShell.Commands { WriteError(new ErrorRecord(accessException, "RenameItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); } - } // RenameItem #endregion RenameItem @@ -2068,7 +2063,6 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(resource, action)) { - // Create the file with read/write access and // not allowing sharing. @@ -2105,9 +2099,9 @@ namespace Microsoft.PowerShell.Commands else if (itemType == ItemType.SymbolicLink || itemType == ItemType.HardLink) { string action = null; - if(itemType == ItemType.SymbolicLink) + if (itemType == ItemType.SymbolicLink) action = FileSystemProviderStrings.NewItemActionSymbolicLink; - else if(itemType == ItemType.HardLink) + else if (itemType == ItemType.HardLink) action = FileSystemProviderStrings.NewItemActionHardLink; string resource = StringUtil.Format(FileSystemProviderStrings.NewItemActionTemplate, path); @@ -2203,7 +2197,7 @@ namespace Microsoft.PowerShell.Commands } else { - if(symLinkExists) + if (symLinkExists) { WriteError(new ErrorRecord(new IOException("NewItemIOError"), "NewItemIOError", ErrorCategory.ResourceExists, path)); return; @@ -2212,26 +2206,26 @@ namespace Microsoft.PowerShell.Commands bool success = false; - if(itemType == ItemType.SymbolicLink) + if (itemType == ItemType.SymbolicLink) { if (Platform.IsWindows) { - success = WinCreateSymbolicLink(path,strTargetPath,isDirectory); + success = WinCreateSymbolicLink(path, strTargetPath, isDirectory); } else { - success = Platform.NonWindowsCreateSymbolicLink(path,strTargetPath); + success = Platform.NonWindowsCreateSymbolicLink(path, strTargetPath); } } - else if(itemType == ItemType.HardLink) + else if (itemType == ItemType.HardLink) { if (Platform.IsWindows) { - success = WinCreateHardLink(path,strTargetPath); + success = WinCreateHardLink(path, strTargetPath); } else { - success = Platform.NonWindowsCreateHardLink(path,strTargetPath); + success = Platform.NonWindowsCreateHardLink(path, strTargetPath); } } @@ -2241,7 +2235,7 @@ namespace Microsoft.PowerShell.Commands Win32Exception w32Exception = new Win32Exception((int)errorCode); - if(errorCode == 1314) //ERROR_PRIVILEGE_NOT_HELD + if (errorCode == 1314) //ERROR_PRIVILEGE_NOT_HELD { string message = FileSystemProviderStrings.ElevationRequired; WriteError(new ErrorRecord(new UnauthorizedAccessException(message, w32Exception), "NewItemSymbolicLinkElevationRequired", ErrorCategory.PermissionDenied, value.ToString())); @@ -2253,7 +2247,7 @@ namespace Microsoft.PowerShell.Commands string message = null; if (itemType == ItemType.SymbolicLink) message = FileSystemProviderStrings.SymbolicLinkNotSupported; - else + else message = FileSystemProviderStrings.HardLinkNotSupported; WriteError(new ErrorRecord(new InvalidOperationException(message, w32Exception), "NewItemInvalidOperation", ErrorCategory.InvalidOperation, value.ToString())); @@ -2264,7 +2258,7 @@ namespace Microsoft.PowerShell.Commands } else { - if(isDirectory) + if (isDirectory) { DirectoryInfo dirInfo = new DirectoryInfo(path); WriteItemObject(dirInfo, path, true); @@ -2284,7 +2278,6 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(resource, action)) { - bool isDirectory = false; string strTargetPath = value.ToString(); @@ -2476,9 +2469,9 @@ namespace Microsoft.PowerShell.Commands ItemType itemType = ItemType.Unknown; WildcardPattern typeEvaluator = - WildcardPattern.Get( input + "*", + WildcardPattern.Get(input + "*", WildcardOptions.IgnoreCase | - WildcardOptions.Compiled ); + WildcardOptions.Compiled); if (typeEvaluator.IsMatch("directory") || typeEvaluator.IsMatch("container")) @@ -2489,7 +2482,7 @@ namespace Microsoft.PowerShell.Commands { itemType = ItemType.File; } - else if(typeEvaluator.IsMatch("symboliclink")) + else if (typeEvaluator.IsMatch("symboliclink")) { itemType = ItemType.SymbolicLink; } @@ -2535,7 +2528,7 @@ namespace Microsoft.PowerShell.Commands String errorMessage = StringUtil.Format(FileSystemProviderStrings.DirectoryExist, path); Exception e = new IOException(errorMessage); - WriteError (new ErrorRecord( + WriteError(new ErrorRecord( e, "DirectoryExist", ErrorCategory.ResourceExists, @@ -2552,14 +2545,12 @@ namespace Microsoft.PowerShell.Commands try { - string action = FileSystemProviderStrings.NewItemActionDirectory; string resource = StringUtil.Format(FileSystemProviderStrings.NewItemActionTemplate, path); if (ShouldProcess(resource, action)) { - // Use the parent directory to create the sub-directory DirectoryInfo parentDirectory = new DirectoryInfo(parentPath); @@ -2739,7 +2730,7 @@ namespace Microsoft.PowerShell.Commands return; } - if ((! removeStreams) && iscontainer) + if ((!removeStreams) && iscontainer) { RemoveDirectoryInfoItem((DirectoryInfo)fsinfo, recurse, Force, true); } @@ -2865,14 +2856,14 @@ namespace Microsoft.PowerShell.Commands return; } - if((directory.Attributes & FileAttributes.ReparsePoint) != 0) + if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { bool success = InternalSymbolicLinkLinkCodeMethods.DeleteJunction(directory.FullName); - if(!success) - { + if (!success) + { string error = StringUtil.Format(FileSystemProviderStrings.CannotRemoveItem, directory.FullName); - Exception e = new IOException(error); + Exception e = new IOException(error); WriteError(new ErrorRecord(e, "DeleteJunctionFailed", ErrorCategory.WriteError, directory)); return; } @@ -2962,9 +2953,9 @@ namespace Microsoft.PowerShell.Commands if (hasChildren && !force) { - String error = StringUtil.Format(FileSystemProviderStrings.DirectoryNotEmpty,directory.FullName); + String error = StringUtil.Format(FileSystemProviderStrings.DirectoryNotEmpty, directory.FullName); Exception e = new IOException(error); - WriteError (new ErrorRecord (e,"DirectoryNotEmpty", ErrorCategory.WriteError, directory)); + WriteError(new ErrorRecord(e, "DirectoryNotEmpty", ErrorCategory.WriteError, directory)); } else // !hasChildren || force { @@ -3456,12 +3447,12 @@ namespace Microsoft.PowerShell.Commands } } - excludeMatcher = SessionStateUtilities.CreateWildcardsFromStrings(Exclude,WildcardOptions.IgnoreCase); - + _excludeMatcher = SessionStateUtilities.CreateWildcardsFromStrings(Exclude, WildcardOptions.IgnoreCase); + // if the source and destination path are same (for a local copy) then flag it as error. if ((toSession == null) && (fromSession == null) && path.Equals(destinationPath, StringComparison.OrdinalIgnoreCase)) { - String error = StringUtil.Format(FileSystemProviderStrings.CopyError,path); + String error = StringUtil.Format(FileSystemProviderStrings.CopyError, path); Exception e = new IOException(error); WriteError(new ErrorRecord(e, "CopyError", ErrorCategory.WriteError, path)); return; @@ -3492,8 +3483,8 @@ namespace Microsoft.PowerShell.Commands } } - excludeMatcher.Clear(); - excludeMatcher = null; + _excludeMatcher.Clear(); + _excludeMatcher = null; } //CopyItem private void CopyItemFromRemoteSession(string path, string destinationPath, bool recurse, bool force, PSSession fromSession) @@ -3551,16 +3542,16 @@ namespace Microsoft.PowerShell.Commands } CopyDirectoryFromRemoteSession( - itemName, + itemName, itemFullName, - destinationPath, - force, - recurse, + destinationPath, + force, + recurse, ps); } else { - bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(itemName, excludeMatcher, false); + bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(itemName, _excludeMatcher, false); if (!excludeFile) { long itemSize = (long)ItemInfo["FileSize"]; @@ -3606,7 +3597,6 @@ namespace Microsoft.PowerShell.Commands { RemoveFunctionPSCopyFileToRemoteSession(ps); } - } // CopyItem private void CopyDirectoryInfoItem( @@ -3642,7 +3632,7 @@ namespace Microsoft.PowerShell.Commands } } - tracer.WriteLine("destination = {0}", destination); + s_tracer.WriteLine("destination = {0}", destination); // Confirm the copy with the user @@ -3798,7 +3788,7 @@ namespace Microsoft.PowerShell.Commands string resource = StringUtil.Format(FileSystemProviderStrings.CopyItemResourceFileTemplate, file.FullName, destinationPath); - bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, excludeMatcher, defaultValue: false); + bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, _excludeMatcher, defaultValue: false); if (!excludeFile) { @@ -3874,11 +3864,11 @@ namespace Microsoft.PowerShell.Commands } // CopyFileInfoItem private void CopyDirectoryFromRemoteSession( - string sourceDirectoryName, + string sourceDirectoryName, string sourceDirectoryFullName, - string destination, - bool force, - bool recurse, + string destination, + bool force, + bool recurse, System.Management.Automation.PowerShell ps) { Dbg.Diagnostics.Assert((sourceDirectoryName != null && sourceDirectoryFullName != null), "The caller should verify directory."); @@ -3888,7 +3878,7 @@ namespace Microsoft.PowerShell.Commands destination = MakePath(destination, sourceDirectoryName); } - tracer.WriteLine("destination = {0}", destination); + s_tracer.WriteLine("destination = {0}", destination); // Confirm the copy with the user string action = FileSystemProviderStrings.CopyItemActionDirectory; @@ -3941,7 +3931,7 @@ namespace Microsoft.PowerShell.Commands return; } - bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(fileName, excludeMatcher, defaultValue : false); + bool excludeFile = SessionStateUtilities.MatchesAnyWildcardPattern(fileName, _excludeMatcher, defaultValue: false); if (!excludeFile) { @@ -4099,9 +4089,9 @@ namespace Microsoft.PowerShell.Commands private void CopyFileFromRemoteSession( string sourceFileName, string sourceFileFullName, - string destinationPath, - bool force, - System.Management.Automation.PowerShell ps, + string destinationPath, + bool force, + System.Management.Automation.PowerShell ps, long fileSize = 0) { Dbg.Diagnostics.Assert(sourceFileFullName != null, "The caller should verify file."); @@ -4151,7 +4141,6 @@ namespace Microsoft.PowerShell.Commands { SetFileMetadata(sourceFileFullName, destinationFile, ps); } - } // ShouldProcess } @@ -4291,7 +4280,7 @@ namespace Microsoft.PowerShell.Commands WriteError(new ErrorRecord(unauthorizedAccessException, "CopyFileInfoItemRemotelyUnauthorizedAccessError", ErrorCategory.PermissionDenied, sourceFileFullName)); } finally - { + { if (wStream != null) { wStream.Dispose(); @@ -4345,7 +4334,7 @@ namespace Microsoft.PowerShell.Commands Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); if (op != null && op["TargetSupportsAlternateStreams"] != null) { - supportsAlternateStreams = (bool) op["TargetSupportsAlternateStreams"]; + supportsAlternateStreams = (bool)op["TargetSupportsAlternateStreams"]; } return supportsAlternateStreams; @@ -4371,11 +4360,11 @@ namespace Microsoft.PowerShell.Commands { if (op["IsDirectoryInfo"] != null) { - isDirectoryInfo = (bool) op["IsDirectoryInfo"]; + isDirectoryInfo = (bool)op["IsDirectoryInfo"]; } if (op["IsFileInfo"] != null) { - isFileInfo = (bool) op["IsFileInfo"]; + isFileInfo = (bool)op["IsFileInfo"]; } if (op["ParentIsDirectoryInfo"] != null) { @@ -4386,7 +4375,7 @@ namespace Microsoft.PowerShell.Commands if (isFileInfo) { // The destination is a file, so we are going to overwrite it. - path = remotePath; + path = remotePath; } else if (isDirectoryInfo) { @@ -4545,13 +4534,11 @@ namespace Microsoft.PowerShell.Commands progress.PercentComplete = percentage; WriteProgress(progress); } - } while (remainingFileSize > 0); progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); success = true; - } catch (IOException ioException) { @@ -4595,7 +4582,7 @@ namespace Microsoft.PowerShell.Commands return metadata; } - + private void SetRemoteFileMetadata(FileInfo file, string remoteFilePath, System.Management.Automation.PowerShell ps) { Hashtable metadata = GetFileMetadata(file); @@ -4699,7 +4686,7 @@ namespace Microsoft.PowerShell.Commands if ((!force) && (bool)op["PathExists"]) { - Exception e = new IOException( StringUtil.Format(FileSystemProviderStrings.DirectoryExist, path)); + Exception e = new IOException(StringUtil.Format(FileSystemProviderStrings.DirectoryExist, path)); WriteError(new ErrorRecord(e, "DirectoryExist", ErrorCategory.ResourceExists, path)); return null; } @@ -4743,10 +4730,10 @@ namespace Microsoft.PowerShell.Commands /// /// The parent of the given path. /// - protected override string GetParentPath (string path, string root) + protected override string GetParentPath(string path, string root) { - string parentPath = base.GetParentPath (path, root); - if (IsUNCPath (path)) + string parentPath = base.GetParentPath(path, root); + if (IsUNCPath(path)) { // Since UNC paths must have "\\server\share" as the base of // the path, you cannot get a parent path higher than this. @@ -4754,7 +4741,7 @@ namespace Microsoft.PowerShell.Commands // ensures that it is in a position where it is preceeded by // "\\s" at a minimum. - int indexOfLastPathSeparator = parentPath.LastIndexOf ('\\'); + int indexOfLastPathSeparator = parentPath.LastIndexOf('\\'); if (indexOfLastPathSeparator < 3) { parentPath = String.Empty; @@ -4762,7 +4749,7 @@ namespace Microsoft.PowerShell.Commands } else { - parentPath = EnsureDriveIsRooted (parentPath); + parentPath = EnsureDriveIsRooted(parentPath); } return parentPath; } // GetParentPath @@ -4790,9 +4777,9 @@ namespace Microsoft.PowerShell.Commands } - private static bool IsUNCPath (string path) + private static bool IsUNCPath(string path) { - return path.StartsWith ("\\\\", StringComparison.Ordinal); + return path.StartsWith("\\\\", StringComparison.Ordinal); } /// @@ -4810,11 +4797,11 @@ namespace Microsoft.PowerShell.Commands /// True if the path is a UNC root, or false otherwise. /// /// - private static bool IsUNCRoot (string path) + private static bool IsUNCRoot(string path) { bool result = false; - if (!String.IsNullOrEmpty (path)) + if (!String.IsNullOrEmpty(path)) { if (IsUNCPath(path)) { @@ -4862,17 +4849,17 @@ namespace Microsoft.PowerShell.Commands /// True if the path is either a drive root or a UNC root, or false otherwise. /// /// - private static bool IsPathRoot (string path) + private static bool IsPathRoot(string path) { - if (String.IsNullOrEmpty (path)) + if (String.IsNullOrEmpty(path)) { return false; } - bool isDriveRoot = String.Equals (path, Path.GetPathRoot (path), StringComparison.OrdinalIgnoreCase); - bool isUNCRoot = IsUNCRoot (path); + bool isDriveRoot = String.Equals(path, Path.GetPathRoot(path), StringComparison.OrdinalIgnoreCase); + bool isUNCRoot = IsUNCRoot(path); bool result = isDriveRoot || isUNCRoot; - tracer.WriteLine ("result = {0}; isDriveRoot = {1}; isUNCRoot = {2}", result, isDriveRoot, isUNCRoot); + s_tracer.WriteLine("result = {0}; isDriveRoot = {1}; isUNCRoot = {2}", result, isDriveRoot, isUNCRoot); return result; } @@ -4912,7 +4899,7 @@ namespace Microsoft.PowerShell.Commands basePath = String.Empty; } - tracer.WriteLine("basePath = {0}", basePath); + s_tracer.WriteLine("basePath = {0}", basePath); string result = path; @@ -4936,13 +4923,13 @@ namespace Microsoft.PowerShell.Commands try { string originalPathComparison = path; - if (! originalPathComparison.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) + if (!originalPathComparison.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) { originalPathComparison += StringLiterals.DefaultPathSeparator; } string basePathComparison = basePath; - if (! basePathComparison.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) + if (!basePathComparison.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) { basePathComparison += StringLiterals.DefaultPathSeparator; } @@ -4952,7 +4939,6 @@ namespace Microsoft.PowerShell.Commands bool isUNCPath = IsUNCPath(result); if (!isUNCPath) { - // Add the base path back on so that it can be used for // processing if (!result.StartsWith(basePath, StringComparison.CurrentCulture)) @@ -5009,7 +4995,6 @@ namespace Microsoft.PowerShell.Commands } else { - String error = StringUtil.Format(FileSystemProviderStrings.PathOutSideBasePath, path); Exception e = new ArgumentException(error); @@ -5079,11 +5064,11 @@ namespace Microsoft.PowerShell.Commands /// are done using StringComparison.InvariantCultureIngoreCase. /// /// - private string NormalizeRelativePathHelper (string path, string basePath) + private string NormalizeRelativePathHelper(string path, string basePath) { if (path == null) { - throw PSTraceSource.NewArgumentNullException ("path"); + throw PSTraceSource.NewArgumentNullException("path"); } if (path.Length == 0) @@ -5096,7 +5081,7 @@ namespace Microsoft.PowerShell.Commands basePath = String.Empty; } - tracer.WriteLine ("basePath = {0}", basePath); + s_tracer.WriteLine("basePath = {0}", basePath); // Remove alternate data stream references // See if they've used the inline stream syntax. They have more than one colon. @@ -5115,19 +5100,19 @@ namespace Microsoft.PowerShell.Commands do // false loop { // Convert to the correct path separators and trim trailing separators - path = path.Replace (StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + path = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); string originalPath = path; - path = path.TrimEnd (StringLiterals.DefaultPathSeparator); - basePath = basePath.Replace (StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); - basePath = basePath.TrimEnd (StringLiterals.DefaultPathSeparator); + path = path.TrimEnd(StringLiterals.DefaultPathSeparator); + basePath = basePath.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator); path = RemoveRelativeTokens(path); // See if the base and the path are already the same. We resolve this to // ..\Leaf, since resolving "." to "." doesn't offer much information. if (String.Equals(path, basePath, StringComparison.OrdinalIgnoreCase) && - (! originalPath.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase))) + (!originalPath.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase))) { string childName = GetChildName(path); result = MakePath("..", childName); @@ -5141,9 +5126,9 @@ namespace Microsoft.PowerShell.Commands // For example: base = c:/temp/bar/baz // path = c:/temp/foo if (( - ! (path + StringLiterals.DefaultPathSeparator).StartsWith( + !(path + StringLiterals.DefaultPathSeparator).StartsWith( basePath + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)) && - (! String.IsNullOrEmpty(basePath)) + (!String.IsNullOrEmpty(basePath)) ) { result = String.Empty; @@ -5171,7 +5156,7 @@ namespace Microsoft.PowerShell.Commands // ..\..\dir* // In that case (as above,) we keep the ..\..\directory1 // instead of ".." as would usually be returned - if (! String.IsNullOrEmpty(commonBase)) + if (!String.IsNullOrEmpty(commonBase)) { if (String.Equals(path, commonBase, StringComparison.OrdinalIgnoreCase) && (!path.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase))) @@ -5278,7 +5263,7 @@ namespace Microsoft.PowerShell.Commands // longer path. If it is not, take the child off of the longer // path and compare again. - while (! String.Equals(path1, path2, StringComparison.OrdinalIgnoreCase)) + while (!String.Equals(path1, path2, StringComparison.OrdinalIgnoreCase)) { if (path2.Length > path1.Length) { @@ -5310,9 +5295,9 @@ namespace Microsoft.PowerShell.Commands /// of the stack and the most ancestoral parent at the top. /// /// - private Stack TokenizePathToStack (string path, string basePath) + private Stack TokenizePathToStack(string path, string basePath) { - Stack tokenizedPathStack = new Stack (); + Stack tokenizedPathStack = new Stack(); string tempPath = path; string previousParent = path; @@ -5322,17 +5307,17 @@ namespace Microsoft.PowerShell.Commands // Get the child name and push it onto the stack // if its valid - string childName = GetChildName (tempPath); - if (String.IsNullOrEmpty (childName)) + string childName = GetChildName(tempPath); + if (String.IsNullOrEmpty(childName)) { // Push the parent on and then stop - tracer.WriteLine ("tokenizedPathStack.Push({0})", tempPath); - tokenizedPathStack.Push (tempPath); + s_tracer.WriteLine("tokenizedPathStack.Push({0})", tempPath); + tokenizedPathStack.Push(tempPath); break; } - tracer.WriteLine ("tokenizedPathStack.Push({0})", childName); - tokenizedPathStack.Push (childName); + s_tracer.WriteLine("tokenizedPathStack.Push({0})", childName); + tokenizedPathStack.Push(childName); // Get the parent path and verify if we have to continue // tokenizing @@ -5342,14 +5327,14 @@ namespace Microsoft.PowerShell.Commands // - not a UNC path and the string length is less than or // equal to 3. "C:\" - tempPath = GetParentPath (tempPath, basePath); + tempPath = GetParentPath(tempPath, basePath); if (tempPath.Length >= previousParent.Length || IsPathRoot(tempPath)) { - if (String.IsNullOrEmpty (basePath)) + if (String.IsNullOrEmpty(basePath)) { - tracer.WriteLine ("tokenizedPathStack.Push({0})", tempPath); - tokenizedPathStack.Push (tempPath); + s_tracer.WriteLine("tokenizedPathStack.Push({0})", tempPath); + tokenizedPathStack.Push(tempPath); } break; } @@ -5378,19 +5363,19 @@ namespace Microsoft.PowerShell.Commands /// pathing tokens removed. /// /// - private Stack NormalizeThePath (string basepath, Stack tokenizedPathStack) + private Stack NormalizeThePath(string basepath, Stack tokenizedPathStack) { - Stack normalizedPathStack = new Stack (); + Stack normalizedPathStack = new Stack(); String currentPath = basepath; while (tokenizedPathStack.Count > 0) { - string childName = tokenizedPathStack.Pop (); + string childName = tokenizedPathStack.Pop(); - tracer.WriteLine ("childName = {0}", childName); + s_tracer.WriteLine("childName = {0}", childName); // Ignore the current directory token - if (childName.Equals (".", StringComparison.OrdinalIgnoreCase)) + if (childName.Equals(".", StringComparison.OrdinalIgnoreCase)) { // Just ignore it and move on. continue; @@ -5411,7 +5396,7 @@ namespace Microsoft.PowerShell.Commands currentPath = ""; } - tracer.WriteLine("normalizedPathStack.Pop() : {0}", poppedName); + s_tracer.WriteLine("normalizedPathStack.Pop() : {0}", poppedName); continue; } else @@ -5447,15 +5432,15 @@ namespace Microsoft.PowerShell.Commands else { // We couldn't find the item - if((! isContainer) && + if ((!isContainer) && (tokenizedPathStack.Count == 0)) { throw PSTraceSource.NewArgumentException("path", FileSystemProviderStrings.ItemDoesNotExist, currentPath); } } } - tracer.WriteLine ("normalizedPathStack.Push({0})", childName); - normalizedPathStack.Push (childName); + s_tracer.WriteLine("normalizedPathStack.Push({0})", childName); + normalizedPathStack.Push(childName); } return normalizedPathStack; @@ -5479,20 +5464,20 @@ namespace Microsoft.PowerShell.Commands /// of the one before it. /// /// - private string CreateNormalizedRelativePathFromStack (Stack normalizedPathStack) + private string CreateNormalizedRelativePathFromStack(Stack normalizedPathStack) { string leafElement = String.Empty; while (normalizedPathStack.Count > 0) { - if (String.IsNullOrEmpty (leafElement)) + if (String.IsNullOrEmpty(leafElement)) { - leafElement = normalizedPathStack.Pop (); + leafElement = normalizedPathStack.Pop(); } else { - string parentElement = normalizedPathStack.Pop (); - leafElement = MakePath (parentElement, leafElement); + string parentElement = normalizedPathStack.Pop(); + leafElement = MakePath(parentElement, leafElement); } } return leafElement; @@ -5543,7 +5528,7 @@ namespace Microsoft.PowerShell.Commands } else { - if (IsUNCPath (path)) + if (IsUNCPath(path)) { // For UNC paths we need to ensure that "\\server\share" is // maintained as a single unit. There is no child for "\\server\share" @@ -5554,12 +5539,12 @@ namespace Microsoft.PowerShell.Commands } else { - result = path.Substring (separatorIndex + 1); + result = path.Substring(separatorIndex + 1); } } else { - result = path.Substring (separatorIndex + 1); + result = path.Substring(separatorIndex + 1); } } @@ -5666,7 +5651,7 @@ namespace Microsoft.PowerShell.Commands try { bool isContainer = IsItemContainer(path); - tracer.WriteLine("Moving {0} to {1}", path, destination); + s_tracer.WriteLine("Moving {0} to {1}", path, destination); if (isContainer) { @@ -5694,7 +5679,6 @@ namespace Microsoft.PowerShell.Commands MoveDirectoryInfoItem(dir, destination, Force); } - } else { @@ -5870,7 +5854,6 @@ namespace Microsoft.PowerShell.Commands //IOException contains specific message about the error occured and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, file)); } - } } // MoveFileInfoItem @@ -5980,7 +5963,7 @@ namespace Microsoft.PowerShell.Commands return; } - foreach(FileInfo file in directory.EnumerateFiles()) + foreach (FileInfo file in directory.EnumerateFiles()) { MoveFileInfoItem(file, Path.Combine(destination, file.Name), force, false); } @@ -5994,7 +5977,6 @@ namespace Microsoft.PowerShell.Commands { RemoveItem(directory.FullName, false); } - } private bool IsSameVolume(string source, string destination) @@ -6076,7 +6058,6 @@ namespace Microsoft.PowerShell.Commands } else { - foreach (string property in providerSpecificPickList) { if (property != null && property.Length > 0) @@ -6104,11 +6085,10 @@ namespace Microsoft.PowerShell.Commands Exception e = new IOException(error); WriteError(new ErrorRecord(e, "GetValueError", ErrorCategory.ReadError, property)); } - } catch (GetValueException exception) { - WriteError (new ErrorRecord (exception, "GetValueError", ErrorCategory.ReadError, property)); + WriteError(new ErrorRecord(exception, "GetValueError", ErrorCategory.ReadError, property)); } } } // foreach (property in providerSpecificPickList @@ -6182,7 +6162,7 @@ namespace Microsoft.PowerShell.Commands /// propertyToSet is null. /// /// - public void SetProperty(string path, PSObject propertyToSet) + public void SetProperty(string path, PSObject propertyToSet) { // verify parameters @@ -6318,7 +6298,6 @@ namespace Microsoft.PowerShell.Commands WriteError(new ErrorRecord(e, "SetPropertyError", ErrorCategory.ReadError, property)); } } // ShouldProcess - } // foreach property if (propertySet) @@ -6336,7 +6315,6 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.ObjectNotFound, path)); } - } // SetProperty /// @@ -6450,12 +6428,11 @@ namespace Microsoft.PowerShell.Commands { fileSystemInfo.Attributes = FileAttributes.Normal; PSObject result = new PSObject(); - result.Properties.Add(new PSNoteProperty(propertiesToClear[0] , fileSystemInfo.Attributes)); + result.Properties.Add(new PSNoteProperty(propertiesToClear[0], fileSystemInfo.Attributes)); // Now write out the attribute that was cleared. WritePropertyObject(result, path); - } // ShouldProcess } catch (UnauthorizedAccessException unauthorizedAccessException) @@ -6555,7 +6532,7 @@ namespace Microsoft.PowerShell.Commands // Get the delimiter delimiterSpecified = dynParams.DelimiterSpecified; - if(delimiterSpecified) + if (delimiterSpecified) delimiter = dynParams.Delimiter; // Get the stream type @@ -6572,7 +6549,6 @@ namespace Microsoft.PowerShell.Commands // Get the stream name streamName = dynParams.Stream; - } // dynParams != null } // DynamicParameters != null @@ -6857,7 +6833,7 @@ namespace Microsoft.PowerShell.Commands clearStream = false; } - if(clearStream) + if (clearStream) { FileStream fileStream = null; @@ -6894,7 +6870,6 @@ namespace Microsoft.PowerShell.Commands // For filesystem once content is cleared WriteItemObject("", path, false); - } catch (ArgumentException argException) { @@ -6922,7 +6897,6 @@ namespace Microsoft.PowerShell.Commands //For filesystem once content is cleare WriteItemObject("", path, false); - } catch (UnauthorizedAccessException failure) { @@ -7076,7 +7050,7 @@ namespace Microsoft.PowerShell.Commands return NativeMethods.PathIsNetworkPath(path); // call the native method } - static class NativeMethods + private static class NativeMethods { /// /// WNetAddConnection2 API makes a connection to a network resource @@ -7102,7 +7076,7 @@ namespace Microsoft.PowerShell.Commands /// type of failure that occured while establishing /// the connection is returned. [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetAddConnection2(ref NetResource netResource, byte [] password, string username, int flags); + internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); /// /// WNetCancelConnection2 function cancels an existing network connection. @@ -7256,7 +7230,7 @@ namespace Microsoft.PowerShell.Commands [Flags] internal enum FileAttributes { - Hidden = 0x0002, + Hidden = 0x0002, Directory = 0x0010 } } @@ -7280,7 +7254,6 @@ namespace Microsoft.PowerShell.Commands [MarshalAs(UnmanagedType.LPWStr)] public string Provider; } - } // class FileSystemProvider internal static class SafeInvokeCommand @@ -7309,7 +7282,6 @@ namespace Microsoft.PowerShell.Commands { fileSystemContext.WriteError(new ErrorRecord(e, "CopyFileRemoteExecutionError", ErrorCategory.InvalidOperation, ps)); ps.Commands.Clear(); - } else { @@ -7416,7 +7388,6 @@ namespace Microsoft.PowerShell.Commands /// Big Endian UTF32 encoding. /// BigEndianUTF32, - } // FileSystemCmdletProviderEncoding #endregion @@ -7447,14 +7418,14 @@ namespace Microsoft.PowerShell.Commands { get { - return evaluator; + return _evaluator; } set { - evaluator = value; + _evaluator = value; } } - private FlagsExpression evaluator; + private FlagsExpression _evaluator; /// /// Gets or sets the filter directory flag @@ -7465,14 +7436,14 @@ namespace Microsoft.PowerShell.Commands { get { - return attributeDirectory; + return _attributeDirectory; } set { - attributeDirectory = value; + _attributeDirectory = value; } } - private bool attributeDirectory; + private bool _attributeDirectory; /// /// Gets or sets the filter file flag @@ -7483,14 +7454,14 @@ namespace Microsoft.PowerShell.Commands { get { - return attributeFile; + return _attributeFile; } set { - attributeFile = value; + _attributeFile = value; } } - private bool attributeFile; + private bool _attributeFile; /// /// Gets or sets the filter hidden flag @@ -7501,14 +7472,14 @@ namespace Microsoft.PowerShell.Commands { get { - return attributeHidden; + return _attributeHidden; } set { - attributeHidden = value; + _attributeHidden = value; } } - private bool attributeHidden; + private bool _attributeHidden; /// /// Gets or sets the filter readonly flag @@ -7519,14 +7490,14 @@ namespace Microsoft.PowerShell.Commands { get { - return attributeReadOnly; + return _attributeReadOnly; } set { - attributeReadOnly = value; + _attributeReadOnly = value; } } - private bool attributeReadOnly; + private bool _attributeReadOnly; /// /// Gets or sets the filter system flag @@ -7537,14 +7508,14 @@ namespace Microsoft.PowerShell.Commands { get { - return attributeSystem; + return _attributeSystem; } set { - attributeSystem = value; + _attributeSystem = value; } } - private bool attributeSystem; + private bool _attributeSystem; } /// @@ -7561,12 +7532,12 @@ namespace Microsoft.PowerShell.Commands { get { - return streamType; + return _streamType; } // get set { - streamType = value; + _streamType = value; } // set } // Encoding @@ -7580,7 +7551,7 @@ namespace Microsoft.PowerShell.Commands /// /// Default to getting a unicode string /// - private FileSystemCmdletProviderEncoding streamType = FileSystemCmdletProviderEncoding.String; + private FileSystemCmdletProviderEncoding _streamType = FileSystemCmdletProviderEncoding.String; /// /// Gets the encoding from the specified StreamType parameter. @@ -7589,7 +7560,7 @@ namespace Microsoft.PowerShell.Commands { get { - return GetEncodingFromEnum(streamType); + return GetEncodingFromEnum(_streamType); } } // EncodingType @@ -7618,27 +7589,27 @@ namespace Microsoft.PowerShell.Commands switch (type) { - case FileSystemCmdletProviderEncoding.String : + case FileSystemCmdletProviderEncoding.String: encoding = System.Text.Encoding.Unicode; break; - case FileSystemCmdletProviderEncoding.Unicode : + case FileSystemCmdletProviderEncoding.Unicode: encoding = System.Text.Encoding.Unicode; break; - case FileSystemCmdletProviderEncoding.BigEndianUnicode : + case FileSystemCmdletProviderEncoding.BigEndianUnicode: encoding = System.Text.Encoding.BigEndianUnicode; break; - case FileSystemCmdletProviderEncoding.UTF8 : + case FileSystemCmdletProviderEncoding.UTF8: encoding = System.Text.Encoding.UTF8; break; - case FileSystemCmdletProviderEncoding.UTF7 : + case FileSystemCmdletProviderEncoding.UTF7: encoding = System.Text.Encoding.UTF7; break; - case FileSystemCmdletProviderEncoding.UTF32 : + case FileSystemCmdletProviderEncoding.UTF32: encoding = System.Text.Encoding.UTF32; break; @@ -7646,11 +7617,11 @@ namespace Microsoft.PowerShell.Commands encoding = System.Text.Encoding.GetEncoding("utf-32BE"); break; - case FileSystemCmdletProviderEncoding.Ascii : + case FileSystemCmdletProviderEncoding.Ascii: encoding = System.Text.Encoding.ASCII; break; - case FileSystemCmdletProviderEncoding.Default : + case FileSystemCmdletProviderEncoding.Default: encoding = ClrFacade.GetDefaultEncoding(); break; @@ -7661,7 +7632,7 @@ namespace Microsoft.PowerShell.Commands } break; - default : + default: // Default to unicode encoding encoding = System.Text.Encoding.Unicode; break; @@ -7678,7 +7649,7 @@ namespace Microsoft.PowerShell.Commands { get { - return streamType == FileSystemCmdletProviderEncoding.Byte; + return _streamType == FileSystemCmdletProviderEncoding.Byte; } // get } // UsingByteEncoding @@ -7690,7 +7661,7 @@ namespace Microsoft.PowerShell.Commands { get { - return (streamType != FileSystemCmdletProviderEncoding.String); + return (_streamType != FileSystemCmdletProviderEncoding.String); } // get } // WasStreamTypeSpecified @@ -7711,7 +7682,6 @@ namespace Microsoft.PowerShell.Commands /// [Parameter] public String Stream { get; set; } - } //FileSystemContentWriterDynamicParameters /// @@ -7728,15 +7698,15 @@ namespace Microsoft.PowerShell.Commands { get { - return suppressNewline; + return _suppressNewline; } set { - suppressNewline = value; + _suppressNewline = value; } } - private bool suppressNewline = false; + private bool _suppressNewline = false; } //FileSystemContentWriterDynamicParameters /// @@ -7753,16 +7723,16 @@ namespace Microsoft.PowerShell.Commands { get { - return delimiter; + return _delimiter; } // get set { - delimiterSpecified = true; - delimiter = value; + _delimiterSpecified = true; + _delimiter = value; } // set } - private string delimiter = "\n"; + private string _delimiter = "\n"; /// /// Gets or sets the Wait flag. The wait flag determines if we want @@ -7774,15 +7744,15 @@ namespace Microsoft.PowerShell.Commands { get { - return wait; + return _wait; } // get set { - wait = value; + _wait = value; } // set } - private bool wait; + private bool _wait; /// /// When the Raw switch is present, we don't do any breaks on newlines, @@ -7793,14 +7763,14 @@ namespace Microsoft.PowerShell.Commands { get { - return isRaw; + return _isRaw; } set { - isRaw = value; + _isRaw = value; } } - private bool isRaw; + private bool _isRaw; /// /// Gets the status of the delimiter parameter. Returns true @@ -7810,11 +7780,10 @@ namespace Microsoft.PowerShell.Commands { get { - return delimiterSpecified; + return _delimiterSpecified; } // get } // DelimiterSpecified - private bool delimiterSpecified; - + private bool _delimiterSpecified; } // class FileSystemContentReaderDynamicParameters @@ -7848,7 +7817,6 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Stream { get; set; } - } // class FileSystemItemProviderDynamicParameters /// @@ -7863,7 +7831,6 @@ namespace Microsoft.PowerShell.Commands [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Stream { get; set; } - } // class FileSystemItemProviderDynamicParameters #endregion @@ -7880,7 +7847,7 @@ namespace Microsoft.PowerShell.Commands // Maximum reparse buffer info size. The max user defined reparse // data is 16KB, plus there's a header. - private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; + private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; private const int ERROR_NOT_A_REPARSE_POINT = 4390; @@ -7979,7 +7946,7 @@ namespace Microsoft.PowerShell.Commands } [StructLayout(LayoutKind.Sequential)] - struct BY_HANDLE_FILE_INFORMATION + private struct BY_HANDLE_FILE_INFORMATION { public uint FileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime; @@ -7994,7 +7961,7 @@ namespace Microsoft.PowerShell.Commands } [StructLayout(LayoutKind.Sequential)] - struct GUID + private struct GUID { public uint Data1; public ushort Data2; @@ -8004,16 +7971,16 @@ namespace Microsoft.PowerShell.Commands } [StructLayout(LayoutKind.Sequential)] - struct REPARSE_GUID_DATA_BUFFER + private struct REPARSE_GUID_DATA_BUFFER { public uint ReparseTag; public ushort ReparseDataLength; public ushort Reserved; public GUID ReparseGuid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_REPARSE_SIZE)] - public Char[] DataBuffer; + public Char[] DataBuffer; } - + [DllImport(PinvokeDllNames.DeviceIoControlDllName, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, @@ -8097,7 +8064,7 @@ namespace Microsoft.PowerShell.Commands return InternalGetLinkType(fileSysInfo); } else - return null; + return null; } private static List InternalGetTarget(string filePath) @@ -8147,7 +8114,7 @@ namespace Microsoft.PowerShell.Commands //Don't add the target link to the list. - if(String.Compare(fInfo.FullName, filePath, StringComparison.OrdinalIgnoreCase) != 0) + if (String.Compare(fInfo.FullName, filePath, StringComparison.OrdinalIgnoreCase) != 0) links.Add(fInfo.FullName); continueFind = InternalSymbolicLinkLinkCodeMethods.FindNextFileName(fileHandle, ref linkStringLength, linkName); @@ -8160,7 +8127,7 @@ namespace Microsoft.PowerShell.Commands continueFind = InternalSymbolicLinkLinkCodeMethods.FindNextFileName(fileHandle, ref linkStringLength, linkName); } - if(!continueFind && lastError != 38) //ERROR_HANDLE_EOF. No more links. + if (!continueFind && lastError != 38) //ERROR_HANDLE_EOF. No more links. { throw new Win32Exception(lastError); } @@ -8265,7 +8232,7 @@ namespace Microsoft.PowerShell.Commands if (Platform.IsWindows) { // Note that this class also has a enum called FileAttributes, so use fully qualified name - return (fileInfo.Attributes & System.IO.FileAttributes.ReparsePoint) + return (fileInfo.Attributes & System.IO.FileAttributes.ReparsePoint) == System.IO.FileAttributes.ReparsePoint; } else @@ -8321,8 +8288,8 @@ namespace Microsoft.PowerShell.Commands [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static bool WinIsHardLink(ref IntPtr handle) - { - BY_HANDLE_FILE_INFORMATION handleInfo; + { + BY_HANDLE_FILE_INFORMATION handleInfo; bool succeeded = InternalSymbolicLinkLinkCodeMethods.GetFileInformationByHandle(handle, out handleInfo); if (!succeeded) @@ -8338,7 +8305,7 @@ namespace Microsoft.PowerShell.Commands return false; } - + private static string InternalGetTarget(SafeFileHandle handle) { if (Platform.IsWindows) @@ -8423,7 +8390,7 @@ namespace Microsoft.PowerShell.Commands // used for that reason if (Platform.IsWindows) { - return WinCreateJunction(path,target); + return WinCreateJunction(path, target); } else { @@ -8498,7 +8465,7 @@ namespace Microsoft.PowerShell.Commands } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static bool DeleteJunction(string junctionPath) { bool result = false; @@ -8507,22 +8474,22 @@ namespace Microsoft.PowerShell.Commands { if (!Platform.IsWindows) { - // For non-Windows platform, treat it as a file. Just delete it. - try - { - File.Delete(junctionPath); - return true; - } - catch - { - return false; - } + // For non-Windows platform, treat it as a file. Just delete it. + try + { + File.Delete(junctionPath); + return true; + } + catch + { + return false; + } } using (SafeHandle handle = OpenReparsePoint(junctionPath, FileDesiredAccess.GenericWrite)) { bool success = false; - int inOutBufferSize = ClrFacade.SizeOf(); + int inOutBufferSize = ClrFacade.SizeOf(); IntPtr outBuffer = Marshal.AllocHGlobal(inOutBufferSize); IntPtr inBuffer = Marshal.AllocHGlobal(inOutBufferSize); @@ -8531,7 +8498,7 @@ namespace Microsoft.PowerShell.Commands handle.DangerousAddRef(ref success); IntPtr dangerousHandle = handle.DangerousGetHandle(); int bytesReturned; - + // Do a FSCTL_GET_REPARSE_POINT first because the ReparseTag could be // IO_REPARSE_TAG_MOUNT_POINT or IO_REPARSE_TAG_SYMLINK. // Using the wrong one results in mismatched-tag error. @@ -8539,7 +8506,7 @@ namespace Microsoft.PowerShell.Commands REPARSE_GUID_DATA_BUFFER junctionData = new REPARSE_GUID_DATA_BUFFER(); ClrFacade.StructureToPtr(junctionData, outBuffer, false); - result = DeviceIoControl(dangerousHandle, FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, + result = DeviceIoControl(dangerousHandle, FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, outBuffer, inOutBufferSize, out bytesReturned, IntPtr.Zero); if (!result) { @@ -8547,7 +8514,7 @@ namespace Microsoft.PowerShell.Commands throw new Win32Exception(lastError); } - junctionData = ClrFacade.PtrToStructure(outBuffer); + junctionData = ClrFacade.PtrToStructure(outBuffer); junctionData.ReparseDataLength = 0; junctionData.DataBuffer = new char[MAX_REPARSE_SIZE]; @@ -8588,7 +8555,7 @@ namespace Microsoft.PowerShell.Commands #if UNIX throw new PlatformNotSupportedException(); #else - return WinOpenReparsePoint(reparsePoint,accessMode); + return WinOpenReparsePoint(reparsePoint, accessMode); #endif } @@ -8611,7 +8578,7 @@ namespace Microsoft.PowerShell.Commands } } -#endregion + #endregion } namespace System.Management.Automation.Internal @@ -8763,7 +8730,7 @@ namespace System.Management.Automation.Internal // the code above seems cleaner and more robust than the IAttachmentExecute approach } - static class NativeMethods + private static class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } @@ -8781,7 +8748,7 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "AlternateStreamNativeData.Name")] internal static extern SafeFindHandle FindFirstStreamW( string lpFileName, StreamInfoLevels InfoLevel, - [In, Out, MarshalAs(UnmanagedType.LPStruct)] + [In, Out, MarshalAs(UnmanagedType.LPStruct)] AlternateStreamNativeData lpFindStreamData, uint dwFlags); [DllImport(PinvokeDllNames.FindNextStreamDllName, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] @@ -8789,7 +8756,7 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "AlternateStreamNativeData.Name")] internal static extern bool FindNextStreamW( SafeFindHandle hndFindFile, - [In, Out, MarshalAs(UnmanagedType.LPStruct)] + [In, Out, MarshalAs(UnmanagedType.LPStruct)] AlternateStreamNativeData lpFindStreamData); } @@ -8839,9 +8806,9 @@ namespace System.Management.Automation.Internal #region PSCopyToSessionHelper internal const string PSCopyToSessionHelperName = @"PSCopyToSessionHelper"; - private static string DriveMaxSizeErrorFormatString = FileSystemProviderStrings.DriveMaxSizeError; - private static string PSCopyToSessionHelperDefinition = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]", DriveMaxSizeErrorFormatString); - private static string PSCopyToSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateUserDrive()]", DriveMaxSizeErrorFormatString); + private static string s_driveMaxSizeErrorFormatString = FileSystemProviderStrings.DriveMaxSizeError; + private static string s_PSCopyToSessionHelperDefinition = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]", s_driveMaxSizeErrorFormatString); + private static string s_PSCopyToSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateUserDrive()]", s_driveMaxSizeErrorFormatString); private const string PSCopyToSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")] @@ -9281,15 +9248,15 @@ namespace System.Management.Automation.Internal }} "; - private static string PSCopyToSessionHelper = functionToken + PSCopyToSessionHelperName + @" + private static string s_PSCopyToSessionHelper = functionToken + PSCopyToSessionHelperName + @" { - " + PSCopyToSessionHelperDefinition + @" + " + s_PSCopyToSessionHelperDefinition + @" } "; - private static Hashtable PSCopyToSessionHelperFunction = new Hashtable() { + private static Hashtable s_PSCopyToSessionHelperFunction = new Hashtable() { {nameToken, PSCopyToSessionHelperName}, - {definitionToken, PSCopyToSessionHelperDefinitionRestricted} + {definitionToken, s_PSCopyToSessionHelperDefinitionRestricted} }; #endregion @@ -9297,8 +9264,8 @@ namespace System.Management.Automation.Internal #region PSCopyFromSessionHelper internal const string PSCopyFromSessionHelperName = @"PSCopyFromSessionHelper"; - private static string PSCopyFromSessionHelperDefinition = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]"); - private static string PSCopyFromSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateUserDrive()]"); + private static string s_PSCopyFromSessionHelperDefinition = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]"); + private static string s_PSCopyFromSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateUserDrive()]"); private const string PSCopyFromSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileFromRemoteSession"", Mandatory=$true)] @@ -9766,13 +9733,13 @@ namespace System.Management.Automation.Internal internal static string PSCopyFromSessionHelper = functionToken + PSCopyFromSessionHelperName + @" { - " + PSCopyFromSessionHelperDefinition + @" + " + s_PSCopyFromSessionHelperDefinition + @" } "; - private static Hashtable PSCopyFromSessionHelperFunction = new Hashtable() { + private static Hashtable s_PSCopyFromSessionHelperFunction = new Hashtable() { {nameToken, PSCopyFromSessionHelperName}, - {definitionToken, PSCopyFromSessionHelperDefinitionRestricted} + {definitionToken, s_PSCopyFromSessionHelperDefinitionRestricted} }; #endregion @@ -9781,7 +9748,7 @@ namespace System.Management.Automation.Internal internal const string PSCopyRemoteUtilsName = @"PSCopyRemoteUtils"; internal static string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); - private static string PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); + private static string s_PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); private const string PSCopyRemoteUtilsDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSRemoteDirectoryExist"", Mandatory=$true)] @@ -9939,24 +9906,24 @@ namespace System.Management.Automation.Internal } "; - internal static Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { + internal static Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { {nameToken, PSCopyRemoteUtilsName}, - {definitionToken, PSCopyRemoteUtilsDefinitionRestricted} + {definitionToken, s_PSCopyRemoteUtilsDefinitionRestricted} }; #endregion - internal static string AllCopyToRemoteScripts = PSCopyToSessionHelper + PSCopyRemoteUtils; + internal static string AllCopyToRemoteScripts = s_PSCopyToSessionHelper + PSCopyRemoteUtils; internal static IEnumerable GetAllCopyToRemoteScriptFunctions() { - yield return PSCopyToSessionHelperFunction; + yield return s_PSCopyToSessionHelperFunction; yield return PSCopyRemoteUtilsFunction; } internal static string AllCopyFromRemoteScripts = PSCopyFromSessionHelper + PSCopyRemoteUtils; internal static IEnumerable GetAllCopyFromRemoteScriptFunctions() { - yield return PSCopyFromSessionHelperFunction; + yield return s_PSCopyFromSessionHelperFunction; yield return PSCopyRemoteUtilsFunction; } } diff --git a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs index a60036238..690965074 100644 --- a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs +++ b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs @@ -47,7 +47,7 @@ namespace Microsoft.PowerShell.Commands public void GetSecurityDescriptor(string path, AccessControlSections sections) { - ObjectSecurity sd=null; + ObjectSecurity sd = null; path = NormalizePath(path); if (String.IsNullOrEmpty(path)) @@ -76,7 +76,7 @@ namespace Microsoft.PowerShell.Commands } catch (System.Security.SecurityException e) { - WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); } finally { @@ -108,7 +108,7 @@ namespace Microsoft.PowerShell.Commands /// securitydescriptor is null. /// public void SetSecurityDescriptor( - string path, + string path, ObjectSecurity securityDescriptor) { if (String.IsNullOrEmpty(path)) @@ -174,10 +174,10 @@ namespace Microsoft.PowerShell.Commands // Try to set the entire security descriptor SetSecurityDescriptor(path, sd, AccessControlSections.All); } - catch(PrivilegeNotHeldException) + catch (PrivilegeNotHeldException) { // Get the security descriptor of the destination path - ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl(); + ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl(); Type ntAccountType = typeof(System.Security.Principal.NTAccount); AccessControlSections sections = AccessControlSections.All; @@ -194,13 +194,13 @@ namespace Microsoft.PowerShell.Commands // If they didn't modify the owner, don't try to set that section. if (sd.GetOwner(ntAccountType) == existingDescriptor.GetOwner(ntAccountType)) { - sections &= ~ AccessControlSections.Owner; + sections &= ~AccessControlSections.Owner; } // If they didn't modify the group, don't try to set that section. if (sd.GetGroup(ntAccountType) == existingDescriptor.GetGroup(ntAccountType)) { - sections &= ~ AccessControlSections.Group; + sections &= ~AccessControlSections.Group; } // Try to set the security descriptor again, this time with a reduced set @@ -324,22 +324,22 @@ namespace Microsoft.PowerShell.Commands { ObjectSecurity sd = null; - switch(itemType) + switch (itemType) { - case ItemType.File: - sd = new FileSecurity(); - break; + case ItemType.File: + sd = new FileSecurity(); + break; - case ItemType.Directory: - sd = new DirectorySecurity(); - break; + case ItemType.Directory: + sd = new DirectorySecurity(); + break; } return sd; } private static ErrorRecord CreateErrorRecord(string path, - string errorId) + string errorId) { string message = null; @@ -355,7 +355,6 @@ namespace Microsoft.PowerShell.Commands } #endregion ISecurityDescriptorCmdletProvider members - } } diff --git a/src/System.Management.Automation/namespaces/FunctionProvider.cs b/src/System.Management.Automation/namespaces/FunctionProvider.cs index b7bb47773..0e7fbefb6 100644 --- a/src/System.Management.Automation/namespaces/FunctionProvider.cs +++ b/src/System.Management.Automation/namespaces/FunctionProvider.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -13,7 +13,6 @@ using System.Management.Automation.Provider; namespace Microsoft.PowerShell.Commands { - /// /// This provider is the data accessor for shell functions. It uses /// the SessionStateProviderBase as the base class to produce a view on @@ -39,8 +38,8 @@ namespace Microsoft.PowerShell.Commands /// The constructor for the provider that exposes variables to the user /// as drives. /// - public FunctionProvider () - { + public FunctionProvider() + { } // constructor #endregion Constructor @@ -55,11 +54,11 @@ namespace Microsoft.PowerShell.Commands /// An array of a single PSDriveInfo object representing the functions drive. /// /// - protected override Collection InitializeDefaultDrives () + protected override Collection InitializeDefaultDrives() { string description = SessionStateStrings.FunctionDriveDescription; - PSDriveInfo functionDrive = + PSDriveInfo functionDrive = new PSDriveInfo( DriveNames.FunctionDrive, ProviderInfo, @@ -174,7 +173,7 @@ namespace Microsoft.PowerShell.Commands !String.IsNullOrEmpty(name), "The caller should verify this parameter"); - FunctionProviderDynamicParameters dynamicParameters = + FunctionProviderDynamicParameters dynamicParameters = DynamicParameters as FunctionProviderDynamicParameters; CommandInfo modifiedItem = null; @@ -281,7 +280,7 @@ namespace Microsoft.PowerShell.Commands /// The name of the function to remove from session state. /// /// - internal override void RemoveSessionStateItem (string name) + internal override void RemoveSessionStateItem(string name) { Dbg.Diagnostics.Assert( !String.IsNullOrEmpty(name), @@ -321,7 +320,7 @@ namespace Microsoft.PowerShell.Commands { value = function.ScriptBlock; } - + return value; } // GetValueOfItem @@ -334,7 +333,7 @@ namespace Microsoft.PowerShell.Commands /// session state. /// /// - internal override IDictionary GetSessionStateTable () + internal override IDictionary GetSessionStateTable() { return SessionState.Internal.GetFunctionTable(); } // GetSessionStateTable @@ -379,7 +378,6 @@ namespace Microsoft.PowerShell.Commands } #endregion protected members - } // FunctionProvider /// @@ -394,14 +392,14 @@ namespace Microsoft.PowerShell.Commands [Parameter] public ScopedItemOptions Options { - get { return options; } - set + get { return _options; } + set { - optionsSet = true; - options = value; + _optionsSet = true; + _options = value; } } - private ScopedItemOptions options = ScopedItemOptions.None; + private ScopedItemOptions _options = ScopedItemOptions.None; /// @@ -410,9 +408,9 @@ namespace Microsoft.PowerShell.Commands /// internal bool OptionsSet { - get { return optionsSet; } + get { return _optionsSet; } } - private bool optionsSet; + private bool _optionsSet; } } diff --git a/src/System.Management.Automation/namespaces/IContentProvider.cs b/src/System.Management.Automation/namespaces/IContentProvider.cs index 9bffafc1b..1cf6423c1 100644 --- a/src/System.Management.Automation/namespaces/IContentProvider.cs +++ b/src/System.Management.Automation/namespaces/IContentProvider.cs @@ -159,10 +159,8 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object ClearContentDynamicParameters(string path); - } // IContentCmdletProvider #endregion IContentCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs index 80e88555c..427e5850b 100644 --- a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs +++ b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs @@ -103,7 +103,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object NewPropertyDynamicParameters( - string path, + string path, string propertyName, string propertyTypeName, object value); @@ -162,9 +162,9 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object RemovePropertyDynamicParameters( - string path, + string path, string propertyName); - + /// /// Renames a property of the item at the specified path /// @@ -229,7 +229,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object RenamePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationProperty); @@ -306,7 +306,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object CopyPropertyDynamicParameters( - string sourcePath, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty); @@ -383,13 +383,12 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object MovePropertyDynamicParameters( - string sourcePath, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty); } // IDynamicPropertyCmdletProvider #endregion IDynamicPropertyCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/IPermissionProvider.cs b/src/System.Management.Automation/namespaces/IPermissionProvider.cs index 73b603f8c..5c256eb7d 100644 --- a/src/System.Management.Automation/namespaces/IPermissionProvider.cs +++ b/src/System.Management.Automation/namespaces/IPermissionProvider.cs @@ -7,7 +7,7 @@ using System.Security.AccessControl; namespace System.Management.Automation.Provider { #region ISecurityDescriptorCmdletProvider - + /// /// Provides an interface that allows simplified interaction /// with namespaces that support security descriptors. The methods @@ -67,9 +67,9 @@ namespace System.Management.Automation.Provider /// /// void SetSecurityDescriptor( - string path, + string path, ObjectSecurity securityDescriptor); - + /// /// Creates a new empty security descriptor of the same type as /// the item specified by the path. For example, if "path" points @@ -121,7 +121,5 @@ namespace System.Management.Automation.Provider AccessControlSections includeSections); } // ISecurityDescriptorCmdletProvider - #endregion ISecurityDescriptorCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs index 517f30088..6f95e873d 100644 --- a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs +++ b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs @@ -91,7 +91,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object GetPropertyDynamicParameters( - string path, + string path, Collection providerSpecificPickList); /// @@ -157,7 +157,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object SetPropertyDynamicParameters( - string path, + string path, PSObject propertyValue); /// @@ -218,13 +218,11 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// object ClearPropertyDynamicParameters( - string path, + string path, Collection propertyToClear); - } // IPropertyCmdletProvider #endregion IPropertyCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/ItemProviderBase.cs b/src/System.Management.Automation/namespaces/ItemProviderBase.cs index c85cd8516..f3078aecb 100644 --- a/src/System.Management.Automation/namespaces/ItemProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ItemProviderBase.cs @@ -144,8 +144,8 @@ namespace System.Management.Automation.Provider /// /// internal object SetItemDynamicParameters( - string path, - object value, + string path, + object value, CmdletProviderContext context) { Context = context; @@ -202,14 +202,14 @@ namespace System.Management.Automation.Provider /// /// internal object ClearItemDynamicParameters( - string path, + string path, CmdletProviderContext context) { Context = context; return ClearItemDynamicParameters(path); } // ClearItemDynamicParameters - - + + /// /// Internal wrapper for the InvokeDefaultAction protected method. It is called instead /// of the protected method that is overridden by derived classes so that the @@ -236,7 +236,7 @@ namespace System.Management.Automation.Provider InvokeDefaultAction(path); } // InvokeDefaultAction - + /// /// Gives the provider to attach additional parameters to /// the invoke-item cmdlet. @@ -260,7 +260,7 @@ namespace System.Management.Automation.Provider /// /// internal object InvokeDefaultActionDynamicParameters( - string path, + string path, CmdletProviderContext context) { Context = context; @@ -285,7 +285,7 @@ namespace System.Management.Automation.Provider /// True if the item exists, false otherwise. /// /// - internal bool ItemExists (string path, CmdletProviderContext context) + internal bool ItemExists(string path, CmdletProviderContext context) { Context = context; @@ -296,7 +296,7 @@ namespace System.Management.Automation.Provider { // Some providers don't expect non-valid path elements, and instead // throw an exception here. - itemExists = ItemExists (path); + itemExists = ItemExists(path); } catch (Exception e) { @@ -329,12 +329,12 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// /// - internal object ItemExistsDynamicParameters ( + internal object ItemExistsDynamicParameters( string path, CmdletProviderContext context) { Context = context; - return ItemExistsDynamicParameters (path); + return ItemExistsDynamicParameters(path); } // ItemExistsDynamicParameters /// @@ -363,13 +363,13 @@ namespace System.Management.Automation.Provider /// and ensure that the path does not refer to a device. /// /// - internal bool IsValidPath (string path, CmdletProviderContext context) + internal bool IsValidPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method - return IsValidPath (path); + return IsValidPath(path); } // IsValidPath /// @@ -627,7 +627,7 @@ namespace System.Management.Automation.Provider /// the path represents an item that is hidden from the user and Force is set to false. /// protected virtual void InvokeDefaultAction( - string path) + string path) { using (PSTransactionManager.GetEngineProtectionScope()) { @@ -774,10 +774,8 @@ namespace System.Management.Automation.Provider } // IsValidPath #endregion Protected methods - } // ItemCmdletProvider #endregion ItemCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 7b09022e9..523a85170 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -28,7 +29,7 @@ namespace System.Management.Automation [Dbg.TraceSourceAttribute( "LocationGlobber", "The location globber converts PowerShell paths with glob characters to zero or more paths.")] - private static Dbg.PSTraceSource tracer = + private static Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("LocationGlobber", "The location globber converts PowerShell paths with glob characters to zero or more paths."); @@ -38,7 +39,7 @@ namespace System.Management.Automation [Dbg.TraceSourceAttribute( "PathResolution", "Traces the path resolution algorithm.")] - private static Dbg.PSTraceSource pathResolutionTracer = + private static Dbg.PSTraceSource s_pathResolutionTracer = Dbg.PSTraceSource.GetTracer( "PathResolution", "Traces the path resolution algorithm.", @@ -67,7 +68,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.sessionState = sessionState; + _sessionState = sessionState; } // LocationGlobber(SessionState) #endregion Constructor @@ -131,7 +132,7 @@ namespace System.Management.Automation out CmdletProvider providerInstance) { CmdletProviderContext context = - new CmdletProviderContext(sessionState.Internal.ExecutionContext); + new CmdletProviderContext(_sessionState.Internal.ExecutionContext); return GetGlobbedMonadPathsFromMonadPath(path, allowNonexistingPaths, context, out providerInstance); } // GetGlobbedMonadPathsFromMonadPath @@ -214,7 +215,7 @@ namespace System.Management.Automation Collection result; - using (pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to MSH path", path)) + using (s_pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to MSH path", path)) { TraceFilters(context); @@ -222,7 +223,7 @@ namespace System.Management.Automation if (IsHomePath(path)) { - using (pathResolutionTracer.TraceScope("Resolving HOME relative path.")) + using (s_pathResolutionTracer.TraceScope("Resolving HOME relative path.")) { path = GetHomeRelativePath(path); } @@ -268,7 +269,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", path); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", path); throw pathNotFound; } @@ -285,7 +286,7 @@ namespace System.Management.Automation ) { // Check the provider capabilities before globbing - providerInstance = sessionState.Internal.GetProviderInstance(providerId); + providerInstance = _sessionState.Internal.GetProviderInstance(providerId); ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider; ItemCmdletProvider itemProvider = providerInstance as ItemCmdletProvider; @@ -298,7 +299,7 @@ namespace System.Management.Automation ProviderCapabilities.ExpandWildcards, providerInstance.ProviderInfo)) { - pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider."); + s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider."); // Only do the expansion if the path actually contains wildcard // characters. @@ -314,7 +315,7 @@ namespace System.Management.Automation } else { - pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine."); + s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine."); if (containerCmdletProvider != null) { @@ -341,7 +342,7 @@ namespace System.Management.Automation { if (itemProvider != null) { - if (allowNonexistingPaths|| itemProvider.ItemExists(providerPath, context)) + if (allowNonexistingPaths || itemProvider.ItemExists(providerPath, context)) { stringResult.Add(providerPath); } @@ -365,7 +366,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", providerPath); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", providerPath); throw pathNotFound; } @@ -393,18 +394,18 @@ namespace System.Management.Automation if (isProviderDirectPath) { - pathResolutionTracer.WriteLine("Path is PROVIDER-DIRECT"); + s_pathResolutionTracer.WriteLine("Path is PROVIDER-DIRECT"); providerPath = path; - providerId = sessionState.Path.CurrentLocation.Provider.Name; + providerId = _sessionState.Path.CurrentLocation.Provider.Name; } else if (isProviderQualifiedPath) { - pathResolutionTracer.WriteLine("Path is PROVIDER-QUALIFIED"); + s_pathResolutionTracer.WriteLine("Path is PROVIDER-QUALIFIED"); providerPath = ParseProviderPath(path, out providerId); } - pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", providerPath); - pathResolutionTracer.WriteLine("Provider: {0}", providerId); + s_pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", providerPath); + s_pathResolutionTracer.WriteLine("Provider: {0}", providerId); Collection stringResult = ResolveProviderPathFromProviderPath( providerPath, @@ -444,8 +445,8 @@ namespace System.Management.Automation escapedPath); } - result.Add(new PathInfo(drive, providerInstance.ProviderInfo, constructedProviderPath, sessionState)); - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", constructedProviderPath); + result.Add(new PathInfo(drive, providerInstance.ProviderInfo, constructedProviderPath, _sessionState)); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", constructedProviderPath); } return result; @@ -462,7 +463,7 @@ namespace System.Management.Automation Collection result = new Collection(); - pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED"); + s_pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED"); string relativePath = GetDriveRootRelativePathFromPSPath(path, context, true, out drive, out providerInstance); @@ -475,14 +476,14 @@ namespace System.Management.Automation "There should always be a way to generate a provider path for a " + "given path"); - pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", relativePath); - pathResolutionTracer.WriteLine("Drive: {0}", drive.Name); - pathResolutionTracer.WriteLine("Provider: {0}", drive.Provider); + s_pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", relativePath); + s_pathResolutionTracer.WriteLine("Drive: {0}", drive.Name); + s_pathResolutionTracer.WriteLine("Provider: {0}", drive.Provider); // Associate the drive with the context context.Drive = drive; - providerInstance = sessionState.Internal.GetContainerProviderInstance(drive.Provider); + providerInstance = _sessionState.Internal.GetContainerProviderInstance(drive.Provider); ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider; ItemCmdletProvider itemProvider = providerInstance as ItemCmdletProvider; @@ -501,18 +502,18 @@ namespace System.Management.Automation userPath = GetDriveQualifiedPath(relativePath, drive); itemPath = GetProviderPath(path, context); } - pathResolutionTracer.WriteLine("PROVIDER path: {0}", itemPath); + s_pathResolutionTracer.WriteLine("PROVIDER path: {0}", itemPath); Collection stringResult = new Collection(); - if (! context.SuppressWildcardExpansion) + if (!context.SuppressWildcardExpansion) { // See if the provider will expand the wildcard if (CmdletProviderManagementIntrinsics.CheckProviderCapabilities( ProviderCapabilities.ExpandWildcards, provider)) { - pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider."); + s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the provider."); // Only do the expansion if the path actually contains wildcard // characters. @@ -532,7 +533,7 @@ namespace System.Management.Automation } else { - pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine."); + s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine."); // Now perform the globbing stringResult = @@ -573,7 +574,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", path); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", path); throw pathNotFound; } @@ -610,9 +611,9 @@ namespace System.Management.Automation expandedPath, drive); } - - result.Add(new PathInfo(drive, provider, userPath, sessionState)); - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", userPath); + + result.Add(new PathInfo(drive, provider, userPath, _sessionState)); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", userPath); } return result; @@ -704,7 +705,7 @@ namespace System.Management.Automation } CmdletProviderContext context = - new CmdletProviderContext(sessionState.Internal.ExecutionContext); + new CmdletProviderContext(_sessionState.Internal.ExecutionContext); return GetGlobbedProviderPathsFromMonadPath(path, allowNonexistingPaths, context, out provider, out providerInstance); } // GetGlobbedProviderPathsFromMonadPath @@ -799,7 +800,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("context"); } - using (pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to PROVIDER-INTERNAL path", path)) + using (s_pathResolutionTracer.TraceScope("Resolving MSH path \"{0}\" to PROVIDER-INTERNAL path", path)) { TraceFilters(context); @@ -815,9 +816,9 @@ namespace System.Management.Automation if (providerPath == null) { providerInstance = null; - tracer.WriteLine("provider returned a null path so return an empty array"); + s_tracer.WriteLine("provider returned a null path so return an empty array"); - pathResolutionTracer.WriteLine("Provider '{0}' returned null", provider); + s_pathResolutionTracer.WriteLine("Provider '{0}' returned null", provider); return new Collection(); } @@ -920,7 +921,7 @@ namespace System.Management.Automation } CmdletProviderContext context = - new CmdletProviderContext(sessionState.Internal.ExecutionContext); + new CmdletProviderContext(_sessionState.Internal.ExecutionContext); Collection results = GetGlobbedProviderPathsFromProviderPath( @@ -1027,7 +1028,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException("context"); } - using (pathResolutionTracer.TraceScope("Resolving PROVIDER-INTERNAL path \"{0}\" to PROVIDER-INTERNAL path", path)) + using (s_pathResolutionTracer.TraceScope("Resolving PROVIDER-INTERNAL path \"{0}\" to PROVIDER-INTERNAL path", path)) { TraceFilters(context); @@ -1166,7 +1167,7 @@ namespace System.Management.Automation } CmdletProviderContext context = - new CmdletProviderContext(sessionState.Internal.ExecutionContext); + new CmdletProviderContext(_sessionState.Internal.ExecutionContext); PSDriveInfo drive = null; provider = null; @@ -1362,7 +1363,7 @@ namespace System.Management.Automation // First check to see if the path starts with a ~ (home) if (IsHomePath(path)) { - using (pathResolutionTracer.TraceScope("Resolving HOME relative path.")) + using (s_pathResolutionTracer.TraceScope("Resolving HOME relative path.")) { path = GetHomeRelativePath(path); } @@ -1371,34 +1372,34 @@ namespace System.Management.Automation // Now check to see if it is a provider-direct path (starts with // or \\) if (IsProviderDirectPath(path)) { - pathResolutionTracer.WriteLine("Path is PROVIDER-DIRECT"); + s_pathResolutionTracer.WriteLine("Path is PROVIDER-DIRECT"); // just return the path directly using the current provider result = path; drive = null; - provider = sessionState.Path.CurrentLocation.Provider; + provider = _sessionState.Path.CurrentLocation.Provider; - pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", result); - pathResolutionTracer.WriteLine("Provider: {0}", provider); + s_pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", result); + s_pathResolutionTracer.WriteLine("Provider: {0}", provider); } else if (IsProviderQualifiedPath(path)) { - pathResolutionTracer.WriteLine("Path is PROVIDER-QUALIFIED"); + s_pathResolutionTracer.WriteLine("Path is PROVIDER-QUALIFIED"); string providerId = null; result = ParseProviderPath(path, out providerId); drive = null; // Get the provider info - provider = sessionState.Internal.GetSingleProvider(providerId); + provider = _sessionState.Internal.GetSingleProvider(providerId); - pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", result); - pathResolutionTracer.WriteLine("Provider: {0}", provider); + s_pathResolutionTracer.WriteLine("PROVIDER-INTERNAL path: {0}", result); + s_pathResolutionTracer.WriteLine("Provider: {0}", provider); } else { - pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED"); + s_pathResolutionTracer.WriteLine("Path is DRIVE-QUALIFIED"); CmdletProvider providerInstance = null; string relativePath = GetDriveRootRelativePathFromPSPath(path, context, false, out drive, out providerInstance); @@ -1412,9 +1413,9 @@ namespace System.Management.Automation "There should always be a way to generate a provider path for a " + "given path"); - pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", relativePath); - pathResolutionTracer.WriteLine("Drive: {0}", drive.Name); - pathResolutionTracer.WriteLine("Provider: {0}", drive.Provider); + s_pathResolutionTracer.WriteLine("DRIVE-RELATIVE path: {0}", relativePath); + s_pathResolutionTracer.WriteLine("Drive: {0}", drive.Name); + s_pathResolutionTracer.WriteLine("Provider: {0}", drive.Provider); // Associate the drive with the context @@ -1429,10 +1430,9 @@ namespace System.Management.Automation result = GetProviderSpecificPath(drive, relativePath, context); } provider = drive.Provider; - } - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", result); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", result); // If this is a private provider, don't allow access to it directly from the runspace. if ((provider != null) && @@ -1447,7 +1447,7 @@ namespace System.Management.Automation (sessionStateProvider.Visibility == SessionStateEntryVisibility.Private) && (context.MyInvocation.CommandOrigin == CommandOrigin.Runspace)) { - pathResolutionTracer.WriteLine("Provider is private: {0}", provider.Name); + s_pathResolutionTracer.WriteLine("Provider is private: {0}", provider.Name); throw new ProviderNotFoundException( provider.Name, @@ -1562,9 +1562,8 @@ namespace System.Management.Automation providerId = path.Substring(0, index); - tracer.WriteLine("providerId = {0}", providerId); + s_tracer.WriteLine("providerId = {0}", providerId); } - } while (false); return result; @@ -1674,11 +1673,9 @@ namespace System.Management.Automation result = true; } - } while (false); return result; - } // IsAbsolutePath /// @@ -1710,15 +1707,15 @@ namespace System.Management.Automation bool result = false; - if (sessionState.Drive.Current != null) + if (_sessionState.Drive.Current != null) { - driveName = sessionState.Drive.Current.Name; + driveName = _sessionState.Drive.Current.Name; } else { driveName = null; } - + do { if (path.Length == 0) @@ -1770,7 +1767,6 @@ namespace System.Management.Automation result = true; } - } while (false); #if DEBUG @@ -1781,14 +1777,13 @@ namespace System.Management.Automation "The drive name should always have a value, " + "the default is the current working drive"); - tracer.WriteLine( + s_tracer.WriteLine( "driveName = {0}", driveName); } #endif return result; - } // IsAbsolutePath #endregion Path manipulation @@ -1800,7 +1795,7 @@ namespace System.Management.Automation /// /// The instance of session state on which this globber acts. /// - private SessionState sessionState; + private SessionState _sessionState; /// /// Removs the back tick "`" from any of the glob characters in the path. @@ -1820,14 +1815,14 @@ namespace System.Management.Automation /// private static string RemoveGlobEscaping(string path) { - if (path == null) - { - throw PSTraceSource.NewArgumentNullException("path"); - } + if (path == null) + { + throw PSTraceSource.NewArgumentNullException("path"); + } - string result = WildcardPattern.Unescape(path); + string result = WildcardPattern.Unescape(path); - return result; + return result; } // RemoveGlobEscaping #region Path manipulation methods @@ -1884,9 +1879,9 @@ namespace System.Management.Automation StringLiterals.Global, StringComparison.OrdinalIgnoreCase) == 0) { - tracer.WriteLine("match found: {0}", StringLiterals.Global); + s_tracer.WriteLine("match found: {0}", StringLiterals.Global); result = true; - scope = sessionState.Internal.GlobalScope; + scope = _sessionState.Internal.GlobalScope; } // globalScope // Is it the local scope? @@ -1896,9 +1891,9 @@ namespace System.Management.Automation StringLiterals.Local, StringComparison.OrdinalIgnoreCase) == 0) { - tracer.WriteLine("match found: {0}", driveName); + s_tracer.WriteLine("match found: {0}", driveName); result = true; - scope = sessionState.Internal.CurrentScope; + scope = _sessionState.Internal.CurrentScope; } // currentScope else { @@ -1998,9 +1993,9 @@ namespace System.Management.Automation workingDriveForPath = null; string driveName = null; - if (sessionState.Drive.Current != null) + if (_sessionState.Drive.Current != null) { - driveName = sessionState.Drive.Current.Name; + driveName = _sessionState.Drive.Current.Name; } // Check to see if the path is relative or absolute @@ -2012,7 +2007,7 @@ namespace System.Management.Automation driveName != null, "IsAbsolutePath should be returning the drive name"); - tracer.WriteLine( + s_tracer.WriteLine( "Drive Name: {0}", driveName); @@ -2021,21 +2016,21 @@ namespace System.Management.Automation // name does not exist. Just let the exception propogate out. try { - workingDriveForPath = sessionState.Drive.Get(driveName); + workingDriveForPath = _sessionState.Drive.Get(driveName); } - catch(DriveNotFoundException) + catch (DriveNotFoundException) { // Check to see if it is a path relative to the // current drive's root. This is true when a drive root // appears to be a drive (like HTTP://). The drive will not // actually exist, but this is not an absolute path. - if (sessionState.Drive.Current == null) + if (_sessionState.Drive.Current == null) { throw; } - string normalizedRoot = sessionState.Drive.Current.Root.Replace( + string normalizedRoot = _sessionState.Drive.Current.Root.Replace( StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); if (normalizedRoot.IndexOf(":", StringComparison.CurrentCulture) >= 0) @@ -2047,7 +2042,7 @@ namespace System.Management.Automation path = path.Substring(normalizedRoot.Length); path = path.TrimStart(StringLiterals.DefaultPathSeparator); path = StringLiterals.DefaultPathSeparator + path; - workingDriveForPath = sessionState.Drive.Current; + workingDriveForPath = _sessionState.Drive.Current; } } @@ -2079,7 +2074,7 @@ namespace System.Management.Automation else { // it's a relative path, so the working drive is the current drive - workingDriveForPath = sessionState.Drive.Current; + workingDriveForPath = _sessionState.Drive.Current; } if (workingDriveForPath == null) @@ -2090,7 +2085,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", path); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", path); throw pathNotFound; } @@ -2098,7 +2093,7 @@ namespace System.Management.Automation try { providerInstance = - sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider); + _sessionState.Internal.GetContainerProviderInstance(workingDriveForPath.Provider); // Add the drive info to the context so that downstream methods // have access to it. @@ -2122,7 +2117,6 @@ namespace System.Management.Automation providerInstance = null; return ""; } - } // GetDriveRootRelativePathFromPSPath private string GetDriveRootRelativePathFromProviderPath( @@ -2133,8 +2127,8 @@ namespace System.Management.Automation { string childPath = ""; - CmdletProvider providerInstance = - sessionState.Internal.GetContainerProviderInstance(drive.Provider); + CmdletProvider providerInstance = + _sessionState.Internal.GetContainerProviderInstance(drive.Provider); NavigationCmdletProvider navigationProvider = providerInstance as NavigationCmdletProvider; // Normalize the paths @@ -2146,12 +2140,12 @@ namespace System.Management.Automation // Keep on lopping off children until the the remaining path // is the drive root. - while((! String.IsNullOrEmpty(providerPath)) && - (! providerPath.Equals(driveRoot, StringComparison.OrdinalIgnoreCase))) + while ((!String.IsNullOrEmpty(providerPath)) && + (!providerPath.Equals(driveRoot, StringComparison.OrdinalIgnoreCase))) { if (!String.IsNullOrEmpty(childPath)) { - childPath = sessionState.Internal.MakePath( + childPath = _sessionState.Internal.MakePath( providerInstance, navigationProvider.GetChildName(providerPath, context), childPath, @@ -2162,7 +2156,7 @@ namespace System.Management.Automation childPath = navigationProvider.GetChildName(providerPath, context); } - providerPath = sessionState.Internal.GetParentPath( + providerPath = _sessionState.Internal.GetParentPath( providerInstance, providerPath, drive.Root, @@ -2292,7 +2286,7 @@ namespace System.Management.Automation path = path.Substring(1); - tracer.WriteLine( + s_tracer.WriteLine( "path = {0}", path); } @@ -2327,14 +2321,14 @@ namespace System.Management.Automation // Use the provider to get the current path driveRootRelativeWorkingPath = - sessionState.Internal.GetParentPath( + _sessionState.Internal.GetParentPath( providerInstance, driveRootRelativeWorkingPath, drive.Root, context); } - tracer.WriteLine( + s_tracer.WriteLine( "Parent path = {0}", driveRootRelativeWorkingPath); @@ -2345,7 +2339,7 @@ namespace System.Management.Automation path.Substring( parentDirSymbolLength); - tracer.WriteLine( + s_tracer.WriteLine( "path = {0}", path); @@ -2364,7 +2358,7 @@ namespace System.Management.Automation path = path.Substring(1); } - tracer.WriteLine( + s_tracer.WriteLine( "path = {0}", path); @@ -2390,7 +2384,6 @@ namespace System.Management.Automation processedSomething = true; path = String.Empty; break; - } if (path.StartsWith(currentDirRelativeSymbolBackslash, StringComparison.Ordinal) || @@ -2398,7 +2391,7 @@ namespace System.Management.Automation { path = path.Substring(currentDirRelativeSymbolBackslash.Length); processedSomething = true; - tracer.WriteLine( + s_tracer.WriteLine( "path = {0}", path); @@ -2431,7 +2424,7 @@ namespace System.Management.Automation if (!String.IsNullOrEmpty(path)) { driveRootRelativeWorkingPath = - sessionState.Internal.MakePath( + _sessionState.Internal.MakePath( providerInstance, driveRootRelativeWorkingPath, path, @@ -2441,7 +2434,7 @@ namespace System.Management.Automation NavigationCmdletProvider navigationProvider = providerInstance as NavigationCmdletProvider; if (navigationProvider != null) { - string rootedPath = sessionState.Internal.MakePath(context.Drive.Root, driveRootRelativeWorkingPath, context); + string rootedPath = _sessionState.Internal.MakePath(context.Drive.Root, driveRootRelativeWorkingPath, context); string normalizedRelativePath = navigationProvider.ContractRelativePath(rootedPath, context.Drive.Root, false, context); if (!String.IsNullOrEmpty(normalizedRelativePath)) @@ -2455,7 +2448,7 @@ namespace System.Management.Automation driveRootRelativeWorkingPath = ""; } - tracer.WriteLine( + s_tracer.WriteLine( "result = {0}", driveRootRelativeWorkingPath); @@ -2527,7 +2520,7 @@ namespace System.Management.Automation // Trace the inputs drive.Trace(); - tracer.WriteLine( + s_tracer.WriteLine( "workingPath = {0}", workingPath); @@ -2536,7 +2529,7 @@ namespace System.Management.Automation try { result = - sessionState.Internal.MakePath( + _sessionState.Internal.MakePath( drive.Provider, result, workingPath, @@ -2757,18 +2750,18 @@ namespace System.Management.Automation if (context != null) { bool includePresent = context.Include != null && context.Include.Count > 0; - pathResolutionTracer.WriteLine("INCLUDE filter present: {0}", includePresent); + s_pathResolutionTracer.WriteLine("INCLUDE filter present: {0}", includePresent); bool excludePresent = context.Exclude != null && context.Exclude.Count > 0; - pathResolutionTracer.WriteLine("EXCLUDE filter present: {0}", excludePresent); + s_pathResolutionTracer.WriteLine("EXCLUDE filter present: {0}", excludePresent); contextContainsIncludeExclude = includePresent || excludePresent; contextContainsNoGlob = context.SuppressWildcardExpansion; - pathResolutionTracer.WriteLine("NOGLOB parameter present: {0}", contextContainsNoGlob); + s_pathResolutionTracer.WriteLine("NOGLOB parameter present: {0}", contextContainsNoGlob); } - pathResolutionTracer.WriteLine("Path contains wildcard characters: {0}", pathContainsGlobCharacters); + s_pathResolutionTracer.WriteLine("Path contains wildcard characters: {0}", pathContainsGlobCharacters); return (pathContainsGlobCharacters || contextContainsIncludeExclude) && (!contextContainsNoGlob); } // ShouldPerformGlobbing @@ -2888,13 +2881,13 @@ namespace System.Management.Automation { throw PSTraceSource.NewArgumentNullException("drive"); } - tracer.WriteLine("path = {0}", path); + s_tracer.WriteLine("path = {0}", path); NavigationCmdletProvider navigationProvider = provider as NavigationCmdletProvider; Collection result = new Collection(); - using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS")) + using (s_pathResolutionTracer.TraceScope("EXPANDING WILDCARDS")) { if (ShouldPerformGlobbing(path, context)) { @@ -2910,7 +2903,7 @@ namespace System.Management.Automation Stack leafElements = new Stack(); - using (pathResolutionTracer.TraceScope("Tokenizing path")) + using (s_pathResolutionTracer.TraceScope("Tokenizing path")) { // If the path contains glob characters then iterate through pulling the // leaf elements off and pushing them on to the leafElements stack until @@ -2938,9 +2931,9 @@ namespace System.Management.Automation break; } - tracer.WriteLine("Pushing leaf element: {0}", leafElement); + s_tracer.WriteLine("Pushing leaf element: {0}", leafElement); - pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); + s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); // Push the leaf element onto the leaf element stack for future use @@ -2983,12 +2976,12 @@ namespace System.Management.Automation path = String.Empty; } - tracer.WriteLine("New path: {0}", path); + s_tracer.WriteLine("New path: {0}", path); - pathResolutionTracer.WriteLine("Parent path: {0}", path); + s_pathResolutionTracer.WriteLine("Parent path: {0}", path); } - tracer.WriteLine("Base container path: {0}", path); + s_tracer.WriteLine("Base container path: {0}", path); // If no glob elements were found there must be an include and/or // exclude specified. Use the parent path to iterate over to @@ -3014,10 +3007,10 @@ namespace System.Management.Automation leafElements.Push(leafElement); - pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); + s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); } - pathResolutionTracer.WriteLine("Root path of resolution: {0}", path); + s_pathResolutionTracer.WriteLine("Root path of resolution: {0}", path); } // Once the container path with no glob characters are found store it @@ -3058,7 +3051,7 @@ namespace System.Management.Automation if (leafElements.Count > 0) { - using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers")) + using (s_pathResolutionTracer.TraceScope("Checking matches to ensure they are containers")) { int index = 0; @@ -3076,17 +3069,17 @@ namespace System.Management.Automation // Check to see if the matching item is a container if (navigationProvider != null && - !sessionState.Internal.IsItemContainer( + !_sessionState.Internal.IsItemContainer( resolvedPath, context)) { // If not, remove it from the collection - tracer.WriteLine( + s_tracer.WriteLine( "Removing {0} because it is not a container", dirs[index]); - pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); + s_pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); dirs.RemoveAt(index); } else if (navigationProvider == null) @@ -3100,7 +3093,7 @@ namespace System.Management.Automation } else { - pathResolutionTracer.WriteLine("{0} is a container", dirs[index]); + s_pathResolutionTracer.WriteLine("{0} is a container", dirs[index]); // If so, leave it and move on to the next one @@ -3118,7 +3111,7 @@ namespace System.Management.Automation foreach (string dir in dirs) { - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", dir); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", dir); result.Add(dir); } @@ -3167,10 +3160,10 @@ namespace System.Management.Automation unescapedPath); // Since we didn't do globbing, be sure the path exists - if (allowNonexistingPaths || + if (allowNonexistingPaths || provider.ItemExists(GetProviderPath(resolvedPath, context), context)) { - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", resolvedPath); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", resolvedPath); result.Add(resolvedPath); } else @@ -3181,7 +3174,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", path); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", path); throw pathNotFound; } @@ -3654,7 +3647,7 @@ namespace System.Management.Automation foreach (string dir in currentDirs) { - using (pathResolutionTracer.TraceScope("Expanding wildcards for items under '{0}'", dir)) + using (s_pathResolutionTracer.TraceScope("Expanding wildcards for items under '{0}'", dir)) { // Make sure to obey StopProcessing if (context.Stopping) @@ -3678,8 +3671,8 @@ namespace System.Management.Automation if (childNamesObjectArray == null) { - tracer.TraceError("GetChildNames returned a null array"); - pathResolutionTracer.WriteLine("No child names returned for '{0}'", dir); + s_tracer.TraceError("GetChildNames returned a null array"); + s_pathResolutionTracer.WriteLine("No child names returned for '{0}'", dir); continue; } @@ -3710,7 +3703,7 @@ namespace System.Management.Automation string parentPath = RemoveMshQualifier(mshQualifiedParentPath, drive); childPath = - sessionState.Internal. + _sessionState.Internal. MakePath( parentPath, child, @@ -3719,7 +3712,7 @@ namespace System.Management.Automation childPath = GetMshQualifiedPath(childPath, drive); } - tracer.WriteLine("Adding child path to dirs {0}", childPath); + s_tracer.WriteLine("Adding child path to dirs {0}", childPath); // -- If there are more leafElements, the current childPath will be treated as a container path later, // we should escape the childPath in case the actual childPath contains wildcard characters such as '[' or ']'. @@ -3734,7 +3727,7 @@ namespace System.Management.Automation } // if (StringContainsGlobCharacters(leafElement)) else { - tracer.WriteLine( + s_tracer.WriteLine( "LeafElement does not contain any glob characters so do a MakePath"); // Loop through the current dirs and add the leafElement to each of @@ -3742,7 +3735,7 @@ namespace System.Management.Automation foreach (string dir in currentDirs) { - using (pathResolutionTracer.TraceScope("Expanding intermediate containers under '{0}'", dir)) + using (s_pathResolutionTracer.TraceScope("Expanding intermediate containers under '{0}'", dir)) { // Make sure to obey StopProcessing if (context.Stopping) @@ -3762,7 +3755,7 @@ namespace System.Management.Automation string parentPath = RemoveMshQualifier(resolvedPath, drive); childPath = - sessionState.Internal. + _sessionState.Internal. MakePath( parentPath, backslashEscapedLeafElement, @@ -3772,21 +3765,19 @@ namespace System.Management.Automation } - if (sessionState.Internal.ItemExists(childPath, context)) + if (_sessionState.Internal.ItemExists(childPath, context)) { - tracer.WriteLine("Adding child path to dirs {0}", childPath); - pathResolutionTracer.WriteLine("Valid intermediate container: {0}", childPath); + s_tracer.WriteLine("Adding child path to dirs {0}", childPath); + s_pathResolutionTracer.WriteLine("Valid intermediate container: {0}", childPath); newDirs.Add(childPath); } } } // foreach (dir in currentDirs) - } // if (StringContainsGlobCharacters(leafElement)) return newDirs; - } // GenerateNewPSPathsWithGlobLeaf /// @@ -3889,13 +3880,13 @@ namespace System.Management.Automation if (changedPathOrFilter) { - if (tracer.IsEnabled) + if (s_tracer.IsEnabled) { - tracer.WriteLine("Provider converted path and filter."); - tracer.WriteLine("Original path: {0}", path); - tracer.WriteLine("Converted path: {0}", convertedPath); - tracer.WriteLine("Original filter: {0}", context.Filter); - tracer.WriteLine("Converted filter: {0}", convertedFilter); + s_tracer.WriteLine("Provider converted path and filter."); + s_tracer.WriteLine("Original path: {0}", path); + s_tracer.WriteLine("Converted path: {0}", convertedPath); + s_tracer.WriteLine("Original filter: {0}", context.Filter); + s_tracer.WriteLine("Converted filter: {0}", convertedFilter); } path = convertedPath; @@ -3904,11 +3895,11 @@ namespace System.Management.Automation NavigationCmdletProvider navigationProvider = provider as NavigationCmdletProvider; - tracer.WriteLine("path = {0}", path); + s_tracer.WriteLine("path = {0}", path); Collection result = new Collection(); - using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS")) + using (s_pathResolutionTracer.TraceScope("EXPANDING WILDCARDS")) { if (ShouldPerformGlobbing(path, context)) { @@ -3924,7 +3915,7 @@ namespace System.Management.Automation Stack leafElements = new Stack(); - using (pathResolutionTracer.TraceScope("Tokenizing path")) + using (s_pathResolutionTracer.TraceScope("Tokenizing path")) { // If the path contains glob characters then iterate through pulling the // leaf elements off and pushing them on to the leafElements stack until @@ -3952,9 +3943,9 @@ namespace System.Management.Automation break; } - tracer.WriteLine("Pushing leaf element: {0}", leafElement); + s_tracer.WriteLine("Pushing leaf element: {0}", leafElement); - pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); + s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); // Push the leaf element onto the leaf element stack for future use @@ -4011,11 +4002,11 @@ namespace System.Management.Automation path = String.Empty; } - tracer.WriteLine("New path: {0}", path); - pathResolutionTracer.WriteLine("Parent path: {0}", path); + s_tracer.WriteLine("New path: {0}", path); + s_pathResolutionTracer.WriteLine("Parent path: {0}", path); } - tracer.WriteLine("Base container path: {0}", path); + s_tracer.WriteLine("Base container path: {0}", path); // If no glob elements were found there must be an include and/or // exclude specified. Use the parent path to iterate over to @@ -4039,10 +4030,10 @@ namespace System.Management.Automation path = String.Empty; } leafElements.Push(leafElement); - pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); + s_pathResolutionTracer.WriteLine("Leaf element: {0}", leafElement); } - pathResolutionTracer.WriteLine("Root path of resolution: {0}", path); + s_pathResolutionTracer.WriteLine("Root path of resolution: {0}", path); } // Once the container path with no glob characters are found store it // so that it's children can be iterated over. @@ -4081,7 +4072,7 @@ namespace System.Management.Automation if (leafElements.Count > 0) { - using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers")) + using (s_pathResolutionTracer.TraceScope("Checking matches to ensure they are containers")) { int index = 0; @@ -4102,11 +4093,11 @@ namespace System.Management.Automation { // If not, remove it from the collection - tracer.WriteLine( + s_tracer.WriteLine( "Removing {0} because it is not a container", dirs[index]); - pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); + s_pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); dirs.RemoveAt(index); } else if (navigationProvider == null) @@ -4120,7 +4111,7 @@ namespace System.Management.Automation } else { - pathResolutionTracer.WriteLine("{0} is a container", dirs[index]); + s_pathResolutionTracer.WriteLine("{0} is a container", dirs[index]); // If so, leave it and move on to the next one @@ -4138,7 +4129,7 @@ namespace System.Management.Automation foreach (string dir in dirs) { - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", dir); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", dir); result.Add(dir); } @@ -4154,7 +4145,7 @@ namespace System.Management.Automation if (allowNonexistingPaths || provider.ItemExists(unescapedPath, context)) { - pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", unescapedPath); + s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", unescapedPath); result.Add(unescapedPath); } else @@ -4165,7 +4156,7 @@ namespace System.Management.Automation "PathNotFound", SessionStateStrings.PathNotFound); - pathResolutionTracer.TraceError("Item does not exist: {0}", path); + s_pathResolutionTracer.TraceError("Item does not exist: {0}", path); throw pathNotFound; } @@ -4301,7 +4292,7 @@ namespace System.Management.Automation foreach (string dir in currentDirs) { - using (pathResolutionTracer.TraceScope("Expanding wildcards for items under '{0}'", dir)) + using (s_pathResolutionTracer.TraceScope("Expanding wildcards for items under '{0}'", dir)) { // Make sure to obey StopProcessing if (context.Stopping) @@ -4316,9 +4307,9 @@ namespace System.Management.Automation if (childNamesObjectArray == null) { - tracer.TraceError("GetChildNames returned a null array"); + s_tracer.TraceError("GetChildNames returned a null array"); - pathResolutionTracer.WriteLine("No child names returned for '{0}'", dir); + s_pathResolutionTracer.WriteLine("No child names returned for '{0}'", dir); continue; } @@ -4347,7 +4338,7 @@ namespace System.Management.Automation context); } - tracer.WriteLine("Adding child path to dirs {0}", childPath); + s_tracer.WriteLine("Adding child path to dirs {0}", childPath); newDirs.Add(childPath); } @@ -4357,7 +4348,7 @@ namespace System.Management.Automation } // if (StringContainsGlobCharacters(leafElement)) else { - tracer.WriteLine( + s_tracer.WriteLine( "LeafElement does not contain any glob characters so do a MakePath"); // Loop through the current dirs and add the leafElement to each of @@ -4365,7 +4356,7 @@ namespace System.Management.Automation foreach (string dir in currentDirs) { - using (pathResolutionTracer.TraceScope("Expanding intermediate containers under '{0}'", dir)) + using (s_pathResolutionTracer.TraceScope("Expanding intermediate containers under '{0}'", dir)) { // Make sure to obey StopProcessing if (context.Stopping) @@ -4392,11 +4383,11 @@ namespace System.Management.Automation if (provider.ItemExists(childPath, context)) { - tracer.WriteLine("Adding child path to dirs {0}", childPath); + s_tracer.WriteLine("Adding child path to dirs {0}", childPath); newDirs.Add(childPath); - pathResolutionTracer.WriteLine("Valid intermediate container: {0}", childPath); + s_pathResolutionTracer.WriteLine("Valid intermediate container: {0}", childPath); } } } // foreach (dir in currentDirs) @@ -4404,7 +4395,6 @@ namespace System.Management.Automation return newDirs; - } // GenerateNewPathsWithGlobLeaf /// @@ -4514,13 +4504,13 @@ namespace System.Management.Automation if (changedPathOrFilter) { - if (tracer.IsEnabled) + if (s_tracer.IsEnabled) { - tracer.WriteLine("Provider converted path and filter."); - tracer.WriteLine("Original path: {0}", leafElement); - tracer.WriteLine("Converted path: {0}", convertedPath); - tracer.WriteLine("Original filter: {0}", context.Filter); - tracer.WriteLine("Converted filter: {0}", convertedFilter); + s_tracer.WriteLine("Provider converted path and filter."); + s_tracer.WriteLine("Original path: {0}", leafElement); + s_tracer.WriteLine("Converted path: {0}", convertedPath); + s_tracer.WriteLine("Original filter: {0}", context.Filter); + s_tracer.WriteLine("Converted filter: {0}", convertedFilter); } leafElement = convertedPath; @@ -4584,7 +4574,6 @@ namespace System.Management.Automation } else { - // If there were no results from globbing but no // exception was thrown, that means there was filtering. // So return an empty collection and let the caller deal @@ -4684,7 +4673,7 @@ namespace System.Management.Automation object baseObject = childObject.BaseObject; if (baseObject is PSCustomObject) { - tracer.TraceError("GetChildNames returned a null object"); + s_tracer.TraceError("GetChildNames returned a null object"); break; } @@ -4692,18 +4681,18 @@ namespace System.Management.Automation if (childName == null) { - tracer.TraceError("GetChildNames returned an object that wasn't a string"); + s_tracer.TraceError("GetChildNames returned an object that wasn't a string"); break; } - pathResolutionTracer.WriteLine("Name returned from provider: {0}", childName); + s_pathResolutionTracer.WriteLine("Name returned from provider: {0}", childName); // Check the glob expression // First see if the child matches the glob expression bool isGlobbed = WildcardPattern.ContainsWildcardCharacters(stringMatcher.Pattern); bool isChildMatch = stringMatcher.IsMatch(childName); - tracer.WriteLine("isChildMatch = {0}", isChildMatch); + s_tracer.WriteLine("isChildMatch = {0}", isChildMatch); bool isIncludeSpecified = (includeMatcher.Count > 0); bool isExcludeSpecified = (excludeMatcher.Count > 0); @@ -4713,18 +4702,18 @@ namespace System.Management.Automation includeMatcher, true); - tracer.WriteLine("isIncludeMatch = {0}", isIncludeMatch); + s_tracer.WriteLine("isIncludeMatch = {0}", isIncludeMatch); // Check if the child name matches, or the include matches if (isChildMatch || (isGlobbed && isIncludeSpecified && isIncludeMatch)) { - pathResolutionTracer.WriteLine("Path wildcard match: {0}", childName); + s_pathResolutionTracer.WriteLine("Path wildcard match: {0}", childName); result = true; // See if it should not be included - if (isIncludeSpecified && ! isIncludeMatch) + if (isIncludeSpecified && !isIncludeMatch) { - pathResolutionTracer.WriteLine("Not included match: {0}", childName); + s_pathResolutionTracer.WriteLine("Not included match: {0}", childName); result = false; } @@ -4732,17 +4721,17 @@ namespace System.Management.Automation if (isExcludeSpecified && SessionStateUtilities.MatchesAnyWildcardPattern(childName, excludeMatcher, false)) { - pathResolutionTracer.WriteLine("Excluded match: {0}", childName); + s_pathResolutionTracer.WriteLine("Excluded match: {0}", childName); result = false; } } else { - pathResolutionTracer.WriteLine("NOT path wildcard match: {0}", childName); + s_pathResolutionTracer.WriteLine("NOT path wildcard match: {0}", childName); } } while (false); - tracer.WriteLine("result = {0}; childName = {1}", result, childName); + s_tracer.WriteLine("result = {0}; childName = {1}", result, childName); return result; } //IsChildNameAMatch @@ -4842,13 +4831,12 @@ namespace System.Management.Automation } } // for () - tracer.WriteLine( + s_tracer.WriteLine( "Original path: {0} Converted to: {1}", path, result.ToString()); return result.ToString(); - } // ConvertMshEscapeToRegexEscape /// @@ -4979,9 +4967,9 @@ namespace System.Management.Automation string result = path; - if (IsHomePath(path) && sessionState.Drive.Current != null) + if (IsHomePath(path) && _sessionState.Drive.Current != null) { - ProviderInfo provider = sessionState.Drive.Current.Provider; + ProviderInfo provider = _sessionState.Drive.Current.Provider; if (IsProviderQualifiedPath(path)) { @@ -4996,7 +4984,7 @@ namespace System.Management.Automation string providerName = path.Substring(0, index); - provider = sessionState.Internal.GetSingleProvider(providerName); + provider = _sessionState.Internal.GetSingleProvider(providerName); path = path.Substring(index + StringLiterals.ProviderPathSeparator.Length); } } // IsProviderPath @@ -5023,10 +5011,10 @@ namespace System.Management.Automation provider.Home.Length > 0) { CmdletProviderContext context = - new CmdletProviderContext(sessionState.Internal.ExecutionContext); + new CmdletProviderContext(_sessionState.Internal.ExecutionContext); - pathResolutionTracer.WriteLine("Getting home path for provider: {0}", provider.Name); - pathResolutionTracer.WriteLine("Provider HOME path: {0}", provider.Home); + s_pathResolutionTracer.WriteLine("Getting home path for provider: {0}", provider.Name); + s_pathResolutionTracer.WriteLine("Provider HOME path: {0}", provider.Home); if (String.IsNullOrEmpty(path)) { @@ -5034,10 +5022,10 @@ namespace System.Management.Automation } else { - path = sessionState.Internal.MakePath(provider, provider.Home, path, context); + path = _sessionState.Internal.MakePath(provider, provider.Home, path, context); } - pathResolutionTracer.WriteLine("HOME relative path: {0}", path); + s_pathResolutionTracer.WriteLine("HOME relative path: {0}", path); } else { @@ -5046,7 +5034,7 @@ namespace System.Management.Automation SessionStateStrings.HomePathNotSet, provider.Name); - pathResolutionTracer.TraceError("HOME path not set for provider: {0}", provider.Name); + s_pathResolutionTracer.TraceError("HOME path not set for provider: {0}", provider.Name); throw e; } } @@ -5058,10 +5046,10 @@ namespace System.Management.Automation private static void TraceFilters(CmdletProviderContext context) { - if ((pathResolutionTracer.Options & PSTraceSourceOptions.WriteLine) != 0) + if ((s_pathResolutionTracer.Options & PSTraceSourceOptions.WriteLine) != 0) { // Trace the filter - pathResolutionTracer.WriteLine("Filter: {0}", context.Filter ?? String.Empty); + s_pathResolutionTracer.WriteLine("Filter: {0}", context.Filter ?? String.Empty); if (context.Include != null) { @@ -5071,7 +5059,7 @@ namespace System.Management.Automation { includeString.AppendFormat("{0} ", includeFilter); } - pathResolutionTracer.WriteLine("Include: {0}", includeString.ToString()); + s_pathResolutionTracer.WriteLine("Include: {0}", includeString.ToString()); } if (context.Exclude != null) @@ -5082,7 +5070,7 @@ namespace System.Management.Automation { excludeString.AppendFormat("{0} ", excludeFilter); } - pathResolutionTracer.WriteLine("Exclude: {0}", excludeString.ToString()); + s_pathResolutionTracer.WriteLine("Exclude: {0}", excludeString.ToString()); } } } diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index beeb0d80d..a4ce0ab1f 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -67,7 +67,7 @@ namespace System.Management.Automation.Provider /// /// internal string MakePath( - string parent, + string parent, string child, CmdletProviderContext context) { @@ -111,7 +111,7 @@ namespace System.Management.Automation.Provider /// /// internal string GetParentPath( - string path, + string path, string root, CmdletProviderContext context) { @@ -154,7 +154,7 @@ namespace System.Management.Automation.Provider /// /// internal string NormalizeRelativePath( - string path, + string path, string basePath, CmdletProviderContext context) { @@ -164,7 +164,7 @@ namespace System.Management.Automation.Provider return NormalizeRelativePath(path, basePath); } // NormalizeRelativePath - + /// /// Internal wrapper for the GetChildName protected method. It is called instead /// of the protected method that is overridden by derived classes so that the @@ -520,7 +520,7 @@ namespace System.Management.Automation.Provider path = NormalizePath(path); path = path.TrimEnd(StringLiterals.DefaultPathSeparator); string rootPath = String.Empty; - + if (root != null) { rootPath = NormalizePath(root); @@ -530,7 +530,7 @@ namespace System.Management.Automation.Provider // of the virtual drive if (String.Compare( - path, + path, rootPath, StringComparison.OrdinalIgnoreCase) == 0) { @@ -589,7 +589,7 @@ namespace System.Management.Automation.Provider /// are done using StringComparison.InvariantCultureIngoreCase. /// protected virtual string NormalizeRelativePath( - string path, + string path, string basePath) { using (PSTransactionManager.GetEngineProtectionScope()) @@ -643,7 +643,7 @@ namespace System.Management.Automation.Provider // Active Directory team. // // WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND - if (! String.Equals(context.ProviderInstance.ProviderInfo.FullName, + if (!String.Equals(context.ProviderInstance.ProviderInfo.FullName, @"Microsoft.ActiveDirectory.Management\ActiveDirectory", StringComparison.OrdinalIgnoreCase)) { normalizedPath = NormalizePath(path); @@ -676,7 +676,7 @@ namespace System.Management.Automation.Provider // If the base path isn't really a base, then we resolve to a parent // path (such as ../../foo) - if (! normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) && + if (!normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) && (basePath.Length > 0)) { result = String.Empty; @@ -835,7 +835,7 @@ namespace System.Management.Automation.Provider result = path; // If the parent path ends with the path separator, we can't split // the path based on that - else if(parentPath.IndexOf(StringLiterals.DefaultPathSeparator) == (parentPath.Length -1 )) + else if (parentPath.IndexOf(StringLiterals.DefaultPathSeparator) == (parentPath.Length - 1)) { separatorIndex = path.IndexOf(parentPath, StringComparison.OrdinalIgnoreCase) + parentPath.Length; result = path.Substring(separatorIndex); @@ -957,7 +957,7 @@ namespace System.Management.Automation.Provider /// The default implemenation returns null. (no additional parameters) /// protected virtual object MoveItemDynamicParameters( - string path, + string path, string destination) { using (PSTransactionManager.GetEngineProtectionScope()) @@ -966,7 +966,7 @@ namespace System.Management.Automation.Provider } } // MoveItemDynamicParameters - + #endregion Protected methods #region private members @@ -1026,7 +1026,7 @@ namespace System.Management.Automation.Provider { result = true; } - else if (this.PSDriveInfo != null && !String.IsNullOrEmpty(this.PSDriveInfo.Root) && + else if (this.PSDriveInfo != null && !String.IsNullOrEmpty(this.PSDriveInfo.Root) && path.StartsWith(this.PSDriveInfo.Root, StringComparison.OrdinalIgnoreCase)) { result = true; @@ -1067,7 +1067,7 @@ namespace System.Management.Automation.Provider if (String.IsNullOrEmpty(childName)) { // Push the parent on and then stop - tokenizedPathStack.Push (tempPath); + tokenizedPathStack.Push(tempPath); break; } @@ -1204,10 +1204,8 @@ namespace System.Management.Automation.Provider } // CreateNormalizedRelativePathFromStack #endregion private members - } // NavigationCmdletProvider #endregion NavigationCmdletProvider - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index 08fc3c7e7..cae86e99c 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -3,7 +3,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -21,10 +21,10 @@ namespace System.Management.Automation { PSDriveInfo result = null; - if (drive != null && - !drive.Hidden) + if (_drive != null && + !_drive.Hidden) { - result = drive; + result = _drive; } return result; @@ -38,10 +38,10 @@ namespace System.Management.Automation { get { - return provider; + return _provider; } } // Provider - + /// /// This is the internal mechanism to get the hidden drive. /// @@ -52,7 +52,7 @@ namespace System.Management.Automation /// internal PSDriveInfo GetDrive() { - return drive; + return _drive; } // GetDrive /// @@ -71,19 +71,19 @@ namespace System.Management.Automation { get { - if (providerPath == null) + if (_providerPath == null) { // Construct the providerPath - LocationGlobber pathGlobber = sessionState.Internal.ExecutionContext.LocationGlobber; - providerPath = pathGlobber.GetProviderPath (Path); + LocationGlobber pathGlobber = _sessionState.Internal.ExecutionContext.LocationGlobber; + _providerPath = pathGlobber.GetProviderPath(Path); } - return providerPath; + return _providerPath; } } - private string providerPath; - private SessionState sessionState; + private string _providerPath; + private SessionState _sessionState; /// /// Gets the MSH path that this object represents. @@ -93,12 +93,12 @@ namespace System.Management.Automation get { return this.ToString(); - } + } } // Path - private PSDriveInfo drive; - private ProviderInfo provider; - private string path = String.Empty; + private PSDriveInfo _drive; + private ProviderInfo _provider; + private string _path = String.Empty; /// /// Gets a string representing the MSH path. @@ -109,21 +109,21 @@ namespace System.Management.Automation /// public override string ToString() { - string result = path; + string result = _path; - if (drive == null || - drive.Hidden) + if (_drive == null || + _drive.Hidden) { // For hidden drives just return the current location result = LocationGlobber.GetProviderQualifiedPath( - path, - provider); + _path, + _provider); } else { - result = LocationGlobber.GetDriveQualifiedPath(path, drive); + result = LocationGlobber.GetDriveQualifiedPath(_path, _drive); } return result; @@ -168,14 +168,13 @@ namespace System.Management.Automation if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException ("sessionState"); + throw PSTraceSource.NewArgumentNullException("sessionState"); } - this.drive = drive; - this.provider = provider; - this.path = path; - this.sessionState = sessionState; + _drive = drive; + _provider = provider; + _path = path; + _sessionState = sessionState; } // constructor } // PathInfo - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index b3396f535..2bdd163dc 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -59,12 +59,12 @@ namespace System.Management.Automation.Provider /// The context under which the provider is running. This will change between each /// invocation of a method in this class or derived classes. /// - private CmdletProviderContext contextBase = null; + private CmdletProviderContext _contextBase = null; /// /// The information that the Monad engine stores on behalf of the provider. /// - private ProviderInfo providerInformation = null; + private ProviderInfo _providerInformation = null; #endregion private data @@ -77,7 +77,7 @@ namespace System.Management.Automation.Provider /// using "CmdletProviderClasses" as the category. /// [TraceSourceAttribute( - "CmdletProviderClasses", + "CmdletProviderClasses", "The namespace provider base classes tracer")] internal static PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( "CmdletProviderClasses", @@ -105,7 +105,7 @@ namespace System.Management.Automation.Provider throw PSTraceSource.NewArgumentNullException("providerInfoToSet"); } - this.providerInformation = providerInfoToSet; + _providerInformation = providerInfoToSet; } // SetProviderInformation /// @@ -137,7 +137,7 @@ namespace System.Management.Automation.Provider { get { - return contextBase; + return _contextBase; } set @@ -150,16 +150,16 @@ namespace System.Management.Automation.Provider // Check that the provider supports the use of credentials if (value.Credential != null && value.Credential != PSCredential.Empty && - !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, providerInformation)) + !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, _providerInformation)) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Credentials_NotSupported); } // Supplying Credentials for the FileSystemProvider is supported only for New-PSDrive Command. - if (providerInformation != null && !string.IsNullOrEmpty(providerInformation.Name) && providerInformation.Name.Equals("FileSystem") && + if (_providerInformation != null && !string.IsNullOrEmpty(_providerInformation.Name) && _providerInformation.Name.Equals("FileSystem") && value.Credential != null && - value.Credential != PSCredential.Empty && + value.Credential != PSCredential.Empty && !value.ExecutionContext.CurrentCommandProcessor.Command.GetType().Name.Equals("NewPSDriveCommand")) { throw PSTraceSource.NewNotSupportedException( @@ -167,8 +167,8 @@ namespace System.Management.Automation.Provider } // Check that the provider supports the use of filters - if ((! String.IsNullOrEmpty(value.Filter)) && - (! CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Filter, providerInformation))) + if ((!String.IsNullOrEmpty(value.Filter)) && + (!CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Filter, _providerInformation))) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Filter_NotSupported); @@ -176,15 +176,15 @@ namespace System.Management.Automation.Provider // Check that the provider supports the use of transactions if the command // requested it - if((value.UseTransaction) && - (! CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Transactions, providerInformation))) + if ((value.UseTransaction) && + (!CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Transactions, _providerInformation))) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.Transactions_NotSupported); } - contextBase = value; - contextBase.ProviderInstance = this; + _contextBase = value; + _contextBase.ProviderInstance = this; } } // Context @@ -224,7 +224,7 @@ namespace System.Management.Automation.Provider internal object StartDynamicParameters(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; - + return StartDynamicParameters(); } // StartDynamicParmaters @@ -316,7 +316,7 @@ namespace System.Management.Automation.Provider /// /// internal object GetPropertyDynamicParameters( - string path, + string path, Collection providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { @@ -395,7 +395,7 @@ namespace System.Management.Automation.Provider /// /// internal object SetPropertyDynamicParameters( - string path, + string path, PSObject propertyValue, CmdletProviderContext cmdletProviderContext) { @@ -478,7 +478,7 @@ namespace System.Management.Automation.Provider /// /// internal object ClearPropertyDynamicParameters( - string path, + string path, Collection providerSpecificPickList, CmdletProviderContext cmdletProviderContext) { @@ -1059,7 +1059,7 @@ namespace System.Management.Automation.Provider /// /// internal object NewPropertyDynamicParameters( - string path, + string path, string propertyName, string propertyTypeName, object value, @@ -1143,7 +1143,7 @@ namespace System.Management.Automation.Provider /// /// internal object RemovePropertyDynamicParameters( - string path, + string path, string propertyName, CmdletProviderContext cmdletProviderContext) { @@ -1234,7 +1234,7 @@ namespace System.Management.Automation.Provider /// /// internal object RenamePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationProperty, CmdletProviderContext cmdletProviderContext) @@ -1249,7 +1249,7 @@ namespace System.Management.Automation.Provider } return propertyProvider.RenamePropertyDynamicParameters(path, sourceProperty, destinationProperty); } // RenamePropertyDynamicParameters - + /// /// Internal wrapper for the CopyProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. @@ -1289,7 +1289,7 @@ namespace System.Management.Automation.Provider { Context = cmdletProviderContext; - IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider ; + IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { @@ -1335,7 +1335,7 @@ namespace System.Management.Automation.Provider /// /// internal object CopyPropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationPath, string destinationProperty, @@ -1351,7 +1351,7 @@ namespace System.Management.Automation.Provider } return propertyProvider.CopyPropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } // CopyPropertyDynamicParameters - + /// /// Internal wrapper for the MoveProperty protected method. This method will /// only be called if the provider implements the IDynamicPropertyCmdletProvider interface. @@ -1391,7 +1391,7 @@ namespace System.Management.Automation.Provider { Context = cmdletProviderContext; - IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider ; + IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; if (propertyProvider == null) { @@ -1437,7 +1437,7 @@ namespace System.Management.Automation.Provider /// /// internal object MovePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationPath, string destinationProperty, @@ -1453,7 +1453,7 @@ namespace System.Management.Automation.Provider } return propertyProvider.MovePropertyDynamicParameters(path, sourceProperty, destinationPath, destinationProperty); } // MovePropertyDynamicParameters - + #endregion IDynamicPropertyCmdletProvider method wrappers #region IContentCmdletProvider method wrappers @@ -1515,7 +1515,7 @@ namespace System.Management.Automation.Provider /// /// internal object GetContentReaderDynamicParameters( - string path, + string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; @@ -1528,7 +1528,7 @@ namespace System.Management.Automation.Provider } return contentProvider.GetContentReaderDynamicParameters(path); } // GetContentReaderDynamicParameters - + /// /// Internal wrapper for the GetContentWriter protected method. This method will @@ -1566,7 +1566,7 @@ namespace System.Management.Automation.Provider return contentProvider.GetContentWriter(path); } // GetContentWriter - + /// /// Gives the provider a chance to attach additional parameters to /// the add-content and set-content cmdlet. @@ -1587,7 +1587,7 @@ namespace System.Management.Automation.Provider /// /// internal object GetContentWriterDynamicParameters( - string path, + string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; @@ -1600,7 +1600,7 @@ namespace System.Management.Automation.Provider } return contentProvider.GetContentWriterDynamicParameters(path); } // GetContentWriterDynamicParameters - + /// /// Internal wrapper for the ClearContent protected method. This method will @@ -1634,7 +1634,7 @@ namespace System.Management.Automation.Provider contentProvider.ClearContent(path); } // ClearContent - + /// /// Gives the provider a chance to attach additional parameters to /// the clear-content cmdlet. @@ -1655,7 +1655,7 @@ namespace System.Management.Automation.Provider /// /// internal object ClearContentDynamicParameters( - string path, + string path, CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; @@ -1668,7 +1668,7 @@ namespace System.Management.Automation.Provider } return contentProvider.ClearContentDynamicParameters(path); } // ClearContentDynamicParameters - + #endregion IContentCmdletProvider method wrappers @@ -1749,7 +1749,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1767,11 +1767,11 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - return new SessionState (Context.ExecutionContext.EngineSessionState); + return new SessionState(Context.ExecutionContext.EngineSessionState); } // TraceProperty } // get } // SessionState @@ -1785,11 +1785,11 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - return new ProviderIntrinsics (Context.ExecutionContext.EngineSessionState); + return new ProviderIntrinsics(Context.ExecutionContext.EngineSessionState); } // TraceProperty } // get } // InvokeProvider @@ -1803,12 +1803,12 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - return new CommandInvocationIntrinsics (Context.ExecutionContext); + return new CommandInvocationIntrinsics(Context.ExecutionContext); } // TraceProperty } // get } // InvokeCommand @@ -1822,7 +1822,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1846,7 +1846,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - return providerInformation; + return _providerInformation; } // TraceProperty } // get } @@ -1860,7 +1860,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1879,7 +1879,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1887,7 +1887,7 @@ namespace System.Management.Automation.Provider } // TraceProperty } // get } // DynamicParameters - + /// /// Gets the force property. /// @@ -1907,7 +1907,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1925,7 +1925,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -1944,16 +1944,15 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); return Context.Include; } // TraceProperty } // get - } // Include - + /// /// Gets the exclude wildcard patterns which is used to determine which items /// will be excluded when taking an action. @@ -1982,7 +1981,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2018,26 +2017,26 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - if (String.IsNullOrEmpty (baseName)) + if (String.IsNullOrEmpty(baseName)) { - throw PSTraceSource.NewArgumentException ("baseName"); + throw PSTraceSource.NewArgumentException("baseName"); } - if (String.IsNullOrEmpty (resourceId)) + if (String.IsNullOrEmpty(resourceId)) { - throw PSTraceSource.NewArgumentException ("resourceId"); + throw PSTraceSource.NewArgumentException("resourceId"); } - ResourceManager manager = - ResourceManagerCache.GetResourceManager ( - this.GetType().GetTypeInfo().Assembly, + ResourceManager manager = + ResourceManagerCache.GetResourceManager( + this.GetType().GetTypeInfo().Assembly, baseName); string retValue = null; try { - retValue = manager.GetString (resourceId, + retValue = manager.GetString(resourceId, System.Globalization.CultureInfo.CurrentUICulture); } catch (MissingManifestResourceException) @@ -2062,10 +2061,10 @@ namespace System.Management.Automation.Provider { if (null == errorRecord) { - throw PSTraceSource.NewArgumentNullException ("errorRecord"); + throw PSTraceSource.NewArgumentNullException("errorRecord"); } - if ( null != errorRecord.ErrorDetails + if (null != errorRecord.ErrorDetails && null != errorRecord.ErrorDetails.TextLookupError) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; @@ -2083,7 +2082,7 @@ namespace System.Management.Automation.Provider // it in ProviderInvocationException. ProviderInvocationException providerInvocationException = - new ProviderInvocationException (ProviderInfo, errorRecord); + new ProviderInvocationException(ProviderInfo, errorRecord); // Log a provider health event @@ -2106,22 +2105,22 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - return Context.ShouldProcess(target); + return Context.ShouldProcess(target); } } // ShouldProcess /// public bool ShouldProcess( - string target, + string target, string action) { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2166,7 +2165,7 @@ namespace System.Management.Automation.Provider verboseWarning, caption, out shouldProcessReason); - } + } } // ShouldProcess /// @@ -2176,11 +2175,11 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - return Context.ShouldContinue (query, caption); + return Context.ShouldContinue(query, caption); } } // ShouldContinue @@ -2193,7 +2192,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2211,7 +2210,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - if(Context == null) + if (Context == null) return false; else return Context.TransactionAvailable(); @@ -2226,7 +2225,7 @@ namespace System.Management.Automation.Provider { get { - if(Context == null) + if (Context == null) return null; else return Context.CurrentPSTransaction; @@ -2239,7 +2238,7 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2279,13 +2278,13 @@ namespace System.Management.Automation.Provider } } // WriteProgress - + /// public void WriteDebug(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2348,7 +2347,7 @@ namespace System.Management.Automation.Provider result.AddOrSetProperty("PSIsContainer", isContainer ? Boxed.True : Boxed.False); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSIsContainer", isContainer); - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2426,7 +2425,7 @@ namespace System.Management.Automation.Provider { PSObject result = WrapOutputInPSObject(item, path); - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); @@ -2461,14 +2460,14 @@ namespace System.Management.Automation.Provider { if (item == null) { - throw PSTraceSource.NewArgumentNullException ("item"); + throw PSTraceSource.NewArgumentNullException("item"); } PSObject result = new PSObject(item); Diagnostics.Assert( ProviderInfo != null, "The ProviderInfo should always be set"); - + // Move the TypeNames to the wrapping object if the wrapped object // was an PSObject @@ -2480,7 +2479,7 @@ namespace System.Management.Automation.Provider // Construct a provider qualified path as the Path note - String providerQualifiedPath = + String providerQualifiedPath = LocationGlobber.GetProviderQualifiedPath(path, ProviderInfo); result.AddOrSetProperty("PSPath", providerQualifiedPath); @@ -2494,7 +2493,7 @@ namespace System.Management.Automation.Provider // Get the parent path string parentPath = null; - + if (PSDriveInfo != null) { parentPath = navProvider.GetParentPath(path, PSDriveInfo.Root, Context); @@ -2506,10 +2505,10 @@ namespace System.Management.Automation.Provider string providerQualifiedParentPath = String.Empty; - if (!String.IsNullOrEmpty (parentPath)) + if (!String.IsNullOrEmpty(parentPath)) { providerQualifiedParentPath = - LocationGlobber.GetProviderQualifiedPath (parentPath, ProviderInfo); + LocationGlobber.GetProviderQualifiedPath(parentPath, ProviderInfo); } result.AddOrSetProperty("PSParentPath", providerQualifiedParentPath); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSParentPath", providerQualifiedParentPath); @@ -2518,7 +2517,7 @@ namespace System.Management.Automation.Provider string childName = navProvider.GetChildName(path, Context); - + result.AddOrSetProperty("PSChildName", childName); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); } @@ -2686,11 +2685,11 @@ namespace System.Management.Automation.Provider { using (PSTransactionManager.GetEngineProtectionScope()) { - Diagnostics.Assert ( + Diagnostics.Assert( Context != null, "The context should always be set"); - if(errorRecord == null) + if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException("errorRecord"); } @@ -2713,7 +2712,6 @@ namespace System.Management.Automation.Provider #endregion protected members - } // CmdletProvider #endregion CmdletProvider diff --git a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs index 0f29367f9..63ae0240f 100644 --- a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs +++ b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation.Provider { #region ISecurityDescriptorCmdletProvider method wrappers - + /// /// Internal wrapper for the GetSecurityDescriptor protected method. This method will /// only be called if the provider implements the ISecurityDescriptorCmdletProvider interface. @@ -80,7 +80,7 @@ namespace System.Management.Automation.Provider /// /// internal void SetSecurityDescriptor( - string path, + string path, ObjectSecurity securityDescriptor, CmdletProviderContext context) { diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index 5b2069a01..1934aa2d5 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; @@ -48,19 +49,19 @@ namespace System.Management.Automation.Provider throw PSTraceSource.NewArgumentNullException("providerName"); } - if (providerName.IndexOfAny(illegalCharacters) != -1) + if (providerName.IndexOfAny(_illegalCharacters) != -1) { throw PSTraceSource.NewArgumentException( "providerName", - SessionStateStrings.ProviderNameNotValid, + SessionStateStrings.ProviderNameNotValid, providerName); } - this.provider = providerName; - this.providerCapabilities = providerCapabilities; + _provider = providerName; + _providerCapabilities = providerCapabilities; } // constructor - private char[] illegalCharacters = new char[] { ':', '\\', '[', ']', '?', '*' }; + private char[] _illegalCharacters = new char[] { ':', '\\', '[', ']', '?', '*' }; /// /// Gets the name of the provider. @@ -69,7 +70,7 @@ namespace System.Management.Automation.Provider { get { - return provider; + return _provider; } } // Provider @@ -81,17 +82,16 @@ namespace System.Management.Automation.Provider { get { - return providerCapabilities; + return _providerCapabilities; } } // FriendlyName #region private data - private string provider = String.Empty; - private ProviderCapabilities providerCapabilities = ProviderCapabilities.None; + private string _provider = String.Empty; + private ProviderCapabilities _providerCapabilities = ProviderCapabilities.None; #endregion private data - } // class CmdletProviderAttribute /// @@ -180,5 +180,4 @@ namespace System.Management.Automation.Provider /// Transactions = 0x40, } // ProviderCapabilities - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 63c1d7ef8..6b67e0f7e 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -10,12 +10,11 @@ using Microsoft.Win32; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using Microsoft.PowerShell.Commands.Internal; namespace Microsoft.PowerShell.Commands { - /// /// Provider that provides access to Registry through cmdlets. This provider /// implements , @@ -61,7 +60,7 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(RegistryKey), typeof(string), typeof(Int32), typeof(Int64), ProviderCmdlet = ProviderCmdlet.GetItemProperty)] [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.NewItem)] - public sealed partial class RegistryProvider : + public sealed partial class RegistryProvider : NavigationCmdletProvider, IPropertyCmdletProvider, #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER @@ -77,10 +76,10 @@ namespace Microsoft.PowerShell.Commands /// using "ProviderProvider" as the category. /// [Dbg.TraceSourceAttribute( - "RegistryProvider", + "RegistryProvider", "The namespace navigation provider for the Windows Registry")] - private static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("RegistryProvider", + private static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("RegistryProvider", "The namespace navigation provider for the Windows Registry"); #endregion tracer @@ -103,13 +102,13 @@ namespace Microsoft.PowerShell.Commands /// or reliability reasons or toprovide extra data to all calls /// using the drive /// --> - protected override PSDriveInfo NewDrive(PSDriveInfo drive) + protected override PSDriveInfo NewDrive(PSDriveInfo drive) { if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } - + if (!ItemExists(drive.Root)) { Exception e = new ArgumentException(RegistryProviderStrings.NewDriveRootDoesNotExist); @@ -132,7 +131,7 @@ namespace Microsoft.PowerShell.Commands /// provider might mount a drive for the defaultNamingContext if the /// machine is joined to a domain. The FileSystem mounts all drives then available. /// - protected override Collection InitializeDefaultDrives() + protected override Collection InitializeDefaultDrives() { Collection drives = new Collection(); @@ -156,7 +155,7 @@ namespace Microsoft.PowerShell.Commands return drives; } // InitializeDefaultDrives - + #endregion DriveCmdletProvider overrides #region ItemCmdletProvider overrides @@ -172,7 +171,7 @@ namespace Microsoft.PowerShell.Commands /// /// True if the path is valid, or False otherwise. /// - protected override bool IsValidPath (string path) + protected override bool IsValidPath(string path) { bool result = true; @@ -182,17 +181,17 @@ namespace Microsoft.PowerShell.Commands // to validate, so just ensure that the path starts with one of the hive roots. string root = NormalizePath(path); - root = root.TrimStart (StringLiterals.DefaultPathSeparator); - root = root.TrimEnd (StringLiterals.DefaultPathSeparator); + root = root.TrimStart(StringLiterals.DefaultPathSeparator); + root = root.TrimEnd(StringLiterals.DefaultPathSeparator); - int pathSeparator = root.IndexOf (StringLiterals.DefaultPathSeparator); + int pathSeparator = root.IndexOf(StringLiterals.DefaultPathSeparator); if (pathSeparator != -1) { - root = root.Substring (0, pathSeparator); + root = root.Substring(0, pathSeparator); } - if (String.IsNullOrEmpty (root)) + if (String.IsNullOrEmpty(root)) { // An empty path means that we are at the root and should // enumerate the hives. So that is a valid path. @@ -200,7 +199,7 @@ namespace Microsoft.PowerShell.Commands break; } - if (GetHiveRoot (root) == null) + if (GetHiveRoot(root) == null) { result = false; } @@ -218,8 +217,8 @@ namespace Microsoft.PowerShell.Commands /// /// The path to the key to retrieve. /// - protected override void GetItem(string path) - { + protected override void GetItem(string path) + { // Get the registry item IRegistryWrapper result = GetRegkeyForPathWriteIfError(path, false); @@ -228,10 +227,10 @@ namespace Microsoft.PowerShell.Commands { return; } - + // Write out the result - WriteRegistryItemObject(result, path); + WriteRegistryItemObject(result, path); } // GetItem @@ -247,22 +246,22 @@ namespace Microsoft.PowerShell.Commands /// /// The new value for the registry value. /// - protected override void SetItem(string path, object value) + protected override void SetItem(string path, object value) { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } - + // Confirm the set item with the user string action = RegistryProviderStrings.SetItemAction; - - string resourceTemplate =RegistryProviderStrings.SetItemResourceTemplate; - string resource = + string resourceTemplate = RegistryProviderStrings.SetItemResourceTemplate; + + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, value); @@ -279,9 +278,9 @@ namespace Microsoft.PowerShell.Commands { return; } - + // Check to see if the type was specified by the user - + bool valueSet = false; if (DynamicParameters != null) { @@ -301,7 +300,7 @@ namespace Microsoft.PowerShell.Commands } catch (ArgumentException argException) { - WriteError (new ErrorRecord (argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, valueName)); + WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, valueName)); key.Close(); return; } @@ -310,7 +309,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } @@ -319,7 +318,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } @@ -327,7 +326,7 @@ namespace Microsoft.PowerShell.Commands { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } @@ -346,7 +345,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } @@ -355,7 +354,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } @@ -364,11 +363,10 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } - } // Write out the result @@ -377,10 +375,10 @@ namespace Microsoft.PowerShell.Commands // Since SetValue can munge the data to a specified // type (RegistryValueKind), retrieve the value again // to output it in the correct form to the user. - result = ReadExistingKeyValue (key, valueName); + result = ReadExistingKeyValue(key, valueName); key.Close(); - WriteItemObject(result, path, false); + WriteItemObject(result, path, false); } // ShouldProcess } // SetItem @@ -400,7 +398,7 @@ namespace Microsoft.PowerShell.Commands /// An instance of the class which /// contains a parameter for the Type. /// - protected override object SetItemDynamicParameters (string path, object value) + protected override object SetItemDynamicParameters(string path, object value) { return new RegistryProviderSetItemDynamicParameter(); } // SetItemDynamicParameters @@ -423,22 +421,21 @@ namespace Microsoft.PowerShell.Commands { throw PSTraceSource.NewArgumentException("path"); } - + // Confirm the clear item with the user string action = RegistryProviderStrings.ClearItemAction; - + string resourceTemplate = RegistryProviderStrings.ClearItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) { - // Get the registry item IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); @@ -460,7 +457,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); return; } catch (System.Security.SecurityException securityException) @@ -468,7 +465,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) @@ -476,7 +473,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } @@ -491,27 +488,27 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to delete the value. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to delete the value. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } // Write out the key - WriteRegistryItemObject(key, path); + WriteRegistryItemObject(key, path); } // ShouldProcess } // ClearItem @@ -538,7 +535,7 @@ namespace Microsoft.PowerShell.Commands bool recurse, uint depth) { - tracer.WriteLine("recurse = {0}, depth = {1}", recurse, depth); + s_tracer.WriteLine("recurse = {0}, depth = {1}", recurse, depth); if (path == null) { @@ -549,7 +546,7 @@ namespace Microsoft.PowerShell.Commands { // If the path is empty or it is / or \, return all the hives - foreach (string hiveName in hiveNames) + foreach (string hiveName in s_hiveNames) { // Making sure to obey the StopProcessing. if (Stopping) @@ -580,7 +577,6 @@ namespace Microsoft.PowerShell.Commands if (keyNames != null) { - foreach (string subkeyName in keyNames) { // Making sure to obey the StopProcessing. @@ -588,7 +584,7 @@ namespace Microsoft.PowerShell.Commands { return; } - + if (!String.IsNullOrEmpty(subkeyName)) { string keypath = path; @@ -628,21 +624,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, keypath)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, keypath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, keypath)); } } } // foreach subkeyName in keyNames @@ -653,23 +649,22 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } - } } // GetChildItems @@ -689,8 +684,8 @@ namespace Microsoft.PowerShell.Commands /// protected override void GetChildNames( string path, - ReturnContainers returnContainers) - { + ReturnContainers returnContainers) + { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); @@ -700,14 +695,14 @@ namespace Microsoft.PowerShell.Commands { // If the path is empty get the names of the hives - foreach (string hiveName in hiveNames) + foreach (string hiveName in s_hiveNames) { // Making sure to obey the StopProcessing. if (Stopping) { return; } - + WriteItemObject(hiveName, hiveName, true); } } @@ -738,7 +733,7 @@ namespace Microsoft.PowerShell.Commands { return; } - + string childName = EscapeChildName(results[index]); string childPath = MakePath(path, childName, childIsLeaf: true); @@ -750,21 +745,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } } // GetChildNames @@ -873,7 +868,7 @@ namespace Microsoft.PowerShell.Commands return result.ToString(); } // EscapeChildName - + /// /// Renames the key at the specified to . /// @@ -887,8 +882,8 @@ namespace Microsoft.PowerShell.Commands /// protected override void RenameItem( string path, - string newName) - { + string newName) + { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); @@ -899,7 +894,7 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentException("newName"); } - tracer.WriteLine("newName = {0}", newName); + s_tracer.WriteLine("newName = {0}", newName); string parentPath = GetParentPath(path, null); string newPath = MakePath(parentPath, newName); @@ -922,12 +917,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the rename item with the user string action = RegistryProviderStrings.RenameItemAction; - + string resourceTemplate = RegistryProviderStrings.RenameItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, newPath); @@ -936,7 +931,7 @@ namespace Microsoft.PowerShell.Commands { // Implement rename as a move operation - MoveRegistryItem(path, newPath); + MoveRegistryItem(path, newPath); } // ShouldProcess } // RenameItem @@ -961,8 +956,8 @@ namespace Microsoft.PowerShell.Commands protected override void NewItem( string path, string type, - object newItem) - { + object newItem) + { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); @@ -971,12 +966,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the new item with the user string action = RegistryProviderStrings.NewItemAction; - + string resourceTemplate = RegistryProviderStrings.NewItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path); if (ShouldProcess(resource, action)) @@ -989,7 +984,7 @@ namespace Microsoft.PowerShell.Commands if (!Force) { Exception e = new System.IO.IOException(RegistryProviderStrings.KeyAlreadyExists); - WriteError (new ErrorRecord ( + WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.ResourceExists, @@ -1052,7 +1047,7 @@ namespace Microsoft.PowerShell.Commands { // The key has been created, but the default value failed to be set. // If possible, just write an error instead of failing the entire operation. - + if ((exception is ArgumentException) || (exception is InvalidCastException) || (exception is System.IO.IOException) || @@ -1080,25 +1075,25 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (ArgumentException argException) { - WriteError (new ErrorRecord (argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, path)); + WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, path)); } catch (NotSupportedException notSupportedException) { @@ -1121,14 +1116,14 @@ namespace Microsoft.PowerShell.Commands /// protected override void RemoveItem( string path, - bool recurse) + bool recurse) { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } - tracer.WriteLine("recurse = {0}", recurse); + s_tracer.WriteLine("recurse = {0}", recurse); // Get the parent and child portions of the path @@ -1147,12 +1142,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the remove item with the user string action = RegistryProviderStrings.RemoveKeyAction; - + string resourceTemplate = RegistryProviderStrings.RemoveKeyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path); @@ -1164,28 +1159,28 @@ namespace Microsoft.PowerShell.Commands } catch (ArgumentException argumentException) { - WriteError (new ErrorRecord (argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (NotSupportedException notSupportedException) { @@ -1207,7 +1202,7 @@ namespace Microsoft.PowerShell.Commands /// /// True if the key at the specified path exists, false otherwise. /// - protected override bool ItemExists(string path) + protected override bool ItemExists(string path) { bool result = false; @@ -1263,22 +1258,22 @@ namespace Microsoft.PowerShell.Commands /// /// True if the specified key has subkeys, false otherwise. /// - protected override bool HasChildItems(string path) - { + protected override bool HasChildItems(string path) + { bool result = false; - + if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } - + try { if (IsHiveContainer(path)) { // An empty path will enumerate the hives - result = hiveNames.Length > 0; + result = s_hiveNames.Length > 0; } else { @@ -1304,7 +1299,7 @@ namespace Microsoft.PowerShell.Commands result = false; } - return result; + return result; } // HasChildItems /// @@ -1326,8 +1321,8 @@ namespace Microsoft.PowerShell.Commands protected override void CopyItem( string path, string destination, - bool recurse) - { + bool recurse) + { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); @@ -1338,8 +1333,8 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentException("destination"); } - tracer.WriteLine("destination = {0}", destination); - tracer.WriteLine("recurse = {0}", recurse); + s_tracer.WriteLine("destination = {0}", destination); + s_tracer.WriteLine("recurse = {0}", recurse); IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); @@ -1357,21 +1352,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } key.Close(); @@ -1380,8 +1375,8 @@ namespace Microsoft.PowerShell.Commands private bool CopyRegistryKey( IRegistryWrapper key, - string path, - string destination, + string path, + string destination, bool recurse, bool streamResult, bool streamFirstOnly) @@ -1411,7 +1406,7 @@ namespace Microsoft.PowerShell.Commands !String.IsNullOrEmpty(destination), "The destination should have been validated by the caller"); - tracer.WriteLine("destination = {0}", destination); + s_tracer.WriteLine("destination = {0}", destination); // Get the parent key of the destination // If the destination already exists and is a key, then it becomes @@ -1443,12 +1438,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the copy item with the user string action = RegistryProviderStrings.CopyKeyAction; - + string resourceTemplate = RegistryProviderStrings.CopyKeyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, destination); @@ -1469,7 +1464,6 @@ namespace Microsoft.PowerShell.Commands if (newKey != null) { - // Now copy all the properties from the source to the destination string[] valueNames = key.GetValueNames(); @@ -1545,7 +1539,7 @@ namespace Microsoft.PowerShell.Commands string sourcePath, string destinationPath) { - tracer.WriteLine("destinationPath = {0}", destinationPath); + s_tracer.WriteLine("destinationPath = {0}", destinationPath); // Note the paths have already been normalized so case-insensitive // comparisons should be sufficient @@ -1592,7 +1586,7 @@ namespace Microsoft.PowerShell.Commands Exception e = new ArgumentException( RegistryProviderStrings.DestinationChildOfSource); - WriteError (new ErrorRecord ( + WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, @@ -1616,7 +1610,7 @@ namespace Microsoft.PowerShell.Commands /// to see if the key exists and returns true if it is does or /// false otherwise. /// - protected override bool IsItemContainer(string path) + protected override bool IsItemContainer(string path) { if (path == null) { @@ -1633,7 +1627,7 @@ namespace Microsoft.PowerShell.Commands { try { - IRegistryWrapper key = GetRegkeyForPath (path, false); + IRegistryWrapper key = GetRegkeyForPath(path, false); if (key != null) { @@ -1643,22 +1637,22 @@ namespace Microsoft.PowerShell.Commands result = true; } } - // Catch known exceptions that are not terminating + // Catch known exceptions that are not terminating catch (System.IO.IOException ioException) { - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) { - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (UnauthorizedAccessException unauthorizedAccess) { - WriteError (new ErrorRecord (unauthorizedAccess, unauthorizedAccess.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccess, unauthorizedAccess.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } - return result; + return result; } // IsItemContainer /// @@ -1674,7 +1668,7 @@ namespace Microsoft.PowerShell.Commands /// protected override void MoveItem( string path, - string destination) + string destination) { if (String.IsNullOrEmpty(path)) { @@ -1686,17 +1680,17 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentException("destination"); } - tracer.WriteLine("destination = {0}", destination); + s_tracer.WriteLine("destination = {0}", destination); // Confirm the rename item with the user string action = RegistryProviderStrings.MoveItemAction; - + string resourceTemplate = RegistryProviderStrings.MoveItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, destination); @@ -1723,14 +1717,13 @@ namespace Microsoft.PowerShell.Commands try { continueWithRemove = CopyRegistryKey(key, path, destination, true, true, true); - } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); key.Close(); return; } @@ -1739,7 +1732,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } @@ -1748,7 +1741,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); key.Close(); return; } @@ -1776,7 +1769,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); return; } catch (System.Security.SecurityException securityException) @@ -1784,7 +1777,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) @@ -1792,10 +1785,9 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } - } } // MoveRegistryItem @@ -1870,7 +1862,6 @@ namespace Microsoft.PowerShell.Commands { WritePropertyObject(propertyResults, path); } - } // GetProperty /// @@ -1922,7 +1913,7 @@ namespace Microsoft.PowerShell.Commands if (DynamicParameters != null) { - RegistryProviderSetItemDynamicParameter dynParams = + RegistryProviderSetItemDynamicParameter dynParams = DynamicParameters as RegistryProviderSetItemDynamicParameter; if (dynParams != null) @@ -1932,16 +1923,16 @@ namespace Microsoft.PowerShell.Commands } string action = RegistryProviderStrings.SetPropertyAction; - + string resourceTemplate = RegistryProviderStrings.SetPropertyResourceTemplate; foreach (PSMemberInfo property in propertyValue.Properties) { object newPropertyValue = property.Value; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, property.Name); @@ -1954,35 +1945,33 @@ namespace Microsoft.PowerShell.Commands } catch (InvalidCastException invalidCast) { - WriteError (new ErrorRecord (invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, property.Name)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, property.Name)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } - } } key.Close(); - } // SetProperty @@ -2007,7 +1996,7 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object SetPropertyDynamicParameters( - string path, + string path, PSObject propertyValue) { return new RegistryProviderSetItemDynamicParameter(); @@ -2112,13 +2101,13 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object GetPropertyDynamicParameters( - string path, + string path, Collection providerSpecificPickList) { return null; } - + /// /// Gives the provider a chance to attach additional parameters to the /// clear-itemproperty cmdlet. @@ -2138,7 +2127,7 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object ClearPropertyDynamicParameters( - string path, + string path, Collection propertyToClear) { return null; @@ -3028,12 +3017,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the set item with the user string action = RegistryProviderStrings.NewPropertyAction; - + string resourceTemplate = RegistryProviderStrings.NewPropertyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, propertyName); @@ -3061,48 +3050,46 @@ namespace Microsoft.PowerShell.Commands { // The property already exists - System.IO.IOException e = + System.IO.IOException e = new System.IO.IOException( RegistryProviderStrings.PropertyAlreadyExists); - WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.ResourceExists, path)); + WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.ResourceExists, path)); key.Close(); return; } - } catch (ArgumentException argumentException) { - WriteError (new ErrorRecord (argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (InvalidCastException invalidCast) { - WriteError (new ErrorRecord (invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(invalidCast, invalidCast.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } key.Close(); - } /// @@ -3143,15 +3130,15 @@ namespace Microsoft.PowerShell.Commands } WildcardPattern propertyNamePattern = - WildcardPattern.Get(propertyName, WildcardOptions.IgnoreCase); + WildcardPattern.Get(propertyName, WildcardOptions.IgnoreCase); bool hadAMatch = false; foreach (string valueName in key.GetValueNames()) { if ( - ((! Context.SuppressWildcardExpansion) && (! propertyNamePattern.IsMatch(valueName))) || - (Context.SuppressWildcardExpansion && (! String.Equals(valueName, propertyName, StringComparison.OrdinalIgnoreCase)))) + ((!Context.SuppressWildcardExpansion) && (!propertyNamePattern.IsMatch(valueName))) || + (Context.SuppressWildcardExpansion && (!String.Equals(valueName, propertyName, StringComparison.OrdinalIgnoreCase)))) { continue; } @@ -3159,12 +3146,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the set item with the user string action = RegistryProviderStrings.RemovePropertyAction; - + string resourceTemplate = RegistryProviderStrings.RemovePropertyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, valueName); @@ -3183,21 +3170,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, propertyNameToRemove)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, propertyNameToRemove)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, propertyNameToRemove)); } } // if should process } // foreach @@ -3206,7 +3193,7 @@ namespace Microsoft.PowerShell.Commands WriteErrorIfPerfectMatchNotFound(hadAMatch, path, propertyName); } - + /// /// Renames a property of the item at the specified . /// @@ -3252,12 +3239,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the set item with the user string action = RegistryProviderStrings.RenamePropertyAction; - + string resourceTemplate = RegistryProviderStrings.RenamePropertyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, sourceProperty, @@ -3274,21 +3261,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); } } @@ -3357,12 +3344,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the set item with the user string action = RegistryProviderStrings.CopyPropertyAction; - + string resourceTemplate = RegistryProviderStrings.CopyPropertyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, sourcePath, sourceProperty, @@ -3380,21 +3367,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } } @@ -3462,12 +3449,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the set item with the user string action = RegistryProviderStrings.MovePropertyAction; - + string resourceTemplate = RegistryProviderStrings.MovePropertyResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, sourcePath, sourceProperty, @@ -3485,21 +3472,21 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourcePath)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourcePath)); } } @@ -3540,9 +3527,9 @@ namespace Microsoft.PowerShell.Commands { bool originalPathExists = ItemExists(path); bool originalPathExistsWithRoot = false; - + // This is an expensive test, only do it if we need to. - if(! originalPathExists) + if (!originalPathExists) originalPathExistsWithRoot = ItemExists(MakePath(root, path)); if ((!String.IsNullOrEmpty(parentPath)) && (originalPathExists || originalPathExistsWithRoot)) @@ -3640,14 +3627,14 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object NewPropertyDynamicParameters( - string path, + string path, string propertyName, string type, object value) { return null; } - + /// /// Gives the provider a chance to attach additional parameters to the /// remove-itemproperty cmdlet. @@ -3667,12 +3654,12 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object RemovePropertyDynamicParameters( - string path, + string path, string propertyName) { return null; } - + /// /// Gives the provider a chance to attach additional parameters to the /// rename-itemproperty cmdlet. @@ -3696,7 +3683,7 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object RenamePropertyDynamicParameters( - string path, + string path, string sourceProperty, string destinationProperty) { @@ -3730,14 +3717,14 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object CopyPropertyDynamicParameters( - string sourcePath, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) { return null; } - + /// /// Gives the provider a chance to attach additional parameters to the /// move-itemproperty cmdlet. @@ -3765,7 +3752,7 @@ namespace Microsoft.PowerShell.Commands /// parsing attributes similar to a cmdlet class. /// public object MovePropertyDynamicParameters( - string sourcePath, + string sourcePath, string sourceProperty, string destinationPath, string destinationProperty) @@ -3781,7 +3768,7 @@ namespace Microsoft.PowerShell.Commands #region Private members private void CopyProperty( - IRegistryWrapper sourceKey, + IRegistryWrapper sourceKey, IRegistryWrapper destinationKey, string sourceProperty, string destinationProperty, @@ -3800,9 +3787,9 @@ namespace Microsoft.PowerShell.Commands WriteWrappedPropertyObject(sourceValue, realSourceProperty, sourceKey.Name); } } // CopyProperty - + private void MoveProperty( - IRegistryWrapper sourceKey, + IRegistryWrapper sourceKey, IRegistryWrapper destinationKey, string sourceProperty, string destinationProperty) @@ -3826,9 +3813,9 @@ namespace Microsoft.PowerShell.Commands // Copy property will throw an exception if it fails CopyProperty( - sourceKey, - destinationKey, - realSourceProperty, + sourceKey, + destinationKey, + realSourceProperty, realDestinationProperty, false); @@ -3839,14 +3826,14 @@ namespace Microsoft.PowerShell.Commands } object newValue = destinationKey.GetValue(realDestinationProperty); - WriteWrappedPropertyObject(newValue,destinationProperty, destinationKey.Name); + WriteWrappedPropertyObject(newValue, destinationProperty, destinationKey.Name); } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourceKey.Name)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.WriteError, sourceKey.Name)); return; } catch (System.Security.SecurityException securityException) @@ -3854,7 +3841,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) @@ -3862,7 +3849,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, sourceKey.Name)); return; } } // MoveProperty @@ -3938,7 +3925,6 @@ namespace Microsoft.PowerShell.Commands if (propertyNames == null) { propertyNames = new Collection(); - } if (propertyNames.Count == 0 && getAll) @@ -4003,7 +3989,7 @@ namespace Microsoft.PowerShell.Commands } } - if( + if ( expandAll || ((Context.SuppressWildcardExpansion == false) && (valueNameMatcher.IsMatch(valueNameToMatch))) || ((Context.SuppressWildcardExpansion == true) && (String.Equals(valueNameToMatch, requestedValueName, StringComparison.OrdinalIgnoreCase)))) @@ -4217,26 +4203,26 @@ namespace Microsoft.PowerShell.Commands } if (TransactionAvailable()) - { - for (int k = 0; k < wellKnownHivesTx.Length; k++) + { + for (int k = 0; k < s_wellKnownHivesTx.Length; k++) { - if (String.Equals(path, hiveNames[k], StringComparison.OrdinalIgnoreCase) || - String.Equals(path, hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) + if (String.Equals(path, s_hiveNames[k], StringComparison.OrdinalIgnoreCase) || + String.Equals(path, s_hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) { using (CurrentPSTransaction) { - return new TransactedRegistryWrapper(wellKnownHivesTx[k], this); + return new TransactedRegistryWrapper(s_wellKnownHivesTx[k], this); } } } } else { - for (int k = 0; k < wellKnownHives.Length; k++) + for (int k = 0; k < s_wellKnownHives.Length; k++) { - if (String.Equals(path, hiveNames[k], StringComparison.OrdinalIgnoreCase) || - String.Equals(path, hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) - return new RegistryWrapper(wellKnownHives[k]); + if (String.Equals(path, s_hiveNames[k], StringComparison.OrdinalIgnoreCase) || + String.Equals(path, s_hiveShortNames[k], StringComparison.OrdinalIgnoreCase)) + return new RegistryWrapper(s_wellKnownHives[k]); } } return null; @@ -4265,7 +4251,6 @@ namespace Microsoft.PowerShell.Commands try { - // 1. Normalize path ( for "//","." etc ) // 2. Open the root // 3. Create subkey @@ -4292,10 +4277,10 @@ namespace Microsoft.PowerShell.Commands // NormalizePath will trim "\" at the end. So there is always something // after index. Asserting just in case.. - Dbg.Diagnostics.Assert( index + 1 < path.Length ,"Bad path"); + Dbg.Diagnostics.Assert(index + 1 < path.Length, "Bad path"); string remainingPath = path.Substring(index + 1); - IRegistryWrapper rootKey = GetHiveRoot (keyRoot); + IRegistryWrapper rootKey = GetHiveRoot(keyRoot); if (remainingPath.Length == 0 || rootKey == null) { @@ -4317,7 +4302,6 @@ namespace Microsoft.PowerShell.Commands } result = true; - } catch (ArgumentException argumentException) { @@ -4382,23 +4366,23 @@ namespace Microsoft.PowerShell.Commands IRegistryWrapper result = null; try { - result = GetRegkeyForPath (path, writeAccess); + result = GetRegkeyForPath(path, writeAccess); if (result == null) { // The key was not found, write out an error. ArgumentException exception = - new ArgumentException ( + new ArgumentException( RegistryProviderStrings.KeyDoesNotExist); - WriteError (new ErrorRecord (exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); + WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); return result; } } catch (ArgumentException argumentException) { - WriteError (new ErrorRecord (argumentException, argumentException.GetType().FullName, ErrorCategory.OpenError, path)); + WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.IO.IOException ioException) @@ -4406,7 +4390,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.OpenError, path)); + WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.Security.SecurityException securityException) @@ -4414,7 +4398,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } catch (System.UnauthorizedAccessException unauthorizedAccessException) @@ -4422,7 +4406,7 @@ namespace Microsoft.PowerShell.Commands // An exception occurred while trying to get the key. Write // out the error. - WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } return result; @@ -4452,7 +4436,7 @@ namespace Microsoft.PowerShell.Commands { // The key was not found, write out an error. - ArgumentException exception = + ArgumentException exception = new ArgumentException( RegistryProviderStrings.KeyDoesNotExist); throw exception; @@ -4464,7 +4448,7 @@ namespace Microsoft.PowerShell.Commands return null; } - tracer.WriteLine("writeAccess = {0}", writeAccess); + s_tracer.WriteLine("writeAccess = {0}", writeAccess); IRegistryWrapper result = null; @@ -4482,14 +4466,14 @@ namespace Microsoft.PowerShell.Commands if (index == -1) { - result = GetHiveRoot (path); + result = GetHiveRoot(path); break; } string keyRoot = path.Substring(0, index); string remainingPath = path.Substring(index + 1); - IRegistryWrapper resultRoot = GetHiveRoot (keyRoot); + IRegistryWrapper resultRoot = GetHiveRoot(keyRoot); if (remainingPath.Length == 0 || resultRoot == null) { @@ -4556,7 +4540,6 @@ namespace Microsoft.PowerShell.Commands return currentKey; } - } while (false); return result; @@ -4565,7 +4548,7 @@ namespace Microsoft.PowerShell.Commands // NB: The HKEY_DYN_DATA hive is left out of the following lists because // it is only available on Win98/ME and we do not support that platform. - private static readonly string[] hiveNames = new string[] { + private static readonly string[] s_hiveNames = new string[] { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER", "HKEY_CLASSES_ROOT", @@ -4574,7 +4557,7 @@ namespace Microsoft.PowerShell.Commands "HKEY_PERFORMANCE_DATA" }; - private static readonly string[] hiveShortNames = new string[] { + private static readonly string[] s_hiveShortNames = new string[] { "HKLM", "HKCU", "HKCR", @@ -4583,7 +4566,7 @@ namespace Microsoft.PowerShell.Commands "HKPD" }; - private static readonly RegistryKey[] wellKnownHives = new RegistryKey[] { + private static readonly RegistryKey[] s_wellKnownHives = new RegistryKey[] { Registry.LocalMachine, Registry.CurrentUser, Registry.ClassesRoot, @@ -4591,15 +4574,15 @@ namespace Microsoft.PowerShell.Commands Registry.Users, Registry.PerformanceData }; - - private static readonly TransactedRegistryKey[] wellKnownHivesTx = new TransactedRegistryKey[] { + + private static readonly TransactedRegistryKey[] s_wellKnownHivesTx = new TransactedRegistryKey[] { TransactedRegistry.LocalMachine, TransactedRegistry.CurrentUser, TransactedRegistry.ClassesRoot, TransactedRegistry.CurrentConfig, TransactedRegistry.Users }; - + /// /// Sets or creates a registry value on a key. /// @@ -4659,10 +4642,10 @@ namespace Microsoft.PowerShell.Commands /// /// private void SetRegistryValue( - IRegistryWrapper key, - string propertyName, - object value, - RegistryValueKind kind, + IRegistryWrapper key, + string propertyName, + object value, + RegistryValueKind kind, string path, bool writeResult) { @@ -4673,7 +4656,7 @@ namespace Microsoft.PowerShell.Commands string propertyNameToSet = GetPropertyName(propertyName); RegistryValueKind existingKind = RegistryValueKind.Unknown; - + // If user does not specify a kind: get the valuekind if the property // already exists if (kind == RegistryValueKind.Unknown) @@ -4687,7 +4670,7 @@ namespace Microsoft.PowerShell.Commands { try { - value = ConvertValueToKind (value, existingKind); + value = ConvertValueToKind(value, existingKind); kind = existingKind; } catch (InvalidCastException) @@ -4717,7 +4700,7 @@ namespace Microsoft.PowerShell.Commands } } - value = ConvertValueToKind (value, kind); + value = ConvertValueToKind(value, kind); } key.SetValue(propertyNameToSet, value, kind); @@ -4774,35 +4757,35 @@ namespace Microsoft.PowerShell.Commands { switch (kind) { - case RegistryValueKind.Binary : + case RegistryValueKind.Binary: value = (value != null) ? (byte[])LanguagePrimitives.ConvertTo( value, typeof(byte[]), - CultureInfo.CurrentCulture) - : new byte[] {} ; + CultureInfo.CurrentCulture) + : new byte[] { }; break; case RegistryValueKind.DWord: - { - if (value != null) { - try + if (value != null) { - value = (int)LanguagePrimitives.ConvertTo(value, typeof(int), CultureInfo.CurrentCulture); + try + { + value = (int)LanguagePrimitives.ConvertTo(value, typeof(int), CultureInfo.CurrentCulture); + } + catch (PSInvalidCastException) + { + value = (UInt32)LanguagePrimitives.ConvertTo(value, typeof(UInt32), CultureInfo.CurrentCulture); + } } - catch (PSInvalidCastException) + else { - value = (UInt32)LanguagePrimitives.ConvertTo(value, typeof(UInt32), CultureInfo.CurrentCulture); + value = 0; } - } - else - { - value = 0; - } - }; break; + }; break; - case RegistryValueKind.ExpandString : + case RegistryValueKind.ExpandString: value = (value != null) ? (string)LanguagePrimitives.ConvertTo( value, @@ -4811,35 +4794,35 @@ namespace Microsoft.PowerShell.Commands : ""; break; - case RegistryValueKind.MultiString : + case RegistryValueKind.MultiString: value = (value != null) ? (string[])LanguagePrimitives.ConvertTo( value, typeof(string[]), CultureInfo.CurrentCulture) - : new string[] {}; + : new string[] { }; break; - case RegistryValueKind.QWord : - { - if (value != null) + case RegistryValueKind.QWord: { - try + if (value != null) { - value = (long) LanguagePrimitives.ConvertTo(value, typeof(long), CultureInfo.CurrentCulture); + try + { + value = (long)LanguagePrimitives.ConvertTo(value, typeof(long), CultureInfo.CurrentCulture); + } + catch (PSInvalidCastException) + { + value = (UInt64)LanguagePrimitives.ConvertTo(value, typeof(UInt64), CultureInfo.CurrentCulture); + } } - catch (PSInvalidCastException) + else { - value = (UInt64) LanguagePrimitives.ConvertTo(value, typeof(UInt64), CultureInfo.CurrentCulture); + value = 0; } - } - else - { - value = 0; - } - }; break; + }; break; - case RegistryValueKind.String : + case RegistryValueKind.String: value = (value != null) ? (string)LanguagePrimitives.ConvertTo( value, @@ -4848,7 +4831,7 @@ namespace Microsoft.PowerShell.Commands : ""; break; - // If kind is Unknown then just leave the value as-is. + // If kind is Unknown then just leave the value as-is. } return value; } @@ -4919,7 +4902,7 @@ namespace Microsoft.PowerShell.Commands return RegistryValueKind.Unknown; } - + /// /// helper to read back an existing registry key value /// @@ -4928,7 +4911,7 @@ namespace Microsoft.PowerShell.Commands /// value of the key, null if it could not retrieve /// it because known exceptions were thrown, else an exception is percolated up /// - private static object ReadExistingKeyValue (IRegistryWrapper key, string valueName) + private static object ReadExistingKeyValue(IRegistryWrapper key, string valueName) { try { @@ -4936,7 +4919,7 @@ namespace Microsoft.PowerShell.Commands // type (RegistryValueKind), retrieve the value again // to output it in the correct form to the user. - return key.GetValue (valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames); + return key.GetValue(valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames); } catch (System.IO.IOException) { @@ -5105,7 +5088,7 @@ namespace Microsoft.PowerShell.Commands var stringComparer = Host.CurrentCulture.CompareInfo; if (stringComparer.Compare( - userEnteredPropertyName, + userEnteredPropertyName, GetLocalizedDefaultToken(), CompareOptions.IgnoreCase) == 0) { @@ -5132,23 +5115,22 @@ namespace Microsoft.PowerShell.Commands /// The only acceptable values for this parameter are those found /// in the RegistryValueKind enum /// - [Parameter (ValueFromPipelineByPropertyName = true)] + [Parameter(ValueFromPipelineByPropertyName = true)] public RegistryValueKind Type { get { - return type; + return _type; } set { - type = value; + _type = value; } } // Type - private RegistryValueKind type = RegistryValueKind.Unknown; + private RegistryValueKind _type = RegistryValueKind.Unknown; } // class RegistryProviderSetItemDynamicParameter - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index bf21fb151..a5c80c868 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -5,7 +5,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Management.Automation; using System.Management.Automation.Provider; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Security.AccessControl; using Microsoft.PowerShell.Commands.Internal; @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands /// /// interfaces. /// - public sealed partial class RegistryProvider : + public sealed partial class RegistryProvider : NavigationCmdletProvider, IPropertyCmdletProvider, #if SUPPORTS_IMULTIVALUEPROPERTYCMDLETPROVIDER @@ -49,7 +49,7 @@ namespace Microsoft.PowerShell.Commands public void GetSecurityDescriptor(string path, AccessControlSections sections) { - ObjectSecurity sd=null; + ObjectSecurity sd = null; IRegistryWrapper key = null; // Validate input first. @@ -63,9 +63,9 @@ namespace Microsoft.PowerShell.Commands throw PSTraceSource.NewArgumentException("sections"); } - path = NormalizePath(path); + path = NormalizePath(path); - key = GetRegkeyForPathWriteIfError(path, false); + key = GetRegkeyForPathWriteIfError(path, false); if (key != null) { @@ -75,7 +75,7 @@ namespace Microsoft.PowerShell.Commands } catch (System.Security.SecurityException e) { - WriteError (new ErrorRecord (e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); + WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } WriteSecurityDescriptorObject(sd, path); @@ -94,7 +94,7 @@ namespace Microsoft.PowerShell.Commands /// The new security descriptor for the item. /// public void SetSecurityDescriptor( - string path, + string path, ObjectSecurity securityDescriptor) { IRegistryWrapper key = null; @@ -219,7 +219,6 @@ namespace Microsoft.PowerShell.Commands } #endregion ISecurityDescriptorCmdletProvider members - } } diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 18794af53..e3992228f 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -35,8 +35,8 @@ namespace Microsoft.PowerShell.Commands void SetAccessControl(ObjectSecurity securityDescriptor); ObjectSecurity GetAccessControl(AccessControlSections includeSections); void Close(); - string Name { get;} - int SubKeyCount { get;} + string Name { get; } + int SubKeyCount { get; } } internal static class RegistryWrapperUtils @@ -111,18 +111,18 @@ namespace Microsoft.PowerShell.Commands internal class RegistryWrapper : IRegistryWrapper { - RegistryKey regKey; + private RegistryKey _regKey; internal RegistryWrapper(RegistryKey regKey) { - this.regKey = regKey; + _regKey = regKey; } #region IRegistryWrapper Members public void SetValue(string name, object value) { - regKey.SetValue(name, value); + _regKey.SetValue(name, value); } public void SetValue(string name, object value, RegistryValueKind valueKind) @@ -130,27 +130,27 @@ namespace Microsoft.PowerShell.Commands value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); - regKey.SetValue(name, value, valueKind); + _regKey.SetValue(name, value, valueKind); } public string[] GetValueNames() { - return regKey.GetValueNames(); + return _regKey.GetValueNames(); } public void DeleteValue(string name) { - regKey.DeleteValue(name); + _regKey.DeleteValue(name); } public string[] GetSubKeyNames() { - return regKey.GetSubKeyNames(); + return _regKey.GetSubKeyNames(); } public IRegistryWrapper CreateSubKey(string subkey) { - RegistryKey newKey = regKey.CreateSubKey(subkey); + RegistryKey newKey = _regKey.CreateSubKey(subkey); if (newKey == null) return null; else @@ -159,7 +159,7 @@ namespace Microsoft.PowerShell.Commands public IRegistryWrapper OpenSubKey(string name, bool writable) { - RegistryKey newKey = regKey.OpenSubKey(name, writable); + RegistryKey newKey = _regKey.OpenSubKey(name, writable); if (newKey == null) return null; else @@ -168,12 +168,12 @@ namespace Microsoft.PowerShell.Commands public void DeleteSubKeyTree(string subkey) { - regKey.DeleteSubKeyTree(subkey); + _regKey.DeleteSubKeyTree(subkey); } public object GetValue(string name) { - object value = regKey.GetValue(name); + object value = _regKey.GetValue(name); try { @@ -189,7 +189,7 @@ namespace Microsoft.PowerShell.Commands public object GetValue(string name, object defaultValue, RegistryValueOptions options) { - object value = regKey.GetValue(name, defaultValue, options); + object value = _regKey.GetValue(name, defaultValue, options); try { @@ -205,37 +205,37 @@ namespace Microsoft.PowerShell.Commands public RegistryValueKind GetValueKind(string name) { - return regKey.GetValueKind(name); + return _regKey.GetValueKind(name); } public void Close() { - regKey.Dispose(); + _regKey.Dispose(); } public string Name { - get { return regKey.Name; } + get { return _regKey.Name; } } public int SubKeyCount { - get { return regKey.SubKeyCount; } + get { return _regKey.SubKeyCount; } } public object RegistryKey { - get { return regKey; } + get { return _regKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { - regKey.SetAccessControl((RegistrySecurity)securityDescriptor); + _regKey.SetAccessControl((RegistrySecurity)securityDescriptor); } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { - return regKey.GetAccessControl(includeSections); + return _regKey.GetAccessControl(includeSections); } #endregion @@ -243,97 +243,97 @@ namespace Microsoft.PowerShell.Commands internal class TransactedRegistryWrapper : IRegistryWrapper { - TransactedRegistryKey txRegKey; - CmdletProvider provider; + private TransactedRegistryKey _txRegKey; + private CmdletProvider _provider; internal TransactedRegistryWrapper(TransactedRegistryKey txRegKey, CmdletProvider provider) { - this.txRegKey = txRegKey; - this.provider = provider; + _txRegKey = txRegKey; + _provider = provider; } #region IRegistryWrapper Members public void SetValue(string name, object value) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - txRegKey.SetValue(name, value); + _txRegKey.SetValue(name, value); } } public void SetValue(string name, object value, RegistryValueKind valueKind) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { value = System.Management.Automation.PSObject.Base(value); value = RegistryWrapperUtils.ConvertUIntToValueForRegistryIfNeeded(value, valueKind); - txRegKey.SetValue(name, value, valueKind); + _txRegKey.SetValue(name, value, valueKind); } } public string[] GetValueNames() { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.GetValueNames(); + return _txRegKey.GetValueNames(); } } public void DeleteValue(string name) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - txRegKey.DeleteValue(name); + _txRegKey.DeleteValue(name); } } public string[] GetSubKeyNames() { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.GetSubKeyNames(); + return _txRegKey.GetSubKeyNames(); } } public IRegistryWrapper CreateSubKey(string subkey) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - TransactedRegistryKey newKey = txRegKey.CreateSubKey(subkey); + TransactedRegistryKey newKey = _txRegKey.CreateSubKey(subkey); if (newKey == null) return null; else - return new TransactedRegistryWrapper(newKey, provider); + return new TransactedRegistryWrapper(newKey, _provider); } } public IRegistryWrapper OpenSubKey(string name, bool writable) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - TransactedRegistryKey newKey = txRegKey.OpenSubKey(name, writable); + TransactedRegistryKey newKey = _txRegKey.OpenSubKey(name, writable); if (newKey == null) return null; else - return new TransactedRegistryWrapper(newKey, provider); + return new TransactedRegistryWrapper(newKey, _provider); } } public void DeleteSubKeyTree(string subkey) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - txRegKey.DeleteSubKeyTree(subkey); + _txRegKey.DeleteSubKeyTree(subkey); } } public object GetValue(string name) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - object value = txRegKey.GetValue(name); + object value = _txRegKey.GetValue(name); try { @@ -350,9 +350,9 @@ namespace Microsoft.PowerShell.Commands public object GetValue(string name, object defaultValue, RegistryValueOptions options) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - object value = txRegKey.GetValue(name, defaultValue, options); + object value = _txRegKey.GetValue(name, defaultValue, options); try { @@ -369,60 +369,60 @@ namespace Microsoft.PowerShell.Commands public RegistryValueKind GetValueKind(string name) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.GetValueKind(name); + return _txRegKey.GetValueKind(name); } } public void Close() { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - txRegKey.Close(); + _txRegKey.Close(); } } public string Name { - get + get { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.Name; + return _txRegKey.Name; } } } public int SubKeyCount { - get + get { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.SubKeyCount; + return _txRegKey.SubKeyCount; } } } public object RegistryKey { - get { return txRegKey; } + get { return _txRegKey; } } public void SetAccessControl(ObjectSecurity securityDescriptor) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - txRegKey.SetAccessControl((TransactedRegistrySecurity)securityDescriptor); + _txRegKey.SetAccessControl((TransactedRegistrySecurity)securityDescriptor); } } public ObjectSecurity GetAccessControl(AccessControlSections includeSections) { - using (provider.CurrentPSTransaction) + using (_provider.CurrentPSTransaction) { - return txRegKey.GetAccessControl(includeSections); + return _txRegKey.GetAccessControl(includeSections); } } diff --git a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs index 006714766..306c3acaa 100644 --- a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs @@ -1,16 +1,10 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // // NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\SafeHandles\SafeRegistryHandle.cs. // Namespace: Microsoft.Win32.SafeHandles // /*============================================================ ** -** Class: SafeRegistryHandle ** ** ** A wrapper for registry handles @@ -35,18 +29,18 @@ using System.Security.Permissions; namespace Microsoft.PowerShell.Commands.Internal { - - internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid { - + internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid + { // Note: Officially -1 is the recommended invalid handle value for // registry keys, but we'll also get back 0 as an invalid handle from // RegOpenKeyEx. - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)] - internal SafeRegistryHandle() : base(true) {} + [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] + internal SafeRegistryHandle() : base(true) { } - [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)] - internal SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { + [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] + internal SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) + { SetHandle(preexistingHandle); } @@ -55,7 +49,7 @@ namespace Microsoft.PowerShell.Commands.Internal ResourceExposure(ResourceScope.None), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int RegCloseKey(IntPtr hKey); - + override protected bool ReleaseHandle() { #if UNIX diff --git a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs index 797193cc6..f9072273d 100644 --- a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs @@ -2,6 +2,7 @@ // Copyright (C) Microsoft. All rights reserved. // #pragma warning disable 1634, 1691 + namespace Microsoft.PowerShell.Commands.Internal { using System; @@ -56,7 +57,7 @@ namespace Microsoft.PowerShell.Commands.Internal { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } - + IntPtr ktmTxHandle; int hr = ktmInterface.GetHandle(out ktmTxHandle); HandleError(hr); diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index f6adf4b6b..0cfa46664 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -6,7 +6,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. #pragma warning disable 56506 using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.IO; @@ -16,7 +16,6 @@ using System.Security; namespace Microsoft.PowerShell.Commands { - /// /// This is the base class for all the providers that produce a view /// on session state data (Variables, Aliases, and Functions) @@ -29,10 +28,10 @@ namespace Microsoft.PowerShell.Commands /// An instance of the PSTraceSource class used for trace output /// [Dbg.TraceSourceAttribute( - "SessionStateProvider", + "SessionStateProvider", "Providers that produce a view of session state data.")] - private readonly static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("SessionStateProvider", + private readonly static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("SessionStateProvider", "Providers that produce a view of session state data."); #endregion tracer @@ -114,7 +113,7 @@ namespace Microsoft.PowerShell.Commands /// the Value property of a DictionaryEntry /// /// - internal virtual object GetValueOfItem (object item) + internal virtual object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( item != null, @@ -165,7 +164,7 @@ namespace Microsoft.PowerShell.Commands /// method. /// /// - protected override void GetItem(string name) + protected override void GetItem(string name) { bool isContainer = false; object item = null; @@ -211,12 +210,12 @@ namespace Microsoft.PowerShell.Commands /// /// protected override void SetItem( - string name, - object value) + string name, + object value) { if (String.IsNullOrEmpty(name)) { - WriteError (new ErrorRecord ( + WriteError(new ErrorRecord( PSTraceSource.NewArgumentNullException("name"), "SetItemNullName", ErrorCategory.InvalidArgument, @@ -264,7 +263,7 @@ namespace Microsoft.PowerShell.Commands /// /// /// - protected override void ClearItem (string path) + protected override void ClearItem(string path) { if (String.IsNullOrEmpty(path)) { @@ -281,12 +280,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the clear item with the user string action = SessionStateProviderBaseStrings.ClearItemAction; - + string resourceTemplate = SessionStateProviderBaseStrings.ClearItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path); @@ -327,7 +326,7 @@ namespace Microsoft.PowerShell.Commands /// Ignored. /// /// - protected override void GetChildItems (string path, bool recurse) + protected override void GetChildItems(string path, bool recurse) { CommandOrigin origin = this.Context.Origin; if (String.IsNullOrEmpty(path)) @@ -340,11 +339,11 @@ namespace Microsoft.PowerShell.Commands } catch (SecurityException e) { - WriteError ( - new ErrorRecord ( - e, - "GetTableSecurityException", - ErrorCategory.ReadError, + WriteError( + new ErrorRecord( + e, + "GetTableSecurityException", + ErrorCategory.ReadError, path)); return; } @@ -356,7 +355,7 @@ namespace Microsoft.PowerShell.Commands sortedEntries.Add(entry); } sortedEntries.Sort( - delegate(DictionaryEntry left, DictionaryEntry right) + delegate (DictionaryEntry left, DictionaryEntry right) { string leftKey = (string)left.Key; string rightKey = (string)right.Key; @@ -398,7 +397,7 @@ namespace Microsoft.PowerShell.Commands else { object item = null; - + try { item = GetSessionStateItem(path); @@ -445,7 +444,7 @@ namespace Microsoft.PowerShell.Commands /// Ignored. /// /// - protected override void GetChildNames (string path, ReturnContainers returnContainers) + protected override void GetChildNames(string path, ReturnContainers returnContainers) { CommandOrigin origin = this.Context.Origin; if (String.IsNullOrEmpty(path)) @@ -458,11 +457,11 @@ namespace Microsoft.PowerShell.Commands } catch (SecurityException e) { - WriteError ( - new ErrorRecord ( - e, - "GetChildNamesSecurityException", - ErrorCategory.ReadError, + WriteError( + new ErrorRecord( + e, + "GetChildNamesSecurityException", + ErrorCategory.ReadError, path)); return; } @@ -502,7 +501,7 @@ namespace Microsoft.PowerShell.Commands else { object item = null; - + try { item = GetSessionStateItem(path); @@ -540,7 +539,7 @@ namespace Microsoft.PowerShell.Commands /// True if path is empty or null, false otherwise. /// /// - protected override bool HasChildItems (string path) + protected override bool HasChildItems(string path) { bool result = false; @@ -562,7 +561,6 @@ namespace Microsoft.PowerShell.Commands ErrorCategory.ReadError, path)); } - } return result; @@ -581,7 +579,7 @@ namespace Microsoft.PowerShell.Commands /// True if the item exists, false otherwise. /// /// - protected override bool ItemExists (string path) + protected override bool ItemExists(string path) { bool result = false; @@ -592,7 +590,7 @@ namespace Microsoft.PowerShell.Commands else { object item = null; - + try { item = GetSessionStateItem(path); @@ -633,9 +631,9 @@ namespace Microsoft.PowerShell.Commands /// . ( ) : /// /// - protected override bool IsValidPath (string path) + protected override bool IsValidPath(string path) { - return !String.IsNullOrEmpty (path); + return !String.IsNullOrEmpty(path); } /// @@ -650,13 +648,13 @@ namespace Microsoft.PowerShell.Commands /// Ignored. /// /// - protected override void RemoveItem (string path, bool recurse) + protected override void RemoveItem(string path, bool recurse) { if (String.IsNullOrEmpty(path)) { Exception e = - PSTraceSource.NewArgumentException ("path"); - WriteError (new ErrorRecord ( + PSTraceSource.NewArgumentException("path"); + WriteError(new ErrorRecord( e, "RemoveItemNullPath", ErrorCategory.InvalidArgument, @@ -667,12 +665,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the remove item with the user string action = SessionStateProviderBaseStrings.RemoveItemAction; - + string resourceTemplate = SessionStateProviderBaseStrings.RemoveItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path); @@ -728,13 +726,13 @@ namespace Microsoft.PowerShell.Commands /// The value of the new item. /// /// - protected override void NewItem (string path, string type, object newItem) + protected override void NewItem(string path, string type, object newItem) { if (String.IsNullOrEmpty(path)) { Exception e = PSTraceSource.NewArgumentException("path"); - WriteError (new ErrorRecord ( + WriteError(new ErrorRecord( e, "NewItemNullPath", ErrorCategory.InvalidArgument, @@ -765,8 +763,8 @@ namespace Microsoft.PowerShell.Commands SessionStateStrings.NewItemAlreadyExists, path); - WriteError ( - new ErrorRecord ( + WriteError( + new ErrorRecord( e.ErrorRecord, e)); return; @@ -776,12 +774,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the new item with the user string action = SessionStateProviderBaseStrings.NewItemAction; - + string resourceTemplate = SessionStateProviderBaseStrings.NewItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, type, @@ -810,7 +808,7 @@ namespace Microsoft.PowerShell.Commands /// Ignored. /// /// - protected override void CopyItem (string path, string copyPath, bool recurse) + protected override void CopyItem(string path, string copyPath, bool recurse) { if (String.IsNullOrEmpty(path)) { @@ -835,7 +833,7 @@ namespace Microsoft.PowerShell.Commands } object item = null; - + try { item = GetSessionStateItem(path); @@ -856,12 +854,12 @@ namespace Microsoft.PowerShell.Commands // Confirm the new item with the user string action = SessionStateProviderBaseStrings.CopyItemAction; - + string resourceTemplate = SessionStateProviderBaseStrings.CopyItemResourceTemplate; - string resource = + string resource = String.Format( - Host.CurrentCulture, + Host.CurrentCulture, resourceTemplate, path, copyPath); @@ -905,7 +903,6 @@ namespace Microsoft.PowerShell.Commands e)); return; } - } // CopyItem /// @@ -935,7 +932,7 @@ namespace Microsoft.PowerShell.Commands } object item = null; - + try { item = GetSessionStateItem(name); @@ -962,8 +959,8 @@ namespace Microsoft.PowerShell.Commands SessionStateStrings.NewItemAlreadyExists, newName); - WriteError ( - new ErrorRecord ( + WriteError( + new ErrorRecord( e.ErrorRecord, e)); return; @@ -1055,7 +1052,6 @@ namespace Microsoft.PowerShell.Commands e)); return; } - } // RenameItem #endregion ContainerCmdletProvider overrides @@ -1110,7 +1106,7 @@ namespace Microsoft.PowerShell.Commands /// This exception is always thrown. /// /// - public void ClearContent(string path) + public void ClearContent(string path) { throw PSTraceSource.NewNotSupportedException( @@ -1190,12 +1186,12 @@ namespace Microsoft.PowerShell.Commands { throw PSTraceSource.NewArgumentNullException("provider"); } - this.path = path; - this.provider = provider; + _path = path; + _provider = provider; } - private string path; - private SessionStateProviderBase provider; + private string _path; + private SessionStateProviderBase _provider; /// /// Reads the content from the item @@ -1218,13 +1214,13 @@ namespace Microsoft.PowerShell.Commands { IList result = null; - if (!contentRead) + if (!_contentRead) { - object item = provider.GetSessionStateItem(path); + object item = _provider.GetSessionStateItem(_path); if (item != null) { - object getItemValueResult = provider.GetValueOfItem(item); + object getItemValueResult = _provider.GetValueOfItem(item); if (getItemValueResult != null) { @@ -1234,13 +1230,13 @@ namespace Microsoft.PowerShell.Commands result = new object[] { getItemValueResult }; } } - contentRead = true; + _contentRead = true; } } return result; } - bool contentRead; + private bool _contentRead; /// /// Writes content to the item. @@ -1261,7 +1257,7 @@ namespace Microsoft.PowerShell.Commands /// public IList Write(IList content) { - if(content == null) + if (content == null) { throw PSTraceSource.NewArgumentNullException("content"); } @@ -1273,7 +1269,7 @@ namespace Microsoft.PowerShell.Commands valueToSet = content[0]; } - provider.SetSessionStateItem(path, valueToSet, false); + _provider.SetSessionStateItem(_path, valueToSet, false); return content; } @@ -1307,7 +1303,7 @@ namespace Microsoft.PowerShell.Commands /// close their reader so do nothing. /// /// - public void Close() {} + public void Close() { } /// /// Closes the reader. None of the derived providers need to diff --git a/src/System.Management.Automation/namespaces/StackInfo.cs b/src/System.Management.Automation/namespaces/StackInfo.cs index b8f11da97..4b53874cf 100644 --- a/src/System.Management.Automation/namespaces/StackInfo.cs +++ b/src/System.Management.Automation/namespaces/StackInfo.cs @@ -44,7 +44,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("stackName"); } - this.stackName = stackName; + _stackName = stackName; // Since the Stack constructor takes an IEnumerable and // not a Stack the stack actually gets enumerated in the @@ -65,10 +65,8 @@ namespace System.Management.Automation /// public string Name { - get { return stackName; } + get { return _stackName; } } - private string stackName = null; - + private string _stackName = null; } // PathInfoStack - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/namespaces/TransactedRegistry.cs b/src/System.Management.Automation/namespaces/TransactedRegistry.cs index 87896a7de..6aaeab765 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistry.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistry.cs @@ -1,8 +1,4 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // // NOTE: A vast majority of this code was copied from BCL in // ndp\clr\src\BCL\Microsoft\Win32\Registry.cs. @@ -13,9 +9,8 @@ using BCLDebug = System.Diagnostics.Debug; namespace Microsoft.PowerShell.Commands.Internal { - - using System; - using System.Runtime.InteropServices; + using System; + using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Win32; using System.Management.Automation; @@ -54,7 +49,7 @@ namespace Microsoft.PowerShell.Commands.Internal // 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. * @@ -73,7 +68,7 @@ namespace Microsoft.PowerShell.Commands.Internal // 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. * @@ -92,7 +87,7 @@ namespace Microsoft.PowerShell.Commands.Internal // 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. * @@ -111,7 +106,7 @@ namespace Microsoft.PowerShell.Commands.Internal // 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. * diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 11e7de70e..e9a8f1e37 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1,8 +1,4 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // // NOTE: A vast majority of this code was copied from BCL in @@ -60,7 +56,6 @@ using Win32Native = Microsoft.PowerShell.Commands.Internal.Win32Native; namespace Microsoft.PowerShell.Commands.Internal { - using System; using System.Collections; using System.Collections.Generic; @@ -111,20 +106,20 @@ namespace Microsoft.PowerShell.Commands.Internal // Dirty indicates that we have munged data that should be potentially // written to disk. // - private const int STATE_DIRTY = 0x0001; + 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; + private const int STATE_SYSTEMKEY = 0x0002; // Access // - private const int STATE_WRITEACCESS = 0x0004; + 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[] hkeyNames = new String[] { + private static readonly String[] s_hkeyNames = new String[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", @@ -142,12 +137,12 @@ namespace Microsoft.PowerShell.Commands.Internal 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; + 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 @@ -158,14 +153,14 @@ namespace Microsoft.PowerShell.Commands.Internal // Suppressed because there is no way for arbitrary data to be passed. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] - int RegOpenKeyTransactedWrapper(SafeRegistryHandle hKey, String lpSubKey, + 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); + error = Win32Native.RegOpenKeyTransacted(_hkey, lpSubKey, ulOptions, samDesired, out hKeyToReturn, hTransaction, pExtendedParameter); if (Win32Native.ERROR_SUCCESS == error && !hKeyToReturn.IsInvalid) { @@ -191,7 +186,7 @@ namespace Microsoft.PowerShell.Commands.Internal { SafeRegistryHandle nonTxKey = null; SafeRegistryHandle txKey = null; - error = Win32Native.RegOpenKeyEx(hkey, lpSubKey, ulOptions, samDesired, out nonTxKey); + 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) @@ -220,27 +215,30 @@ namespace Microsoft.PowerShell.Commands.Internal * 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) { - this.hkey = hkey; - this.keyName = ""; - if (systemkey) { - this.state |= STATE_SYSTEMKEY; + private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, + System.Transactions.Transaction transaction, SafeTransactionHandle txHandle) + { + _hkey = hkey; + _keyName = ""; + if (systemkey) + { + _state |= STATE_SYSTEMKEY; } - if (writable) { - this.state |= STATE_WRITEACCESS; + 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 (null != transaction) { - this.myTransaction = transaction.Clone(); - this.myTransactionHandle = txHandle; + _myTransaction = transaction.Clone(); + _myTransactionHandle = txHandle; } else { - this.myTransaction = null; - this.myTransactionHandle = null; + _myTransaction = null; + _myTransactionHandle = null; } } @@ -251,15 +249,15 @@ namespace Microsoft.PowerShell.Commands.Internal // 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 (null != this.myTransaction) + if (null != _myTransaction) { - if (!this.myTransaction.Equals(Transaction.Current)) + if (!_myTransaction.Equals(Transaction.Current)) { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); } else { - safeTransactionHandle = this.myTransactionHandle; + safeTransactionHandle = _myTransactionHandle; } } else // we want to use Transaction.Current for the transaction. @@ -278,27 +276,33 @@ namespace Microsoft.PowerShell.Commands.Internal Dispose(true); } - private void Dispose(bool disposing) { - if (hkey != null) { - if (!IsSystemKey()) { - try { - hkey.Dispose(); + private void Dispose(bool disposing) + { + if (_hkey != null) + { + if (!IsSystemKey()) + { + try + { + _hkey.Dispose(); } - catch (IOException){ + catch (IOException) + { // we don't really care if the handle is invalid at this point } - finally { - hkey = null; + finally + { + _hkey = null; } } } - if (null != this.myTransaction) + if (null != _myTransaction) { // Dispose the transaction because we cloned it. try { - this.myTransaction.Dispose(); + _myTransaction.Dispose(); } catch (TransactionException) { @@ -306,7 +310,7 @@ namespace Microsoft.PowerShell.Commands.Internal } finally { - this.myTransaction = null; + _myTransaction = null; } } } @@ -318,14 +322,15 @@ namespace Microsoft.PowerShell.Commands.Internal { // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. VerifyTransaction(); - if (hkey != null) + if (_hkey != null) { - if (IsDirty()) { - int ret = Win32Native.RegFlushKey(hkey); - if (Win32Native.ERROR_SUCCESS != ret) - { - throw new IOException(Win32Native.GetMessage(ret), ret); - } + if (IsDirty()) + { + int ret = Win32Native.RegFlushKey(_hkey); + if (Win32Native.ERROR_SUCCESS != ret) + { + throw new IOException(Win32Native.GetMessage(ret), ret); + } } } } @@ -352,7 +357,7 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public TransactedRegistryKey CreateSubKey(String subkey) { - return CreateSubKey(subkey, checkMode); + return CreateSubKey(subkey, _checkMode); } /// @@ -403,7 +408,6 @@ namespace Microsoft.PowerShell.Commands.Internal [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) @@ -411,25 +415,27 @@ namespace Microsoft.PowerShell.Commands.Internal throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrEmpty); } - ValidateKeyMode(permissionCheck); + 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 + if (existingKey != null) + { // Key already exits CheckSubKeyWritePermission(subkey); CheckSubTreePermission(subkey, permissionCheck); - existingKey.checkMode = permissionCheck; + existingKey._checkMode = permissionCheck; return existingKey; } - CheckSubKeyCreatePermission(subkey); - + 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) { + if (registrySecurity != null) + { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); @@ -446,8 +452,8 @@ namespace Microsoft.PowerShell.Commands.Internal SafeRegistryHandle result = null; int ret = 0; SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = Win32Native.RegCreateKeyTransacted(hkey, + + ret = Win32Native.RegCreateKeyTransacted(_hkey, subkey, 0, null, @@ -460,20 +466,21 @@ namespace Microsoft.PowerShell.Commands.Internal IntPtr.Zero ); - if (ret == 0 && !result.IsInvalid) { + if (ret == 0 && !result.IsInvalid) + { TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, - Transaction.Current, safeTransactionHandle); - CheckSubTreePermission(subkey, permissionCheck); - key.checkMode = permissionCheck; - + Transaction.Current, safeTransactionHandle); + CheckSubTreePermission(subkey, permissionCheck); + key._checkMode = permissionCheck; + if (subkey.Length == 0) - key.keyName = keyName; + key._keyName = _keyName; else - key.keyName = keyName + "\\" + subkey; + key._keyName = _keyName + "\\" + subkey; return key; } else if (ret != 0) // syscall failed, ret is an error code. - Win32Error(ret, keyName + "\\" + subkey); // Access denied? + Win32Error(ret, _keyName + "\\" + subkey); // Access denied? BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey"); return null; @@ -513,34 +520,38 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public void DeleteSubKey(String subkey, bool throwOnMissingSubKey) { - ValidateKeyName(subkey); + 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); + TransactedRegistryKey key = InternalOpenSubKey(subkey, false); if (key != null) { - try { - if (key.InternalSubKeyCount() > 0) { + try + { + if (key.InternalSubKeyCount() > 0) + { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_RegRemoveSubKey); } } - finally { + finally + { key.Close(); } int ret = 0; SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = Win32Native.RegDeleteKeyTransacted(hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); + ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); if (ret != 0) { - if (ret == Win32Native.ERROR_FILE_NOT_FOUND) { + if (ret == Win32Native.ERROR_FILE_NOT_FOUND) + { if (throwOnMissingSubKey) { throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); @@ -550,7 +561,8 @@ namespace Microsoft.PowerShell.Commands.Internal Win32Error(ret, null); } } - else { // there is no key which also means there is no subkey + else + { // there is no key which also means there is no subkey if (throwOnMissingSubKey) throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); } @@ -568,10 +580,11 @@ namespace Microsoft.PowerShell.Commands.Internal 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()) { + if ((string.IsNullOrEmpty(subkey) || subkey.Length == 0) && IsSystemKey()) + { throw new ArgumentException(RegistryProviderStrings.ArgRegKeyDelHive); } @@ -581,30 +594,35 @@ namespace Microsoft.PowerShell.Commands.Internal SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - CheckSubTreeWritePermission(subkey); + CheckSubTreeWritePermission(subkey); TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) { - try { - if (key.InternalSubKeyCount() > 0) { + if (key != null) + { + try + { + if (key.InternalSubKeyCount() > 0) + { String[] keys = key.InternalGetSubKeyNames(); - for (int i=0; i 0) { + try + { + if (key.InternalSubKeyCount() > 0) + { String[] keys = key.InternalGetSubKeyNames(); - for (int i=0; i /// Deletes the specified value from this key. /// Utilizes Transaction.Current for its transaction. @@ -650,7 +672,8 @@ namespace Microsoft.PowerShell.Commands.Internal /// [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - public void DeleteValue(String name) { + public void DeleteValue(String name) + { DeleteValue(name, true); } @@ -664,13 +687,14 @@ namespace Microsoft.PowerShell.Commands.Internal /// [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - public void DeleteValue(String name, bool throwOnMissingValue) { + 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); - + 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. @@ -708,17 +732,18 @@ namespace Microsoft.PowerShell.Commands.Internal * * @return the TransactedRegistryKey requested. */ - internal static TransactedRegistryKey GetBaseKey(IntPtr hKey) { + internal static TransactedRegistryKey GetBaseKey(IntPtr hKey) + { int index = ((int)hKey) & 0x0FFFFFFF; - BCLDebug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!"); + 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 = hkeyNames[index]; + key._checkMode = RegistryKeyPermissionCheck.Default; + key._keyName = s_hkeyNames[index]; return key; } @@ -734,32 +759,35 @@ namespace Microsoft.PowerShell.Commands.Internal [ResourceConsumption(ResourceScope.Machine)] // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, bool writable ) { + public TransactedRegistryKey OpenSubKey(string name, bool writable) + { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash - CheckOpenSubKeyPermission(name, writable); + CheckOpenSubKeyPermission(name, writable); SafeRegistryHandle result = null; int ret = 0; SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = RegOpenKeyTransactedWrapper(hkey, name, 0, GetRegistryKeyAccess(writable), out result, safeTransactionHandle, IntPtr.Zero); + 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 = GetSubKeyPermissonCheck(writable); - key.keyName = keyName + "\\" + name; + if (ret == 0 && !result.IsInvalid) + { + TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); + key._checkMode = GetSubKeyPermissonCheck(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) { + 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; } @@ -777,8 +805,8 @@ namespace Microsoft.PowerShell.Commands.Internal // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public TransactedRegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck) - { - ValidateKeyMode(permissionCheck); + { + ValidateKeyMode(permissionCheck); return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)); } @@ -808,7 +836,7 @@ namespace Microsoft.PowerShell.Commands.Internal private TransactedRegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights) { ValidateKeyName(name); - ValidateKeyMode(permissionCheck); + ValidateKeyMode(permissionCheck); ValidateKeyRights(rights); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash @@ -819,26 +847,28 @@ namespace Microsoft.PowerShell.Commands.Internal SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = RegOpenKeyTransactedWrapper(hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero); + ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero); - if (ret == 0 && !result.IsInvalid) { + if (ret == 0 && !result.IsInvalid) + { TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, Transaction.Current, safeTransactionHandle); - key.keyName = keyName + "\\" + name; - key.checkMode = permissionCheck; + 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) { + if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) + { // We need to throw SecurityException here for compatiblity reason, // although UnauthorizedAccessException will make more sense. throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); } - - return null; - } - + + 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 [ResourceExposure(ResourceScope.Machine)] @@ -855,11 +885,12 @@ namespace Microsoft.PowerShell.Commands.Internal int ret = 0; SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = RegOpenKeyTransactedWrapper(hkey, name, 0, winAccess, out result, safeTransactionHandle, IntPtr.Zero); + ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, winAccess, out result, safeTransactionHandle, IntPtr.Zero); - if (ret == 0 && !result.IsInvalid) { + if (ret == 0 && !result.IsInvalid) + { TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); - key.keyName = keyName + "\\" + name; + key._keyName = _keyName + "\\" + name; return key; } return null; @@ -889,7 +920,8 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public int SubKeyCount { - get { + get + { CheckKeyReadPermission(); return InternalSubKeyCount(); } @@ -899,27 +931,27 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] internal int InternalSubKeyCount() { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. + 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); + 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; + if (ret != 0) + Win32Error(ret, null); + return subkeys; } /// @@ -931,7 +963,7 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public String[] GetSubKeyNames() { - CheckKeyReadPermission(); + CheckKeyReadPermission(); return InternalGetSubKeyNames(); } @@ -944,13 +976,15 @@ namespace Microsoft.PowerShell.Commands.Internal int subkeys = InternalSubKeyCount(); String[] names = new String[subkeys]; // Returns 0-length array if empty. - if (subkeys > 0) { + if (subkeys > 0) + { StringBuilder name = new StringBuilder(256); int namelen; - for (int i=0; i public int ValueCount { - get { - CheckKeyReadPermission(); + get + { + CheckKeyReadPermission(); return InternalValueCount(); } } @@ -986,7 +1021,7 @@ namespace Microsoft.PowerShell.Commands.Internal // 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, + int ret = Win32Native.RegQueryInfoKey(_hkey, null, null, Win32Native.NULL, @@ -999,7 +1034,7 @@ namespace Microsoft.PowerShell.Commands.Internal null, null); if (ret != 0) - Win32Error(ret, null); + Win32Error(ret, null); return values; } @@ -1010,20 +1045,22 @@ namespace Microsoft.PowerShell.Commands.Internal /// public String[] GetValueNames() { - CheckKeyReadPermission(); + 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) { + if (values > 0) + { StringBuilder name = new StringBuilder(256); int namelen; int currentlen; int ret; - for (int i=0; i public Object GetValue(String name) { - CheckValueReadPermission(name); + CheckValueReadPermission(name); return InternalGetValue(name, null, false, true); } @@ -1091,7 +1128,7 @@ namespace Microsoft.PowerShell.Commands.Internal /// public Object GetValue(String name, Object defaultValue) { - CheckValueReadPermission(name); + CheckValueReadPermission(name); return InternalGetValue(name, defaultValue, false, true); } @@ -1107,20 +1144,23 @@ namespace Microsoft.PowerShell.Commands.Internal /// The data associated with the value. /// [ComVisible(false)] - public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) { - if( options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { + 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); + CheckValueReadPermission(name); return InternalGetValue(name, defaultValue, doNotExpand, true); } internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) - { - if (checkSecurity) { + { + if (checkSecurity) + { // Name can be null! It's the most common use of RegQueryValueEx EnsureNotDisposed(); } @@ -1131,115 +1171,125 @@ namespace Microsoft.PowerShell.Commands.Internal int type = 0; int datasize = 0; - int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize); + int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - if (ret != 0) { + 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) + 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); + 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_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; + 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_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(); + 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); + char[] blob = new char[datasize / 2]; + ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - int cur = 0; - int len = blob.Length; + int cur = 0; + int len = blob.Length; - while (ret == 0 && cur < len) { + while (ret == 0 && cur < len) + { + int nextNull = cur; + while (nextNull < len && blob[nextNull] != (char)0) + { + nextNull++; + } - 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; + } - 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; + 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; @@ -1253,20 +1303,21 @@ namespace Microsoft.PowerShell.Commands.Internal /// A RegistryValueKind value representing the registry data type of the value associated with name. /// [ComVisible(false)] - public RegistryValueKind GetValueKind(string name) { + 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); + 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; + return (RegistryValueKind)type; } /** @@ -1277,16 +1328,19 @@ namespace Microsoft.PowerShell.Commands.Internal * * @return true if the key has been modified. */ - private bool IsDirty() { - return (this.state & STATE_DIRTY) != 0; + private bool IsDirty() + { + return (_state & STATE_DIRTY) != 0; } - private bool IsSystemKey() { - return (this.state & STATE_SYSTEMKEY) != 0; + private bool IsSystemKey() + { + return (_state & STATE_SYSTEMKEY) != 0; } - private bool IsWritable() { - return (this.state & STATE_WRITEACCESS) != 0; + private bool IsWritable() + { + return (_state & STATE_WRITEACCESS) != 0; } /// @@ -1295,14 +1349,16 @@ namespace Microsoft.PowerShell.Commands.Internal /// public String Name { - get { + get + { EnsureNotDisposed(); - return keyName; + return _keyName; } } - private void SetDirty() { - this.state |= STATE_DIRTY; + private void SetDirty() + { + _state |= STATE_DIRTY; } /// @@ -1322,8 +1378,9 @@ namespace Microsoft.PowerShell.Commands.Internal /// The registry data type to use when storing the data. /// [ComVisible(false)] - public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) { - if (value==null) + public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) + { + if (value == null) throw new ArgumentNullException(RegistryProviderStrings.Arg_Value); if (name != null && name.Length > MaxValueNameLength) @@ -1342,30 +1399,34 @@ namespace Microsoft.PowerShell.Commands.Internal if (ContainsRegistryValue(name)) { // Existing key CheckValueWritePermission(name); - } - else { // Creating a new value - CheckValueCreatePermission(name); + } + else + { // Creating a new value + CheckValueCreatePermission(name); } - if (valueKind == RegistryValueKind.Unknown) { + 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) { + 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) + if (MaxValueDataLength / 2 < data.Length) { throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); } - ret = Win32Native.RegSetValueEx(hkey, + ret = Win32Native.RegSetValueEx(_hkey, name, 0, valueKind, @@ -1384,11 +1445,13 @@ namespace Microsoft.PowerShell.Commands.Internal // First determine the size of the array // - for (int i=0; i @@ -1545,7 +1615,7 @@ namespace Microsoft.PowerShell.Commands.Internal { EnsureNotDisposed(); // Don't require a transaction. We don't want to throw for "Base" keys. - return new TransactedRegistrySecurity(hkey, keyName, includeSections); + return new TransactedRegistrySecurity(_hkey, _keyName, includeSections); } /// @@ -1561,7 +1631,7 @@ namespace Microsoft.PowerShell.Commands.Internal // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. VerifyTransaction(); - registrySecurity.Persist(hkey, keyName); + registrySecurity.Persist(_hkey, _keyName); } /** @@ -1571,8 +1641,10 @@ namespace Microsoft.PowerShell.Commands.Internal * 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) { + internal void Win32Error(int errorCode, String str) + { + switch (errorCode) + { case Win32Native.ERROR_ACCESS_DENIED: if (str != null) { @@ -1599,8 +1671,8 @@ namespace Microsoft.PowerShell.Commands.Internal //* 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. // - this.hkey.SetHandleAsInvalid(); - this.hkey = null; + _hkey.SetHandleAsInvalid(); + _hkey = null; goto default; case Win32Native.ERROR_FILE_NOT_FOUND: @@ -1614,8 +1686,10 @@ namespace Microsoft.PowerShell.Commands.Internal throw new IOException(Win32Native.GetMessage(errorCode), errorCode); } } - internal static void Win32ErrorStatic(int errorCode, String str) { - switch (errorCode) { + internal static void Win32ErrorStatic(int errorCode, String str) + { + switch (errorCode) + { case Win32Native.ERROR_ACCESS_DENIED: if (str != null) { @@ -1625,7 +1699,7 @@ namespace Microsoft.PowerShell.Commands.Internal } else throw new UnauthorizedAccessException(); - + default: throw new IOException(Win32Native.GetMessage(errorCode), errorCode); } @@ -1633,7 +1707,7 @@ namespace Microsoft.PowerShell.Commands.Internal internal static String FixupName(String name) { - BCLDebug.Assert(name!=null,"[FixupName]name!=null"); + BCLDebug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) return name; @@ -1648,7 +1722,7 @@ namespace Microsoft.PowerShell.Commands.Internal private static void FixupPath(StringBuilder path) { - int length = path.Length; + int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; @@ -1662,14 +1736,13 @@ namespace Microsoft.PowerShell.Commands.Internal { if (path[i] == '\\') { - path[i] = markerChar; - i++; - fixup = true; + path[i] = markerChar; + i++; + fixup = true; } else - break; + break; } - } i++; } @@ -1680,7 +1753,7 @@ namespace Microsoft.PowerShell.Commands.Internal int j = 0; while (i < length) { - if(path[i] == markerChar) + if (path[i] == markerChar) { i++; continue; @@ -1691,7 +1764,6 @@ namespace Microsoft.PowerShell.Commands.Internal } path.Length += j - i; } - } // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey @@ -1700,12 +1772,14 @@ namespace Microsoft.PowerShell.Commands.Internal { // 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); + if (_checkMode == RegistryKeyPermissionCheck.Default) + { + CheckSubKeyReadPermission(subkeyName); + } + + if (subKeyWritable && (_checkMode == RegistryKeyPermissionCheck.ReadSubTree)) + { + CheckSubTreeReadWritePermission(subkeyName); } } @@ -1713,24 +1787,31 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck) { - if(subKeyCheck == RegistryKeyPermissionCheck.Default) { - if( checkMode == RegistryKeyPermissionCheck.Default) { - CheckSubKeyReadPermission(subkeyName); + 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); - } + 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); - } + else if (subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree) + { + if (_checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree) + { + CheckSubTreeReadWritePermission(subkeyName); + } } } @@ -1740,10 +1821,11 @@ namespace Microsoft.PowerShell.Commands.Internal [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) { + 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(); + new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\.").Demand(); } } @@ -1753,8 +1835,8 @@ namespace Microsoft.PowerShell.Commands.Internal [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(); + 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 @@ -1762,10 +1844,11 @@ namespace Microsoft.PowerShell.Commands.Internal // 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(); + { + 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(); } } @@ -1775,8 +1858,9 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] private void CheckSubTreeReadPermission(string subkeyName) { - if( checkMode == RegistryKeyPermissionCheck.Default) { - new RegistryPermission(RegistryPermissionAccess.Read, keyName + "\\" + subkeyName + "\\").Demand(); + if (_checkMode == RegistryKeyPermissionCheck.Default) + { + new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\").Demand(); } } @@ -1784,9 +1868,10 @@ namespace Microsoft.PowerShell.Commands.Internal [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(); + 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(); } } @@ -1795,29 +1880,31 @@ namespace Microsoft.PowerShell.Commands.Internal 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(); + 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!"); + 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(); - } + 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!"); + 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(); + if (_checkMode == RegistryKeyPermissionCheck.Default) + { + new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + valueName).Demand(); } } @@ -1825,9 +1912,10 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] private void CheckValueReadPermission(string valueName) { - if( checkMode == RegistryKeyPermissionCheck.Default) { + if (_checkMode == RegistryKeyPermissionCheck.Default) + { // only need to check for default mode (dynamice check) - new RegistryPermission(RegistryPermissionAccess.Read, keyName+"\\"+valueName).Demand(); + new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + valueName).Demand(); } } @@ -1835,60 +1923,71 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] private void CheckKeyReadPermission() { - if( checkMode == RegistryKeyPermissionCheck.Default) { + if (_checkMode == RegistryKeyPermissionCheck.Default) + { // only need to check for default mode (dynamice check) - new RegistryPermission(RegistryPermissionAccess.Read, keyName + "\\.").Demand(); + 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 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, + private void EnsureNotDisposed() + { + if (_hkey == null) + { + throw new ObjectDisposedException(_keyName, RegistryProviderStrings.ObjectDisposed_RegKeyClosed); } } - private void EnsureWriteable() { + private void EnsureWriteable() + { EnsureNotDisposed(); - if (!IsWritable()) { + if (!IsWritable()) + { throw new UnauthorizedAccessException(RegistryProviderStrings.UnauthorizedAccess_RegistryNoWrite); } } - static int GetRegistryKeyAccess(bool isWritable) { + private static int GetRegistryKeyAccess(bool isWritable) + { int winAccess; - if (!isWritable) { + if (!isWritable) + { winAccess = Win32Native.KEY_READ; } - else { + else + { winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; } return winAccess; } - static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) { + private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) + { int winAccess = 0; - switch(mode) { - case RegistryKeyPermissionCheck.ReadSubTree: - case RegistryKeyPermissionCheck.Default: - winAccess = Win32Native.KEY_READ; + 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: + winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; + break; + + default: BCLDebug.Assert(false, "unexpected code path"); break; - } + } return winAccess; } @@ -1896,26 +1995,32 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) { - if( checkMode == RegistryKeyPermissionCheck.Default) { - return checkMode; - } - - if(subkeyWritable) { + if (_checkMode == RegistryKeyPermissionCheck.Default) + { + return _checkMode; + } + + if (subkeyWritable) + { return RegistryKeyPermissionCheck.ReadWriteSubTree; } - else { + else + { return RegistryKeyPermissionCheck.ReadSubTree; } } - static private void ValidateKeyName(string name) { - if (name == null) { + static private void ValidateKeyName(string name) + { + if (name == null) + { throw new ArgumentNullException(RegistryProviderStrings.Arg_Name); } int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase); int current = 0; - while (nextSlash != -1) { + while (nextSlash != -1) + { if ((nextSlash - current) > MaxKeyLength) throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); @@ -1925,39 +2030,41 @@ namespace Microsoft.PowerShell.Commands.Internal if ((name.Length - current) > MaxKeyLength) throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - - } - - static private void ValidateKeyMode(RegistryKeyPermissionCheck mode) { - if( mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) { - throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck); - } } - static private void ValidateKeyRights(int rights) { - if(0 != (rights & ~((int) RegistryRights.FullControl))) { + static private void ValidateKeyMode(RegistryKeyPermissionCheck mode) + { + if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) + { + throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck); + } + } + + static private void ValidateKeyRights(int rights) + { + if (0 != (rights & ~((int)RegistryRights.FullControl))) + { // We need to throw SecurityException here for compatiblity 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 (null == this.myTransaction) + if (null == _myTransaction) { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NotAssociatedWithTransaction); } - if (!this.myTransaction.Equals(Transaction.Current)) + 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_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 index bcb4c4c38..6e28a54e8 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs @@ -1,8 +1,4 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // // NOTE: A vast majority of this code was copied from BCL in // ndp\clr\src\BCL\System\Security\AccessControl\RegistrySecurity.cs. @@ -10,7 +6,6 @@ // /*============================================================ ** -** Class: TransactedRegistrySecurity ** ** ** Purpose: Managed ACL wrapper for registry keys. @@ -32,7 +27,6 @@ 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. /// @@ -50,8 +44,8 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) + : this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } @@ -62,8 +56,8 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + internal TransactedRegistryAccessRule(String identity, RegistryRights registryRights, AccessControlType type) + : this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } @@ -78,7 +72,7 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type) { } @@ -92,7 +86,7 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type) { } @@ -106,14 +100,14 @@ namespace Microsoft.PowerShell.Commands.Internal bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, - AccessControlType type ) + AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, - type ) + type) { } @@ -121,8 +115,8 @@ namespace Microsoft.PowerShell.Commands.Internal /// Gets the rights allowed or denied by the access rule. /// public RegistryRights RegistryRights - { - get { return (RegistryRights) base.AccessMask; } + { + get { return (RegistryRights)base.AccessMask; } } } @@ -145,7 +139,7 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { } @@ -159,7 +153,7 @@ namespace Microsoft.PowerShell.Commands.Internal /// 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) + : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { } @@ -172,8 +166,8 @@ namespace Microsoft.PowerShell.Commands.Internal /// Gets the access rights affected by the audit rule. /// public RegistryRights RegistryRights - { - get { return (RegistryRights) base.AccessMask; } + { + get { return (RegistryRights)base.AccessMask; } } } @@ -208,11 +202,11 @@ namespace Microsoft.PowerShell.Commands.Internal } */ - [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] + [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] // 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 ) + : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null) { new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); } @@ -220,22 +214,23 @@ namespace Microsoft.PowerShell.Commands.Internal 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; + switch (errorCode) + { + case Win32Native.ERROR_FILE_NOT_FOUND: + exception = new IOException(RegistryProviderStrings.Arg_RegKeyNotFound); + break; - case Win32Native.ERROR_INVALID_HANDLE: - exception = new ArgumentException(RegistryProviderStrings.AccessControl_InvalidHandle); - break; + case Win32Native.ERROR_INVALID_NAME: + exception = new ArgumentException(RegistryProviderStrings.Arg_RegInvalidKeyName); + break; - default: - break; + case Win32Native.ERROR_INVALID_HANDLE: + exception = new ArgumentException(RegistryProviderStrings.AccessControl_InvalidHandle); + break; + + default: + break; } return exception; @@ -287,7 +282,7 @@ namespace Microsoft.PowerShell.Commands.Internal return persistRules; } - [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] + [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] // Suppressed because the passed keyName won't change. [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] internal void Persist(SafeRegistryHandle hKey, String keyName) diff --git a/src/System.Management.Automation/namespaces/VariableProvider.cs b/src/System.Management.Automation/namespaces/VariableProvider.cs index 0e9126f1a..88614bdb7 100644 --- a/src/System.Management.Automation/namespaces/VariableProvider.cs +++ b/src/System.Management.Automation/namespaces/VariableProvider.cs @@ -4,7 +4,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. using System; -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -13,7 +13,6 @@ using System.Management.Automation.Provider; namespace Microsoft.PowerShell.Commands { - /// /// This provider is the data accessor for shell variables. It uses /// the HashtableProvider as the base class to get a hashtable as @@ -38,8 +37,8 @@ namespace Microsoft.PowerShell.Commands /// The constructor for the provider that exposes variables to the user /// as drives. /// - public VariableProvider () - { + public VariableProvider() + { } // constructor #endregion Constructor @@ -54,11 +53,11 @@ namespace Microsoft.PowerShell.Commands /// An array of a single PSDriveInfo object representing the variables drive. /// /// - protected override Collection InitializeDefaultDrives () + protected override Collection InitializeDefaultDrives() { string description = SessionStateStrings.VariableDriveDescription; - PSDriveInfo variableDrive = + PSDriveInfo variableDrive = new PSDriveInfo( DriveNames.VariableDrive, ProviderInfo, @@ -161,7 +160,7 @@ namespace Microsoft.PowerShell.Commands /// The name of the variable to remove from session state. /// /// - internal override void RemoveSessionStateItem (string name) + internal override void RemoveSessionStateItem(string name) { Dbg.Diagnostics.Assert( !String.IsNullOrEmpty(name), @@ -179,7 +178,7 @@ namespace Microsoft.PowerShell.Commands /// session state. /// /// - internal override IDictionary GetSessionStateTable () + internal override IDictionary GetSessionStateTable() { return (IDictionary)SessionState.Internal.GetVariableTable(); } // GetSessionStateTable @@ -197,7 +196,7 @@ namespace Microsoft.PowerShell.Commands /// The value of the specified item. /// /// - internal override object GetValueOfItem (object item) + internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( item != null, diff --git a/src/System.Management.Automation/namespaces/Win32Native.cs b/src/System.Management.Automation/namespaces/Win32Native.cs index 22ad6169f..4e406c85e 100644 --- a/src/System.Management.Automation/namespaces/Win32Native.cs +++ b/src/System.Management.Automation/namespaces/Win32Native.cs @@ -1,20 +1,7 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== + // NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\Win32Native.cs. // Namespace: Microsoft.Win32 // -/*============================================================ -** -** Class: Microsoft.PowerShell.Commands.Win32Native -** -** -** -** -===========================================================*/ /* * Notes to PInvoke users: Getting the syntax exactly correct is crucial, and * more than a little confusing. Here's some guidelines. @@ -38,7 +25,7 @@ namespace Microsoft.PowerShell.Commands.Internal using BOOL = System.Int32; using DWORD = System.UInt32; using ULONG = System.UInt32; - + #if CORECLR // Use stubs for SuppressUnmanagedCodeSecurityAttribute and ReliabilityContractAttribute using Microsoft.PowerShell.CoreClr.Stubs; @@ -53,16 +40,16 @@ namespace Microsoft.PowerShell.Commands.Internal // global declaration on the class. // [SuppressUnmanagedCodeSecurityAttribute()] - internal static class Win32Native + internal static class Win32Native { #region Integer Const - + internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; - + #endregion Integer Const - + #region Enum - + internal enum TOKEN_INFORMATION_CLASS { TokenUser = 1, @@ -84,7 +71,7 @@ namespace Microsoft.PowerShell.Commands.Internal TokenOrigin } - internal enum SID_NAME_USE + internal enum SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, @@ -100,20 +87,22 @@ namespace Microsoft.PowerShell.Commands.Internal #endregion Enum #region Struct - - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct SID_AND_ATTRIBUTES { + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct SID_AND_ATTRIBUTES + { internal IntPtr Sid; - internal uint Attributes; + internal uint Attributes; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct TOKEN_USER { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct TOKEN_USER + { internal SID_AND_ATTRIBUTES User; } #endregion Struct - + #region PInvoke methods /// @@ -145,7 +134,7 @@ namespace Microsoft.PowerShell.Commands.Internal [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] internal static extern bool CloseHandle(IntPtr handle); - + /// /// Retrieves the current process token. /// @@ -158,8 +147,8 @@ namespace Microsoft.PowerShell.Commands.Internal [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenProcessToken(SafeHandle processHandle, uint desiredAccess, out IntPtr tokenHandle); - - /// + + /// /// The GetTokenInformation function retrieves a specified type of information about an access token. /// The calling process must have appropriate access rights to obtain the information. /// @@ -178,7 +167,7 @@ namespace Microsoft.PowerShell.Commands.Internal IntPtr tokenInformation, int tokenInformationLength, out int returnLength); - + #endregion PInvoke Methods internal enum SECURITY_IMPERSONATION_LEVEL : short @@ -190,86 +179,86 @@ namespace Microsoft.PowerShell.Commands.Internal } // Security Quality of Service flags - internal const int SECURITY_ANONYMOUS = ((int)SECURITY_IMPERSONATION_LEVEL.Anonymous << 16); - internal const int SECURITY_SQOS_PRESENT = 0x00100000; + internal const int SECURITY_ANONYMOUS = ((int)SECURITY_IMPERSONATION_LEVEL.Anonymous << 16); + internal const int SECURITY_SQOS_PRESENT = 0x00100000; #if !CORECLR // Only enable/port what is needed by CORE CLR. private const string resBaseName = "RegistryProviderStrings"; internal const int KEY_QUERY_VALUE = 0x0001; - internal const int KEY_SET_VALUE = 0x0002; - internal const int KEY_CREATE_SUB_KEY = 0x0004; + internal const int KEY_SET_VALUE = 0x0002; + internal const int KEY_CREATE_SUB_KEY = 0x0004; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; - internal const int KEY_NOTIFY = 0x0010; - internal const int KEY_CREATE_LINK = 0x0020; - internal const int KEY_READ =((STANDARD_RIGHTS_READ | - KEY_QUERY_VALUE | - KEY_ENUMERATE_SUB_KEYS | - KEY_NOTIFY) - & + internal const int KEY_NOTIFY = 0x0010; + internal const int KEY_CREATE_LINK = 0x0020; + internal const int KEY_READ = ((STANDARD_RIGHTS_READ | + KEY_QUERY_VALUE | + KEY_ENUMERATE_SUB_KEYS | + KEY_NOTIFY) + & (~SYNCHRONIZE)); - - internal const int KEY_WRITE =((STANDARD_RIGHTS_WRITE | - KEY_SET_VALUE | - KEY_CREATE_SUB_KEY) - & + + internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | + KEY_SET_VALUE | + KEY_CREATE_SUB_KEY) + & (~SYNCHRONIZE)); internal const int KEY_WOW64_64KEY = 0x100; internal const int KEY_WOW64_32KEY = 0x200; - internal const int REG_NONE = 0; // No value type - internal const int REG_SZ = 1; // Unicode nul terminated string - internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string + internal const int REG_NONE = 0; // No value type + internal const int REG_SZ = 1; // Unicode nul terminated string + internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string // (with environment variable references) - internal const int REG_BINARY = 3; // Free form binary - internal const int REG_DWORD = 4; // 32-bit number - internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) - internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number - internal const int REG_LINK = 6; // Symbolic Link (unicode) - internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings - internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map - internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description - internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; - internal const int REG_QWORD = 11; // 64-bit number + internal const int REG_BINARY = 3; // Free form binary + internal const int REG_DWORD = 4; // 32-bit number + internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) + internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number + internal const int REG_LINK = 6; // Symbolic Link (unicode) + internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings + internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map + internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description + internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; + internal const int REG_QWORD = 11; // 64-bit number - internal const int HWND_BROADCAST = 0xffff; - internal const int WM_SETTINGCHANGE = 0x001A; + internal const int HWND_BROADCAST = 0xffff; + internal const int WM_SETTINGCHANGE = 0x001A; // CryptProtectMemory and CryptUnprotectMemory. - internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16; - internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00; + internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16; + internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00; internal const uint CRYPTPROTECTMEMORY_CROSS_PROCESS = 0x01; - internal const uint CRYPTPROTECTMEMORY_SAME_LOGON = 0x02; + internal const uint CRYPTPROTECTMEMORY_SAME_LOGON = 0x02; // Access Control library. internal const string MICROSOFT_KERBEROS_NAME = "Kerberos"; internal const uint ANONYMOUS_LOGON_LUID = 0x3e6; - internal const int SECURITY_ANONYMOUS_LOGON_RID = 0x00000007; + internal const int SECURITY_ANONYMOUS_LOGON_RID = 0x00000007; internal const int SECURITY_AUTHENTICATED_USER_RID = 0x0000000B; - internal const int SECURITY_LOCAL_SYSTEM_RID = 0x00000012; - internal const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020; - internal const int DOMAIN_USER_RID_GUEST = 0x000001F5; + internal const int SECURITY_LOCAL_SYSTEM_RID = 0x00000012; + internal const int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020; + internal const int DOMAIN_USER_RID_GUEST = 0x000001F5; - internal const uint SE_GROUP_MANDATORY = 0x00000001; + internal const uint SE_GROUP_MANDATORY = 0x00000001; internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002; - internal const uint SE_GROUP_ENABLED = 0x00000004; - internal const uint SE_GROUP_OWNER = 0x00000008; - internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010; - internal const uint SE_GROUP_LOGON_ID = 0xC0000000; - internal const uint SE_GROUP_RESOURCE = 0x20000000; + internal const uint SE_GROUP_ENABLED = 0x00000004; + internal const uint SE_GROUP_OWNER = 0x00000008; + internal const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010; + internal const uint SE_GROUP_LOGON_ID = 0xC0000000; + internal const uint SE_GROUP_RESOURCE = 0x20000000; - internal const uint DUPLICATE_CLOSE_SOURCE = 0x00000001; - internal const uint DUPLICATE_SAME_ACCESS = 0x00000002; - internal const uint DUPLICATE_SAME_ATTRIBUTES = 0x00000004; + internal const uint DUPLICATE_CLOSE_SOURCE = 0x00000001; + internal const uint DUPLICATE_SAME_ACCESS = 0x00000002; + internal const uint DUPLICATE_SAME_ATTRIBUTES = 0x00000004; // Win32 ACL-related constants: - internal const int READ_CONTROL = 0x00020000; - internal const int SYNCHRONIZE = 0x00100000; + internal const int READ_CONTROL = 0x00020000; + internal const int SYNCHRONIZE = 0x00100000; + + internal const int STANDARD_RIGHTS_READ = READ_CONTROL; + internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; - internal const int STANDARD_RIGHTS_READ = READ_CONTROL; - internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; - // STANDARD_RIGHTS_REQUIRED (0x000F0000L) // SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3) @@ -279,18 +268,20 @@ namespace Microsoft.PowerShell.Commands.Internal // Note that you may need to specify the SYNCHRONIZE bit as well // to be able to open a synchronization primitive. internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; - internal const int EVENT_MODIFY_STATE = 0x00000002; - internal const int MUTEX_MODIFY_STATE = 0x00000001; - internal const int MUTEX_ALL_ACCESS = 0x001F0001; + internal const int EVENT_MODIFY_STATE = 0x00000002; + internal const int MUTEX_MODIFY_STATE = 0x00000001; + internal const int MUTEX_ALL_ACCESS = 0x001F0001; - internal const int LMEM_FIXED = 0x0000; + internal const int LMEM_FIXED = 0x0000; internal const int LMEM_ZEROINIT = 0x0040; - internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); + internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - internal class OSVERSIONINFO { - internal OSVERSIONINFO() { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + internal class OSVERSIONINFO + { + internal OSVERSIONINFO() + { OSVersionInfoSize = (int)Marshal.SizeOf(this); } @@ -300,14 +291,15 @@ namespace Microsoft.PowerShell.Commands.Internal internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal String CSDVersion = null; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] - internal class OSVERSIONINFOEX { - - public OSVERSIONINFOEX() { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] + internal class OSVERSIONINFOEX + { + public OSVERSIONINFOEX() + { OSVersionInfoSize = (int)Marshal.SizeOf(this); } @@ -317,38 +309,41 @@ namespace Microsoft.PowerShell.Commands.Internal internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string CSDVersion = null; internal ushort ServicePackMajor = 0; internal ushort ServicePackMinor = 0; internal short SuiteMask = 0; internal byte ProductType = 0; - internal byte Reserved = 0; + internal byte Reserved = 0; } [StructLayout(LayoutKind.Sequential)] - internal struct SYSTEM_INFO { + internal struct SYSTEM_INFO + { internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs. - internal int dwPageSize; - internal IntPtr lpMinimumApplicationAddress; - internal IntPtr lpMaximumApplicationAddress; - internal IntPtr dwActiveProcessorMask; - internal int dwNumberOfProcessors; - internal int dwProcessorType; - internal int dwAllocationGranularity; - internal short wProcessorLevel; + internal int dwPageSize; + internal IntPtr lpMinimumApplicationAddress; + internal IntPtr lpMaximumApplicationAddress; + internal IntPtr dwActiveProcessorMask; + internal int dwNumberOfProcessors; + internal int dwProcessorType; + internal int dwAllocationGranularity; + internal short wProcessorLevel; internal short wProcessorRevision; } [StructLayout(LayoutKind.Sequential)] - internal class SECURITY_ATTRIBUTES { + internal class SECURITY_ATTRIBUTES + { internal int nLength = 0; - internal unsafe byte * pSecurityDescriptor = null; + internal unsafe byte* pSecurityDescriptor = null; internal int bInheritHandle = 0; } [StructLayout(LayoutKind.Sequential), Serializable] - internal struct WIN32_FILE_ATTRIBUTE_DATA { + internal struct WIN32_FILE_ATTRIBUTE_DATA + { internal int fileAttributes; internal uint ftCreationTimeLow; internal uint ftCreationTimeHigh; @@ -361,14 +356,17 @@ namespace Microsoft.PowerShell.Commands.Internal } [StructLayout(LayoutKind.Sequential)] - internal struct FILE_TIME { - public FILE_TIME(long fileTime) { - ftTimeLow = (uint) fileTime; - ftTimeHigh = (uint) (fileTime >> 32); + internal struct FILE_TIME + { + public FILE_TIME(long fileTime) + { + ftTimeLow = (uint)fileTime; + ftTimeHigh = (uint)(fileTime >> 32); } - public long ToTicks() { - return ((long) ftTimeHigh << 32) + ftTimeLow; + public long ToTicks() + { + return ((long)ftTimeHigh << 32) + ftTimeLow; } internal uint ftTimeLow; @@ -376,16 +374,18 @@ namespace Microsoft.PowerShell.Commands.Internal } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct KERB_S4U_LOGON { - internal uint MessageType; - internal uint Flags; - internal UNICODE_INTPTR_STRING ClientUpn; // REQUIRED: UPN for client - internal UNICODE_INTPTR_STRING ClientRealm; // Optional: Client Realm, if known + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct KERB_S4U_LOGON + { + internal uint MessageType; + internal uint Flags; + internal UNICODE_INTPTR_STRING ClientUpn; // REQUIRED: UPN for client + internal UNICODE_INTPTR_STRING ClientRealm; // Optional: Client Realm, if known } [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct LSA_OBJECT_ATTRIBUTES { + internal struct LSA_OBJECT_ATTRIBUTES + { internal int Length; internal IntPtr RootDirectory; internal IntPtr ObjectName; @@ -394,18 +394,22 @@ namespace Microsoft.PowerShell.Commands.Internal internal IntPtr SecurityQualityOfService; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct UNICODE_STRING { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct UNICODE_STRING + { internal ushort Length; internal ushort MaximumLength; - [MarshalAs(UnmanagedType.LPWStr)] internal string Buffer; + [MarshalAs(UnmanagedType.LPWStr)] + internal string Buffer; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct UNICODE_INTPTR_STRING { - internal UNICODE_INTPTR_STRING (int length, int maximumLength, IntPtr buffer) { - this.Length = (ushort) length; - this.MaxLength = (ushort) maximumLength; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct UNICODE_INTPTR_STRING + { + internal UNICODE_INTPTR_STRING(int length, int maximumLength, IntPtr buffer) + { + this.Length = (ushort)length; + this.MaxLength = (ushort)maximumLength; this.Buffer = buffer; } internal ushort Length; @@ -414,41 +418,47 @@ namespace Microsoft.PowerShell.Commands.Internal } [StructLayout(LayoutKind.Sequential)] - internal struct LSA_TRANSLATED_NAME { + internal struct LSA_TRANSLATED_NAME + { internal int Use; internal UNICODE_INTPTR_STRING Name; internal int DomainIndex; } [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct LSA_TRANSLATED_SID { + internal struct LSA_TRANSLATED_SID + { internal int Use; internal uint Rid; internal int DomainIndex; } [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct LSA_TRANSLATED_SID2 { + internal struct LSA_TRANSLATED_SID2 + { internal int Use; internal IntPtr Sid; internal int DomainIndex; - uint Flags; + private uint Flags; } [StructLayout(LayoutKind.Sequential)] - internal struct LSA_TRUST_INFORMATION { + internal struct LSA_TRUST_INFORMATION + { internal UNICODE_INTPTR_STRING Name; internal IntPtr Sid; } [StructLayout(LayoutKind.Sequential)] - internal struct LSA_REFERENCED_DOMAIN_LIST { + internal struct LSA_REFERENCED_DOMAIN_LIST + { internal int Entries; internal IntPtr Domains; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct QUOTA_LIMITS { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct QUOTA_LIMITS + { internal IntPtr PagedPoolLimit; internal IntPtr NonPagedPoolLimit; internal IntPtr MinimumWorkingSetSize; @@ -457,16 +467,19 @@ namespace Microsoft.PowerShell.Commands.Internal internal IntPtr TimeLimit; } - [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] - internal struct TOKEN_GROUPS { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct TOKEN_GROUPS + { internal uint GroupCount; internal SID_AND_ATTRIBUTES Groups; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY]; } [StructLayout(LayoutKind.Sequential)] - internal class MEMORYSTATUSEX { - internal MEMORYSTATUSEX() { - length = (int) Marshal.SizeOf(this); + internal class MEMORYSTATUSEX + { + internal MEMORYSTATUSEX() + { + length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. @@ -483,9 +496,11 @@ namespace Microsoft.PowerShell.Commands.Internal // Use only on Win9x [StructLayout(LayoutKind.Sequential)] - internal class MEMORYSTATUS { - internal MEMORYSTATUS() { - length = (int) Marshal.SizeOf(this); + internal class MEMORYSTATUS + { + internal MEMORYSTATUS() + { + length = (int)Marshal.SizeOf(this); } // The length field must be set to the size of this data structure. @@ -500,7 +515,8 @@ namespace Microsoft.PowerShell.Commands.Internal } [StructLayout(LayoutKind.Sequential)] - internal unsafe struct MEMORY_BASIC_INFORMATION { + internal unsafe struct MEMORY_BASIC_INFORMATION + { internal UIntPtr BaseAddress; internal UIntPtr AllocationBase; internal uint AllocationProtect; @@ -511,20 +527,20 @@ namespace Microsoft.PowerShell.Commands.Internal } internal const String KERNEL32 = "kernel32.dll"; - internal const String USER32 = "user32.dll"; + internal const String USER32 = "user32.dll"; internal const String ADVAPI32 = "advapi32.dll"; - internal const String OLE32 = "ole32.dll"; + internal const String OLE32 = "ole32.dll"; internal const String OLEAUT32 = "oleaut32.dll"; internal const String SHFOLDER = "shfolder.dll"; - internal const String SHIM = "mscoree.dll"; - internal const String CRYPT32 = "crypt32.dll"; - internal const String SECUR32 = "secur32.dll"; + internal const String SHIM = "mscoree.dll"; + internal const String CRYPT32 = "crypt32.dll"; + internal const String SECUR32 = "secur32.dll"; internal const String MSCORWKS = "mscorwks.dll"; - - internal const String LSTRCPY = "lstrcpy"; + + internal const String LSTRCPY = "lstrcpy"; internal const String LSTRCPYN = "lstrcpyn"; - internal const String LSTRLEN = "lstrlen"; + internal const String LSTRLEN = "lstrlen"; internal const String LSTRLENA = "lstrlenA"; internal const String LSTRLENW = "lstrlenW"; internal const String MOVEMEMORY = "RtlMoveMemory"; @@ -585,7 +601,7 @@ namespace Microsoft.PowerShell.Commands.Internal - + internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h internal static readonly IntPtr NULL = IntPtr.Zero; @@ -765,7 +781,7 @@ namespace Microsoft.PowerShell.Commands.Internal int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); - [DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)] + [DllImport(PinvokeDllNames.RegQueryValueExDllName, CharSet = CharSet.Auto, BestFitMapping = false)] [ResourceExposure(ResourceScope.None)] // Suppressed because there is no way for arbitrary data to be passed. [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index e93270e6c..ac3a0e850 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -24,7 +24,7 @@ using System.Security.Cryptography.X509Certificates; using Microsoft.PowerShell.CoreClr.Stubs; #endif -using DWORD = System.UInt32; +using DWORD = System.UInt32; namespace System.Management.Automation { @@ -66,10 +66,10 @@ namespace System.Management.Automation /// /// tracer for SignatureHelper /// - [Dbg.TraceSource( "SignatureHelper", + [Dbg.TraceSource("SignatureHelper", "tracer for SignatureHelper")] - private readonly static Dbg.PSTraceSource tracer = - Dbg.PSTraceSource.GetTracer ("SignatureHelper", + private readonly static Dbg.PSTraceSource s_tracer = + Dbg.PSTraceSource.GetTracer("SignatureHelper", "tracer for SignatureHelper"); /// @@ -150,18 +150,18 @@ namespace System.Management.Automation } // Validate that the hash algorithm is valid - if(! String.IsNullOrEmpty(hashAlgorithm)) + if (!String.IsNullOrEmpty(hashAlgorithm)) { IntPtr intptrAlgorithm = Marshal.StringToHGlobalUni(hashAlgorithm); IntPtr oidPtr = NativeMethods.CryptFindOIDInfo(NativeConstants.CRYPT_OID_INFO_NAME_KEY, intptrAlgorithm, 0); - + // If we couldn't find an OID for the hash // algorithm, it was invalid. - if(oidPtr == IntPtr.Zero) + if (oidPtr == IntPtr.Zero) { throw PSTraceSource.NewArgumentException( "certificate", @@ -171,7 +171,7 @@ namespace System.Management.Automation { NativeMethods.CRYPT_OID_INFO oidInfo = ClrFacade.PtrToStructure(oidPtr); - + hashOid = oidInfo.pszOID; } } @@ -210,20 +210,20 @@ namespace System.Management.Automation pSignInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(si)); Marshal.StructureToPtr(si, pSignInfo, false); - + // // sign the file // // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. - #pragma warning disable 56523 +#pragma warning disable 56523 result = NativeMethods.CryptUIWizDigitalSign( (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, IntPtr.Zero, IntPtr.Zero, pSignInfo, IntPtr.Zero); - #pragma warning enable 56523 +#pragma warning enable 56523 if (si.pSignExtInfo != null) { @@ -256,15 +256,14 @@ namespace System.Management.Automation } else { - if(error == Win32Errors.NTE_BAD_ALGID) + if (error == Win32Errors.NTE_BAD_ALGID) { throw PSTraceSource.NewArgumentException( "certificate", Authenticode.InvalidHashAlgorithm); - } - tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}", + s_tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}", error); } } @@ -275,7 +274,7 @@ namespace System.Management.Automation } else { - signature = new Signature(fileName, (DWORD) error); + signature = new Signature(fileName, (DWORD)error); } } finally @@ -329,8 +328,8 @@ namespace System.Management.Automation if ((signature == null) || (signature.Status != SignatureStatus.Valid)) { signature = GetSignatureFromWinVerifyTrust(fileName, fileContent); - } - + } + return signature; } @@ -399,7 +398,7 @@ namespace System.Management.Automation if (!Signature.CatalogApiAvailable.HasValue) { string productFile = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psm1"); - if(signature.Status != SignatureStatus.Valid) + if (signature.Status != SignatureStatus.Valid) { if (string.Equals(filename, productFile, StringComparison.OrdinalIgnoreCase)) { @@ -423,12 +422,12 @@ namespace System.Management.Automation } finally { - if(phStateData != IntPtr.Zero) + if (phStateData != IntPtr.Zero) { NativeMethods.FreeWVTStateData(phStateData); } - if(ppCertContext != IntPtr.Zero) + if (ppCertContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(ppCertContext); } @@ -447,7 +446,7 @@ namespace System.Management.Automation private static DWORD GetErrorFromSignatureState(NativeMethods.SIGNATURE_STATE state) { - switch(state) + switch (state) { case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_MISSING: return Win32Errors.TRUST_E_NOSIGNATURE; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_UNSUPPORTED: return Win32Errors.TRUST_E_NOSIGNATURE; @@ -457,7 +456,7 @@ namespace System.Management.Automation case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_VALID: return Win32Errors.NO_ERROR; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_TRUSTED: return Win32Errors.NO_ERROR; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNTRUSTED: return Win32Errors.TRUST_E_EXPLICIT_DISTRUST; - + // Should not happen default: System.Diagnostics.Debug.Fail("Should not get here - could not map SIGNATURE_STATE"); @@ -485,7 +484,7 @@ namespace System.Management.Automation if (error != Win32Errors.NO_ERROR) { - tracer.WriteLine("GetWinTrustData failed: {0:x}", error); + s_tracer.WriteLine("GetWinTrustData failed: {0:x}", error); } signature = GetSignatureFromWintrustData(fileName, error, wtd); @@ -494,7 +493,7 @@ namespace System.Management.Automation if (error != Win32Errors.NO_ERROR) { - tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", error); + s_tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", error); } } catch (AccessViolationException) @@ -509,7 +508,6 @@ namespace System.Management.Automation private static DWORD GetWinTrustData(string fileName, string fileContent, out NativeMethods.WINTRUST_DATA wtData) { - DWORD dwResult = Win32Errors.E_FAIL; IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; IntPtr wtdBuffer = IntPtr.Zero; @@ -543,12 +541,12 @@ namespace System.Management.Automation // The result is returned to the caller, and handled generically. // Disable the PreFast check for Win32 error codes, as we don't care. - #pragma warning disable 56523 +#pragma warning disable 56523 dwResult = NativeMethods.WinVerifyTrust( IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, wtdBuffer); - #pragma warning enable 56523 +#pragma warning enable 56523 wtData = ClrFacade.PtrToStructure(wtdBuffer); } @@ -569,10 +567,10 @@ namespace System.Management.Automation // We don't care about the Win32 error code here, so disable // the PreFast complaint that we're not retrieving it. - #pragma warning disable 56523 +#pragma warning disable 56523 IntPtr pCert = NativeMethods.WTHelperGetProvCertFromChain(pSigner, 0); - #pragma warning enable 56523 +#pragma warning enable 56523 if (pCert != IntPtr.Zero) { @@ -581,7 +579,7 @@ namespace System.Management.Automation ClrFacade.PtrToStructure(pCert); signerCert = new X509Certificate2(provCert.pCert); } - + return signerCert; } @@ -595,15 +593,15 @@ namespace System.Management.Automation X509Certificate2 signerCert = null; X509Certificate2 timestamperCert = null; - tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error); - + s_tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error); + // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. - #pragma warning disable 56523 +#pragma warning disable 56523 IntPtr pProvData = NativeMethods.WTHelperProvDataFromStateData(wtd.hWVTStateData); - #pragma warning enable 56523 - +#pragma warning enable 56523 + if (pProvData != IntPtr.Zero) { IntPtr pProvSigner = @@ -617,7 +615,7 @@ namespace System.Management.Automation if (signerCert != null) { - NativeMethods.CRYPT_PROVIDER_SGNR provSigner = + NativeMethods.CRYPT_PROVIDER_SGNR provSigner = (NativeMethods.CRYPT_PROVIDER_SGNR) ClrFacade.PtrToStructure(pProvSigner); if (provSigner.csCounterSigners == 1) @@ -626,7 +624,6 @@ namespace System.Management.Automation // time stamper cert available // timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); - } if (timestamperCert != null) diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 66649901b..46ef4a05c 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -18,11 +18,10 @@ using System.Management.Automation.Internal; using System.Management.Automation.Provider; using System.Management.Automation.Security; using System.Runtime.InteropServices; -using DWORD = System.UInt32; +using DWORD = System.UInt32; namespace System.Management.Automation { - /// /// Defines the possible status when validating integrity of catalog /// @@ -47,7 +46,7 @@ namespace System.Management.Automation /// /// status of catalog /// - public CatalogValidationStatus Status { get; set; } + public CatalogValidationStatus Status { get; set; } /// /// Hash Algorithm used to calculate the hashes of files in Catalog @@ -57,12 +56,12 @@ namespace System.Management.Automation /// /// Dictionary mapping files relative paths to their hash values found from Catalog /// - public Dictionary CatalogItems { get; set;} + public Dictionary CatalogItems { get; set; } /// /// Dictionary mapping files relative paths to their hash values /// - public Dictionary PathItems { get; set;} + public Dictionary PathItems { get; set; } /// /// Signature for the catalog @@ -75,7 +74,6 @@ namespace System.Management.Automation /// internal static class CatalogHelper { - // Catalog Version is (0X100 = 256) for Catalog Version 1 private static int catalogVersion1 = 256; @@ -84,7 +82,7 @@ namespace System.Management.Automation // Hash Algorithms supported by Windows Catalog private static string HashAlgorithmSHA1 = "SHA1"; - private static string HashAlgorithmSHA256 = "SHA256"; + private static string HashAlgorithmSHA256 = "SHA256"; private static PSCmdlet _cmdlet = null; /// @@ -95,21 +93,21 @@ namespace System.Management.Automation private static int GetCatalogVersion(IntPtr catalogHandle) { int catalogVersion = -1; - - IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); + + IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); NativeMethods.CRYPTCATSTORE catalogInfo = ClrFacade.PtrToStructure(catalogData); - + if (catalogInfo.dwPublicVersion == catalogVersion2) - { + { catalogVersion = 2; } // One Windows 7 this API sent version information as decimal 1 not hex (0X100 = 256) // so we are checking for that value as well. Reason we are not checking for version 2 above in // this scenario because catalog verion 2 is not supported on win7. else if ((catalogInfo.dwPublicVersion == catalogVersion1) || (catalogInfo.dwPublicVersion == 1)) - { + { catalogVersion = 1; - } + } else { // catalog version we don't understand @@ -118,9 +116,9 @@ namespace System.Management.Automation catalogVersion2.ToString("X"))); ErrorRecord errorRecord = new ErrorRecord(exception, "UnKnownCatalogVersion", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + _cmdlet.ThrowTerminatingError(errorRecord); } - return catalogVersion; + return catalogVersion; } /// @@ -168,36 +166,36 @@ namespace System.Management.Automation /// hash method used to generate hashes for the Catalog /// HashSet for the relative Path for files in Catalog internal static string GenerateCDFFile(Collection Path, string catalogFilePath, string cdfFilePath, int catalogVersion, string hashAlgorithm) - { + { HashSet relativePaths = new HashSet(); string cdfHeaderContent = string.Empty; string cdfFilesContent = string.Empty; int catAttributeCount = 0; - + // First create header and files section for the catalog then write in file - cdfHeaderContent += "[CatalogHeader]" + Environment.NewLine; - cdfHeaderContent += @"Name=" + catalogFilePath + Environment.NewLine; - cdfHeaderContent += "CatalogVersion=" + catalogVersion + Environment.NewLine; - cdfHeaderContent += "HashAlgorithms=" + hashAlgorithm + Environment.NewLine; + cdfHeaderContent += "[CatalogHeader]" + Environment.NewLine; + cdfHeaderContent += @"Name=" + catalogFilePath + Environment.NewLine; + cdfHeaderContent += "CatalogVersion=" + catalogVersion + Environment.NewLine; + cdfHeaderContent += "HashAlgorithms=" + hashAlgorithm + Environment.NewLine; cdfFilesContent += "[CatalogFiles]" + Environment.NewLine; foreach (string catalogFile in Path) { if (System.IO.Directory.Exists(catalogFile)) - { + { var directoryItems = Directory.EnumerateFiles(catalogFile, "*.*", SearchOption.AllDirectories); foreach (string fileItem in directoryItems) { - ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(fileItem), new DirectoryInfo(catalogFile), ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); + ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(fileItem), new DirectoryInfo(catalogFile), ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } else if (System.IO.File.Exists(catalogFile)) { - ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(catalogFile), null, ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); + ProcessFileToBeAddedInCatalogDefinitionFile(new FileInfo(catalogFile), null, ref relativePaths, ref cdfHeaderContent, ref cdfFilesContent, ref catAttributeCount); } } - + using (System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(new FileStream(cdfFilePath, FileMode.Create))) { fileWriter.WriteLine(cdfHeaderContent); @@ -224,20 +222,20 @@ namespace System.Management.Automation if (dirInfo != null) { //Relative path of the file is the path inside the containing folder excluding folder Name - relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); + relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); } else { - relativePath = fileToHash.Name; + relativePath = fileToHash.Name; } - + if (!relativePaths.Contains(relativePath)) { relativePaths.Add(relativePath); if (fileToHash.Length != 0) - { + { cdfFilesContent += "" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine; - cdfFilesContent += "" + fileToHash.FullName + "ATTR1=0x10010001:FilePath:" + relativePath + Environment.NewLine; + cdfFilesContent += "" + fileToHash.FullName + "ATTR1=0x10010001:FilePath:" + relativePath + Environment.NewLine; } else { @@ -270,7 +268,7 @@ namespace System.Management.Automation if (resultCDF != IntPtr.Zero) { // First navigate all catalog level attributes entries first, they represent zero size files - IntPtr catalogAttr = IntPtr.Zero; + IntPtr catalogAttr = IntPtr.Zero; do { catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack); @@ -278,7 +276,7 @@ namespace System.Management.Automation if (catalogAttr != IntPtr.Zero) { string filePath = ProcessFilePathAttributeInCatalog(catalogAttr); - _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath)); + _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath)); } } while (catalogAttr != IntPtr.Zero); @@ -296,7 +294,6 @@ namespace System.Management.Automation if (!String.IsNullOrEmpty(fileName)) { - IntPtr memberAttr = IntPtr.Zero; string fileRelativePath = String.Empty; do @@ -314,15 +311,15 @@ namespace System.Management.Automation string itemName = fileName.Substring(6); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); break; - } + } } } while (memberAttr != IntPtr.Zero); } - } while (fileName != null); + } while (fileName != null); } finally { - NativeMethods.CryptCATCDFClose(resultCDF); + NativeMethods.CryptCATCDFClose(resultCDF); } } else @@ -348,7 +345,7 @@ namespace System.Management.Automation string hashAlgorithm = GetCatalogHashAlgorithm(catalogVersion); if (!String.IsNullOrEmpty(hashAlgorithm)) - { + { // Generate Path for Catalog Defintion File string cdfFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); cdfFilePath = cdfFilePath + ".cdf"; @@ -388,7 +385,7 @@ namespace System.Management.Automation string relativePath = string.Empty; NativeMethods.CRYPTCATATTRIBUTE currentMemberAttr = ClrFacade.PtrToStructure(memberAttrInfo); - + // check if this is the attribute we are looking for // catalog generated other way not using New-FileCatalog can have attributes we don't understand if (currentMemberAttr.pwszReferenceTag.Equals("FilePath", StringComparison.OrdinalIgnoreCase)) @@ -403,7 +400,7 @@ namespace System.Management.Automation return relativePath; } - + /// /// Make a hash for the file /// @@ -413,7 +410,7 @@ namespace System.Management.Automation /// HashValue for the file internal static string CalculateFileHash(string filePath, string hashAlgorithm) { - string hashValue = string.Empty; + string hashValue = string.Empty; IntPtr catAdmin = IntPtr.Zero; // To get handle to the hash algorithm to be used to calculate hashes @@ -428,7 +425,7 @@ namespace System.Management.Automation IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle - IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0 , OPEN_EXISTING, 0, IntPtr.Zero); + IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero); if (fileHandle != INVALID_HANDLE_VALUE) { try @@ -453,11 +450,10 @@ namespace System.Management.Automation ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } - + byte[] hashBytes = new byte[size]; Marshal.Copy(hashBuffer, hashBytes, 0, size); hashValue = BitConverter.ToString(hashBytes).Replace("-", ""); - } finally { @@ -481,7 +477,7 @@ namespace System.Management.Automation } return hashValue; } - + /// /// Make list of hashes for given Catalog File /// @@ -489,13 +485,13 @@ namespace System.Management.Automation /// /// The version of input catalog we read from catalog meta data after opening it. /// Dictionary mapping files relative paths to HashValues - internal static Dictionary GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns,out int catalogVersion) + internal static Dictionary GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion) { IntPtr resultCatalog = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); Dictionary catalogHashes = new Dictionary(StringComparer.CurrentCultureIgnoreCase); catalogVersion = 0; - + if (resultCatalog != INVALID_HANDLE_VALUE) { try @@ -530,11 +526,11 @@ namespace System.Management.Automation { NativeMethods.CRYPTCATMEMBER currentMember = ClrFacade.PtrToStructure(memberInfo); NativeMethods.SIP_INDIRECT_DATA pIndirectData = ClrFacade.PtrToStructure(currentMember.pIndirectData); - + // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well // We validate those along with file hashes so we are skipping duplicate entries if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) - { + { string relativePath = String.Empty; IntPtr memberAttrInfo = IntPtr.Zero; do @@ -561,10 +557,10 @@ namespace System.Management.Automation _cmdlet.ThrowTerminatingError(errorRecord); } - ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); + ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); } } - } while (memberInfo != IntPtr.Zero); + } while (memberInfo != IntPtr.Zero); } finally { @@ -572,7 +568,7 @@ namespace System.Management.Automation } } else - { + { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); } @@ -591,7 +587,7 @@ namespace System.Management.Automation { // Found the attribute we are looking for _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileHashInCatlogItem, relativePath, fileHash)); - + // Only add the file for validation if it does not meet exclusion criteria if (!CheckExcludedCriteria((new FileInfo(relativePath)).Name, excludedPatterns)) { @@ -616,7 +612,7 @@ namespace System.Management.Automation internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, string hashAlgorithm, WildcardPattern[] excludedPatterns, ref Dictionary fileHashes) { string relativePath = string.Empty; - string exclude = string.Empty; + string exclude = string.Empty; if (dirInfo != null) { @@ -627,16 +623,16 @@ namespace System.Management.Automation else { relativePath = fileToHash.Name; - exclude = relativePath; + exclude = relativePath; } - if (!CheckExcludedCriteria(exclude, excludedPatterns)) + if (!CheckExcludedCriteria(exclude, excludedPatterns)) { string fileHash = string.Empty; - - if(fileToHash.Length != 0) + + if (fileToHash.Length != 0) { - fileHash = CalculateFileHash(fileToHash.FullName, hashAlgorithm); + fileHash = CalculateFileHash(fileToHash.FullName, hashAlgorithm); } if (!fileHashes.ContainsKey(relativePath)) @@ -654,7 +650,7 @@ namespace System.Management.Automation { // Verbose about skipping file from path _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.SkipValidationOfPathFile, relativePath)); - } + } } /// @@ -674,20 +670,20 @@ namespace System.Management.Automation foreach (string folderPath in folderPaths) { if (System.IO.Directory.Exists(folderPath)) - { + { var directoryItems = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.AllDirectories); - foreach (string fileItem in directoryItems) - { + foreach (string fileItem in directoryItems) + { // if its the catalog file we are validating we will skip it if (String.Equals(fileItem, catalogFilePath, StringComparison.OrdinalIgnoreCase)) continue; - ProcessPathFile(new FileInfo(fileItem), new DirectoryInfo(folderPath), hashAlgorithm, excludedPatterns, ref fileHashes); + ProcessPathFile(new FileInfo(fileItem), new DirectoryInfo(folderPath), hashAlgorithm, excludedPatterns, ref fileHashes); } } else if (System.IO.File.Exists(folderPath)) - { - ProcessPathFile(new FileInfo(folderPath), null , hashAlgorithm, excludedPatterns, ref fileHashes); + { + ProcessPathFile(new FileInfo(folderPath), null, hashAlgorithm, excludedPatterns, ref fileHashes); } } return fileHashes; @@ -712,14 +708,14 @@ namespace System.Management.Automation // Find entires those are not in both list lists. These should be empty lists for success // Hashes in Catalog should be exact similar to the ones from folder List relativePathsNotInFolder = relativePathsFromFolder.Except(relativePathsFromCatalog, StringComparer.CurrentCultureIgnoreCase).ToList(); - List relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); + List relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); //Found extra hashes in Folder if ((relativePathsNotInFolder.Count != 0) || (relativePathsNotInCatalog.Count != 0)) { Status = false; } - + foreach (KeyValuePair item in catalogItems) { string catalogHashValue = (string)catalogItems[item.Key]; @@ -773,7 +769,7 @@ namespace System.Management.Automation catalog.Signature = SignatureHelper.GetSignature(catalogFilePath, null); return catalog; } - return null; + return null; } /// @@ -793,14 +789,14 @@ namespace System.Management.Automation return true; } } - } + } return false; } /// /// Call back when error is thrown by catalog API's /// private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, string pwszLine) - { + { switch (dwErrorArea) { case NativeConstants.CRYPTCAT_E_AREA_HEADER: break; @@ -811,7 +807,7 @@ namespace System.Management.Automation switch (dwLocalError) { case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILE_PATH: - { + { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileNameOrPathForCatalogMember, pwszLine)), "UnableToFindFileNameOrPathForCatalogMember", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; @@ -825,7 +821,7 @@ namespace System.Management.Automation case NativeConstants.CRYPTCAT_E_CDF_MEMBER_FILENOTFOUND: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToFindFileToHash, pwszLine)), "UnableToFindFileToHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + _cmdlet.ThrowTerminatingError(errorRecord); break; } case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: break; @@ -833,7 +829,7 @@ namespace System.Management.Automation case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: break; case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: break; case NativeConstants.CRYPTCAT_E_CDF_DUPLICATE: - { + { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFileMemberInCatalog, pwszLine)), "FoundDuplicateFileMemberInCatalog", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; diff --git a/src/System.Management.Automation/security/CredentialParameter.cs b/src/System.Management.Automation/security/CredentialParameter.cs index ff63e8019..89132d4a2 100644 --- a/src/System.Management.Automation/security/CredentialParameter.cs +++ b/src/System.Management.Automation/security/CredentialParameter.cs @@ -12,7 +12,7 @@ namespace System.Management.Automation /// should accept credentials. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] - public sealed class CredentialAttribute : ArgumentTransformationAttribute + public sealed class CredentialAttribute : ArgumentTransformationAttribute { /// /// Transforms the input data to an PSCredential. @@ -36,7 +36,7 @@ namespace System.Management.Automation string userName = null; bool shouldPrompt = false; - if((engineIntrinsics == null) || + if ((engineIntrinsics == null) || (engineIntrinsics.Host == null) || (engineIntrinsics.Host.UI == null)) { @@ -57,7 +57,7 @@ namespace System.Management.Automation { shouldPrompt = true; userName = LanguagePrimitives.FromObjectAs(inputData); - + // If we couldn't get the username (as a string,) // throw an exception if (userName == null) @@ -70,12 +70,12 @@ namespace System.Management.Automation if (shouldPrompt) { string caption = null; - string prompt = null; + string prompt = null; caption = CredentialAttributeStrings.CredentialAttribute_Prompt_Caption; - prompt = CredentialAttributeStrings.CredentialAttribute_Prompt; + prompt = CredentialAttributeStrings.CredentialAttribute_Prompt; cred = engineIntrinsics.Host.UI.PromptForCredential( caption, diff --git a/src/System.Management.Automation/security/MshSignature.cs b/src/System.Management.Automation/security/MshSignature.cs index b9dc1d26b..4258dd3c5 100644 --- a/src/System.Management.Automation/security/MshSignature.cs +++ b/src/System.Management.Automation/security/MshSignature.cs @@ -3,29 +3,29 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System.Management.Automation.Internal; using System.Security.Cryptography.X509Certificates; using System.ComponentModel; using System.IO; -using DWORD = System.UInt32; +using DWORD = System.UInt32; namespace System.Management.Automation { internal static class Win32Errors { - internal const DWORD NO_ERROR = 0; - internal const DWORD E_FAIL = 0x80004005; - internal const DWORD TRUST_E_NOSIGNATURE = 0x800b0100; - internal const DWORD TRUST_E_BAD_DIGEST = 0x80096010; - internal const DWORD TRUST_E_PROVIDER_UNKNOWN = 0x800b0001; + internal const DWORD NO_ERROR = 0; + internal const DWORD E_FAIL = 0x80004005; + internal const DWORD TRUST_E_NOSIGNATURE = 0x800b0100; + internal const DWORD TRUST_E_BAD_DIGEST = 0x80096010; + internal const DWORD TRUST_E_PROVIDER_UNKNOWN = 0x800b0001; internal const DWORD TRUST_E_SUBJECT_FORM_UNKNOWN = 0x800B0003; - internal const DWORD CERT_E_UNTRUSTEDROOT = 0x800b0109; - internal const DWORD TRUST_E_EXPLICIT_DISTRUST = 0x800B0111; - internal const DWORD CRYPT_E_BAD_MSG = 0x8009200d; - internal const DWORD NTE_BAD_ALGID = 0x80090008; + internal const DWORD CERT_E_UNTRUSTEDROOT = 0x800b0109; + internal const DWORD TRUST_E_EXPLICIT_DISTRUST = 0x800B0111; + internal const DWORD CRYPT_E_BAD_MSG = 0x8009200d; + internal const DWORD NTE_BAD_ALGID = 0x80090008; } /// @@ -98,19 +98,19 @@ namespace System.Management.Automation /// Catalog = 2 }; - + /// /// Represents a digital signature on a signed /// file. /// public sealed class Signature { - private string path; - private SignatureStatus status = SignatureStatus.UnknownError; - private DWORD win32Error; - private X509Certificate2 signerCert; - private string statusMessage = String.Empty; - private X509Certificate2 timeStamperCert; + private string _path; + private SignatureStatus _status = SignatureStatus.UnknownError; + private DWORD _win32Error; + private X509Certificate2 _signerCert; + private string _statusMessage = String.Empty; + private X509Certificate2 _timeStamperCert; //private DateTime signedOn = new DateTime(0); // Three states: @@ -129,7 +129,7 @@ namespace System.Management.Automation { get { - return signerCert; + return _signerCert; } } @@ -141,7 +141,7 @@ namespace System.Management.Automation { get { - return timeStamperCert; + return _timeStamperCert; } } @@ -152,10 +152,10 @@ namespace System.Management.Automation { get { - return status; + return _status; } } - + /// /// Gets the message corresponding to the status of the /// signature on the file. @@ -164,7 +164,7 @@ namespace System.Management.Automation { get { - return statusMessage; + return _statusMessage; } } @@ -176,7 +176,7 @@ namespace System.Management.Automation { get { - return path; + return _path; } } @@ -295,18 +295,18 @@ namespace System.Management.Automation DWORD error, X509Certificate2 timestamper) { - path = filePath; - win32Error = error; - signerCert = signer; - timeStamperCert = timestamper; + _path = filePath; + _win32Error = error; + _signerCert = signer; + _timeStamperCert = timestamper; SignatureType = SignatureType.None; SignatureStatus isc = GetSignatureStatusFromWin32Error(error); - status = isc; + _status = isc; - statusMessage = GetSignatureStatusMessage(isc, + _statusMessage = GetSignatureStatusMessage(isc, error, filePath); } @@ -316,32 +316,32 @@ namespace System.Management.Automation { SignatureStatus isc = SignatureStatus.UnknownError; - switch(error) + switch (error) { - case Win32Errors.NO_ERROR: - isc = SignatureStatus.Valid; - break; + case Win32Errors.NO_ERROR: + isc = SignatureStatus.Valid; + break; - case Win32Errors.NTE_BAD_ALGID: - isc = SignatureStatus.Incompatible; - break; + case Win32Errors.NTE_BAD_ALGID: + isc = SignatureStatus.Incompatible; + break; - case Win32Errors.TRUST_E_NOSIGNATURE: - isc = SignatureStatus.NotSigned; - break; + case Win32Errors.TRUST_E_NOSIGNATURE: + isc = SignatureStatus.NotSigned; + break; - case Win32Errors.TRUST_E_BAD_DIGEST: - case Win32Errors.CRYPT_E_BAD_MSG: - isc = SignatureStatus.HashMismatch; - break; + case Win32Errors.TRUST_E_BAD_DIGEST: + case Win32Errors.CRYPT_E_BAD_MSG: + isc = SignatureStatus.HashMismatch; + break; - case Win32Errors.TRUST_E_PROVIDER_UNKNOWN: - isc = SignatureStatus.NotSupportedFileFormat; - break; + case Win32Errors.TRUST_E_PROVIDER_UNKNOWN: + isc = SignatureStatus.NotSupportedFileFormat; + break; - case Win32Errors.TRUST_E_EXPLICIT_DISTRUST: - isc = SignatureStatus.NotTrusted; - break; + case Win32Errors.TRUST_E_EXPLICIT_DISTRUST: + isc = SignatureStatus.NotTrusted; + break; } return isc; @@ -357,56 +357,56 @@ namespace System.Management.Automation switch (status) { - case SignatureStatus.Valid: - resourceString = MshSignature.MshSignature_Valid; - break; + case SignatureStatus.Valid: + resourceString = MshSignature.MshSignature_Valid; + break; - case SignatureStatus.UnknownError: - int intError = SecuritySupport.GetIntFromDWORD(error); - Win32Exception e = new Win32Exception(intError); - message = e.Message; - break; + case SignatureStatus.UnknownError: + int intError = SecuritySupport.GetIntFromDWORD(error); + Win32Exception e = new Win32Exception(intError); + message = e.Message; + break; - case SignatureStatus.Incompatible: - if (error == Win32Errors.NTE_BAD_ALGID) - { - resourceString = MshSignature.MshSignature_Incompatible_HashAlgorithm; - } - else - { - resourceString = MshSignature.MshSignature_Incompatible; - } - arg = filePath; - break; + case SignatureStatus.Incompatible: + if (error == Win32Errors.NTE_BAD_ALGID) + { + resourceString = MshSignature.MshSignature_Incompatible_HashAlgorithm; + } + else + { + resourceString = MshSignature.MshSignature_Incompatible; + } + arg = filePath; + break; - case SignatureStatus.NotSigned: - resourceString = MshSignature.MshSignature_NotSigned; - arg = filePath; - break; + case SignatureStatus.NotSigned: + resourceString = MshSignature.MshSignature_NotSigned; + arg = filePath; + break; - case SignatureStatus.HashMismatch: - resourceString = MshSignature.MshSignature_HashMismatch; - arg = filePath; - break; + case SignatureStatus.HashMismatch: + resourceString = MshSignature.MshSignature_HashMismatch; + arg = filePath; + break; - case SignatureStatus.NotTrusted: - resourceString = MshSignature.MshSignature_NotTrusted; - arg = filePath; - break; + case SignatureStatus.NotTrusted: + resourceString = MshSignature.MshSignature_NotTrusted; + arg = filePath; + break; - case SignatureStatus.NotSupportedFileFormat: - resourceString = MshSignature.MshSignature_NotSupportedFileFormat; - arg = System.IO.Path.GetExtension(filePath); + case SignatureStatus.NotSupportedFileFormat: + resourceString = MshSignature.MshSignature_NotSupportedFileFormat; + arg = System.IO.Path.GetExtension(filePath); - if (String.IsNullOrEmpty(arg)) - { - resourceString = MshSignature.MshSignature_NotSupportedFileFormat_NoExtension; - arg = null; - } - break; + if (String.IsNullOrEmpty(arg)) + { + resourceString = MshSignature.MshSignature_NotSupportedFileFormat_NoExtension; + arg = null; + } + break; } - if ( message == null ) + if (message == null) { if (arg == null) { diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index 89f777ce7..fec66b017 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -14,7 +14,6 @@ using System.Text; namespace Microsoft.PowerShell { - /// /// helper class for secure string related functionality /// @@ -24,7 +23,7 @@ namespace Microsoft.PowerShell // Some random hex characters to identify the beginning of a // V2-exported SecureString. internal static string SecureStringExportHeader = "76492d1116743f0423413b16050a5345"; - + /// /// Create a new SecureString based on the specified binary data. /// @@ -38,7 +37,7 @@ namespace Microsoft.PowerShell /// private static SecureString New(byte[] data) { - if((data.Length % 2) != 0) + if ((data.Length % 2) != 0) { // If the data is not an even length, they supplied an invalid key String error = Serialization.InvalidKey; @@ -53,16 +52,16 @@ namespace Microsoft.PowerShell // int len = data.Length / 2; - for (int i=0; i < len; i++) + for (int i = 0; i < len; i++) { - ch = (char) (data[2*i+1]*256 + data[2*i]); + ch = (char)(data[2 * i + 1] * 256 + data[2 * i]); ss.AppendChar(ch); // // zero out the data slots as soon as we use them // - data[2*i] = 0; - data[2*i+1] = 0; + data[2 * i] = 0; + data[2 * i + 1] = 0; } return ss; @@ -82,7 +81,7 @@ namespace Microsoft.PowerShell // // each unicode char is 2 bytes. // - byte[] data = new byte[s.Length*2]; + byte[] data = new byte[s.Length * 2]; if (s.Length > 0) { @@ -117,7 +116,7 @@ namespace Microsoft.PowerShell { StringBuilder sb = new StringBuilder(); - for (int i=0; i < data.Length; i++) + for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString("x2", System.Globalization.CultureInfo.InvariantCulture)); } @@ -139,15 +138,15 @@ namespace Microsoft.PowerShell // // two hex chars per byte // - int dataLen = s.Length/2; + int dataLen = s.Length / 2; byte[] data = new byte[dataLen]; if (s.Length > 0) { - for (int i=0; i < dataLen; i++) + for (int i = 0; i < dataLen; i++) { - data[i] = byte.Parse(s.Substring(2*i,2), - NumberStyles.AllowHexSpecifier, + data[i] = byte.Parse(s.Substring(2 * i, 2), + NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.InvariantCulture); } } @@ -171,17 +170,17 @@ namespace Microsoft.PowerShell string output = ""; byte[] data = null; byte[] protectedData = null; - + data = GetData(input); protectedData = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser); - for (int i=0; i < data.Length; i++) + for (int i = 0; i < data.Length; i++) { data[i] = 0; } output = ByteArrayToString(protectedData); - + return output; } @@ -209,7 +208,7 @@ namespace Microsoft.PowerShell SecureString s; protectedData = ByteArrayFromString(input); - + data = ProtectedData.Unprotect(protectedData, null, DataProtectionScope.CurrentUser); @@ -294,7 +293,6 @@ namespace Microsoft.PowerShell using (cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { - // // get clear text data from the input SecureString // @@ -356,7 +354,7 @@ namespace Microsoft.PowerShell // Array.Clear(keyBlob, 0, keyBlob.Length); - return output; + return output; } /// @@ -390,8 +388,8 @@ namespace Microsoft.PowerShell encryptedData = ByteArrayFromString(input); ICryptoTransform decryptor = null; - - if(IV != null) + + if (IV != null) { decryptor = aes.CreateDecryptor(key, IV); } @@ -399,7 +397,7 @@ namespace Microsoft.PowerShell { decryptor = aes.CreateDecryptor(key, aes.IV); } - + MemoryStream ms = new MemoryStream(encryptedData); using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) @@ -439,8 +437,8 @@ namespace Microsoft.PowerShell { internal EncryptionResult(string encrypted, string IV) { - this.encryptedData = encrypted; - this.iv = IV; + _encryptedData = encrypted; + _iv = IV; } /// @@ -450,10 +448,10 @@ namespace Microsoft.PowerShell { get { - return encryptedData; + return _encryptedData; } } - private String encryptedData; + private String _encryptedData; /// /// Gets the IV used to encrypt the data @@ -462,10 +460,10 @@ namespace Microsoft.PowerShell { get { - return iv; + return _iv; } } - private String iv; + private String _iv; } #if CORECLR @@ -480,7 +478,7 @@ namespace Microsoft.PowerShell CurrentUser = 0x00, LocalMachine = 0x01 } - + internal static class ProtectedData { /// @@ -522,7 +520,7 @@ namespace Microsoft.PowerShell new IntPtr(&blob))) { int lastWin32Error = Marshal.GetLastWin32Error(); - + // One of the most common reasons that DPAPI operations fail is that the user // profile is not loaded (for instance in the case of impersonation or running in a // service. In those cases, throw an exception that provides more specific details @@ -656,7 +654,7 @@ namespace Microsoft.PowerShell [In] IntPtr pPromptStruct, [In] uint dwFlags, [In, Out] IntPtr pDataBlob); - + [DllImport("CRYPT32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool CryptUnprotectData( [In] IntPtr pDataIn, diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 80446a297..2dd5df8a6 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -2,7 +2,7 @@ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ -using Dbg=System.Management.Automation; +using Dbg = System.Management.Automation; using System; using System.Management.Automation; using System.Management.Automation.Security; @@ -21,7 +21,7 @@ using Environment = System.Management.Automation.Environment; #endif namespace Microsoft.PowerShell -{ +{ /// /// Defines the authorization policy that controls the way scripts /// (and other command types) are handled by Monad. This authorization @@ -72,10 +72,10 @@ namespace Microsoft.PowerShell #region constructor // execution policy that dictates what can run in msh - private ExecutionPolicy executionPolicy; + private ExecutionPolicy _executionPolicy; //shellId supplied by runspace configuration - private string shellId; + private string _shellId; /// /// Initializes a new instance of the PSAuthorizationManager @@ -86,13 +86,13 @@ namespace Microsoft.PowerShell /// to. For example, Microsoft.PowerShell /// public PSAuthorizationManager(string shellId) - :base(shellId) + : base(shellId) { if (string.IsNullOrEmpty(shellId)) { throw PSTraceSource.NewArgumentNullException("shellId"); } - this.shellId = shellId; + _shellId = shellId; } #endregion constructor @@ -147,10 +147,10 @@ namespace Microsoft.PowerShell return true; // Get the execution policy - executionPolicy = SecuritySupport.GetExecutionPolicy(shellId); + _executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId); // See if they want to bypass the authorization manager - if (executionPolicy == ExecutionPolicy.Bypass) + if (_executionPolicy == ExecutionPolicy.Bypass) return true; #if !CORECLR // Always check the SAFER APIs if code integrity isn't being handled system-wide through @@ -193,7 +193,7 @@ namespace Microsoft.PowerShell } } #endif - if (executionPolicy == ExecutionPolicy.Unrestricted) + if (_executionPolicy == ExecutionPolicy.Unrestricted) { // We need to give the "Remote File" warning // if the file originated from the internet @@ -260,12 +260,12 @@ namespace Microsoft.PowerShell // Don't need to check the signature if the file is local // and we're in "RemoteSigned" mode else if ((IsLocalFile(fi.FullName)) && - (executionPolicy == ExecutionPolicy.RemoteSigned)) + (_executionPolicy == ExecutionPolicy.RemoteSigned)) { policyCheckPassed = true; } - else if ((executionPolicy == ExecutionPolicy.AllSigned) || - (executionPolicy == ExecutionPolicy.RemoteSigned)) + else if ((_executionPolicy == ExecutionPolicy.AllSigned) || + (_executionPolicy == ExecutionPolicy.RemoteSigned)) { // if policy requires signature verification, // make it so. @@ -325,7 +325,7 @@ namespace Microsoft.PowerShell // But accept mshxml files from publishers that we // trust, or files in the system protected directories - bool reasonSet = false; + bool reasonSet = false; if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] trustedDirectories = new string[] @@ -333,13 +333,13 @@ namespace Microsoft.PowerShell Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; - foreach(string trustedDirectory in trustedDirectories) + foreach (string trustedDirectory in trustedDirectories) { - if(fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase)) + if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase)) policyCheckPassed = true; } - if(! policyCheckPassed) + if (!policyCheckPassed) { // Get the signature of the file. Signature signature = GetSignatureWithEncodingRetry(path, script); @@ -402,7 +402,7 @@ namespace Microsoft.PowerShell policyCheckPassed = false; }; break; } - + return policyCheckPassed; } @@ -432,10 +432,10 @@ namespace Microsoft.PowerShell X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser); trustedPublishers.Open(OpenFlags.ReadOnly); - foreach(X509Certificate2 trustedCertificate in trustedPublishers.Certificates) + foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates) { if (String.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)) - if(! IsUntrustedPublisher(signature, file)) return true; + if (!IsUntrustedPublisher(signature, file)) return true; } return false; @@ -451,7 +451,7 @@ namespace Microsoft.PowerShell X509Store trustedPublishers = new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser); trustedPublishers.Open(OpenFlags.ReadOnly); - foreach(X509Certificate2 trustedCertificate in trustedPublishers.Certificates) + foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates) { if (String.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)) return true; @@ -761,10 +761,10 @@ namespace Microsoft.PowerShell string alwaysRunHelp = Authenticode.Choice_AlwaysRun_Help; - choices.Add( new ChoiceDescription( neverRun, neverRunHelp )); - choices.Add( new ChoiceDescription( doNotRun, doNotRunHelp )); - choices.Add( new ChoiceDescription( runOnce, runOnceHelp )); - choices.Add( new ChoiceDescription( alwaysRun, alwaysRunHelp )); + choices.Add(new ChoiceDescription(neverRun, neverRunHelp)); + choices.Add(new ChoiceDescription(doNotRun, doNotRunHelp)); + choices.Add(new ChoiceDescription(runOnce, runOnceHelp)); + choices.Add(new ChoiceDescription(alwaysRun, alwaysRunHelp)); return choices; } @@ -788,6 +788,6 @@ namespace Microsoft.PowerShell return choices; } } -} +} diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index bb4174863..9da5da10e 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -23,8 +23,8 @@ using System.Runtime.InteropServices; using Microsoft.Win32; -using DWORD = System.UInt32; -using BOOL = System.UInt32; +using DWORD = System.UInt32; +using BOOL = System.UInt32; namespace Microsoft.PowerShell { @@ -163,70 +163,70 @@ namespace System.Management.Automation.Internal } // Set the execution policy - switch(scope) + switch (scope) { case ExecutionPolicyScope.Process: - { - if(policy == ExecutionPolicy.Undefined) - executionPolicy = null; - - Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); - break; - } + { + if (policy == ExecutionPolicy.Undefined) + executionPolicy = null; + + Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); + break; + } case ExecutionPolicyScope.CurrentUser: - { - // They want to remove it - if(policy == ExecutionPolicy.Undefined) { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(preferenceKey, true)) + // They want to remove it + if (policy == ExecutionPolicy.Undefined) { - if(key != null) + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(preferenceKey, true)) { - if(key.GetValue(PolicyKeyValueName) != null) - key.DeleteValue(PolicyKeyValueName); + if (key != null) + { + if (key.GetValue(PolicyKeyValueName) != null) + key.DeleteValue(PolicyKeyValueName); + } + } + + CleanKeyParents(Registry.CurrentUser, preferenceKey); + } + else + { + using (RegistryKey key = Registry.CurrentUser.CreateSubKey(preferenceKey)) + { + key.SetValue(PolicyKeyValueName, executionPolicy, RegistryValueKind.String); } } - CleanKeyParents(Registry.CurrentUser, preferenceKey); + break; } - else - { - using (RegistryKey key = Registry.CurrentUser.CreateSubKey(preferenceKey)) - { - key.SetValue(PolicyKeyValueName, executionPolicy, RegistryValueKind.String); - } - } - - break; - } case ExecutionPolicyScope.LocalMachine: - { - // They want to remove it - if (policy == ExecutionPolicy.Undefined) { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(preferenceKey, true)) + // They want to remove it + if (policy == ExecutionPolicy.Undefined) { - if (key != null) + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(preferenceKey, true)) { - if (key.GetValue(PolicyKeyValueName) != null) - key.DeleteValue(PolicyKeyValueName); + if (key != null) + { + if (key.GetValue(PolicyKeyValueName) != null) + key.DeleteValue(PolicyKeyValueName); + } + } + + CleanKeyParents(Registry.LocalMachine, preferenceKey); + } + else + { + using (RegistryKey key = Registry.LocalMachine.CreateSubKey(preferenceKey)) + { + key.SetValue(PolicyKeyValueName, executionPolicy, RegistryValueKind.String); } } - CleanKeyParents(Registry.LocalMachine, preferenceKey); + break; } - else - { - using (RegistryKey key = Registry.LocalMachine.CreateSubKey(preferenceKey)) - { - key.SetValue(PolicyKeyValueName, executionPolicy, RegistryValueKind.String); - } - } - - break; - } } #endif } @@ -273,10 +273,10 @@ namespace System.Management.Automation.Internal internal static ExecutionPolicy GetExecutionPolicy(string shellId) { - foreach(ExecutionPolicyScope scope in ExecutionPolicyScopePreferences) + foreach (ExecutionPolicyScope scope in ExecutionPolicyScopePreferences) { ExecutionPolicy policy = GetExecutionPolicy(shellId, scope); - if(policy != ExecutionPolicy.Undefined) + if (policy != ExecutionPolicy.Undefined) return policy; } @@ -291,80 +291,80 @@ namespace System.Management.Automation.Internal switch (scope) { case ExecutionPolicyScope.Process: - { - string policy = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference"); + { + string policy = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference"); - if (!String.IsNullOrEmpty(policy)) - return ParseExecutionPolicy(policy); - else - return ExecutionPolicy.Undefined; - } + if (!String.IsNullOrEmpty(policy)) + return ParseExecutionPolicy(policy); + else + return ExecutionPolicy.Undefined; + } case ExecutionPolicyScope.CurrentUser: case ExecutionPolicyScope.LocalMachine: - { - string policy = GetLocalPreferenceValue(shellId, scope); + { + string policy = GetLocalPreferenceValue(shellId, scope); - if (!String.IsNullOrEmpty(policy)) - return ParseExecutionPolicy(policy); - else - return ExecutionPolicy.Undefined; - } + if (!String.IsNullOrEmpty(policy)) + return ParseExecutionPolicy(policy); + else + return ExecutionPolicy.Undefined; + } case ExecutionPolicyScope.UserPolicy: case ExecutionPolicyScope.MachinePolicy: - { - string groupPolicyPreference = GetGroupPolicyValue(shellId, scope); - if (!String.IsNullOrEmpty(groupPolicyPreference)) { - // Be sure we aren't being called by Group Policy - // itself. A group policy should never block a logon / - // logoff script. - Process currentProcess = Process.GetCurrentProcess(); - string gpScriptPath = IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.System), - "gpscript.exe"); - bool foundGpScriptParent = false; - - try + string groupPolicyPreference = GetGroupPolicyValue(shellId, scope); + if (!String.IsNullOrEmpty(groupPolicyPreference)) { - while (currentProcess != null) + // Be sure we aren't being called by Group Policy + // itself. A group policy should never block a logon / + // logoff script. + Process currentProcess = Process.GetCurrentProcess(); + string gpScriptPath = IO.Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.System), + "gpscript.exe"); + bool foundGpScriptParent = false; + + try { - if (String.Equals(gpScriptPath, - PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase)) + while (currentProcess != null) { - foundGpScriptParent = true; - break; - } - else - { - currentProcess = PsUtils.GetParentProcess(currentProcess); + if (String.Equals(gpScriptPath, + PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase)) + { + foundGpScriptParent = true; + break; + } + else + { + currentProcess = PsUtils.GetParentProcess(currentProcess); + } } } - } - catch (System.ComponentModel.Win32Exception) - { - // If you attempt to retrieve the MainModule of a 64-bit process - // from a WOW64 (32-bit) process, the Win32 API has a fatal - // flaw that causes this to return the error: - // "Only part of a ReadProcessMemory or WriteProcessMemory - // request was completed." - // In this case, we just catch the exception and eat it. - // The implication is that logon / logoff scripts that somehow - // launch the Wow64 version of PowerShell will be subject - // to the execution policy deployed by Group Policy (where - // our goal here is to not have the Group Policy execution policy - // affect logon / logoff scripts. + catch (System.ComponentModel.Win32Exception) + { + // If you attempt to retrieve the MainModule of a 64-bit process + // from a WOW64 (32-bit) process, the Win32 API has a fatal + // flaw that causes this to return the error: + // "Only part of a ReadProcessMemory or WriteProcessMemory + // request was completed." + // In this case, we just catch the exception and eat it. + // The implication is that logon / logoff scripts that somehow + // launch the Wow64 version of PowerShell will be subject + // to the execution policy deployed by Group Policy (where + // our goal here is to not have the Group Policy execution policy + // affect logon / logoff scripts. + } + + if (!foundGpScriptParent) + { + return ParseExecutionPolicy(groupPolicyPreference); + } } - if (!foundGpScriptParent) - { - return ParseExecutionPolicy(groupPolicyPreference); - } + return ExecutionPolicy.Undefined; } - - return ExecutionPolicy.Undefined; - } } return ExecutionPolicy.Restricted; @@ -424,7 +424,7 @@ namespace System.Management.Automation.Internal /// True when file has product binary signature public static bool IsProductBinary(string file) { - if(String.IsNullOrEmpty(file) || (! IO.File.Exists(file))) + if (String.IsNullOrEmpty(file) || (!IO.File.Exists(file))) { return false; } @@ -484,11 +484,11 @@ namespace System.Management.Automation.Internal codeProperties.cbSize = (uint)Marshal.SizeOf(typeof(SAFER_CODE_PROPERTIES)); codeProperties.dwCheckFlags = ( NativeConstants.SAFER_CRITERIA_IMAGEPATH | - NativeConstants.SAFER_CRITERIA_IMAGEHASH | + NativeConstants.SAFER_CRITERIA_IMAGEHASH | NativeConstants.SAFER_CRITERIA_AUTHENTICODE); codeProperties.ImagePath = path; - if(handle != null) + if (handle != null) { codeProperties.hImageFileHandle = handle.DangerousGetHandle(); } @@ -561,14 +561,14 @@ namespace System.Management.Automation.Internal switch (scope) { case ExecutionPolicyScope.MachinePolicy: - { - scopeKey = Utils.RegLocalMachine; - }; break; + { + scopeKey = Utils.RegLocalMachine; + }; break; case ExecutionPolicyScope.UserPolicy: - { - scopeKey = Utils.RegCurrentUser; - }; break; + { + scopeKey = Utils.RegCurrentUser; + }; break; } Dictionary groupPolicySettings = Utils.GetGroupPolicySetting(".", scopeKey); @@ -611,35 +611,35 @@ namespace System.Management.Automation.Internal { // 1: Look up the current-user preference case ExecutionPolicyScope.CurrentUser: - { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(LocalPreferenceKey)) { - if (key != null) + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(LocalPreferenceKey)) { - object temp = key.GetValue(PolicyValueName); - string policy = temp as string; - key.Dispose(); + if (key != null) + { + object temp = key.GetValue(PolicyValueName); + string policy = temp as string; + key.Dispose(); - return policy; + return policy; + } } - } - }; break; + }; break; // 1: Look up the system-wide preference case ExecutionPolicyScope.LocalMachine: - { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalPreferenceKey)) { - if (key != null) + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalPreferenceKey)) { - object temp = key.GetValue(PolicyValueName); - string policy = temp as string; - key.Dispose(); + if (key != null) + { + object temp = key.GetValue(PolicyValueName); + string policy = temp as string; + key.Dispose(); - return policy; + return policy; + } } - } - }; break; + }; break; } return null; @@ -709,7 +709,7 @@ namespace System.Management.Automation.Internal private static bool CertHasOid(X509Certificate2 c, string oid) { Collection ekus = GetCertEKU(c); - + foreach (string testOid in ekus) { if (testOid == oid) @@ -785,7 +785,7 @@ namespace System.Management.Automation.Internal ekuBuffer, out structSize)) { - Security.NativeMethods.CERT_ENHKEY_USAGE ekuStruct = + Security.NativeMethods.CERT_ENHKEY_USAGE ekuStruct = (Security.NativeMethods.CERT_ENHKEY_USAGE) ClrFacade.PtrToStructure(ekuBuffer); IntPtr ep = ekuStruct.rgpszUsageIdentifier; @@ -830,7 +830,7 @@ namespace System.Management.Automation.Internal internal static DWORD GetDWORDFromInt(int n) { UInt32 result = BitConverter.ToUInt32(BitConverter.GetBytes(n), 0); - return (DWORD) result; + return (DWORD)result; } /// @@ -846,7 +846,7 @@ namespace System.Management.Automation.Internal internal static int GetIntFromDWORD(DWORD n) { Int64 n64 = n - 0x100000000L; - return (int) n64; + return (int)n64; } } @@ -864,8 +864,8 @@ namespace System.Management.Automation.Internal /// internal CertificatePurpose Purpose { - get { return purpose; } - set { purpose = value; } + get { return _purpose; } + set { _purpose = value; } } /// @@ -873,8 +873,8 @@ namespace System.Management.Automation.Internal /// internal bool SSLServerAuthentication { - get { return sslServerAuthentication; } - set { sslServerAuthentication = value; } + get { return _sslServerAuthentication; } + set { _sslServerAuthentication = value; } } /// @@ -882,7 +882,7 @@ namespace System.Management.Automation.Internal /// internal string DnsName { - set { dnsName = value; } + set { _dnsName = value; } } /// @@ -890,7 +890,7 @@ namespace System.Management.Automation.Internal /// internal string[] Eku { - set { eku = value; } + set { _eku = value; } } /// @@ -898,7 +898,7 @@ namespace System.Management.Automation.Internal /// internal int ExpiringInDays { - set { expiringInDays = value; } + set { _expiringInDays = value; } } /// @@ -910,24 +910,24 @@ namespace System.Management.Automation.Internal { string filterString = ""; - if (dnsName != null) + if (_dnsName != null) { - filterString = AppendFilter(filterString, "dns", dnsName); + filterString = AppendFilter(filterString, "dns", _dnsName); } string ekuT = ""; - if (eku != null) + if (_eku != null) { - for (int i = 0; i < eku.Length; i++) + for (int i = 0; i < _eku.Length; i++) { if (ekuT.Length != 0) { ekuT = ekuT + ","; } - ekuT = ekuT + eku[i]; + ekuT = ekuT + _eku[i]; } } - if (purpose == CertificatePurpose.CodeSigning) + if (_purpose == CertificatePurpose.CodeSigning) { if (ekuT.Length != 0) { @@ -935,7 +935,7 @@ namespace System.Management.Automation.Internal } ekuT = ekuT + CodeSigningOid; } - if (purpose == CertificatePurpose.DocumentEncryption) + if (_purpose == CertificatePurpose.DocumentEncryption) { if (ekuT.Length != 0) { @@ -943,7 +943,7 @@ namespace System.Management.Automation.Internal } ekuT = ekuT + DocumentEncryptionOid; } - if (sslServerAuthentication) + if (_sslServerAuthentication) { if (ekuT.Length != 0) { @@ -954,18 +954,18 @@ namespace System.Management.Automation.Internal if (ekuT.Length != 0) { filterString = AppendFilter(filterString, "eku", ekuT); - if (purpose == CertificatePurpose.CodeSigning || - sslServerAuthentication) + if (_purpose == CertificatePurpose.CodeSigning || + _sslServerAuthentication) { filterString = AppendFilter(filterString, "key", "*"); } } - if (expiringInDays >= 0) + if (_expiringInDays >= 0) { filterString = AppendFilter( filterString, "ExpiringInDays", - expiringInDays.ToString(System.Globalization.CultureInfo.InvariantCulture)); + _expiringInDays.ToString(System.Globalization.CultureInfo.InvariantCulture)); } if (filterString.Length == 0) @@ -1007,11 +1007,11 @@ namespace System.Management.Automation.Internal return filterString + newfilter; } - private CertificatePurpose purpose = 0; - private bool sslServerAuthentication = false; - private string dnsName = null; - private string[] eku = null; - private int expiringInDays = -1; + private CertificatePurpose _purpose = 0; + private bool _sslServerAuthentication = false; + private string _dnsName = null; + private string[] _eku = null; + private int _expiringInDays = -1; internal const string CodeSigningOid = "1.3.6.1.5.5.7.3.3"; internal const string szOID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; @@ -1028,7 +1028,7 @@ namespace Microsoft.PowerShell.Commands /// Defines the valid purposes by which /// we can filter certificates. /// - enum CertificatePurpose + internal enum CertificatePurpose { /// /// Certificates where a purpose has not been specified. @@ -1058,7 +1058,6 @@ namespace Microsoft.PowerShell.Commands namespace System.Management.Automation { - #if !CORECLR using System.Security.Cryptography.Pkcs; @@ -1099,7 +1098,7 @@ namespace System.Management.Automation { recipient.Resolve(sessionState, ResolutionPurpose.Encryption, out error); } - + if (error != null) { return null; @@ -1203,10 +1202,10 @@ namespace System.Management.Automation /// public CmsMessageRecipient(string identifier) { - this.identifier = identifier; + _identifier = identifier; this.Certificates = new X509Certificate2Collection(); } - private string identifier = null; + private string _identifier = null; /// /// Creates an instance of the CmsMessageRecipient class @@ -1214,10 +1213,10 @@ namespace System.Management.Automation /// The certificate to use. public CmsMessageRecipient(X509Certificate2 certificate) { - pendingCertificate = certificate; + _pendingCertificate = certificate; this.Certificates = new X509Certificate2Collection(); } - private X509Certificate2 pendingCertificate = null; + private X509Certificate2 _pendingCertificate = null; /// /// Gets the certificate associated with this recipient @@ -1239,17 +1238,17 @@ namespace System.Management.Automation error = null; // Process the certificate if that was supplied exactly - if (pendingCertificate != null) + if (_pendingCertificate != null) { ProcessResolvedCertificates(purpose, - new List { pendingCertificate }, out error); + new List { _pendingCertificate }, out error); if ((error != null) || (Certificates.Count != 0)) { return; } } - if (identifier != null) + if (_identifier != null) { // First try to resolve assuming that the cert was Base64 encoded. ResolveFromBase64Encoding(purpose, out error); @@ -1285,13 +1284,13 @@ namespace System.Management.Automation // don't generate an error if they used wildcards. If they did not use wildcards, // then generate an error because they were expecting something specific. if ((purpose == ResolutionPurpose.Encryption) || - (!WildcardPattern.ContainsWildcardCharacters(identifier))) + (!WildcardPattern.ContainsWildcardCharacters(_identifier))) { error = new ErrorRecord( new ArgumentException( String.Format(CultureInfo.InvariantCulture, - SecuritySupportStrings.NoCertificateFound, identifier)), - "NoCertificateFound", ErrorCategory.ObjectNotFound, identifier); + SecuritySupportStrings.NoCertificateFound, _identifier)), + "NoCertificateFound", ErrorCategory.ObjectNotFound, _identifier); } return; @@ -1304,7 +1303,7 @@ namespace System.Management.Automation byte[] messageBytes = null; try { - messageBytes = CmsUtils.RemoveAsciiArmor(identifier, CmsUtils.BEGIN_CERTIFICATE_SIGIL, CmsUtils.END_CERTIFICATE_SIGIL, out startIndex, out endIndex); + messageBytes = CmsUtils.RemoveAsciiArmor(_identifier, CmsUtils.BEGIN_CERTIFICATE_SIGIL, CmsUtils.END_CERTIFICATE_SIGIL, out startIndex, out endIndex); } catch (FormatException) { @@ -1345,7 +1344,7 @@ namespace System.Management.Automation try { - resolvedPaths = sessionState.Path.GetResolvedProviderPathFromPSPath(identifier, out pathProvider); + resolvedPaths = sessionState.Path.GetResolvedProviderPathFromPSPath(_identifier, out pathProvider); } catch (SessionStateException) { @@ -1361,7 +1360,7 @@ namespace System.Management.Automation error = new ErrorRecord( new ArgumentException( String.Format(CultureInfo.InvariantCulture, - SecuritySupportStrings.CertificatePathMustBeFileSystemPath, identifier)), + SecuritySupportStrings.CertificatePathMustBeFileSystemPath, _identifier)), "CertificatePathMustBeFileSystemPath", ErrorCategory.ObjectNotFound, pathProvider); return; } @@ -1419,7 +1418,7 @@ namespace System.Management.Automation private void ResolveFromThumbprint(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { // Quickly check that this is a thumbprint-like pattern (just hex) - if (!System.Text.RegularExpressions.Regex.IsMatch(identifier, "^[a-f0-9]+$", Text.RegularExpressions.RegexOptions.IgnoreCase)) + if (!System.Text.RegularExpressions.Regex.IsMatch(_identifier, "^[a-f0-9]+$", Text.RegularExpressions.RegexOptions.IgnoreCase)) { error = null; return; @@ -1430,7 +1429,7 @@ namespace System.Management.Automation try { // Get first from 'My' store - string certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::CurrentUser\\My", identifier); + string certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::CurrentUser\\My", _identifier); if (sessionState.InvokeProvider.Item.Exists(certificatePath)) { foreach (PSObject certificateObject in sessionState.InvokeProvider.Item.Get(certificatePath)) @@ -1440,7 +1439,7 @@ namespace System.Management.Automation } // Second from 'LocalMachine' store - certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::LocalMachine\\My", identifier); + certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::LocalMachine\\My", _identifier); if (sessionState.InvokeProvider.Item.Exists(certificatePath)) { foreach (PSObject certificateObject in sessionState.InvokeProvider.Item.Get(certificatePath)) @@ -1470,7 +1469,7 @@ namespace System.Management.Automation private void ResolveFromSubjectName(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { Collection certificates = new Collection(); - WildcardPattern subjectNamePattern = WildcardPattern.Get(identifier, WildcardOptions.IgnoreCase); + WildcardPattern subjectNamePattern = WildcardPattern.Get(_identifier, WildcardOptions.IgnoreCase); try { @@ -1519,7 +1518,7 @@ namespace System.Management.Automation { // If they specified a specific cert, generate an error if it isn't good // for encryption. - if (!WildcardPattern.ContainsWildcardCharacters(identifier)) + if (!WildcardPattern.ContainsWildcardCharacters(_identifier)) { error = new ErrorRecord( new ArgumentException( @@ -1562,7 +1561,7 @@ namespace System.Management.Automation error = new ErrorRecord( new ArgumentException( String.Format(CultureInfo.InvariantCulture, - SecuritySupportStrings.IdentifierMustReferenceSingleCertificate, identifier, "To")), + SecuritySupportStrings.IdentifierMustReferenceSingleCertificate, _identifier, "To")), "IdentifierMustReferenceSingleCertificate", ErrorCategory.LimitsExceeded, certificatesToProcess); Certificates.Clear(); return; @@ -1594,9 +1593,9 @@ namespace System.Management.Automation { internal static int Init() { - Diagnostics.Assert(amsiContext == IntPtr.Zero, "Init should be called just once"); + Diagnostics.Assert(s_amsiContext == IntPtr.Zero, "Init should be called just once"); - lock (amsiLockObject) + lock (s_amsiLockObject) { Process currentProcess = Process.GetCurrentProcess(); string hostname; @@ -1619,10 +1618,10 @@ namespace System.Management.Automation AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; #endif - var hr = AmsiNativeMethods.AmsiInitialize(hostname, ref amsiContext); + var hr = AmsiNativeMethods.AmsiInitialize(hostname, ref s_amsiContext); if (!Utils.Succeeded(hr)) { - amsiInitFailed = true; + s_amsiInitFailed = true; } return hr; @@ -1642,7 +1641,7 @@ namespace System.Management.Automation #if UNIX return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; #else - return WinScanContent(content,sourceMetadata); + return WinScanContent(content, sourceMetadata); #endif } @@ -1663,14 +1662,14 @@ namespace System.Management.Automation } // If we had a previous initialization failure, just return the neutral result. - if (amsiInitFailed) + if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } - lock (amsiLockObject) + lock (s_amsiLockObject) { - if (amsiInitFailed) + if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } @@ -1681,27 +1680,27 @@ namespace System.Management.Automation // Initialize AntiMalware Scan Interface, if not already initialized. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") - if (amsiContext == IntPtr.Zero) + if (s_amsiContext == IntPtr.Zero) { hr = Init(); - if (! Utils.Succeeded(hr)) + if (!Utils.Succeeded(hr)) { - amsiInitFailed = true; + s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } // Initialize the session, if one isn't already started. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") - if (amsiSession == IntPtr.Zero) + if (s_amsiSession == IntPtr.Zero) { - hr = AmsiNativeMethods.AmsiOpenSession(amsiContext, ref amsiSession); + hr = AmsiNativeMethods.AmsiOpenSession(s_amsiContext, ref s_amsiSession); AmsiInitialized = true; if (!Utils.Succeeded(hr)) { - amsiInitFailed = true; + s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } @@ -1709,10 +1708,10 @@ namespace System.Management.Automation AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_CLEAN; hr = AmsiNativeMethods.AmsiScanString( - amsiContext, + s_amsiContext, content, sourceMetadata, - amsiSession, + s_amsiSession, ref result); if (!Utils.Succeeded(hr)) @@ -1725,7 +1724,7 @@ namespace System.Management.Automation } catch (DllNotFoundException) { - amsiInitFailed = true; + s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } @@ -1739,12 +1738,12 @@ namespace System.Management.Automation } [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - static IntPtr amsiContext = IntPtr.Zero; + private static IntPtr s_amsiContext = IntPtr.Zero; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - static IntPtr amsiSession = IntPtr.Zero; + private static IntPtr s_amsiSession = IntPtr.Zero; - static bool amsiInitFailed = false; - static object amsiLockObject = new Object(); + private static bool s_amsiInitFailed = false; + private static object s_amsiLockObject = new Object(); /// /// Reset the AMSI session (used to track related script invocations) @@ -1758,17 +1757,17 @@ namespace System.Management.Automation internal static void WinCloseSession() { - if (!amsiInitFailed) + if (!s_amsiInitFailed) { - if ((amsiContext != IntPtr.Zero) && (amsiSession != IntPtr.Zero)) + if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { - lock (amsiLockObject) + lock (s_amsiLockObject) { // Clean up the session if one was open. - if ((amsiContext != IntPtr.Zero) && (amsiSession != IntPtr.Zero)) + if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { - AmsiNativeMethods.AmsiCloseSession(amsiContext, amsiSession); - amsiSession = IntPtr.Zero; + AmsiNativeMethods.AmsiCloseSession(s_amsiContext, s_amsiSession); + s_amsiSession = IntPtr.Zero; } } } @@ -1788,18 +1787,18 @@ namespace System.Management.Automation internal static void WinUninitialize() { AmsiUninitializeCalled = true; - if (!amsiInitFailed) + if (!s_amsiInitFailed) { - lock (amsiLockObject) + lock (s_amsiLockObject) { - if (amsiContext != IntPtr.Zero) + if (s_amsiContext != IntPtr.Zero) { CloseSession(); // Uninitialize the AMSI interface. AmsiCleanedUp = true; - AmsiNativeMethods.AmsiUninitialize(amsiContext); - amsiContext = IntPtr.Zero; + AmsiNativeMethods.AmsiUninitialize(s_amsiContext); + s_amsiContext = IntPtr.Zero; } } } diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index b297e8241..3d423420d 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -12,8 +12,8 @@ using System.Security.Cryptography.X509Certificates; using System.Management.Automation.Internal; using Microsoft.Win32.SafeHandles; -using DWORD = System.UInt32; -using BOOL = System.UInt32; +using DWORD = System.UInt32; +using BOOL = System.UInt32; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; #if CORECLR @@ -566,7 +566,6 @@ namespace System.Management.Automation.Security { CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN = 1, CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT = 2 - }; [StructLayout(LayoutKind.Sequential)] @@ -616,8 +615,8 @@ namespace System.Management.Automation.Security } [StructLayout(LayoutKind.Sequential)] - internal struct CRYPT_OID_INFO { - + internal struct CRYPT_OID_INFO + { /// DWORD->unsigned int public uint cbSize; @@ -1076,36 +1075,36 @@ namespace System.Management.Automation.Security [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_CERT { - DWORD cbStruct; + private DWORD _cbStruct; internal IntPtr pCert; // PCCERT_CONTEXT - BOOL fCommercial; - BOOL fTrustedRoot; - BOOL fSelfSigned; - BOOL fTestCert; - DWORD dwRevokedReason; - DWORD dwConfidence; - DWORD dwError; - IntPtr pTrustListContext; // CTL_CONTEXT* - BOOL fTrustListSignerCert; - IntPtr pCtlContext; // PCCTL_CONTEXT - DWORD dwCtlError; - BOOL fIsCyclic; - IntPtr pChainElement; // PCERT_CHAIN_ELEMENT + private BOOL _fCommercial; + private BOOL _fTrustedRoot; + private BOOL _fSelfSigned; + private BOOL _fTestCert; + private DWORD _dwRevokedReason; + private DWORD _dwConfidence; + private DWORD _dwError; + private IntPtr _pTrustListContext; // CTL_CONTEXT* + private BOOL _fTrustListSignerCert; + private IntPtr _pCtlContext; // PCCTL_CONTEXT + private DWORD _dwCtlError; + private BOOL _fIsCyclic; + private IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_SGNR { - DWORD cbStruct; - FILETIME sftVerifyAsOf; - DWORD csCertChain; - IntPtr pasCertChain; // CRYPT_PROVIDER_CERT* - DWORD dwSignerType; - IntPtr psSigner; // CMSG_SIGNER_INFO* - DWORD dwError; + private DWORD _cbStruct; + private FILETIME _sftVerifyAsOf; + private DWORD _csCertChain; + private IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* + private DWORD _dwSignerType; + private IntPtr _psSigner; // CMSG_SIGNER_INFO* + private DWORD _dwError; internal DWORD csCounterSigners; internal IntPtr pasCounterSigners; // CRYPT_PROVIDER_SGNR* - IntPtr pChainContext; // PCCERT_CHAIN_CONTEXT + private IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT }; [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] @@ -1217,7 +1216,6 @@ namespace System.Management.Automation.Security internal enum SIGNATURE_STATE { - /// SIGNATURE_STATE_UNSIGNED_MISSING -> 0 SIGNATURE_STATE_UNSIGNED_MISSING = 0, @@ -1238,7 +1236,6 @@ namespace System.Management.Automation.Security internal enum SIGNATURE_INFO_FLAGS { - /// SIF_NONE -> 0x0000 SIF_NONE = 0, @@ -1266,7 +1263,6 @@ namespace System.Management.Automation.Security internal enum SIGNATURE_INFO_AVAILABILITY { - /// SIA_DISPLAYNAME -> 0x0001 SIA_DISPLAYNAME = 1, @@ -1282,7 +1278,6 @@ namespace System.Management.Automation.Security internal enum SIGNATURE_INFO_TYPE { - /// SIT_UNKNOWN -> 0 SIT_UNKNOWN = 0, @@ -1294,7 +1289,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct SIGNATURE_INFO { - /// DWORD->unsigned int internal uint cbSize; @@ -1344,7 +1338,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_INFO { - /// DWORD->unsigned int internal uint dwVersion; @@ -1385,7 +1378,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { - /// LPSTR->CHAR* [MarshalAsAttribute(UnmanagedType.LPStr)] internal string pszObjId; @@ -1397,7 +1389,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct FILETIME { - /// DWORD->unsigned int internal uint dwLowDateTime; @@ -1408,7 +1399,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { - /// CRYPT_ALGORITHM_IDENTIFIER->_CRYPT_ALGORITHM_IDENTIFIER internal CRYPT_ALGORITHM_IDENTIFIER Algorithm; @@ -1419,7 +1409,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CRYPT_BIT_BLOB { - /// DWORD->unsigned int internal uint cbData; @@ -1433,7 +1422,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct CERT_EXTENSION { - /// LPSTR->CHAR* [MarshalAsAttribute(UnmanagedType.LPStr)] internal string pszObjId; @@ -1647,7 +1635,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Explicit)] internal struct LARGE_INTEGER { - /// Anonymous_9320654f_2227_43bf_a385_74cc8c562686 [FieldOffsetAttribute(0)] public Anonymous_9320654f_2227_43bf_a385_74cc8c562686 Struct1; @@ -1664,7 +1651,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct HWND__ { - /// int public int unused; } @@ -1672,7 +1658,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct Anonymous_9320654f_2227_43bf_a385_74cc8c562686 { - /// DWORD->unsigned int public uint LowPart; @@ -1683,7 +1668,6 @@ namespace System.Management.Automation.Security [StructLayoutAttribute(LayoutKind.Sequential)] internal struct Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 { - /// DWORD->unsigned int public uint LowPart; @@ -2011,13 +1995,12 @@ namespace System.Management.Automation.Security // CRYPTCAT_E_CDF_ATTR_TYPECOMBO = "0x00020004"; public const int CRYPTCAT_E_CDF_ATTR_TYPECOMBO = 131076; - } - /// - /// pinvoke methods from wintrust.dll - /// These are added to Generate and Validate Window Catalog Files - /// + /// + /// pinvoke methods from wintrust.dll + /// These are added to Generate and Validate Window Catalog Files + /// internal static partial class NativeMethods { [StructLayout(LayoutKind.Sequential)] @@ -2039,14 +2022,14 @@ namespace System.Management.Automation.Security [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATCDF { - DWORD cbStruct; - IntPtr hFile; - DWORD dwCurFilePos; - DWORD dwLastMemberOffset; - BOOL fEOF; + private DWORD _cbStruct; + private IntPtr _hFile; + private DWORD _dwCurFilePos; + private DWORD _dwLastMemberOffset; + private BOOL _fEOF; [MarshalAs(UnmanagedType.LPWStr)] - string pwszResultDir; - IntPtr hCATStore; + private string _pwszResultDir; + private IntPtr _hCATStore; }; [StructLayout(LayoutKind.Sequential)] @@ -2070,29 +2053,29 @@ namespace System.Management.Automation.Security [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATATTRIBUTE { - DWORD cbStruct; + private DWORD _cbStruct; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; - DWORD dwAttrTypeAndAction; + private DWORD _dwAttrTypeAndAction; internal DWORD cbValue; internal System.IntPtr pbValue; - DWORD dwReserved; + private DWORD _dwReserved; }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATSTORE { - DWORD cbStruct; - internal DWORD dwPublicVersion; + private DWORD _cbStruct; + internal DWORD dwPublicVersion; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszP7File; - IntPtr hProv; - DWORD dwEncodingType; - DWORD fdwStoreFlags; - IntPtr hReserved; - IntPtr hAttrs; - IntPtr hCryptMsg; - IntPtr hSorted; + private IntPtr _hProv; + private DWORD _dwEncodingType; + private DWORD _fdwStoreFlags; + private IntPtr _hReserved; + private IntPtr _hAttrs; + private IntPtr _hCryptMsg; + private IntPtr _hSorted; }; [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] @@ -2170,7 +2153,7 @@ namespace System.Management.Automation.Security ); [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern unsafe IntPtr CreateFile( + internal static extern unsafe IntPtr CreateFile( string lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, @@ -2179,7 +2162,7 @@ namespace System.Management.Automation.Security DWORD dwFlagsAndAttributes, IntPtr hTemplateFile ); - + [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool CryptCATAdminCalcHashFromFileHandle2( IntPtr hCatAdmin, @@ -2224,7 +2207,7 @@ namespace System.Management.Automation.Security void CryptCATCDFEnumMembersByCDFTagExErrorCallBack(DWORD NotUsedDWORD1, DWORD NotUsedDWORD2, [MarshalAs(UnmanagedType.LPWStr)] - string NotUsedString); + string NotUsedString); } } diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 1bc416616..059720935 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -43,23 +43,23 @@ namespace System.Management.Automation.Security /// An EnforcementMode that describes the system policy public static SystemEnforcementMode GetSystemLockdownPolicy() { - if (wasSystemPolicyDebugPolicy || (systemLockdownPolicy == null)) + if (s_wasSystemPolicyDebugPolicy || (s_systemLockdownPolicy == null)) { - lock (systemLockdownPolicyLock) + lock (s_systemLockdownPolicyLock) { - if (wasSystemPolicyDebugPolicy || (systemLockdownPolicy == null)) + if (s_wasSystemPolicyDebugPolicy || (s_systemLockdownPolicy == null)) { - systemLockdownPolicy = GetLockdownPolicy(null, null); + s_systemLockdownPolicy = GetLockdownPolicy(null, null); } } } - return systemLockdownPolicy.Value; + return s_systemLockdownPolicy.Value; } - private static object systemLockdownPolicyLock = new Object(); - private static Nullable systemLockdownPolicy = null; - private static bool wasSystemPolicyDebugPolicy = false; + private static object s_systemLockdownPolicyLock = new Object(); + private static Nullable s_systemLockdownPolicy = null; + private static bool s_wasSystemPolicyDebugPolicy = false; /// /// Gets lockdown policy as applied to a file @@ -69,7 +69,7 @@ namespace System.Management.Automation.Security { // Check the WLDP API SystemEnforcementMode lockdownPolicy = GetWldpPolicy(path, handle); - if(lockdownPolicy == SystemEnforcementMode.Enforce) + if (lockdownPolicy == SystemEnforcementMode.Enforce) { return lockdownPolicy; } @@ -77,7 +77,7 @@ namespace System.Management.Automation.Security // At this point, LockdownPolicy = Audit or Allowed. // If there was a WLDP policy, but WLDP didn't block it, // then it was explicitly allowed. Therefore, return the result for the file. - SystemEnforcementMode systemWldpPolicy = cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); + SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); if ((systemWldpPolicy == SystemEnforcementMode.Enforce) || (systemWldpPolicy == SystemEnforcementMode.Audit)) { @@ -93,7 +93,7 @@ namespace System.Management.Automation.Security // If there was a system-wide AppLocker policy, but AppLocker didn't block it, // then return AppLocker's status. - if (cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) == + if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) == SaferPolicy.Disallowed) { return lockdownPolicy; @@ -108,18 +108,18 @@ namespace System.Management.Automation.Security private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handle) { // If the WLDP assembly is missing (such as windows 7 or down OS), return default/None to skip WLDP valification - if (hadMissingWldpAssembly || !IO.File.Exists(IO.Path.Combine(Environment.SystemDirectory, "wldp.dll"))) + if (s_hadMissingWldpAssembly || !IO.File.Exists(IO.Path.Combine(Environment.SystemDirectory, "wldp.dll"))) { - hadMissingWldpAssembly = true; - return cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); + s_hadMissingWldpAssembly = true; + return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } // If path is NULL, see if we have the cached system-wide lockdown policy. if (String.IsNullOrEmpty(path)) { - if ((cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) + if ((s_cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) { - return cachedWldpSystemPolicy.Value; + return s_cachedWldpSystemPolicy.Value; } } @@ -150,7 +150,7 @@ namespace System.Management.Automation.Security // If this is a query for the system-wide lockdown policy, cache it. if (String.IsNullOrEmpty(path)) { - cachedWldpSystemPolicy = resultingLockdownPolicy; + s_cachedWldpSystemPolicy = resultingLockdownPolicy; } return resultingLockdownPolicy; @@ -163,12 +163,12 @@ namespace System.Management.Automation.Security } catch (DllNotFoundException) { - hadMissingWldpAssembly = true; - return cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); + s_hadMissingWldpAssembly = true; + return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } } - private static SystemEnforcementMode? cachedWldpSystemPolicy = null; - + private static SystemEnforcementMode? s_cachedWldpSystemPolicy = null; + private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle handle) { @@ -180,9 +180,9 @@ namespace System.Management.Automation.Security // no AppLocker script policy. if (String.IsNullOrEmpty(path)) { - if ((cachedSaferSystemPolicy != null) && (! InternalTestHooks.BypassAppLockerPolicyCaching)) + if ((s_cachedSaferSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) { - result = cachedSaferSystemPolicy.Value; + result = s_cachedSaferSystemPolicy.Value; } else { @@ -265,8 +265,8 @@ namespace System.Management.Automation.Security if (IO.File.Exists(testPathScript)) { IO.File.Delete(testPathScript); } if (IO.File.Exists(testPathModule)) { IO.File.Delete(testPathModule); } } - - cachedSaferSystemPolicy = result; + + s_cachedSaferSystemPolicy = result; } if (result == SaferPolicy.Disallowed) @@ -290,7 +290,7 @@ namespace System.Management.Automation.Security return SystemEnforcementMode.None; } } - private static SaferPolicy? cachedSaferSystemPolicy = null; + private static SaferPolicy? s_cachedSaferSystemPolicy = null; private static string GetKnownFolderPath(Guid knownFolderId) { @@ -331,7 +331,7 @@ namespace System.Management.Automation.Security return SystemEnforcementMode.Enforce; } - wasSystemPolicyDebugPolicy = true; + s_wasSystemPolicyDebugPolicy = true; // Support fall-back debug hook for path exclusions on non-WOA platforms if (path != null) @@ -371,7 +371,7 @@ namespace System.Management.Automation.Security // No explicit debug allowance for the file, so return the system policy if there // is one. - return systemLockdownPolicy.GetValueOrDefault(SystemEnforcementMode.None); + return s_systemLockdownPolicy.GetValueOrDefault(SystemEnforcementMode.None); } // Support fall-back debug hook for system-wide policy on non-WOA platforms @@ -386,9 +386,9 @@ namespace System.Management.Automation.Security // If the system-wide debug policy had no preference, then there is no enforcement. return SystemEnforcementMode.None; } - private static bool hadMissingWldpAssembly = false; + private static bool s_hadMissingWldpAssembly = false; + - /// /// Gets lockdown policy as applied to a COM object @@ -405,14 +405,14 @@ namespace System.Management.Automation.Security int pIsApproved = 0; int result = WldpNativeMethods.WldpIsClassInApprovedList(ref clsid, ref hostInformation, ref pIsApproved, 0); - if(result >= 0) + if (result >= 0) { - if(pIsApproved == 1) + if (pIsApproved == 1) { // Hook for testability. If we've got an environmental override, say that ADODB.Parameter // is not allowed. // 0000050b-0000-0010-8000-00aa006d2ea4 = ADODB.Parameter - if (wasSystemPolicyDebugPolicy) + if (s_wasSystemPolicyDebugPolicy) { if (String.Equals(clsid.ToString(), "0000050b-0000-0010-8000-00aa006d2ea4", StringComparison.OrdinalIgnoreCase)) { @@ -566,7 +566,7 @@ namespace System.Management.Automation.Security [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int SHGetKnownFolderPath( - [MarshalAs(UnmanagedType.LPStruct)] + [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, int dwFlags, IntPtr hToken, diff --git a/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs b/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs index 92be0ceb8..bfae84b3e 100644 --- a/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs +++ b/src/System.Management.Automation/singleshell/Commands/ConsoleCommands.cs @@ -81,22 +81,22 @@ namespace Microsoft.PowerShell.Commands /// If a parameter is not supplied then the file represented by $console /// will be used for saving. /// - [Parameter(Position = 0, Mandatory=false, ValueFromPipeline=true, - ValueFromPipelineByPropertyName=true)] + [Parameter(Position = 0, Mandatory = false, ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string Path { get { - return fileName; + return _fileName; } set { - fileName = value; + _fileName = value; } } - private string fileName; + private string _fileName; /// /// Property that sets force parameter. This will reset the read-only @@ -107,14 +107,14 @@ namespace Microsoft.PowerShell.Commands { get { - return force; + return _force; } set { - force = value; + _force = value; } } - private bool force; + private bool _force; /// /// Property that prevents file overwrite. @@ -125,14 +125,14 @@ namespace Microsoft.PowerShell.Commands { get { - return noclobber; + return _noclobber; } set { - noclobber = value; + _noclobber = value; } } - private bool noclobber; + private bool _noclobber; #endregion @@ -237,7 +237,7 @@ namespace Microsoft.PowerShell.Commands } catch (PSArgumentException mae) { - ThrowError(resolvedPath, + ThrowError(resolvedPath, "PathNotAbsolute", mae, ErrorCategory.InvalidArgument); } catch (PSArgumentNullException mane) @@ -250,7 +250,7 @@ namespace Microsoft.PowerShell.Commands ThrowError(resolvedPath, "InvalidCharacetersInPath", ae, ErrorCategory.InvalidArgument); } - + // looks like saving succeeded. // Now try changing $console Exception e = null; @@ -295,9 +295,9 @@ namespace Microsoft.PowerShell.Commands { e = pin; } - - if ( e != null ) - { + + if (e != null) + { throw PSTraceSource.NewInvalidOperationException(e, ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath); } @@ -523,10 +523,10 @@ namespace Microsoft.PowerShell.Commands /// private string GetFileName() { - if (!string.IsNullOrEmpty(fileName)) + if (!string.IsNullOrEmpty(_fileName)) { // if user specified input..just return - return fileName; + return _fileName; } // no input is specified.. // check whether $console is set @@ -556,7 +556,7 @@ namespace Microsoft.PowerShell.Commands return consoleValue; } - throw PSTraceSource.NewArgumentException("fileName", ConsoleInfoErrorStrings.ConsoleCannotbeConvertedToString); + throw PSTraceSource.NewArgumentException("fileName", ConsoleInfoErrorStrings.ConsoleCannotbeConvertedToString); } /// diff --git a/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs b/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs index cfe5c7721..e703b4ec0 100644 --- a/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs +++ b/src/System.Management.Automation/singleshell/Commands/MshSnapinCommands.cs @@ -35,10 +35,10 @@ namespace Microsoft.PowerShell.Commands { if (_disposed == false) { - if (resourceReader != null) + if (_resourceReader != null) { - resourceReader.Dispose(); - resourceReader = null; + _resourceReader.Dispose(); + _resourceReader = null; } GC.SuppressFinalize(this); } @@ -48,17 +48,17 @@ namespace Microsoft.PowerShell.Commands #endregion IDisposable Members #region Cmdlet Methods - + /// /// Disposes the resource reader. /// /// protected override void EndProcessing() { - if (resourceReader != null) + if (_resourceReader != null) { - resourceReader.Dispose(); - resourceReader = null; + _resourceReader.Dispose(); + _resourceReader = null; } } @@ -128,7 +128,7 @@ namespace Microsoft.PowerShell.Commands // return an empty list return listToReturn; } - + WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); // We are doing WildCard search foreach (PSSnapInInfo psSnapIn in searchList) @@ -159,7 +159,7 @@ namespace Microsoft.PowerShell.Commands // See if the assembly-qualified names match and return the existing PSSnapInInfo // if they do. string loadedSnapInAssemblyName = loadedPSSnapInInfo.AssemblyName; - if (string.Equals(loadedPSSnapInInfo.Name, psSnapInInfo.Name, StringComparison.OrdinalIgnoreCase) && + if (string.Equals(loadedPSSnapInInfo.Name, psSnapInInfo.Name, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(loadedSnapInAssemblyName) && string.Equals(loadedSnapInAssemblyName, psSnapInInfo.AssemblyName, System.StringComparison.OrdinalIgnoreCase)) { @@ -176,7 +176,6 @@ namespace Microsoft.PowerShell.Commands /// protected internal Collection GetSnapIns(string pattern) { - // If RunspaceConfiguration is not null, then return the list that it has if (Runspace != null) { @@ -251,14 +250,14 @@ namespace Microsoft.PowerShell.Commands { get { - if (resourceReader == null) + if (_resourceReader == null) { - resourceReader = RegistryStringResourceIndirect.GetResourceIndirectReader(); + _resourceReader = RegistryStringResourceIndirect.GetResourceIndirectReader(); } - return resourceReader; + return _resourceReader; } } - private RegistryStringResourceIndirect resourceReader; + private RegistryStringResourceIndirect _resourceReader; #endregion } @@ -271,8 +270,8 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Add, "PSSnapin", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113281")] [OutputType(typeof(PSSnapInInfo))] - public sealed class AddPSSnapinCommand : PSSnapInCommandBase - { + public sealed class AddPSSnapinCommand : PSSnapInCommandBase + { #region Parameters /// @@ -350,7 +349,7 @@ namespace Microsoft.PowerShell.Commands if (listToSearch == null) { // cache snapin registry information... - + // For 3.0 PowerShell, we still use "1" as the registry version key for // Snapin and Custom shell lookup/discovery. // For 3.0 PowerShell, we use "3" as the registry version key only for Engine @@ -434,7 +433,7 @@ namespace Microsoft.PowerShell.Commands // bind the cmdlets from the snapins... if (Context.RunspaceConfiguration == null) { - Collection loadedSnapins = base.GetSnapIns(null); + Collection loadedSnapins = base.GetSnapIns(null); InitialSessionState iss = InitialSessionState.Create(); bool isAtleastOneSnapinLoaded = false; foreach (string snapIn in snapInList) @@ -526,9 +525,9 @@ namespace Microsoft.PowerShell.Commands if (exception != null) { - WriteNonTerminatingError(psSnapIn, - "AddPSSnapInRead", - exception, + WriteNonTerminatingError(psSnapIn, + "AddPSSnapInRead", + exception, ErrorCategory.InvalidArgument); } } @@ -693,7 +692,6 @@ namespace Microsoft.PowerShell.Commands WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument); } } - } // ShouldContinue } } @@ -718,7 +716,7 @@ namespace Microsoft.PowerShell.Commands /// /// Name(s) of PSSnapIn(s). /// - [Parameter(Position = 0, Mandatory = false)] + [Parameter(Position = 0, Mandatory = false)] public string[] Name { get @@ -731,7 +729,7 @@ namespace Microsoft.PowerShell.Commands } } private string[] _pssnapins; - + /// /// Property that determines whether to get all pssnapins that are currently /// registered ( in registry ). @@ -764,7 +762,6 @@ namespace Microsoft.PowerShell.Commands /// protected override void BeginProcessing() { - if (_pssnapins != null) { foreach (string psSnapIn in _pssnapins) @@ -851,8 +848,6 @@ namespace Microsoft.PowerShell.Commands } #endregion - - } #endregion diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleInfo.cs b/src/System.Management.Automation/singleshell/config/MshConsoleInfo.cs index d5321d45d..a6c911ec0 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleInfo.cs @@ -12,7 +12,6 @@ using System.Collections.Generic; namespace System.Management.Automation.Runspaces { - /// /// Class that understands Monad Console File Format. The format for the console /// file is applied/read by this class only. @@ -57,7 +56,7 @@ namespace System.Management.Automation.Runspaces #region Data - private readonly string monadVersion; + private readonly string _monadVersion; /// /// MonadVersion from the console file @@ -66,11 +65,11 @@ namespace System.Management.Automation.Runspaces { get { - return monadVersion; + return _monadVersion; } } - private readonly Collection mshsnapins; + private readonly Collection _mshsnapins; /// /// List of MshSnapin IDs from the console file @@ -79,7 +78,7 @@ namespace System.Management.Automation.Runspaces { get { - return mshsnapins; + return _mshsnapins; } } @@ -89,17 +88,17 @@ namespace System.Management.Automation.Runspaces private PSConsoleFileElement(string version) { - monadVersion = version; + _monadVersion = version; // Dont make collections null... // making them null, wont be good for foreach statements - mshsnapins = new Collection(); + _mshsnapins = new Collection(); } #endregion #region tracer - static private readonly PSTraceSource _mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + static private readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); #endregion #region Static Methods @@ -120,13 +119,13 @@ namespace System.Management.Automation.Runspaces { Diagnostics.Assert(path != null, "Filename should not be null"); - _mshsnapinTracer.WriteLine("Saving console info to file {0}.", path); + s_mshsnapinTracer.WriteLine("Saving console info to file {0}.", path); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; - using(Stream stream = new FileStream(path, FileMode.OpenOrCreate)) + using (Stream stream = new FileStream(path, FileMode.OpenOrCreate)) { // Generate xml for the consoleinfo object. using (XmlWriter writer = XmlWriter.Create(stream, settings)) @@ -153,7 +152,7 @@ namespace System.Management.Automation.Runspaces } } - _mshsnapinTracer.WriteLine("Saving console info succeeded."); + s_mshsnapinTracer.WriteLine("Saving console info succeeded."); } /// @@ -173,26 +172,26 @@ namespace System.Management.Automation.Runspaces { Diagnostics.Assert(path != null, "Filename should not be null"); - _mshsnapinTracer.WriteLine("Loading console info from file {0}.", path); + s_mshsnapinTracer.WriteLine("Loading console info from file {0}.", path); XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( - new FileInfo(path), + new FileInfo(path), false, /* ignore whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ // Validate content if (doc[MSHCONSOLEFILE] == null) { - _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, MSHCONSOLEFILE); + s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, MSHCONSOLEFILE); throw new XmlException( StringUtil.Format(ConsoleInfoErrorStrings.MonadConsoleNotFound, path)); } - if ( (doc[MSHCONSOLEFILE][PSVERSION] == null) || - (string.IsNullOrEmpty(doc[MSHCONSOLEFILE][PSVERSION].InnerText)) ) + if ((doc[MSHCONSOLEFILE][PSVERSION] == null) || + (string.IsNullOrEmpty(doc[MSHCONSOLEFILE][PSVERSION].InnerText))) { - _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, PSVERSION); + s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag {1}.", path, PSVERSION); throw new XmlException( StringUtil.Format(ConsoleInfoErrorStrings.MonadVersionNotFound, path)); @@ -200,25 +199,24 @@ namespace System.Management.Automation.Runspaces // This will never be null.. XmlElement xmlElement = (XmlElement)doc[MSHCONSOLEFILE]; - + if (xmlElement.HasAttribute(CSCHEMAVERSION)) { if (!xmlElement.GetAttribute(CSCHEMAVERSION).Equals(CSCHEMAVERSIONNUMBER, StringComparison.OrdinalIgnoreCase)) { - string resourceTemplate = StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path); string message = string.Format(CultureInfo.CurrentCulture, resourceTemplate, CSCHEMAVERSIONNUMBER); - _mshsnapinTracer.TraceError(message); + s_mshsnapinTracer.TraceError(message); throw new XmlException(message); } } else { - _mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", path); + s_mshsnapinTracer.TraceError("Console file {0} doesn't contain tag schema version.", path); throw new XmlException( StringUtil.Format(ConsoleInfoErrorStrings.BadConsoleVersion, path)); @@ -230,7 +228,7 @@ namespace System.Management.Automation.Runspaces // Construct PSConsoleFileElement as we seem to have valid data PSConsoleFileElement consoleFileElement = new PSConsoleFileElement(xmlElement.InnerText.Trim()); - + bool isPSSnapInsProcessed = false; bool isPSVersionProcessed = false; @@ -254,7 +252,7 @@ namespace System.Management.Automation.Runspaces { if (isPSVersionProcessed) { - _mshsnapinTracer.TraceError("Console file {0} contains more than one msh versions", path); + s_mshsnapinTracer.TraceError("Console file {0} contains more than one msh versions", path); throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, PSVERSION)); } @@ -265,7 +263,7 @@ namespace System.Management.Automation.Runspaces if (xmlElement.Name != SNAPINS) { - _mshsnapinTracer.TraceError("Tag {0} is not supported in console file", xmlElement.Name); + s_mshsnapinTracer.TraceError("Tag {0} is not supported in console file", xmlElement.Name); throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.BadXMLElementFound, xmlElement.Name, MSHCONSOLEFILE, PSVERSION, SNAPINS)); } @@ -274,11 +272,11 @@ namespace System.Management.Automation.Runspaces // PSSnapIns elements if (isPSSnapInsProcessed) { - _mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", path); + s_mshsnapinTracer.TraceError("Console file {0} contains more than one mshsnapin lists", path); throw new XmlException(StringUtil.Format(ConsoleInfoErrorStrings.MultipleMshSnapinsElementNotSupported, SNAPINS)); } - + // We are about to process mshsnapins element..so we should not // process some more mshsnapins elements..this boolean keeps track // of this. @@ -302,17 +300,17 @@ namespace System.Management.Automation.Runspaces throw new XmlException(ConsoleInfoErrorStrings.IDNotFound); } - consoleFileElement.mshsnapins.Add(id); + consoleFileElement._mshsnapins.Add(id); - _mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", id, path); + s_mshsnapinTracer.WriteLine("Found in mshsnapin {0} in console file {1}", id, path); } } return consoleFileElement; } - + #endregion - } + } /// /// Class that manages(reads/writes) Monad Console files and constructs objects @@ -333,22 +331,22 @@ namespace System.Management.Automation.Runspaces #region Private Data // Monad Version that this console file depends on. - private readonly Version psVersion; + private readonly Version _psVersion; // MshSnapins that are not shipped with monad. - private readonly Collection externalPSSnapIns; + private readonly Collection _externalPSSnapIns; // Monad specific mshsnapins - private Collection defaultPSSnapIns; + private Collection _defaultPSSnapIns; // An internal representation that tells whether a console file is modified. - private bool isDirty; + private bool _isDirty; // A string that stores fileName of the current consoleinfo object - private string fileName; + private string _fileName; #endregion #region Class specific data - static private readonly PSTraceSource _mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); - + static private readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + #endregion #region Properties @@ -360,7 +358,7 @@ namespace System.Management.Automation.Runspaces { get { - return psVersion; + return _psVersion; } } @@ -371,10 +369,10 @@ namespace System.Management.Automation.Runspaces { get { - Diagnostics.Assert(psVersion != null, + Diagnostics.Assert(_psVersion != null, "PSVersion is null"); - return psVersion.Major.ToString(System.Globalization.CultureInfo.InvariantCulture); + return _psVersion.Major.ToString(System.Globalization.CultureInfo.InvariantCulture); } } @@ -405,9 +403,9 @@ namespace System.Management.Automation.Runspaces get { // externalPSSnapIns is never null - Diagnostics.Assert(externalPSSnapIns != null, "externalPSSnapIns is null"); + Diagnostics.Assert(_externalPSSnapIns != null, "externalPSSnapIns is null"); - return externalPSSnapIns; + return _externalPSSnapIns; } } @@ -422,7 +420,7 @@ namespace System.Management.Automation.Runspaces { get { - return isDirty; + return _isDirty; } } @@ -440,27 +438,27 @@ namespace System.Management.Automation.Runspaces { get { - return fileName; + return _fileName; } } #endregion #region Constructors - + /// /// Construct a MshConsoleInfo object for the Monad version specified. /// /// Monad Version. private MshConsoleInfo(Version version) { - psVersion = version; - isDirty = false; - fileName = null; + _psVersion = version; + _isDirty = false; + _fileName = null; // Intialize list of mshsnapins.. - defaultPSSnapIns = new Collection(); - externalPSSnapIns = new Collection(); + _defaultPSSnapIns = new Collection(); + _externalPSSnapIns = new Collection(); } #endregion @@ -485,14 +483,14 @@ namespace System.Management.Automation.Runspaces MshConsoleInfo consoleInfo = new MshConsoleInfo(PSVersionInfo.PSVersion); try { - consoleInfo.defaultPSSnapIns = PSSnapInReader.ReadEnginePSSnapIns(); + consoleInfo._defaultPSSnapIns = PSSnapInReader.ReadEnginePSSnapIns(); } catch (PSArgumentException ae) { string message = ConsoleInfoErrorStrings.CannotLoadDefaults; // If we were unalbe to load default mshsnapins throw PSSnapInException - _mshsnapinTracer.TraceError(message); + s_mshsnapinTracer.TraceError(message); throw new PSSnapInException(message, ae); } @@ -501,12 +499,12 @@ namespace System.Management.Automation.Runspaces string message = ConsoleInfoErrorStrings.CannotLoadDefaults; // If we were unalbe to load default mshsnapins throw PSSnapInException - _mshsnapinTracer.TraceError(message); + s_mshsnapinTracer.TraceError(message); throw new PSSnapInException(message, se); } - return consoleInfo; + return consoleInfo; } /// @@ -539,19 +537,19 @@ namespace System.Management.Automation.Runspaces /// static internal MshConsoleInfo CreateFromConsoleFile(string fileName, out PSConsoleLoadException cle) { - _mshsnapinTracer.WriteLine("Creating console info from file {0}", fileName); + s_mshsnapinTracer.WriteLine("Creating console info from file {0}", fileName); // Construct default mshsnapins MshConsoleInfo consoleInfo = CreateDefaultConfiguration(); - + // Check whether the filename specified is an absolute path. - string absolutePath = Path.GetFullPath(fileName); - consoleInfo.fileName = absolutePath; + string absolutePath = Path.GetFullPath(fileName); + consoleInfo._fileName = absolutePath; // Construct externalPSSnapIns by loading file. consoleInfo.Load(absolutePath, out cle); - _mshsnapinTracer.WriteLine("Console info created successfully"); + s_mshsnapinTracer.WriteLine("Console info created successfully"); return consoleInfo; } @@ -589,21 +587,21 @@ namespace System.Management.Automation.Runspaces if (!Path.IsPathRooted(absolutePath)) { - absolutePath = Path.GetFullPath(fileName); + absolutePath = Path.GetFullPath(_fileName); } // Ignore case when looking for file extension. if (!absolutePath.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { - _mshsnapinTracer.TraceError("Console file {0} doesn't have the right extension {1}.", path, StringLiterals.PowerShellConsoleFileExtension); + s_mshsnapinTracer.TraceError("Console file {0} doesn't have the right extension {1}.", path, StringLiterals.PowerShellConsoleFileExtension); throw PSTraceSource.NewArgumentException("absolutePath", ConsoleInfoErrorStrings.BadConsoleExtension); } //ConsoleFileElement will write to file - PSConsoleFileElement.WriteToFile(absolutePath, this.PSVersion, this.ExternalPSSnapIns ); + PSConsoleFileElement.WriteToFile(absolutePath, this.PSVersion, this.ExternalPSSnapIns); //update the console file variable - fileName = absolutePath; - isDirty = false; + _fileName = absolutePath; + _isDirty = false; } /// @@ -615,13 +613,13 @@ namespace System.Management.Automation.Runspaces /// internal void Save() { - if (null == fileName) + if (null == _fileName) { throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.SaveDefaultError); } - PSConsoleFileElement.WriteToFile(fileName, this.PSVersion, this.ExternalPSSnapIns); - isDirty = false; + PSConsoleFileElement.WriteToFile(_fileName, this.PSVersion, this.ExternalPSSnapIns); + _isDirty = false; } /// @@ -650,16 +648,16 @@ namespace System.Management.Automation.Runspaces } // Check whether the mshsnapin is already present in defaultmshsnapins/externalMshSnapins - if (IsDefaultPSSnapIn(mshSnapInID, defaultPSSnapIns)) + if (IsDefaultPSSnapIn(mshSnapInID, _defaultPSSnapIns)) { - _mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", mshSnapInID); + s_mshsnapinTracer.TraceError("MshSnapin {0} can't be added since it is a default mshsnapin", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotLoadDefault); } if (IsActiveExternalPSSnapIn(mshSnapInID)) { - _mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", mshSnapInID); + s_mshsnapinTracer.TraceError("MshSnapin {0} is already loaded.", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.PSSnapInAlreadyExists, mshSnapInID); } @@ -669,20 +667,20 @@ namespace System.Management.Automation.Runspaces if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString())) { - _mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", mshSnapInID); + s_mshsnapinTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.AddPSSnapInBadMonadVersion, newPSSnapIn.PSVersion.ToString(), - psVersion.ToString()); + _psVersion.ToString()); } // new mshsnapin will never be null //if this is a valid new mshsnapin,add this to external mshsnapins - externalPSSnapIns.Add(newPSSnapIn); - _mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", mshSnapInID); + _externalPSSnapIns.Add(newPSSnapIn); + s_mshsnapinTracer.WriteLine("MshSnapin {0} successfully added to consoleinfo list.", mshSnapInID); //Set IsDirty to true - isDirty = true; + _isDirty = true; return newPSSnapIn; } @@ -706,7 +704,7 @@ namespace System.Management.Automation.Runspaces { if (string.IsNullOrEmpty(mshSnapInID)) { - PSTraceSource.NewArgumentNullException("mshSnapInID"); + PSTraceSource.NewArgumentNullException("mshSnapInID"); } // Monad has specific restrictions on the mshsnapinid like @@ -715,26 +713,26 @@ namespace System.Management.Automation.Runspaces PSSnapInInfo removedPSSnapIn = null; // Check external mshsnapins - foreach (PSSnapInInfo mshSnapIn in externalPSSnapIns) + foreach (PSSnapInInfo mshSnapIn in _externalPSSnapIns) { if (string.Equals(mshSnapInID, mshSnapIn.Name, System.StringComparison.OrdinalIgnoreCase)) { // We found the mshsnapin..remove from the list and break removedPSSnapIn = mshSnapIn; - externalPSSnapIns.Remove(mshSnapIn); + _externalPSSnapIns.Remove(mshSnapIn); // The state of console file is changing..so set // dirty flag. - isDirty = true; + _isDirty = true; break; } } if (removedPSSnapIn == null) { - if (IsDefaultPSSnapIn(mshSnapInID, defaultPSSnapIns)) + if (IsDefaultPSSnapIn(mshSnapInID, _defaultPSSnapIns)) { - _mshsnapinTracer.WriteLine("MshSnapin {0} can't be removed since it is a default mshsnapin.", mshSnapInID); + s_mshsnapinTracer.WriteLine("MshSnapin {0} can't be removed since it is a default mshsnapin.", mshSnapInID); throw PSTraceSource.NewArgumentException("mshSnapInID", ConsoleInfoErrorStrings.CannotRemoveDefault, mshSnapInID); } @@ -789,8 +787,8 @@ namespace System.Management.Automation.Runspaces // If there is nothing to search.. if (listToSearch == null) - return listToReturn; - + return listToReturn; + if (!doWildCardSearch) { // We are not doing wildcard search.. @@ -856,7 +854,7 @@ namespace System.Management.Automation.Runspaces // Intialize the out parameter.. cle = null; - _mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", path); + s_mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", path); if (string.IsNullOrEmpty(path)) { @@ -866,30 +864,30 @@ namespace System.Management.Automation.Runspaces // Check whether the path is an absolute path if (!Path.IsPathRooted(path)) { - _mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", path); + s_mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", path); throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.PathNotAbsolute, path); } if (!path.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { - _mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", path, StringLiterals.PowerShellConsoleFileExtension); + s_mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", path, StringLiterals.PowerShellConsoleFileExtension); - throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.BadConsoleExtension); + throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.BadConsoleExtension); } PSConsoleFileElement consoleFileElement; // exceptions are thrown to the caller consoleFileElement = PSConsoleFileElement.CreateFromFile(path); - + // consoleFileElement will never be null.. if (!Utils.IsPSVersionSupported(consoleFileElement.MonadVersion)) { - _mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", consoleFileElement.MonadVersion); + s_mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", consoleFileElement.MonadVersion); throw PSTraceSource.NewArgumentException("PSVersion", ConsoleInfoErrorStrings.BadMonadVersion, consoleFileElement.MonadVersion, - psVersion.ToString()); + _psVersion.ToString()); } // Create a store for exceptions @@ -902,7 +900,7 @@ namespace System.Management.Automation.Runspaces this.AddPSSnapIn(mshsnapin); } catch (PSArgumentException ae) - { + { PSSnapInException sle = new PSSnapInException(mshsnapin, ae.Message, ae); // Eat ArgumentException and continue.. @@ -926,9 +924,9 @@ namespace System.Management.Automation.Runspaces // We are able to load console file and currently monad engine // can service this. So mark the isdirty flag. - isDirty = false; + _isDirty = false; - return this.externalPSSnapIns; + return _externalPSSnapIns; } /// @@ -959,7 +957,7 @@ namespace System.Management.Automation.Runspaces private bool IsActiveExternalPSSnapIn(string mshSnapInID) { // Check whether the mshsnapin is present in externalmshsnapins. - foreach (PSSnapInInfo mshSnapIn in externalPSSnapIns) + foreach (PSSnapInInfo mshSnapIn in _externalPSSnapIns) { if (string.Equals(mshSnapInID, mshSnapIn.Name, System.StringComparison.OrdinalIgnoreCase)) { @@ -978,15 +976,15 @@ namespace System.Management.Automation.Runspaces private Collection MergeDefaultExternalMshSnapins() { //Default mshsnapins should never be null - Diagnostics.Assert(defaultPSSnapIns != null, "Default MshSnapins for the current console is empty"); + Diagnostics.Assert(_defaultPSSnapIns != null, "Default MshSnapins for the current console is empty"); Collection mshSnapIns = new Collection(); - foreach (PSSnapInInfo mshSnapIn in defaultPSSnapIns) + foreach (PSSnapInInfo mshSnapIn in _defaultPSSnapIns) { mshSnapIns.Add(mshSnapIn); } - foreach (PSSnapInInfo mshSnapIn in externalPSSnapIns) + foreach (PSSnapInInfo mshSnapIn in _externalPSSnapIns) { mshSnapIns.Add(mshSnapIn); } @@ -994,5 +992,5 @@ namespace System.Management.Automation.Runspaces return mshSnapIns; } #endregion - } + } } diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index eb8b8c9ab..375defddb 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -53,7 +53,7 @@ namespace System.Management.Automation.Runspaces /// /// Initiate an instance of PSConsoleLoadException. /// - public PSConsoleLoadException () : base() + public PSConsoleLoadException() : base() { } @@ -174,7 +174,7 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); - info.AddValue("ConsoleFileName", this._consoleFileName); + info.AddValue("ConsoleFileName", _consoleFileName); } #endregion Serialization diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index dd0209b66..787b0e48f 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Win32; @@ -68,7 +69,6 @@ namespace System.Management.Automation internal const string ManagementMshSnapinName = "Microsoft.PowerShell.Management"; internal const string SecurityMshSnapinName = "Microsoft.PowerShell.Security"; internal const string UtilityMshSnapinName = "Microsoft.PowerShell.Utility"; - } /// @@ -122,7 +122,7 @@ namespace System.Management.Automation if (customPSSnapInType != null) { throw PSTraceSource.NewArgumentException( - "customPSSnapInType", + "customPSSnapInType", MshSnapInCmdletResources.CustomPSSnapInNotSupportedInPowerShellCore); } #endif @@ -185,8 +185,8 @@ namespace System.Management.Automation ) : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, descriptionFallback, vendorFallback, customPSSnapInType) { - this._description = description; - this._vendor = vendor; + _description = description; + _vendor = vendor; } internal PSSnapInInfo @@ -207,13 +207,13 @@ namespace System.Management.Automation string vendorFallback, string vendorIndirect, string customPSSnapInType - ):this(name,isDefault,applicationBase,assemblyName,moduleName,psVersion,version,types,formats,description,descriptionFallback,vendor,vendorFallback,customPSSnapInType) + ) : this(name, isDefault, applicationBase, assemblyName, moduleName, psVersion, version, types, formats, description, descriptionFallback, vendor, vendorFallback, customPSSnapInType) { // add descriptionIndirect and vendorIndirect only if the mshsnapin is a default mshsnapin if (isDefault) { - this._descriptionIndirect = descriptionIndirect; - this._vendorIndirect = vendorIndirect; + _descriptionIndirect = descriptionIndirect; + _vendorIndirect = vendorIndirect; } } @@ -484,7 +484,6 @@ namespace System.Management.Automation RegistryStrings.MshSnapin_VendorResource, _assemblyName, _moduleName); - } } @@ -803,7 +802,7 @@ namespace System.Management.Automation mshsnapinKey = mshSnapInRoot.OpenSubKey(mshsnapinId); if (mshsnapinKey == null) { - _mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId); + s_mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId); throw PSTraceSource.NewArgumentException("mshsnapinId", MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId); } @@ -816,13 +815,13 @@ namespace System.Management.Automation string description = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Description, false); if (description == null) { - _mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); + s_mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); description = string.Empty; } string vendor = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Vendor, false); if (vendor == null) { - _mshsnapinTracer.WriteLine("No vendor is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); + s_mshsnapinTracer.WriteLine("No vendor is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); vendor = string.Empty; } @@ -830,7 +829,7 @@ namespace System.Management.Automation string logPipelineExecutionDetailsStr = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_LogPipelineExecutionDetails, false); if (!String.IsNullOrEmpty(logPipelineExecutionDetailsStr)) { - if(String.Compare("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase) == 0) + if (String.Compare("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase) == 0) logPipelineExecutionDetails = true; } @@ -843,7 +842,7 @@ namespace System.Management.Automation Collection types = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInTypes, false); Collection formats = ReadMultiStringValue(mshsnapinKey, RegistryStrings.MshSnapin_BuiltInFormats, false); - _mshsnapinTracer.WriteLine("Successfully read registry values for mshsnapin {0}. Constructing PSSnapInInfo object.", mshsnapinId); + s_mshsnapinTracer.WriteLine("Successfully read registry values for mshsnapin {0}. Constructing PSSnapInInfo object.", mshsnapinId); PSSnapInInfo mshSnapinInfo = new PSSnapInInfo(mshsnapinId, false, applicationBase, assemblyName, moduleName, monadVersion, version, types, formats, description, vendor, customPSSnapInType); mshSnapinInfo.LogPipelineExecutionDetails = logPipelineExecutionDetails; @@ -870,7 +869,7 @@ namespace System.Management.Automation // If this key should be present..throw error if (mandatory) { - _mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", + s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } @@ -898,7 +897,7 @@ namespace System.Management.Automation { if (mandatory) { - _mshsnapinTracer.TraceError("Cannot get string/multi-string value for mandatory property {0} in registry key {1}", + s_mshsnapinTracer.TraceError("Cannot get string/multi-string value for mandatory property {0} in registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotInCorrectFormatMultiString, name, mshsnapinKey.Name); } @@ -908,7 +907,7 @@ namespace System.Management.Automation } } - _mshsnapinTracer.WriteLine("Successfully read property {0} from {1}", + s_mshsnapinTracer.WriteLine("Successfully read property {0} from {1}", name, mshsnapinKey.Name); return new Collection(msv); } @@ -933,7 +932,7 @@ namespace System.Management.Automation object value = mshsnapinKey.GetValue(name); if (value == null && mandatory == true) { - _mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", + s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } @@ -941,12 +940,12 @@ namespace System.Management.Automation string s = value as string; if (string.IsNullOrEmpty(s) && mandatory == true) { - _mshsnapinTracer.TraceError("Value is null or empty for mandatory property {0} in {1}", + s_mshsnapinTracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, mshsnapinKey.Name); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotInCorrectFormat, name, mshsnapinKey.Name); } - _mshsnapinTracer.WriteLine("Successfully read value {0} for property {1} from {2}", + s_mshsnapinTracer.WriteLine("Successfully read value {0} for property {1} from {2}", s, name, mshsnapinKey.Name); return s; } @@ -958,7 +957,7 @@ namespace System.Management.Automation string temp = ReadStringValue(mshsnapinKey, name, mandatory); if (temp == null) { - _mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", + s_mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", name, mshsnapinKey.ToString()); Dbg.Assert(!mandatory, "mandatory is true, ReadStringValue should have thrown exception"); return null; @@ -971,26 +970,26 @@ namespace System.Management.Automation } catch (ArgumentOutOfRangeException) { - _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); + s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (ArgumentException) { - _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); + s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (OverflowException) { - _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); + s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (FormatException) { - _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); + s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } - _mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v); + s_mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v); return v; } @@ -1038,7 +1037,7 @@ namespace System.Management.Automation static internal string ConvertByteArrayToString(byte[] tokens) { - Dbg.Assert(tokens != null,"Input tokens should never be null"); + Dbg.Assert(tokens != null, "Input tokens should never be null"); StringBuilder tokenBuilder = new StringBuilder(tokens.Length * 2); foreach (byte b in tokens) { @@ -1072,14 +1071,14 @@ namespace System.Management.Automation "Registry.format.ps1xml"}); string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", - CoreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); + s_coreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); - string moduleName = Path.Combine(applicationBase, CoreSnapin.AssemblyName + ".dll"); + string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll"); - PSSnapInInfo coreMshSnapin = new PSSnapInInfo(CoreSnapin.PSSnapInName, true, applicationBase, + PSSnapInInfo coreMshSnapin = new PSSnapInInfo(s_coreSnapin.PSSnapInName, true, applicationBase, strongName, moduleName, psVersion, assemblyVersion, types, formats, null, - CoreSnapin.Description, CoreSnapin.DescriptionIndirect, null, null, - CoreSnapin.VendorIndirect, null); + s_coreSnapin.Description, s_coreSnapin.DescriptionIndirect, null, null, + s_coreSnapin.VendorIndirect, null); SetSnapInLoggingInformation(coreMshSnapin); return coreMshSnapin; @@ -1130,7 +1129,7 @@ namespace System.Management.Automation StringComparison.OrdinalIgnoreCase)) { types = new Collection(new string[] { "GetEvent.types.ps1xml" }); - formats = new Collection(new string[] { "Event.format.ps1xml","Diagnostics.format.ps1xml" }); + formats = new Collection(new string[] { "Event.format.ps1xml", "Diagnostics.format.ps1xml" }); } else if (defaultMshSnapinInfo.AssemblyName.Equals("Microsoft.WSMan.Management", StringComparison.OrdinalIgnoreCase)) { @@ -1367,10 +1366,9 @@ namespace System.Management.Automation DescriptionIndirect = sDescriptionIndirect; VendorIndirect = sVendorIndirect; } - } - private static DefaultPSSnapInInformation CoreSnapin = + private static DefaultPSSnapInInformation s_coreSnapin = new DefaultPSSnapInInformation("Microsoft.PowerShell.Core", "System.Management.Automation", null, "CoreMshSnapInResources,Description", "CoreMshSnapInResources,Vendor"); @@ -1382,13 +1380,13 @@ namespace System.Management.Automation { get { - if (defaultMshSnapins == null) + if (s_defaultMshSnapins == null) { - lock (_syncObject) + lock (s_syncObject) { - if (defaultMshSnapins == null) + if (s_defaultMshSnapins == null) { - defaultMshSnapins = new List() + s_defaultMshSnapins = new List() { #if !PORTABLE // Microsoft.PowerShell.Commands.Diagnostics.dll needs to be ported new DefaultPSSnapInInformation("Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics", null, @@ -1397,7 +1395,7 @@ namespace System.Management.Automation new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null, "HostMshSnapInResources,Description","HostMshSnapInResources,Vendor"), - CoreSnapin, + s_coreSnapin, new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null, "UtilityMshSnapInResources,Description","UtilityMshSnapInResources,Vendor"), @@ -1412,7 +1410,7 @@ namespace System.Management.Automation #if !PORTABLE if (!Utils.IsWinPEHost()) { - defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null, + s_defaultMshSnapins.Add(new DefaultPSSnapInInformation("Microsoft.WSMan.Management", "Microsoft.WSMan.Management", null, "WsManResources,Description", "WsManResources,Vendor")); } #endif @@ -1420,15 +1418,15 @@ namespace System.Management.Automation } } - return defaultMshSnapins; + return s_defaultMshSnapins; } } - private static IList defaultMshSnapins = null; - private static object _syncObject = new object(); + private static IList s_defaultMshSnapins = null; + private static object s_syncObject = new object(); #endregion - static private PSTraceSource _mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + static private PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); } } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index 02f939759..2fb4df239 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -74,7 +74,7 @@ namespace System.Management.Automation.Runspaces /// /// Initiate an instance of PSSnapInException. /// - public PSSnapInException () : base() + public PSSnapInException() : base() { } @@ -203,8 +203,8 @@ namespace System.Management.Automation.Runspaces base.GetObjectData(info, context); - info.AddValue("PSSnapIn", this._PSSnapin); - info.AddValue("Reason", this._reason); + info.AddValue("PSSnapIn", _PSSnapin); + info.AddValue("Reason", _reason); } #endregion Serialization diff --git a/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs b/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs index 0b836a84e..e7125cde0 100644 --- a/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs +++ b/src/System.Management.Automation/singleshell/config/RegistryStringResourceIndirect.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Collections; using System.Globalization; @@ -142,7 +143,7 @@ namespace System.Management.Automation /// /// internal string GetResourceStringIndirect( - RegistryKey key, + RegistryKey key, string valueName, string assemblyName, string modulePath) @@ -185,7 +186,6 @@ namespace System.Management.Automation } result = GetResourceStringIndirect(assemblyName, modulePath, regValue); - } while (false); return result; @@ -278,7 +278,6 @@ namespace System.Management.Automation // Get the resource in the app-domain result = _resourceRetriever.GetStringResource(assemblyName, modulePath, baseName, resourceID); - } while (false); return result; @@ -325,8 +324,6 @@ namespace System.Management.Automation return result; } - - } /// @@ -398,7 +395,7 @@ namespace System.Management.Automation { break; } - + currentCulture = currentCulture.Parent; } while (true); @@ -496,8 +493,8 @@ namespace System.Management.Automation /// /// private static Assembly LoadAssemblyForCulture( - CultureInfo culture, - AssemblyName assemblyName, + CultureInfo culture, + AssemblyName assemblyName, string moduleBase, string moduleFile) { @@ -610,7 +607,6 @@ namespace System.Management.Automation */ return result; } - } } diff --git a/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs b/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs index 28b00731e..56556760f 100644 --- a/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs +++ b/src/System.Management.Automation/singleshell/config/RunspaceConfigForSingleShell.cs @@ -32,7 +32,7 @@ namespace System.Management.Automation.Runspaces /// and RunspaceConfigForSingleShell may merge into one class. /// /// - internal class RunspaceConfigForSingleShell: RunspaceConfiguration + internal class RunspaceConfigForSingleShell : RunspaceConfiguration { #region RunspaceConfigForSingleShell Factory @@ -53,13 +53,13 @@ namespace System.Management.Automation.Runspaces { PSConsoleLoadException warning1 = null; - _mshsnapinTracer.WriteLine("Creating MshConsoleInfo. consoleFile={0}", consoleFile); + s_mshsnapinTracer.WriteLine("Creating MshConsoleInfo. consoleFile={0}", consoleFile); MshConsoleInfo consoleInfo = MshConsoleInfo.CreateFromConsoleFile(consoleFile, out warning1); - if(warning1 != null) + if (warning1 != null) { - _mshsnapinTracer.TraceWarning("There was a warning while creating MshConsoleInfo: {0}", warning1.Message); + s_mshsnapinTracer.TraceWarning("There was a warning while creating MshConsoleInfo: {0}", warning1.Message); } // At this time, consoleInfo should not be null. @@ -73,7 +73,7 @@ namespace System.Management.Automation.Runspaces if (warning2 != null) { - _mshsnapinTracer.TraceWarning("There was a warning while loading console: {0}", warning2.Message); + s_mshsnapinTracer.TraceWarning("There was a warning while loading console: {0}", warning2.Message); } warning = CombinePSConsoleLoadException(warning1, warning2); @@ -111,7 +111,7 @@ namespace System.Management.Automation.Runspaces /// internal static RunspaceConfigForSingleShell CreateDefaultConfiguration() { - _mshsnapinTracer.WriteLine("Creating default runspace configuration."); + s_mshsnapinTracer.WriteLine("Creating default runspace configuration."); MshConsoleInfo consoleInfo = MshConsoleInfo.CreateDefaultConfiguration(); @@ -126,13 +126,13 @@ namespace System.Management.Automation.Runspaces if (warning != null) { - _mshsnapinTracer.TraceWarning("There was a warning while loading console: {0}", warning.Message); + s_mshsnapinTracer.TraceWarning("There was a warning while loading console: {0}", warning.Message); } return rspcfg; } - _mshsnapinTracer.WriteLine("Default runspace configuration created."); + s_mshsnapinTracer.WriteLine("Default runspace configuration created."); return null; } @@ -186,7 +186,7 @@ namespace System.Management.Automation.Runspaces { warning = null; - _mshsnapinTracer.WriteLine("Adding mshsnapin {0}", name); + s_mshsnapinTracer.WriteLine("Adding mshsnapin {0}", name); if (_consoleInfo == null) return null; @@ -197,16 +197,16 @@ namespace System.Management.Automation.Runspaces { mshsnapinInfo = _consoleInfo.AddPSSnapIn(name); } - catch(PSArgumentException mae) + catch (PSArgumentException mae) { - _mshsnapinTracer.TraceError(mae.Message); - _mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", name); + s_mshsnapinTracer.TraceError(mae.Message); + s_mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", name); throw; } - catch(PSArgumentNullException mane) + catch (PSArgumentNullException mane) { - _mshsnapinTracer.TraceError(mane.Message); - _mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", name); + s_mshsnapinTracer.TraceError(mane.Message); + s_mshsnapinTracer.WriteLine("Adding mshsnapin {0} failed.", name); throw; } @@ -217,10 +217,10 @@ namespace System.Management.Automation.Runspaces if (warning != null) { - _mshsnapinTracer.TraceWarning("There was a warning when loading mshsnapin {0}: {1}", name, warning.Message); + s_mshsnapinTracer.TraceWarning("There was a warning when loading mshsnapin {0}: {1}", name, warning.Message); } - _mshsnapinTracer.WriteLine("MshSnapin {0} added", name); + s_mshsnapinTracer.WriteLine("MshSnapin {0} added", name); return mshsnapinInfo; } @@ -238,13 +238,13 @@ namespace System.Management.Automation.Runspaces if (_consoleInfo == null) return null; - _mshsnapinTracer.WriteLine("Removing mshsnapin {0}", name); + s_mshsnapinTracer.WriteLine("Removing mshsnapin {0}", name); PSSnapInInfo mshsnapinInfo = _consoleInfo.RemovePSSnapIn(name); UnloadPSSnapIn(mshsnapinInfo, out warning); - _mshsnapinTracer.WriteLine("MshSnapin {0} removed", name); + s_mshsnapinTracer.WriteLine("MshSnapin {0} removed", name); return mshsnapinInfo; } @@ -264,7 +264,7 @@ namespace System.Management.Automation.Runspaces this.Cmdlets.Update(); this.Providers.Update(); - _mshsnapinTracer.WriteLine("Updating types and formats"); + s_mshsnapinTracer.WriteLine("Updating types and formats"); try { @@ -272,7 +272,7 @@ namespace System.Management.Automation.Runspaces } catch (RuntimeException e) { - _mshsnapinTracer.TraceWarning("There was a warning updating types: {0}", e.Message); + s_mshsnapinTracer.TraceWarning("There was a warning updating types: {0}", e.Message); errors += e.Message + "\n"; } @@ -283,7 +283,7 @@ namespace System.Management.Automation.Runspaces } catch (RuntimeException e) { - _mshsnapinTracer.TraceWarning("There was a warning updating formats: {0}", e.Message); + s_mshsnapinTracer.TraceWarning("There was a warning updating formats: {0}", e.Message); errors += e.Message + "\n"; } @@ -294,12 +294,12 @@ namespace System.Management.Automation.Runspaces } catch (RuntimeException e) { - _mshsnapinTracer.TraceWarning("There was a warning updating assemblies: {0}", e.Message); + s_mshsnapinTracer.TraceWarning("There was a warning updating assemblies: {0}", e.Message); errors += e.Message + "\n"; } - _mshsnapinTracer.WriteLine("Types and formats updated successfully"); + s_mshsnapinTracer.WriteLine("Types and formats updated successfully"); } #endregion @@ -325,22 +325,22 @@ namespace System.Management.Automation.Runspaces { LoadPSSnapIn(mshsnapinInfo); } - catch(PSSnapInException) + catch (PSSnapInException) { - if(!mshsnapinInfo.IsDefault) + if (!mshsnapinInfo.IsDefault) _consoleInfo.RemovePSSnapIn(mshsnapinInfo.Name); // exception during load mshsnapin are fatal. throw; } - string errors; + string errors; UpdateAll(out errors); if (!String.IsNullOrEmpty(errors)) { - _mshsnapinTracer.TraceWarning("There was a warning while loading mshsnapin {0}:{1}", mshsnapinInfo.Name, errors); + s_mshsnapinTracer.TraceWarning("There was a warning while loading mshsnapin {0}:{1}", mshsnapinInfo.Name, errors); warning = new PSSnapInException(mshsnapinInfo.Name, errors, true); } @@ -361,7 +361,7 @@ namespace System.Management.Automation.Runspaces LoadPSSnapIn(mshsnapinInfo); partialSuccess = true; } - catch(PSSnapInException e) + catch (PSSnapInException e) { if (!mshsnapinInfo.IsDefault) { @@ -383,15 +383,15 @@ namespace System.Management.Automation.Runspaces if (!String.IsNullOrEmpty(errors)) { - _mshsnapinTracer.TraceWarning(errors); + s_mshsnapinTracer.TraceWarning(errors); mshsnapinExceptions.Add(new PSSnapInException(null, errors, true)); } } if (mshsnapinExceptions.Count > 0) { - warning = new PSConsoleLoadException(this._consoleInfo, mshsnapinExceptions); - _mshsnapinTracer.TraceWarning(warning.Message); + warning = new PSConsoleLoadException(_consoleInfo, mshsnapinExceptions); + s_mshsnapinTracer.TraceWarning(warning.Message); } } @@ -409,17 +409,17 @@ namespace System.Management.Automation.Runspaces #endif Assembly assembly = null; - _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name); assembly = LoadMshSnapinAssembly(mshsnapinInfo); if (assembly == null) { - _mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name); + s_mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name); return; } - _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name); Dictionary cmdlets = null; Dictionary> aliases = null; @@ -482,13 +482,13 @@ namespace System.Management.Automation.Runspaces Assembly assembly = null; - _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0}", mshsnapinInfo.Name); assembly = LoadMshSnapinAssembly(mshsnapinInfo); if (assembly == null) { - _mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name); + s_mshsnapinTracer.TraceError("Loading assembly for mshsnapin {0} failed", mshsnapinInfo.Name); return; } @@ -502,7 +502,7 @@ namespace System.Management.Automation.Runspaces customPSSnapIn = (CustomPSSnapIn)Activator.CreateInstance(type); } - _mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Loading assembly for mshsnapin {0} succeeded", mshsnapinInfo.Name); } catch (TypeLoadException tle) { @@ -539,11 +539,11 @@ namespace System.Management.Automation.Runspaces if (mshsnapinInfo == null || customPSSnapIn == null) return; - _mshsnapinTracer.WriteLine("Merging configuration from custom mshsnapin {0}", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Merging configuration from custom mshsnapin {0}", mshsnapinInfo.Name); if (customPSSnapIn.Cmdlets != null) { - foreach(CmdletConfigurationEntry entry in customPSSnapIn.Cmdlets) + foreach (CmdletConfigurationEntry entry in customPSSnapIn.Cmdlets) { CmdletConfigurationEntry cmdlet = new CmdletConfigurationEntry(entry.Name, entry.ImplementingType, entry.HelpFileName, mshsnapinInfo); _cmdlets.AddBuiltInItem(cmdlet); @@ -582,7 +582,7 @@ namespace System.Management.Automation.Runspaces AssemblyConfigurationEntry assemblyEntry = new AssemblyConfigurationEntry(mshsnapinInfo.AssemblyName, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo); this.Assemblies.AddBuiltInItem(assemblyEntry); - _mshsnapinTracer.WriteLine("Configuration from custom mshsnapin {0} merged", mshsnapinInfo.Name); + s_mshsnapinTracer.WriteLine("Configuration from custom mshsnapin {0} merged", mshsnapinInfo.Name); } #endif @@ -603,7 +603,7 @@ namespace System.Management.Automation.Runspaces if (!String.IsNullOrEmpty(errors)) { - _mshsnapinTracer.TraceWarning(errors); + s_mshsnapinTracer.TraceWarning(errors); warning = new PSSnapInException(mshsnapinInfo.Name, errors, true); } } @@ -613,7 +613,7 @@ namespace System.Management.Automation.Runspaces { Assembly assembly = null; - _mshsnapinTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", mshsnapinInfo.AssemblyName); + s_mshsnapinTracer.WriteLine("Loading assembly from GAC. Assembly Name: {0}", mshsnapinInfo.AssemblyName); try { @@ -622,21 +622,21 @@ namespace System.Management.Automation.Runspaces } catch (FileLoadException e) { - _mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); } catch (BadImageFormatException e) { - _mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); } catch (FileNotFoundException e) { - _mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceWarning("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); } if (assembly != null) return assembly; - _mshsnapinTracer.WriteLine("Loading assembly from path: {0}", mshsnapinInfo.AssemblyName); + s_mshsnapinTracer.WriteLine("Loading assembly from path: {0}", mshsnapinInfo.AssemblyName); try { @@ -644,7 +644,7 @@ namespace System.Management.Automation.Runspaces if (string.Compare(assemblyName.FullName, mshsnapinInfo.AssemblyName, StringComparison.OrdinalIgnoreCase) != 0) { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInAssemblyNameMismatch, mshsnapinInfo.AbsoluteModulePath, mshsnapinInfo.AssemblyName); - _mshsnapinTracer.TraceError(message); + s_mshsnapinTracer.TraceError(message); throw new PSSnapInException(mshsnapinInfo.Name, message); } @@ -652,17 +652,17 @@ namespace System.Management.Automation.Runspaces } catch (FileLoadException e) { - _mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); throw new PSSnapInException(mshsnapinInfo.Name, e.Message); } catch (BadImageFormatException e) { - _mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); throw new PSSnapInException(mshsnapinInfo.Name, e.Message); } catch (FileNotFoundException e) { - _mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); + s_mshsnapinTracer.TraceError("Not able to load assembly {0}: {1}", mshsnapinInfo.AssemblyName, e.Message); throw new PSSnapInException(mshsnapinInfo.Name, e.Message); } @@ -768,6 +768,6 @@ namespace System.Management.Automation.Runspaces #endregion - static private PSTraceSource _mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + static private PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); } } diff --git a/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs b/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs index 4ca1b6730..e6bd6f696 100644 --- a/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/CustomMshSnapin.cs @@ -42,7 +42,7 @@ namespace System.Management.Automation { get { - return this.GetType().FullName; + return this.GetType().FullName; } } diff --git a/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs b/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs index ec52d59e3..5be77a4ee 100644 --- a/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/MshCoreMshSnapin.cs @@ -77,7 +77,7 @@ namespace Microsoft.PowerShell get { return "This PSSnapIn contains MSH management cmdlets used to manage components affecting the MSH engine."; - } + } } /// @@ -91,7 +91,7 @@ namespace Microsoft.PowerShell } } - private string[] _types = new string[] {"types.ps1xml"}; + private string[] _types = new string[] { "types.ps1xml" }; /// /// Get type files to be used for this mshsnapin. @@ -104,8 +104,8 @@ namespace Microsoft.PowerShell } } - private string[] _formats = new string[] { - "Certificate.format.ps1xml", + private string[] _formats = new string[] { + "Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml", "Help.format.ps1xml", diff --git a/src/System.Management.Automation/singleshell/installer/MshSnapin.cs b/src/System.Management.Automation/singleshell/installer/MshSnapin.cs index 0b80f4318..c8f69b689 100644 --- a/src/System.Management.Automation/singleshell/installer/MshSnapin.cs +++ b/src/System.Management.Automation/singleshell/installer/MshSnapin.cs @@ -74,7 +74,7 @@ namespace System.Management.Automation { _regValues = base.RegValues; - if(this.Types != null && this.Types.Length > 0) + if (this.Types != null && this.Types.Length > 0) _regValues[RegistryStrings.MshSnapin_BuiltInTypes] = this.Types; if (this.Formats != null && this.Formats.Length > 0) diff --git a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs b/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs index 9cf302f0f..2f57c52db 100644 --- a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs +++ b/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs @@ -15,13 +15,13 @@ namespace System.Management.Automation.Internal /// NativeMethods. This allows us to generate code coverage /// data specific to architecture sensitive code. /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] internal class ArchitectureSensitiveAttribute : Attribute { /// /// Constructor for the ArchitectureSensitiveAttribute class. /// - internal ArchitectureSensitiveAttribute () + internal ArchitectureSensitiveAttribute() { } } diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs index 00a28e885..c4647e2a9 100644 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ b/src/System.Management.Automation/utils/BackgroundDispatcher.cs @@ -1,5 +1,4 @@ //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index f9cd78eb4..97b9e69e4 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -39,7 +40,7 @@ namespace System.Management.Automation /// We need it to avoid calling lookups inside dynamic assemblies with PS Types, so we exclude it from GetAssemblies(). /// We use this convention for names to achive it. /// - internal static readonly char FIRST_CHAR_PSASSEMBLY_MARK = (char) 0x29f9; + internal static readonly char FIRST_CHAR_PSASSEMBLY_MARK = (char)0x29f9; #region Type @@ -207,7 +208,7 @@ namespace System.Management.Automation bool deleteOld) { #if CORECLR - Marshal.StructureToPtr( structure, ptr, deleteOld ); + Marshal.StructureToPtr(structure, ptr, deleteOld); #else Marshal.StructureToPtr(structure, ptr, deleteOld); #endif @@ -374,38 +375,38 @@ namespace System.Management.Automation /// internal static Encoding GetDefaultEncoding() { - if (_defaultEncoding == null) + if (s_defaultEncoding == null) { #if CORECLR // Encoding.Default is not in CoreCLR // As suggested by CoreCLR team (tarekms), use latin1 (ISO-8859-1, CodePage 28591) as the default encoding. // We will revisit this if it causes any failures when running tests on Core PS. - _defaultEncoding = Encoding.GetEncoding(28591); + s_defaultEncoding = Encoding.GetEncoding(28591); #else - _defaultEncoding = Encoding.Default; + s_defaultEncoding = Encoding.Default; #endif } - return _defaultEncoding; + return s_defaultEncoding; } - private static volatile Encoding _defaultEncoding; + private static volatile Encoding s_defaultEncoding; /// /// Facade for getting OEM encoding /// internal static Encoding GetOEMEncoding() { - if (_oemEncoding == null) + if (s_oemEncoding == null) { #if CORECLR // The OEM code page '437' is not supported by CoreCLR. // Use the default encoding (ISO-8859-1, CodePage 28591) as the OEM encoding in OneCore powershell. - _oemEncoding = GetDefaultEncoding(); + s_oemEncoding = GetDefaultEncoding(); #else uint oemCp = NativeMethods.GetOEMCP(); - _oemEncoding = Encoding.GetEncoding((int)oemCp); + s_oemEncoding = Encoding.GetEncoding((int)oemCp); #endif } - return _oemEncoding; + return s_oemEncoding; } - private static volatile Encoding _oemEncoding; + private static volatile Encoding s_oemEncoding; #endregion Encoding @@ -656,7 +657,7 @@ namespace System.Management.Automation internal static void SetProfileOptimizationRoot(string directoryPath) { #if CORECLR - PSAssemblyLoadContext.SetProfileOptimizationRootImpl(directoryPath); + PSAssemblyLoadContext.SetProfileOptimizationRootImpl(directoryPath); #else System.Runtime.ProfileOptimization.SetProfileRoot(directoryPath); #endif @@ -669,7 +670,7 @@ namespace System.Management.Automation internal static void StartProfileOptimization(string profile) { #if CORECLR - PSAssemblyLoadContext.StartProfileOptimizationImpl(profile); + PSAssemblyLoadContext.StartProfileOptimizationImpl(profile); #else System.Runtime.ProfileOptimization.StartProfile(profile); #endif diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index 24adf5d46..c3c7fe328 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -54,16 +54,16 @@ namespace System.Management.Automation string errorIdAndResourceId, string resourceStr, params object[] messageArgs) - : base (BuildMessage(commandName,resourceStr,messageArgs), innerException) + : base(BuildMessage(commandName, resourceStr, messageArgs), innerException) { - this.commandName = commandName; + _commandName = commandName; _errorId = errorIdAndResourceId; } /// /// Constructs a CommandNotFoundException. /// - public CommandNotFoundException() : base() { ;} + public CommandNotFoundException() : base() {; } /// /// Constructs a CommandNotFoundException @@ -72,7 +72,7 @@ namespace System.Management.Automation /// /// The message used in the exception. /// - public CommandNotFoundException(string message) : base(message) { ;} + public CommandNotFoundException(string message) : base(message) {; } /// /// Constructs a CommandNotFoundException @@ -85,7 +85,7 @@ namespace System.Management.Automation /// /// An exception that led to this exception. /// - public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { ;} + public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) {; } #region Serialization /// @@ -108,7 +108,7 @@ namespace System.Management.Automation throw new PSArgumentNullException("info"); } - commandName = info.GetString("CommandName"); + _commandName = info.GetString("CommandName"); } /// @@ -131,7 +131,7 @@ namespace System.Management.Automation } base.GetObjectData(info, context); - info.AddValue("CommandName", commandName); + info.AddValue("CommandName", _commandName); } #endregion Serialization @@ -149,7 +149,7 @@ namespace System.Management.Automation new ParentContainsErrorRecordException(this), _errorId, _errorCategory, - this.commandName); + _commandName); } return _errorRecord; } @@ -161,10 +161,10 @@ namespace System.Management.Automation /// public string CommandName { - get { return commandName; } - set { commandName = value; } + get { return _commandName; } + set { _commandName = value; } } - private string commandName = String.Empty; + private string _commandName = String.Empty; #endregion Properties @@ -226,13 +226,13 @@ namespace System.Management.Automation string requiresShellId, string requiresShellPath, string errorId) - : base (BuildMessage(commandName, requiresShellId, requiresShellPath, true)) + : base(BuildMessage(commandName, requiresShellId, requiresShellPath, true)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); - this._commandName = commandName; - this._requiresShellId = requiresShellId; - this._requiresShellPath = requiresShellPath; + _commandName = commandName; + _requiresShellId = requiresShellId; + _requiresShellPath = requiresShellPath; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); @@ -267,8 +267,8 @@ namespace System.Management.Automation Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(null != requiresPSVersion, "requiresPSVersion is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); - this._commandName = commandName; - this._requiresPSVersion = requiresPSVersion; + _commandName = commandName; + _requiresPSVersion = requiresPSVersion; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); @@ -301,7 +301,6 @@ namespace System.Management.Automation bool forSnapins) : this(commandName, missingItems, errorId, forSnapins, null) { - } /// @@ -339,8 +338,8 @@ namespace System.Management.Automation Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(missingItems != null && missingItems.Count > 0, "missingItems is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); - this._commandName = commandName; - this._missingPSSnapIns = new ReadOnlyCollection(missingItems); + _commandName = commandName; + _missingPSSnapIns = new ReadOnlyCollection(missingItems); this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.ResourceUnavailable); @@ -365,7 +364,7 @@ namespace System.Management.Automation { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); - this._commandName = commandName; + _commandName = commandName; this.SetErrorId(errorId); this.SetTargetObject(commandName); this.SetErrorCategory(ErrorCategory.PermissionDenied); @@ -374,7 +373,7 @@ namespace System.Management.Automation /// /// Constructs an PSVersionNotCompatibleException /// - public ScriptRequiresException() : base() { ;} + public ScriptRequiresException() : base() {; } /// /// Constructs an PSVersionNotCompatibleException @@ -383,7 +382,7 @@ namespace System.Management.Automation /// /// The message used in the exception. /// - public ScriptRequiresException(string message) : base(message) { ;} + public ScriptRequiresException(string message) : base(message) {; } /// /// Constructs an PSVersionNotCompatibleException @@ -396,7 +395,7 @@ namespace System.Management.Automation /// /// The exception that led to this exception. /// - public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) { ;} + public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) {; } #region Serialization /// @@ -416,7 +415,7 @@ namespace System.Management.Automation { _commandName = info.GetString("CommandName"); _requiresPSVersion = (Version)info.GetValue("RequiresPSVersion", typeof(Version)); - _missingPSSnapIns = (ReadOnlyCollection) info.GetValue("MissingPSSnapIns", typeof(ReadOnlyCollection)); + _missingPSSnapIns = (ReadOnlyCollection)info.GetValue("MissingPSSnapIns", typeof(ReadOnlyCollection)); _requiresShellId = info.GetString("RequiresShellId"); _requiresShellPath = info.GetString("RequiresShellPath"); } @@ -505,7 +504,7 @@ namespace System.Management.Automation string commandName, Collection missingItems, bool forSnapins) - { + { StringBuilder sb = new StringBuilder(); if (missingItems == null) { @@ -535,7 +534,7 @@ namespace System.Management.Automation sb.ToString()); } } - + private static string BuildMessage( string commandName, string first, @@ -543,7 +542,7 @@ namespace System.Management.Automation bool forShellId) { string resourceStr = null; - + if (forShellId) { if (String.IsNullOrEmpty(first)) @@ -552,8 +551,8 @@ namespace System.Management.Automation } else { - resourceStr = String.IsNullOrEmpty(second) - ? DiscoveryExceptions.RequiresInterpreterNotCompatibleNoPath + resourceStr = String.IsNullOrEmpty(second) + ? DiscoveryExceptions.RequiresInterpreterNotCompatibleNoPath : DiscoveryExceptions.RequiresInterpreterNotCompatible; } } diff --git a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs index d05dc059e..8cf5a5bc3 100644 --- a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs +++ b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs @@ -82,7 +82,7 @@ namespace System.Management.Automation /// The inner exception to use when initializing this object /// constructed object internal ApplicationFailedException(string message, string errorId, Exception innerException) - : base(message,innerException) + : base(message, innerException) { base.SetErrorId(errorId); base.SetErrorCategory(ErrorCategory.ResourceUnavailable); @@ -97,12 +97,11 @@ namespace System.Management.Automation /// constructed object public ApplicationFailedException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { base.SetErrorId(errorIdString); base.SetErrorCategory(ErrorCategory.ResourceUnavailable); } #endregion ctor } // ApplicationFailedException - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index bc794d99b..c05775c56 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -74,7 +74,7 @@ namespace System.Management.Automation.Internal return PSCryptoNativeUtils.CryptDestroyKey(handle); } - private static PSSafeCryptKey _zero = new PSSafeCryptKey(); + private static PSSafeCryptKey s_zero = new PSSafeCryptKey(); /// /// Equivalent of IntPtr.Zero for the safe crypt key @@ -83,7 +83,7 @@ namespace System.Management.Automation.Internal { get { - return _zero; + return s_zero; } } } @@ -315,7 +315,6 @@ namespace System.Management.Automation.Internal public const int ALG_SID_AES_128 = 14; #endregion Constants - } /// @@ -432,25 +431,25 @@ namespace System.Management.Automation.Internal { #region Private Members - private PSSafeCryptProvHandle hProv; + private PSSafeCryptProvHandle _hProv; // handle to the provider - private bool canEncrypt = false; // this flag indicates that this class has a key + private bool _canEncrypt = false; // this flag indicates that this class has a key // imported from the remote end and so can be // used for encryption - private PSSafeCryptKey hRSAKey; + private PSSafeCryptKey _hRSAKey; // handle to the RSA key with which the session // key is exchange. This can either be generated // or imported - private PSSafeCryptKey hSessionKey; + private PSSafeCryptKey _hSessionKey; // handle to the session key. This can either // be generated or imported - private bool sessionKeyGenerated = false; + private bool _sessionKeyGenerated = false; // bool indicating if session key was generated before - - private static PSSafeCryptProvHandle _hStaticProv; - private static PSSafeCryptKey _hStaticRSAKey; - private static bool keyPairGenerated = false; - private static object syncObject = new object(); + + private static PSSafeCryptProvHandle s_hStaticProv; + private static PSSafeCryptKey s_hStaticRSAKey; + private static bool s_keyPairGenerated = false; + private static object s_syncObject = new object(); #endregion Private Members @@ -465,11 +464,11 @@ namespace System.Management.Automation.Internal { if (serverMode) { - hProv = new PSSafeCryptProvHandle(); + _hProv = new PSSafeCryptProvHandle(); // We need PROV_RSA_AES to support AES-256 symmetric key // encryption. PROV_RSA_FULL supports only RC2 and RC4 - bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref hProv, + bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref _hProv, null, null, PSCryptoNativeUtils.PROV_RSA_AES, @@ -477,9 +476,9 @@ namespace System.Management.Automation.Internal CheckStatus(ret); - hRSAKey = new PSSafeCryptKey(); + _hRSAKey = new PSSafeCryptKey(); } - hSessionKey = new PSSafeCryptKey(); + _hSessionKey = new PSSafeCryptKey(); } #endregion Constructors @@ -495,7 +494,7 @@ namespace System.Management.Automation.Internal uint publicKeyLength = 0; // Get key length first - bool ret = PSCryptoNativeUtils.CryptExportKey(hRSAKey, + bool ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey, PSSafeCryptKey.Zero, PSCryptoNativeUtils.PUBLICKEYBLOB, 0, @@ -505,7 +504,7 @@ namespace System.Management.Automation.Internal // Create enough buffer and get the actual data byte[] publicKey = new byte[publicKeyLength]; - ret = PSCryptoNativeUtils.CryptExportKey(hRSAKey, + ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey, PSSafeCryptKey.Zero, PSCryptoNativeUtils.PUBLICKEYBLOB, 0, @@ -525,22 +524,22 @@ namespace System.Management.Automation.Internal /// internal void GenerateSessionKey() { - if (sessionKeyGenerated) + if (_sessionKeyGenerated) return; - lock (syncObject) + lock (s_syncObject) { - if (!sessionKeyGenerated) + if (!_sessionKeyGenerated) { - bool ret = PSCryptoNativeUtils.CryptGenKey(hProv, + bool ret = PSCryptoNativeUtils.CryptGenKey(_hProv, PSCryptoNativeUtils.CALG_AES_256, 0x01000000 | // key length = 256 bits PSCryptoNativeUtils.CRYPT_EXPORTABLE | PSCryptoNativeUtils.CRYPT_CREATE_SALT, - ref hSessionKey); + ref _hSessionKey); CheckStatus(ret); - sessionKeyGenerated = true; - canEncrypt = true; // we can encrypt and decrypt once session key is available + _sessionKeyGenerated = true; + _canEncrypt = true; // we can encrypt and decrypt once session key is available } } } @@ -561,8 +560,8 @@ namespace System.Management.Automation.Internal uint length = 0; // get key length first - bool ret = PSCryptoNativeUtils.CryptExportKey(hSessionKey, - hRSAKey, + bool ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey, + _hRSAKey, PSCryptoNativeUtils.SIMPLEBLOB, 0, null, @@ -571,8 +570,8 @@ namespace System.Management.Automation.Internal // allocate buffer and export the key byte[] sessionkey = new byte[length]; - ret = PSCryptoNativeUtils.CryptExportKey(hSessionKey, - hRSAKey, + ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey, + _hRSAKey, PSCryptoNativeUtils.SIMPLEBLOB, 0, sessionkey, @@ -580,7 +579,7 @@ namespace System.Management.Automation.Internal CheckStatus(ret); // now we can encrypt as we have the session key - canEncrypt = true; + _canEncrypt = true; // convert the key to base64 before exporting return Convert.ToBase64String(sessionkey); @@ -597,12 +596,12 @@ namespace System.Management.Automation.Internal byte[] convertedBase64 = Convert.FromBase64String(publicKey); - bool ret = PSCryptoNativeUtils.CryptImportKey(hProv, + bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv, convertedBase64, convertedBase64.Length, PSSafeCryptKey.Zero, 0, - ref hRSAKey); + ref _hRSAKey); CheckStatus(ret); } @@ -619,17 +618,17 @@ namespace System.Management.Automation.Internal byte[] convertedBase64 = Convert.FromBase64String(sessionKey); - bool ret = PSCryptoNativeUtils.CryptImportKey(hProv, + bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv, convertedBase64, convertedBase64.Length, - hRSAKey, + _hRSAKey, 0, - ref hSessionKey); + ref _hSessionKey); CheckStatus(ret); // now we have imported the key and will be able to // encrypt using the session key - canEncrypt = true; + _canEncrypt = true; } /// @@ -642,7 +641,7 @@ namespace System.Management.Automation.Internal // first make a copy of the original data.This is needed // as CryptEncrypt uses the same buffer to write the encrypted data // into. - Dbg.Assert(canEncrypt, "Remote key has not been imported to encrypt"); + Dbg.Assert(_canEncrypt, "Remote key has not been imported to encrypt"); byte[] encryptedData = new byte[data.Length]; Array.Copy(data, 0, encryptedData, 0, data.Length); @@ -650,7 +649,7 @@ namespace System.Management.Automation.Internal int dataLength = encryptedData.Length; // encryption always happens using the session key - bool ret = PSCryptoNativeUtils.CryptEncrypt(hSessionKey, + bool ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey, IntPtr.Zero, true, 0, @@ -674,7 +673,7 @@ namespace System.Management.Automation.Internal Array.Copy(data, 0, encryptedData, 0, data.Length); dataLength = data.Length; - ret = PSCryptoNativeUtils.CryptEncrypt(hSessionKey, + ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey, IntPtr.Zero, true, 0, @@ -709,7 +708,7 @@ namespace System.Management.Automation.Internal int dataLength = decryptedData.Length; - bool ret = PSCryptoNativeUtils.CryptDecrypt(hSessionKey, + bool ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey, IntPtr.Zero, true, 0, @@ -724,7 +723,7 @@ namespace System.Management.Automation.Internal decryptedData = new byte[dataLength]; Array.Copy(data, 0, decryptedData, 0, data.Length); - ret = PSCryptoNativeUtils.CryptDecrypt(hSessionKey, + ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey, IntPtr.Zero, true, 0, @@ -755,16 +754,16 @@ namespace System.Management.Automation.Internal /// internal void GenerateKeyPair() { - if (!keyPairGenerated) + if (!s_keyPairGenerated) { - lock (syncObject) + lock (s_syncObject) { - if (!keyPairGenerated) + if (!s_keyPairGenerated) { - _hStaticProv = new PSSafeCryptProvHandle(); + s_hStaticProv = new PSSafeCryptProvHandle(); // We need PROV_RSA_AES to support AES-256 symmetric key // encryption. PROV_RSA_FULL supports only RC2 and RC4 - bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref _hStaticProv, + bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref s_hStaticProv, null, null, PSCryptoNativeUtils.PROV_RSA_AES, @@ -772,22 +771,22 @@ namespace System.Management.Automation.Internal CheckStatus(ret); - _hStaticRSAKey = new PSSafeCryptKey(); - ret = PSCryptoNativeUtils.CryptGenKey(_hStaticProv, + s_hStaticRSAKey = new PSSafeCryptKey(); + ret = PSCryptoNativeUtils.CryptGenKey(s_hStaticProv, PSCryptoNativeUtils.AT_KEYEXCHANGE, 0x08000000 | PSCryptoNativeUtils.CRYPT_EXPORTABLE, // key length -> 2048 - ref _hStaticRSAKey); + ref s_hStaticRSAKey); CheckStatus(ret); // key needs to be generated once - keyPairGenerated = true; + s_keyPairGenerated = true; } } } - hProv = _hStaticProv; - hRSAKey = _hStaticRSAKey; + _hProv = s_hStaticProv; + _hRSAKey = s_hStaticRSAKey; } /// @@ -798,11 +797,11 @@ namespace System.Management.Automation.Internal { get { - return canEncrypt; + return _canEncrypt; } set { - canEncrypt = value; + _canEncrypt = value; } } @@ -822,8 +821,8 @@ namespace System.Management.Automation.Internal PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(false); // set the handles for provider and rsa key - cryptoProvider.hProv = _hStaticProv; - cryptoProvider.hRSAKey = _hStaticRSAKey; + cryptoProvider._hProv = s_hStaticProv; + cryptoProvider._hRSAKey = s_hStaticRSAKey; return cryptoProvider; } @@ -882,13 +881,13 @@ namespace System.Management.Automation.Internal { if (disposing) { - if (null != hSessionKey) + if (null != _hSessionKey) { - if (!hSessionKey.IsInvalid) + if (!_hSessionKey.IsInvalid) { - hSessionKey.Dispose(); + _hSessionKey.Dispose(); } - hSessionKey = null; + _hSessionKey = null; } // we need to dismiss the provider and key @@ -896,27 +895,27 @@ namespace System.Management.Automation.Internal // since otherwise, these are just references // to the static members - if (null == _hStaticRSAKey) + if (null == s_hStaticRSAKey) { - if (null != hRSAKey) + if (null != _hRSAKey) { - if (!hRSAKey.IsInvalid) + if (!_hRSAKey.IsInvalid) { - hRSAKey.Dispose(); + _hRSAKey.Dispose(); } - hRSAKey = null; + _hRSAKey = null; } } - if (null == _hStaticProv) + if (null == s_hStaticProv) { - if (null != hProv) + if (null != _hProv) { - if (!hProv.IsInvalid) + if (!_hProv.IsInvalid) { - hProv.Dispose(); + _hProv.Dispose(); } - hProv = null; + _hProv = null; } } } @@ -964,7 +963,7 @@ namespace System.Management.Automation.Internal /// protected object syncObject = new object(); - private bool keyExchangeStarted = false; + private bool _keyExchangeStarted = false; /// /// @@ -981,9 +980,9 @@ namespace System.Management.Automation.Internal { if (!_rsaCryptoProvider.CanEncrypt) { - if (!keyExchangeStarted) + if (!_keyExchangeStarted) { - keyExchangeStarted = true; + _keyExchangeStarted = true; _keyExchangeCompleted.Reset(); Session.StartKeyExchange(); } @@ -1295,7 +1294,6 @@ namespace System.Management.Automation.Internal } return true; - } /// @@ -1312,7 +1310,6 @@ namespace System.Management.Automation.Internal } #endregion Internal Methods - } /// @@ -1381,9 +1378,9 @@ namespace System.Management.Automation.Internal { _rsaCryptoProvider.GenerateKeyPair(); } - catch(PSCryptoException) + catch (PSCryptoException) { - throw; + throw; // the caller has to ensure that they // complete the key exchange process @@ -1465,7 +1462,7 @@ namespace System.Management.Automation.Internal internal override RemotingDestination MySelf { - get + get { return RemotingDestination.InvalidDestination; } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index ac4318c0a..e0fbbd48b 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -38,11 +38,11 @@ namespace System.Management.Automation /// /// internal CmdletInvocationException(ErrorRecord errorRecord) - : base( RetrieveMessage(errorRecord), RetrieveException(errorRecord) ) + : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { if (null == errorRecord) { - throw new ArgumentNullException ("errorRecord"); + throw new ArgumentNullException("errorRecord"); } _errorRecord = errorRecord; if (null != errorRecord.Exception) @@ -62,30 +62,30 @@ namespace System.Management.Automation /// internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) - : base (RetrieveMessage(innerException), innerException) + : base(RetrieveMessage(innerException), innerException) { if (null == innerException) { - throw new ArgumentNullException ("innerException"); + throw new ArgumentNullException("innerException"); } // invocationInfo may be null IContainsErrorRecord icer = innerException as IContainsErrorRecord; if (null != icer && null != icer.ErrorRecord) { - _errorRecord = new ErrorRecord (icer.ErrorRecord, innerException); + _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } else { // When no ErrorId is specified by a thrown exception, // we use innerException.GetType().FullName. - _errorRecord = new ErrorRecord ( + _errorRecord = new ErrorRecord( innerException, innerException.GetType().FullName, ErrorCategory.NotSpecified, null); } - _errorRecord.SetInvocationInfo (invocationInfo); + _errorRecord.SetInvocationInfo(invocationInfo); // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = innerException.HelpLink; // Exception.Source is set by Throw // Source = innerException.Source; @@ -117,7 +117,7 @@ namespace System.Management.Automation /// constructed object public CmdletInvocationException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } @@ -145,14 +145,14 @@ namespace System.Management.Automation /// serialization information /// streaming context [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] - public override void GetObjectData (SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } - base.GetObjectData (info, context); + base.GetObjectData(info, context); bool hasErrorRecord = (null != _errorRecord); info.AddValue("HasErrorRecord", hasErrorRecord); if (hasErrorRecord) @@ -184,7 +184,6 @@ namespace System.Management.Automation private ErrorRecord _errorRecord = null; #endregion Properties - } // class CmdletInvocationException #endregion CmdletInvocationException @@ -210,11 +209,11 @@ namespace System.Management.Automation internal CmdletProviderInvocationException( ProviderInvocationException innerException, InvocationInfo myInvocation) - : base (GetInnerException(innerException), myInvocation) + : base(GetInnerException(innerException), myInvocation) { if (null == innerException) { - throw new ArgumentNullException ("innerException"); + throw new ArgumentNullException("innerException"); } _providerInvocationException = innerException; } @@ -261,7 +260,7 @@ namespace System.Management.Automation /// constructed object public CmdletProviderInvocationException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { _providerInvocationException = innerException as ProviderInvocationException; } @@ -296,11 +295,11 @@ namespace System.Management.Automation : _providerInvocationException.ProviderInfo; } } - + #endregion Properties #region Internal - private static Exception GetInnerException (Exception e) + private static Exception GetInnerException(Exception e) { return (e == null) ? null : e.InnerException; } @@ -375,7 +374,7 @@ namespace System.Management.Automation /// constructed object public PipelineStoppedException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -473,11 +472,11 @@ namespace System.Management.Automation /// /// constructed object internal ActionPreferenceStopException(ErrorRecord error) - : this( RetrieveMessage(error) ) + : this(RetrieveMessage(error)) { if (null == error) { - throw new ArgumentNullException ("error"); + throw new ArgumentNullException("error"); } _errorRecord = error; } @@ -589,7 +588,7 @@ namespace System.Management.Automation /// constructed object public ActionPreferenceStopException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetErrorCategory(ErrorCategory.OperationStopped); SetErrorId("ActionPreferenceStop"); @@ -651,7 +650,7 @@ namespace System.Management.Automation // Please remove the #pragma warning when this is fixed. public ParentContainsErrorRecordException(Exception wrapperException) { - this.wrapperException = wrapperException; + _wrapperException = wrapperException; } #pragma warning restore 56506 @@ -663,7 +662,7 @@ namespace System.Management.Automation /// constructed object public ParentContainsErrorRecordException(string message) { - this.message = message; + _message = message; } /// @@ -683,9 +682,9 @@ namespace System.Management.Automation /// constructed object public ParentContainsErrorRecordException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { - this.message = message; + _message = message; } #endregion Constructors @@ -703,7 +702,7 @@ namespace System.Management.Automation SerializationInfo info, StreamingContext context) : base(info, context) { - message = info.GetString("ParentContainsErrorRecordException_Message"); + _message = info.GetString("ParentContainsErrorRecordException_Message"); } #endregion Serialization /// @@ -713,12 +712,12 @@ namespace System.Management.Automation { get { - if (null == message) + if (null == _message) { - message = (null != wrapperException) ? wrapperException.Message : String.Empty; + _message = (null != _wrapperException) ? _wrapperException.Message : String.Empty; } - return message; + return _message; } } @@ -740,8 +739,8 @@ namespace System.Management.Automation #region Private Data - private readonly Exception wrapperException; - private string message; + private readonly Exception _wrapperException; + private string _message; #endregion } @@ -792,7 +791,7 @@ namespace System.Management.Automation /// constructed object public RedirectedException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetErrorId("RedirectedException"); SetErrorCategory(ErrorCategory.NotSpecified); @@ -860,7 +859,7 @@ namespace System.Management.Automation /// constructed object public ScriptCallDepthException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -904,18 +903,18 @@ namespace System.Management.Automation { get { - if (null == errorRecord) + if (null == _errorRecord) { - errorRecord = new ErrorRecord( + _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), "CallDepthOverflow", ErrorCategory.InvalidOperation, CallDepth); } - return errorRecord; + return _errorRecord; } } - private ErrorRecord errorRecord = null; + private ErrorRecord _errorRecord = null; /// /// Always 0 - depth is not tracked as there is no hard coded maximum. @@ -1012,18 +1011,18 @@ namespace System.Management.Automation { get { - if (null == errorRecord) + if (null == _errorRecord) { - errorRecord = new ErrorRecord( + _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), "CallDepthOverflow", ErrorCategory.InvalidOperation, CallDepth); } - return errorRecord; + return _errorRecord; } } - private ErrorRecord errorRecord = null; + private ErrorRecord _errorRecord = null; /// /// Always 0 - depth is not tracked as there is no hard coded maximum. diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index 70bc32ea7..909f6af9f 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -1,6 +1,7 @@ // // Copyright (C) Microsoft. All rights reserved. // + using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -81,7 +82,7 @@ namespace System.Management.Automation /// Type.EmptyTypes is not in CoreCLR. Use this one to replace it. /// internal static Type[] EmptyTypes = new Type[0]; - private static readonly Type ComObjectType = Type.GetType("System.__ComObject"); + private static readonly Type s_comObjectType = Type.GetType("System.__ComObject"); /// /// Check does the type have an instance default constructor with visibility that allows calling it from subclass. @@ -133,7 +134,7 @@ namespace System.Management.Automation #if UNIX return false; #elif CORECLR // Type.IsComObject(Type) is not in CoreCLR - return ComObjectType.IsAssignableFrom(type); + return s_comObjectType.IsAssignableFrom(type); #else return type.IsCOMObject; #endif @@ -150,7 +151,7 @@ namespace System.Management.Automation } internal static IEnumerable GetCustomAttributes(this Type type, bool inherit) - where T: Attribute + where T : Attribute { return from attr in type.GetTypeInfo().GetCustomAttributes(typeof(T), inherit) where attr is T @@ -160,12 +161,11 @@ namespace System.Management.Automation internal static class WeakReferenceExtensions { - internal static bool TryGetTarget(this WeakReference weakReference, out T target) where T:class + internal static bool TryGetTarget(this WeakReference weakReference, out T target) where T : class { var t = weakReference.Target; target = t as T; return (target != null); } } - } diff --git a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs index b93c7ec62..406d1f7d7 100644 --- a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs +++ b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs @@ -1,5 +1,4 @@ //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // // @@ -29,17 +28,17 @@ namespace System.Management.Automation.Internal /// /// Initialized in GetGraphicalHostReflectionWrapper with the Microsoft.PowerShell.GraphicalHost.dll assembly. /// - private Assembly graphicalHostAssembly; + private Assembly _graphicalHostAssembly; /// /// A type in Microsoft.PowerShell.GraphicalHost.dll we want to invoke members on /// - private Type graphicalHostHelperType; + private Type _graphicalHostHelperType; /// /// An object in Microsoft.PowerShell.GraphicalHost.dll of type graphicalHostHelperType /// - private object graphicalHostHelperObject; + private object _graphicalHostHelperObject; /// /// Prevents a default instance of the GraphicalHostReflectionWrapper class from being created @@ -101,14 +100,14 @@ namespace System.Management.Automation.Internal try { - returnValue.graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName); + returnValue._graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName); } catch (FileNotFoundException fileNotFoundEx) { // This exception is thrown if the Microsoft.PowerShell.GraphicalHost.dll could not be found (was not installed). string errorMessage = StringUtil.Format( HelpErrors.GraphicalHostAssemblyIsNotFound, - featureName, + featureName, fileNotFoundEx.Message); parentCmdlet.ThrowTerminatingError( @@ -129,19 +128,19 @@ namespace System.Management.Automation.Internal graphicalHostAssemblyName)); } - returnValue.graphicalHostHelperType = returnValue.graphicalHostAssembly.GetType(graphicalHostHelperTypeName); + returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName); - Diagnostics.Assert(returnValue.graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost"); - ConstructorInfo constructor = returnValue.graphicalHostHelperType.GetConstructor( - BindingFlags.NonPublic | BindingFlags.Instance, - null, - new Type[] { }, + Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost"); + ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor( + BindingFlags.NonPublic | BindingFlags.Instance, + null, + new Type[] { }, null); if (constructor != null) { - returnValue.graphicalHostHelperObject = constructor.Invoke(new object[] { }); - Diagnostics.Assert(returnValue.graphicalHostHelperObject != null, "the constructor does not throw anything"); + returnValue._graphicalHostHelperObject = constructor.Invoke(new object[] { }); + Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything"); } return returnValue; @@ -165,10 +164,10 @@ namespace System.Management.Automation.Internal /// The method return value internal object CallMethod(string methodName, params object[] arguments) { - Diagnostics.Assert(this.graphicalHostHelperObject != null, "there should be a constructor in order to call an instance method"); - MethodInfo method = this.graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); + Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to call an instance method"); + MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); - return method.Invoke(this.graphicalHostHelperObject, arguments); + return method.Invoke(_graphicalHostHelperObject, arguments); } /// @@ -179,7 +178,7 @@ namespace System.Management.Automation.Internal /// The method return value internal object CallStaticMethod(string methodName, params object[] arguments) { - MethodInfo method = this.graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); return method.Invoke(null, arguments); } @@ -191,10 +190,10 @@ namespace System.Management.Automation.Internal /// the value of an instance property with name internal object GetPropertyValue(string propertyName) { - Diagnostics.Assert(this.graphicalHostHelperObject != null, "there should be a constructor in order to get an instance property value"); - PropertyInfo property = this.graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); + Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to get an instance property value"); + PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); - return property.GetValue(this.graphicalHostHelperObject, new object[] { }); + return property.GetValue(_graphicalHostHelperObject, new object[] { }); } /// @@ -204,7 +203,7 @@ namespace System.Management.Automation.Internal /// the value of a static property with name internal object GetStaticPropertyValue(string propertyName) { - PropertyInfo property = this.graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static); + PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static); Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); return property.GetValue(null, new object[] { }); } diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index 88b66cb5c..7979458bc 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -78,7 +78,7 @@ namespace System.Management.Automation.Host public HostException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetDefaultErrorRecord(); } @@ -117,7 +117,7 @@ namespace System.Management.Automation.Host /// public - HostException(string message, Exception innerException, string errorId, ErrorCategory errorCategory): + HostException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) : base(message, innerException) { SetErrorId(errorId); @@ -175,7 +175,7 @@ namespace System.Management.Automation.Host /// public - PromptingException() : base(StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate,typeof(PromptingException).FullName)) + PromptingException() : base(StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate, typeof(PromptingException).FullName)) { SetDefaultErrorRecord(); } @@ -219,7 +219,7 @@ namespace System.Management.Automation.Host public PromptingException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { SetDefaultErrorRecord(); } @@ -258,7 +258,7 @@ namespace System.Management.Automation.Host /// public - PromptingException(string message, Exception innerException, string errorId, ErrorCategory errorCategory): + PromptingException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) : base(message, innerException, errorId, errorCategory) { } diff --git a/src/System.Management.Automation/utils/IObjectReader.cs b/src/System.Management.Automation/utils/IObjectReader.cs index aedffb7fa..bf7973775 100644 --- a/src/System.Management.Automation/utils/IObjectReader.cs +++ b/src/System.Management.Automation/utils/IObjectReader.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + using System; using System.Threading; using System.Collections.Generic; @@ -15,7 +16,7 @@ namespace System.Management.Automation.Runspaces /// /// /// - public abstract class PipelineReader + public abstract class PipelineReader { /// /// Event fired when data is added to the buffer diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 467f6e738..33f264696 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation.Runspaces { using System; @@ -124,22 +125,22 @@ namespace System.Management.Automation.Runspaces internal class DiscardingPipelineWriter : PipelineWriter { - private ManualResetEvent waitHandle = new ManualResetEvent(true); + private ManualResetEvent _waitHandle = new ManualResetEvent(true); public override WaitHandle WaitHandle { - get { return this.waitHandle; } + get { return _waitHandle; } } - private bool isOpen = true; + private bool _isOpen = true; public override bool IsOpen { - get { return this.isOpen; } + get { return _isOpen; } } - private int count = 0; + private int _count = 0; public override int Count { - get { return this.count; } + get { return _count; } } public override int MaxCapacity @@ -149,7 +150,7 @@ namespace System.Management.Automation.Runspaces public override void Close() { - this.isOpen = false; + _isOpen = false; } public override void Flush() @@ -159,7 +160,7 @@ namespace System.Management.Automation.Runspaces public override int Write(object obj) { int numberOfObjectsWritten = 1; - this.count += numberOfObjectsWritten; + _count += numberOfObjectsWritten; return numberOfObjectsWritten; } @@ -184,7 +185,7 @@ namespace System.Management.Automation.Runspaces numberOfObjectsWritten++; } - this.count += numberOfObjectsWritten; + _count += numberOfObjectsWritten; return numberOfObjectsWritten; } } diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index aa9b4e4b5..66cfee3b4 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -28,7 +28,7 @@ namespace System.Management.Automation /// /// serialization information /// streaming context - protected MetadataException(SerializationInfo info, StreamingContext context): base(info, context) + protected MetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { SetErrorCategory(ErrorCategory.MetadataError); } @@ -37,7 +37,7 @@ namespace System.Management.Automation /// Initializes a new instance of MetadataException with the message set /// to typeof(MetadataException).FullName /// - public MetadataException():base(typeof(MetadataException).FullName) + public MetadataException() : base(typeof(MetadataException).FullName) { SetErrorCategory(ErrorCategory.MetadataError); } @@ -46,7 +46,7 @@ namespace System.Management.Automation /// Initializes a new instance of MetadataException setting the message /// /// the exception's message - public MetadataException(string message):base(message) + public MetadataException(string message) : base(message) { SetErrorCategory(ErrorCategory.MetadataError); } @@ -56,13 +56,13 @@ namespace System.Management.Automation /// /// the exception's message /// the exceptions's inner exception - public MetadataException(string message, Exception innerException):base(message,innerException) + public MetadataException(string message, Exception innerException) : base(message, innerException) { SetErrorCategory(ErrorCategory.MetadataError); } - internal MetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments): + internal MetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : base(StringUtil.Format(resourceStr, arguments), innerException) { SetErrorCategory(ErrorCategory.MetadataError); @@ -109,23 +109,23 @@ namespace System.Management.Automation /// /// serialization information /// streaming context - protected ValidationMetadataException(SerializationInfo info, StreamingContext context): base(info,context) { } + protected ValidationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// /// Initializes a new instance of ValidationMetadataException with the message set /// to typeof(ValidationMetadataException).FullName /// - public ValidationMetadataException():base(typeof(ValidationMetadataException).FullName) { } + public ValidationMetadataException() : base(typeof(ValidationMetadataException).FullName) { } /// /// Initializes a new instance of ValidationMetadataException setting the message /// /// the exception's message - public ValidationMetadataException(string message):this(message, false) { } + public ValidationMetadataException(string message) : this(message, false) { } /// /// Initializes a new instance of ValidationMetadataException setting the message and innerException /// /// the exception's message /// the exceptions's inner exception - public ValidationMetadataException(string message, Exception innerException):base(message, innerException) { } + public ValidationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ValidationMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : @@ -174,23 +174,23 @@ namespace System.Management.Automation /// /// serialization information /// streaming context - protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context): base(info,context) { } + protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// /// Initializes a new instance of ArgumentTransformationMetadataException with the message set /// to typeof(ArgumentTransformationMetadataException).FullName /// - public ArgumentTransformationMetadataException():base(typeof(ArgumentTransformationMetadataException).FullName) { } + public ArgumentTransformationMetadataException() : base(typeof(ArgumentTransformationMetadataException).FullName) { } /// /// Initializes a new instance of ArgumentTransformationMetadataException setting the message /// /// the exception's message - public ArgumentTransformationMetadataException(string message):base(message) { } + public ArgumentTransformationMetadataException(string message) : base(message) { } /// /// Initializes a new instance of ArgumentTransformationMetadataException setting the message and innerException /// /// the exception's message /// the exceptions's inner exception - public ArgumentTransformationMetadataException(string message, Exception innerException):base(message, innerException) { } + public ArgumentTransformationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ArgumentTransformationMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : @@ -212,23 +212,23 @@ namespace System.Management.Automation /// /// serialization information /// streaming context - protected ParsingMetadataException(SerializationInfo info, StreamingContext context): base(info,context) { } + protected ParsingMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// /// Initializes a new instance of ParsingMetadataException with the message set /// to typeof(ParsingMetadataException).FullName /// - public ParsingMetadataException():base(typeof(ParsingMetadataException).FullName) { } + public ParsingMetadataException() : base(typeof(ParsingMetadataException).FullName) { } /// /// Initializes a new instance of ParsingMetadataException setting the message /// /// the exception's message - public ParsingMetadataException(string message):base(message) { } + public ParsingMetadataException(string message) : base(message) { } /// /// Initializes a new instance of ParsingMetadataException setting the message and innerException /// /// the exception's message /// the exceptions's inner exception - public ParsingMetadataException(string message, Exception innerException):base(message, innerException) { } + public ParsingMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ParsingMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index b5b1c28e1..ea51a0a5a 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -115,7 +115,7 @@ namespace System.Management.Automation /// constructed object public PSArgumentException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { _message = message; } @@ -135,8 +135,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.InvalidArgument, null); @@ -146,7 +146,7 @@ namespace System.Management.Automation } private ErrorRecord _errorRecord; private string _errorId = "Argument"; - + /// /// see /// diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index 487da0f25..407efa08a 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -133,8 +133,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.InvalidArgument, null); diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index c36938166..f29b33049 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -112,7 +112,7 @@ namespace System.Management.Automation /// constructed object public PSArgumentOutOfRangeException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -131,8 +131,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.InvalidArgument, null); diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index e9e42da54..03752dba3 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -93,7 +93,7 @@ namespace System.Management.Automation /// constructed object public PSInvalidOperationException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } @@ -129,8 +129,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, _errorCategory, _target); @@ -147,7 +147,6 @@ namespace System.Management.Automation private ErrorCategory _errorCategory = ErrorCategory.InvalidOperation; private object _target = null; - } // PSInvalidOperationException } // System.Management.Automation diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index 5fb8eea95..09ae88143 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -93,7 +93,7 @@ namespace System.Management.Automation /// constructed object public PSNotImplementedException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -112,8 +112,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.NotImplemented, null); diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index a318ae6f1..1e8d33d02 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -92,7 +92,7 @@ namespace System.Management.Automation /// constructed object public PSNotSupportedException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -111,8 +111,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.NotImplemented, null); diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index be1ab32b5..19092e5e0 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -118,8 +118,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, ErrorCategory.InvalidOperation, null); diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 14602e073..2d7af5efb 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -9,7 +9,6 @@ using System.Management.Automation.Internal; namespace System.Management.Automation { - /// /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance /// that is used the the Monad components to produce trace output. @@ -56,7 +55,7 @@ namespace System.Management.Automation /// /// Lock object for the GetTracer method /// - private static object getTracerLock = new object(); + private static object s_getTracerLock = new object(); /// /// A helper to get an instance of the PSTraceSource class @@ -122,7 +121,7 @@ namespace System.Management.Automation throw new ArgumentNullException("name"); } - lock (PSTraceSource.getTracerLock) + lock (PSTraceSource.s_getTracerLock) { PSTraceSource result = null; @@ -216,17 +215,17 @@ namespace System.Management.Automation // uniform output string fullName = name; -/* - // This is here to ensure all the trace category names are 16 characters, - // the problem is that the app-config file would need to contain the same - // trailing spaces if this actually does pad the name. + /* + // This is here to ensure all the trace category names are 16 characters, + // the problem is that the app-config file would need to contain the same + // trailing spaces if this actually does pad the name. - name = - String.Format( - System.Globalization.CultureInfo.InvariantCulture, - "{0,-16}", - name); -*/ + name = + String.Format( + System.Globalization.CultureInfo.InvariantCulture, + "{0,-16}", + name); + */ PSTraceSource result = new PSTraceSource( fullName, @@ -257,7 +256,7 @@ namespace System.Management.Automation string message = StringUtil.Format(AutomationExceptions.ArgumentNull, paramName); var e = new PSArgumentNullException(paramName, message); - + return e; } @@ -368,7 +367,7 @@ namespace System.Management.Automation new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name); #endif var e = new PSInvalidOperationException(message); - + return e; } @@ -476,7 +475,7 @@ namespace System.Management.Automation return e; } - + /// /// Traces the Message and StackTrace properties of the exception /// and returns the new exception. This is not allowed to call other @@ -517,7 +516,7 @@ namespace System.Management.Automation } string message = StringUtil.Format(AutomationExceptions.ArgumentOutOfRange, paramName); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); - + return e; } @@ -553,7 +552,7 @@ namespace System.Management.Automation string message = StringUtil.Format(resourceString, args); var e = new PSArgumentOutOfRangeException(paramName, actualValue, message); - + return e; } @@ -584,7 +583,6 @@ namespace System.Management.Automation } #endregion TraceFlags.New*Exception methods/helpers - } // class PSTraceSource } diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 7115cad74..a454d56bf 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation.Internal { using System; @@ -23,11 +24,11 @@ namespace System.Management.Automation.Internal /// /// the stream to read /// Thrown if the specified stream is null - public ObjectReaderBase ([In, Out] ObjectStreamBase stream) + public ObjectReaderBase([In, Out] ObjectStreamBase stream) { if (stream == null) { - throw new ArgumentNullException ("stream", "stream may not be null"); + throw new ArgumentNullException("stream", "stream may not be null"); } _stream = stream; @@ -48,7 +49,7 @@ namespace System.Management.Automation.Internal InternalDataReady += value; if (firstRegistrant) { - _stream.DataReady += new EventHandler (this.OnDataReady); + _stream.DataReady += new EventHandler(this.OnDataReady); } } } @@ -59,7 +60,7 @@ namespace System.Management.Automation.Internal InternalDataReady -= value; if (null == InternalDataReady) { - _stream.DataReady -= new EventHandler (this.OnDataReady); + _stream.DataReady -= new EventHandler(this.OnDataReady); } } } @@ -160,10 +161,10 @@ namespace System.Management.Automation.Internal /// /// The stream is already disposed /// - public override void Close () + public override void Close() { // 2003/09/02-JonN added call to close underlying stream - _stream.Close (); + _stream.Close(); } #endregion Public Methods @@ -175,7 +176,7 @@ namespace System.Management.Automation.Internal /// /// The stream raising the event /// standard event args. - private void OnDataReady (object sender, EventArgs args) + private void OnDataReady(object sender, EventArgs args) { // call any event handlers on this, replacing the // ObjectStream sender with 'this' since receivers @@ -225,7 +226,6 @@ namespace System.Management.Automation.Internal protected abstract void Dispose(bool disposing); #endregion IDisposable - } // ObjectReaderBase /// @@ -242,9 +242,9 @@ namespace System.Management.Automation.Internal /// /// the stream to read /// Thrown if the specified stream is null - public ObjectReader ([In, Out] ObjectStream stream) + public ObjectReader([In, Out] ObjectStream stream) : base(stream) - {} + { } #endregion ctor /// @@ -256,9 +256,9 @@ namespace System.Management.Automation.Internal /// This method blocks if the number of objects in the stream is less than /// and the stream is not closed. /// - public override Collection Read (int count) + public override Collection Read(int count) { - return _stream.Read (count); + return _stream.Read(count); } /// @@ -266,9 +266,9 @@ namespace System.Management.Automation.Internal /// /// the next object in the stream /// This method blocks if the stream is empty - public override object Read () + public override object Read() { - return _stream.Read (); + return _stream.Read(); } /// @@ -278,9 +278,9 @@ namespace System.Management.Automation.Internal /// /// If the stream is empty, an empty collection is returned. /// - public override Collection ReadToEnd () + public override Collection ReadToEnd() { - return _stream.ReadToEnd (); + return _stream.ReadToEnd(); } /// @@ -293,9 +293,9 @@ namespace System.Management.Automation.Internal /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// - public override Collection NonBlockingRead () + public override Collection NonBlockingRead() { - return _stream.NonBlockingRead (Int32.MaxValue); + return _stream.NonBlockingRead(Int32.MaxValue); } /// @@ -311,18 +311,18 @@ namespace System.Management.Automation.Internal /// /// Return no more than maxRequested objects. /// - public override Collection NonBlockingRead (int maxRequested) + public override Collection NonBlockingRead(int maxRequested) { - return _stream.NonBlockingRead (maxRequested); + return _stream.NonBlockingRead(maxRequested); } /// /// Peek the next object /// /// The next object in the stream or ObjectStream.EmptyObject if the stream is empty - public override object Peek () + public override object Peek() { - return _stream.Peek (); + return _stream.Peek(); } /// @@ -352,9 +352,9 @@ namespace System.Management.Automation.Internal /// /// the stream to read /// Thrown if the specified stream is null - public PSObjectReader ([In, Out] ObjectStream stream) + public PSObjectReader([In, Out] ObjectStream stream) : base(stream) - {} + { } #endregion ctor /// @@ -366,9 +366,9 @@ namespace System.Management.Automation.Internal /// This method blocks if the number of objects in the stream is less than /// and the stream is not closed. /// - public override Collection Read (int count) + public override Collection Read(int count) { - return MakePSObjectCollection (_stream.Read (count)); + return MakePSObjectCollection(_stream.Read(count)); } /// @@ -376,9 +376,9 @@ namespace System.Management.Automation.Internal /// /// the next PSObject in the stream /// This method blocks if the stream is empty - public override PSObject Read () + public override PSObject Read() { - return MakePSObject (_stream.Read ()); + return MakePSObject(_stream.Read()); } /// @@ -388,9 +388,9 @@ namespace System.Management.Automation.Internal /// /// If the stream is empty, an empty collection is returned. /// - public override Collection ReadToEnd () + public override Collection ReadToEnd() { - return MakePSObjectCollection (_stream.ReadToEnd ()); + return MakePSObjectCollection(_stream.ReadToEnd()); } /// @@ -403,9 +403,9 @@ namespace System.Management.Automation.Internal /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// - public override Collection NonBlockingRead () + public override Collection NonBlockingRead() { - return MakePSObjectCollection (_stream.NonBlockingRead (Int32.MaxValue)); + return MakePSObjectCollection(_stream.NonBlockingRead(Int32.MaxValue)); } /// @@ -421,18 +421,18 @@ namespace System.Management.Automation.Internal /// /// Return no more than maxRequested objects. /// - public override Collection NonBlockingRead (int maxRequested) + public override Collection NonBlockingRead(int maxRequested) { - return MakePSObjectCollection (_stream.NonBlockingRead (maxRequested)); + return MakePSObjectCollection(_stream.NonBlockingRead(maxRequested)); } /// /// Peek the next PSObject /// /// The next PSObject in the stream or ObjectStream.EmptyObject if the stream is empty - public override PSObject Peek () + public override PSObject Peek() { - return MakePSObject (_stream.Peek ()); + return MakePSObject(_stream.Peek()); } /// @@ -448,27 +448,27 @@ namespace System.Management.Automation.Internal } #region Private - private static PSObject MakePSObject (object o) + private static PSObject MakePSObject(object o) { if (null == o) return null; - return PSObject.AsPSObject (o); + return PSObject.AsPSObject(o); } // It might ultimately be more efficient to // make ObjectStream generic and convert the objects to PSObject // before inserting them into the initial Collection, so that we // don't have to convert the collection later. - private static Collection MakePSObjectCollection ( + private static Collection MakePSObjectCollection( Collection coll) { if (null == coll) return null; - Collection retval = new Collection (); + Collection retval = new Collection(); foreach (object o in coll) { - retval.Add (MakePSObject (o)); + retval.Add(MakePSObject(o)); } return retval; } @@ -484,13 +484,13 @@ namespace System.Management.Automation.Internal /// commands concurrently. /// Only Read() operation is supported currently. /// - internal class PSDataCollectionReader - : ObjectReaderBase + internal class PSDataCollectionReader + : ObjectReaderBase { #region Private Data - private PSDataCollectionEnumerator enumerator; - + private PSDataCollectionEnumerator _enumerator; + #endregion #region ctor @@ -504,7 +504,7 @@ namespace System.Management.Automation.Internal { System.Management.Automation.Diagnostics.Assert(null != stream.ObjectStore, "Stream should have a valid data store"); - enumerator = (PSDataCollectionEnumerator)stream.ObjectStore.GetEnumerator(); + _enumerator = (PSDataCollectionEnumerator)stream.ObjectStore.GetEnumerator(); } #endregion ctor @@ -532,12 +532,12 @@ namespace System.Management.Automation.Internal public override ReturnType Read() { object result = AutomationNull.Value; - if (enumerator.MoveNext()) + if (_enumerator.MoveNext()) { - result = enumerator.Current; + result = _enumerator.Current; } - return ConvertToReturnType(result); + return ConvertToReturnType(result); } /// @@ -574,7 +574,7 @@ namespace System.Management.Automation.Internal { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } - + if (maxRequested == 0) { return new Collection(); @@ -582,12 +582,12 @@ namespace System.Management.Automation.Internal Collection results = new Collection(); int readCount = maxRequested; - while (readCount > 0) + while (readCount > 0) { - if (enumerator.MoveNext(false)) + if (_enumerator.MoveNext(false)) { - results.Add(ConvertToReturnType(enumerator.Current)); - continue; + results.Add(ConvertToReturnType(_enumerator.Current)); + continue; } break; @@ -630,7 +630,6 @@ namespace System.Management.Automation.Internal System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); - } } @@ -648,9 +647,9 @@ namespace System.Management.Automation.Internal { #region Private Data - private PSDataCollection datastore; - private String computerName; - private Guid runspaceId; + private PSDataCollection _datastore; + private String _computerName; + private Guid _runspaceId; #endregion Private Data @@ -667,9 +666,9 @@ namespace System.Management.Automation.Internal { System.Management.Automation.Diagnostics.Assert(null != stream.ObjectStore, "Stream should have a valid data store"); - datastore = stream.ObjectStore; - this.computerName = computerName; - this.runspaceId = runspaceId; + _datastore = stream.ObjectStore; + _computerName = computerName; + _runspaceId = runspaceId; } #endregion ctor @@ -682,7 +681,7 @@ namespace System.Management.Automation.Internal { get { - return computerName; + return _computerName; } } @@ -694,7 +693,7 @@ namespace System.Management.Automation.Internal { get { - return runspaceId; + return _runspaceId; } } @@ -721,9 +720,9 @@ namespace System.Management.Automation.Internal public override ReturnType Read() { object result = AutomationNull.Value; - if (datastore.Count > 0) + if (_datastore.Count > 0) { - Collection resultCollection = datastore.ReadAndRemove(1); + Collection resultCollection = _datastore.ReadAndRemove(1); // ReadAndRemove returns a Collection type but we // just want the single object contained in the collection. @@ -780,9 +779,9 @@ namespace System.Management.Automation.Internal while (readCount > 0) { - if (datastore.Count > 0) + if (_datastore.Count > 0) { - results.Add(ConvertToReturnType((datastore.ReadAndRemove(1))[0])); + results.Add(ConvertToReturnType((_datastore.ReadAndRemove(1))[0])); readCount--; continue; } @@ -820,7 +819,6 @@ namespace System.Management.Automation.Internal System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); - } #region IDisposable @@ -833,7 +831,7 @@ namespace System.Management.Automation.Internal { if (disposing) { - datastore.Dispose(); + _datastore.Dispose(); } } diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 6cac49537..f53b1719b 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -45,7 +45,7 @@ namespace System.Management.Automation.Internal #endregion Public events #region Virtual Properties - + /// /// Get the capacity of the stream /// @@ -146,7 +146,7 @@ namespace System.Management.Automation.Internal /// Return an PipelineWriter for this stream /// internal abstract PipelineWriter ObjectWriter { get; } - + #endregion #region Read Abstractions @@ -522,8 +522,8 @@ namespace System.Management.Automation.Internal /// /// Constructs a stream with a miximum size of Int32.Max /// - internal ObjectStream () - : this (Int32.MaxValue) + internal ObjectStream() + : this(Int32.MaxValue) { } @@ -539,27 +539,27 @@ namespace System.Management.Automation.Internal /// is less than or equal to zero /// is greater than Int32.MaxValue /// - internal ObjectStream (int capacity) + internal ObjectStream(int capacity) { if (capacity <= 0 || capacity > Int32.MaxValue) { - throw PSTraceSource.NewArgumentOutOfRangeException ("capacity",capacity); + throw PSTraceSource.NewArgumentOutOfRangeException("capacity", capacity); } // the maximum number of objects to allow in the stream at a given time. _capacity = capacity; // event is not signaled since there is no data to read - _readHandle = new AutoResetEvent (false); + _readHandle = new AutoResetEvent(false); // event is signaled since there is available buffer space - _writeHandle = new AutoResetEvent (true); + _writeHandle = new AutoResetEvent(true); // event is not signaled since the thread is still readable - _readClosedHandle = new ManualResetEvent (false); + _readClosedHandle = new ManualResetEvent(false); // event is signaled since the thread is still writeable - _writeClosedHandle = new ManualResetEvent (false); + _writeClosedHandle = new ManualResetEvent(false); // the FIFO set of objects in the stream _objects = new List(); @@ -618,7 +618,7 @@ namespace System.Management.Automation.Internal // Pipeline readers that execute asynchronously. Since the pipeline // may complete with zero objects before the caller objects this // handle, it will block indefinitely unless it is set. - _readWaitHandle = new ManualResetEvent (_objects.Count > 0 || !_isOpen); + _readWaitHandle = new ManualResetEvent(_objects.Count > 0 || !_isOpen); } handle = _readWaitHandle; @@ -645,7 +645,7 @@ namespace System.Management.Automation.Internal { if (_writeWaitHandle == null) { - _writeWaitHandle = new ManualResetEvent (_objects.Count < _capacity || !_isOpen); + _writeWaitHandle = new ManualResetEvent(_objects.Count < _capacity || !_isOpen); } handle = _writeWaitHandle; @@ -674,7 +674,7 @@ namespace System.Management.Automation.Internal // stream will be in the EndOfPipeline state because the // stream is closed and has zero data. Since this is a valid // and expected execution path, we don't want to throw an exception. - _reader = new ObjectReader (this); + _reader = new ObjectReader(this); } reader = _reader; @@ -704,7 +704,7 @@ namespace System.Management.Automation.Internal // stream will be in the EndOfPipeline state because the // stream is closed and has zero data. Since this is a valid // and expected execution path, we don't want to throw an exception. - _mshreader = new PSObjectReader (this); + _mshreader = new PSObjectReader(this); } reader = _mshreader; @@ -728,7 +728,7 @@ namespace System.Management.Automation.Internal { if (_writer == null) { - _writer = new ObjectWriter (this) as PipelineWriter; + _writer = new ObjectWriter(this) as PipelineWriter; } writer = _writer; @@ -818,14 +818,14 @@ namespace System.Management.Automation.Internal /// before the caller has a chance to read the data. /// This method should never be called within a lock(_monitorObject). /// - private bool WaitRead () + private bool WaitRead() { if (EndOfPipeline == false) { try { WaitHandle[] ha = { _readHandle, _readClosedHandle }; - WaitHandle.WaitAny (ha); // ignore return value + WaitHandle.WaitAny(ha); // ignore return value } catch (ObjectDisposedException) { @@ -848,14 +848,14 @@ namespace System.Management.Automation.Internal /// when the event was signaled. /// This method should never be called within a lock(_monitorObject). /// - private bool WaitWrite () + private bool WaitWrite() { if (IsOpen) { try { WaitHandle[] ha = { _writeHandle, _writeClosedHandle }; - WaitHandle.WaitAny (ha); // ignore return value + WaitHandle.WaitAny(ha); // ignore return value } catch (ObjectDisposedException) { @@ -878,7 +878,7 @@ namespace System.Management.Automation.Internal /// RaiseEvents is fairly idempotent, although it will signal /// DataReady every time. /// - private void RaiseEvents () + private void RaiseEvents() { bool unblockReaders = true; bool unblockWriters = true; @@ -978,7 +978,7 @@ namespace System.Management.Automation.Internal // client-provided handler. if (unblockReaders) { - FireDataReadyEvent (this, EventArgs.Empty); + FireDataReadyEvent(this, EventArgs.Empty); } #if (false) // @@ -1000,7 +1000,7 @@ namespace System.Management.Automation.Internal /// /// Flush the data from the stream. Closed streams may be flushed. /// - internal override void Flush () + internal override void Flush() { bool raiseEvents = false; @@ -1083,7 +1083,7 @@ namespace System.Management.Automation.Internal { return result[0]; } - Diagnostics.Assert (result.Count == 0, "Invalid number of objects returned"); + Diagnostics.Assert(result.Count == 0, "Invalid number of objects returned"); return AutomationNull.Value; } @@ -1116,17 +1116,17 @@ namespace System.Management.Automation.Internal { if (count < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException ("count",count); + throw PSTraceSource.NewArgumentOutOfRangeException("count", count); } if (count == 0) { - return new Collection (); + return new Collection(); } - Collection results = new Collection (); + Collection results = new Collection(); bool raiseEvents = false; - while ((count > 0) && WaitRead ()) + while ((count > 0) && WaitRead()) { try { @@ -1220,7 +1220,7 @@ namespace System.Management.Automation.Internal } if (maxRequested < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested",maxRequested); + throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } try @@ -1255,7 +1255,7 @@ namespace System.Management.Automation.Internal } if (results == null) { - results = new Collection (); + results = new Collection(); } return results; @@ -1341,7 +1341,7 @@ namespace System.Management.Automation.Internal enumerable = LanguagePrimitives.GetEnumerable(obj); } if (null == enumerable) - a.Add (obj); + a.Add(obj); else { foreach (object o in enumerable) @@ -1358,7 +1358,7 @@ namespace System.Management.Automation.Internal // we just ignore it continue; } - a.Add (o); + a.Add(o); } // foreach } @@ -1371,7 +1371,7 @@ namespace System.Management.Automation.Internal // wait for buffer available // false indicates EndOfPipeline - if (WaitWrite () == false) + if (WaitWrite() == false) { break; } @@ -1380,7 +1380,6 @@ namespace System.Management.Automation.Internal { lock (_monitorObject) { - if (!IsOpen) { // NOTE: lock is released in finally @@ -1525,7 +1524,6 @@ namespace System.Management.Automation.Internal } #endregion IDisposable - } // class ObjectStream /// @@ -1541,8 +1539,8 @@ namespace System.Management.Automation.Internal #region Private Fields private PSDataCollection _objects; - private Guid psInstanceId; - private bool isOpen; + private Guid _psInstanceId; + private bool _isOpen; private PipelineWriter _writer; private PipelineReader _objectReader; private PipelineReader _psobjectReader; @@ -1576,8 +1574,8 @@ namespace System.Management.Automation.Internal } _objects = storeToUse; - this.psInstanceId = psInstanceId; - isOpen = true; + _psInstanceId = psInstanceId; + _isOpen = true; // increment ref count for the store. PowerShell engine // is about to use this store. storeToUse.AddRef(); @@ -1610,7 +1608,7 @@ namespace System.Management.Automation.Internal /// internal override int Count { - get + get { return _objects.Count; } @@ -1627,7 +1625,7 @@ namespace System.Management.Automation.Internal lock (_syncObject) { - endOfStream = (_objects.Count == 0 && !isOpen); + endOfStream = (_objects.Count == 0 && !_isOpen); } return endOfStream; } @@ -1646,7 +1644,7 @@ namespace System.Management.Automation.Internal get { // check both the current stream and the object store. - return isOpen && _objects.IsOpen; + return _isOpen && _objects.IsOpen; } } @@ -1701,7 +1699,7 @@ namespace System.Management.Automation.Internal { if (null == _objectReaderForPipeline) { - _objectReaderForPipeline = + _objectReaderForPipeline = new PSDataCollectionPipelineReader(this, computerName, runspaceId); } } @@ -1748,7 +1746,7 @@ namespace System.Management.Automation.Internal { if (null == _psobjectReaderForPipeline) { - _psobjectReaderForPipeline = + _psobjectReaderForPipeline = new PSDataCollectionPipelineReader(this, computerName, runspaceId); } } @@ -1855,7 +1853,7 @@ namespace System.Management.Automation.Internal } // foreach } - _objects.InternalAddRange(psInstanceId, objectsToAdd); + _objects.InternalAddRange(_psInstanceId, objectsToAdd); return objectsToAdd.Count; } @@ -1878,7 +1876,7 @@ namespace System.Management.Automation.Internal // Make sure decrementref is called only once. if this // stream is already closed..no need to decrement again. // isOpen controls if this current stream is open or not. - if (isOpen) + if (_isOpen) { // Decrement ref count (and other event handlers) for the store. // PowerShell engine is done using this store. @@ -1887,7 +1885,7 @@ namespace System.Management.Automation.Internal _objects.Completed -= HandleClosed; raiseEvents = true; - isOpen = false; + _isOpen = false; } } diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index ec31b7d34..2301ba582 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -1,6 +1,7 @@ /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ + namespace System.Management.Automation.Internal { using System; @@ -21,11 +22,11 @@ namespace System.Management.Automation.Internal /// /// the stream to write /// Thrown if the specified stream is null - public ObjectWriter ([In, Out] ObjectStreamBase stream) + public ObjectWriter([In, Out] ObjectStreamBase stream) { if (stream == null) { - throw new ArgumentNullException ("stream"); + throw new ArgumentNullException("stream"); } _stream = stream; @@ -108,9 +109,9 @@ namespace System.Management.Automation.Internal /// /// The stream is already disposed /// - public override void Close () + public override void Close() { - _stream.Close (); + _stream.Close(); // 2003/09/02-JonN I removed setting _stream // to null, now all of the tests for null can come out. } @@ -122,9 +123,9 @@ namespace System.Management.Automation.Internal /// /// The underlying stream is disposed /// - public override void Flush () + public override void Flush() { - _stream.Flush (); + _stream.Flush(); } /// @@ -144,7 +145,7 @@ namespace System.Management.Automation.Internal /// public override int Write(object obj) { - return _stream.Write (obj); + return _stream.Write(obj); } /// @@ -170,7 +171,7 @@ namespace System.Management.Automation.Internal /// public override int Write(object obj, bool enumerateCollection) { - return _stream.Write (obj, enumerateCollection); + return _stream.Write(obj, enumerateCollection); } #if (false) @@ -216,7 +217,7 @@ namespace System.Management.Automation.Internal internal class PSDataCollectionWriter : ObjectWriter { #region Constructors - + /// /// Construct with an existing PSDataCollectionStream /// diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index 38fd1093b..06c6bd848 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -26,7 +26,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class TelemetryAPI { -#region Public API + #region Public API /// /// Public API to expose Telemetry in PowerShell @@ -38,12 +38,12 @@ namespace Microsoft.PowerShell.Telemetry.Internal TelemetryWrapper.TraceMessage(message, arguments); } -#endregion + #endregion - static int anyPowerShellSessionOpen; - static DateTime sessionStartTime; + private static int s_anyPowerShellSessionOpen; + private static DateTime s_sessionStartTime; - enum HostIsInteractive + private enum HostIsInteractive { Unknown, Iteractive, @@ -57,7 +57,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal { // Avoid reporting startup more than once, except if we report "exited" and // another runspace gets opened. - if (Interlocked.CompareExchange(ref anyPowerShellSessionOpen, 1, 0) == 1) + if (Interlocked.CompareExchange(ref s_anyPowerShellSessionOpen, 1, 0) == 1) return; bool is32Bit; @@ -92,7 +92,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal ProcessName = hostName, }); } - sessionStartTime = DateTime.Now; + s_sessionStartTime = DateTime.Now; } /// @@ -104,15 +104,15 @@ namespace Microsoft.PowerShell.Telemetry.Internal TelemetryWrapper.TraceMessage("PSHostStop", new { InteractiveCommandCount = ihptd != null ? ihptd.InteractiveCommandCount : 0, - TabCompletionTimes = tabCompletionTimes, - TabCompletionCounts = tabCompletionCounts, - TabCompletionResultCounts = tabCompletionResultCounts, - SessionTime = (DateTime.Now - sessionStartTime).TotalMilliseconds + TabCompletionTimes = s_tabCompletionTimes, + TabCompletionCounts = s_tabCompletionCounts, + TabCompletionResultCounts = s_tabCompletionResultCounts, + SessionTime = (DateTime.Now - s_sessionStartTime).TotalMilliseconds }); // In case a host opens another runspace, we will want another PSHostStart event, // so reset our flag here to allow that event to fire. - anyPowerShellSessionOpen = 0; + s_anyPowerShellSessionOpen = 0; } /// @@ -138,24 +138,25 @@ namespace Microsoft.PowerShell.Telemetry.Internal } - private static long[] tabCompletionTimes = new long[(int)CompletionResultType.DynamicKeyword + 1]; - private static int[] tabCompletionCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; - private static int[] tabCompletionResultCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; + private static long[] s_tabCompletionTimes = new long[(int)CompletionResultType.DynamicKeyword + 1]; + private static int[] s_tabCompletionCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; + private static int[] s_tabCompletionResultCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; internal static void ReportTabCompletionTelemetry(long elapsedMilliseconds, int count, CompletionResultType completionResultType) { // We'll collect some general statistics. int idx = (int)completionResultType; if (idx >= 0 && idx <= (int)CompletionResultType.DynamicKeyword) { - tabCompletionTimes[idx] += elapsedMilliseconds; - tabCompletionCounts[idx]++; - tabCompletionResultCounts[idx] += count; + s_tabCompletionTimes[idx] += elapsedMilliseconds; + s_tabCompletionCounts[idx]++; + s_tabCompletionResultCounts[idx] += count; } // Also write an event for any slow tab completion (> 250ms). if (elapsedMilliseconds > 250) { - TelemetryWrapper.TraceMessage("PSSlowTabCompletion", new { + TelemetryWrapper.TraceMessage("PSSlowTabCompletion", new + { Time = elapsedMilliseconds, Count = count, Type = completionResultType, @@ -206,7 +207,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal }); } - enum RemoteSessionType + private enum RemoteSessionType { Unknown, LocalProcess, @@ -215,7 +216,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal ContainerRemote } - enum RemoteConfigurationType + private enum RemoteConfigurationType { Unknown, PSDefault, @@ -310,7 +311,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal } } - enum ScriptFileType + private enum ScriptFileType { None = 0, Ps1 = 1, @@ -319,7 +320,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal Other = 4, } - private static readonly int promptHashCode = "prompt".GetHashCode(); + private static readonly int s_promptHashCode = "prompt".GetHashCode(); /// /// Report some telemetry about the scripts that are run @@ -337,7 +338,7 @@ namespace Microsoft.PowerShell.Telemetry.Internal // Ignore 'prompt' so we don't generate an event for every 'prompt' that is invoked. // (We really should only create 'prompt' once, but we don't. - if (hash == promptHashCode) + if (hash == s_promptHashCode) return; var visitor = new ScriptBlockTelemetry(); @@ -370,41 +371,41 @@ namespace Microsoft.PowerShell.Telemetry.Internal TelemetryWrapper.TraceMessage("PSScriptDetails", new { - Hash = hash, - IsDotSourced = dotSourced, - ScriptFileType = scriptFileType, - Length = text.Length, - LineCount = extent.EndLineNumber - extent.StartLineNumber, - CompileTimeInMS = compileTimeInMS, - StatementCount = visitor.StatementCount, - CountOfCommands = visitor.CountOfCommands, - CountOfDotSourcedCommands = visitor.CountOfDotSourcedCommands, - MaxArrayLength = visitor.MaxArraySize, - ArrayLiteralCount = visitor.ArrayLiteralCount, - ArrayLiteralCumulativeSize = visitor.ArrayLiteralCumulativeSize, - MaxStringLength = visitor.MaxStringSize, - StringLiteralCount = visitor.StringLiteralCount, - StringLiteralCumulativeSize = visitor.StringLiteralCumulativeSize, - MaxPipelineDepth = visitor.MaxPipelineDepth, - PipelineCount = visitor.PipelineCount, - FunctionCount = visitor.FunctionCount, - ScriptBlockCount = visitor.ScriptBlockCount, - ClassCount = visitor.ClassCount, - EnumCount = visitor.EnumCount, - CommandsCalled = visitor.CommandsCalled, + Hash = hash, + IsDotSourced = dotSourced, + ScriptFileType = scriptFileType, + Length = text.Length, + LineCount = extent.EndLineNumber - extent.StartLineNumber, + CompileTimeInMS = compileTimeInMS, + StatementCount = visitor.StatementCount, + CountOfCommands = visitor.CountOfCommands, + CountOfDotSourcedCommands = visitor.CountOfDotSourcedCommands, + MaxArrayLength = visitor.MaxArraySize, + ArrayLiteralCount = visitor.ArrayLiteralCount, + ArrayLiteralCumulativeSize = visitor.ArrayLiteralCumulativeSize, + MaxStringLength = visitor.MaxStringSize, + StringLiteralCount = visitor.StringLiteralCount, + StringLiteralCumulativeSize = visitor.StringLiteralCumulativeSize, + MaxPipelineDepth = visitor.MaxPipelineDepth, + PipelineCount = visitor.PipelineCount, + FunctionCount = visitor.FunctionCount, + ScriptBlockCount = visitor.ScriptBlockCount, + ClassCount = visitor.ClassCount, + EnumCount = visitor.EnumCount, + CommandsCalled = visitor.CommandsCalled, }); }); } } - class ScriptBlockTelemetry : AstVisitor2 + internal class ScriptBlockTelemetry : AstVisitor2 { internal ScriptBlockTelemetry() { CommandsCalled = new Dictionary(StringComparer.OrdinalIgnoreCase); } - internal Dictionary CommandsCalled { get; private set; } + internal Dictionary CommandsCalled { get; private set; } internal int CountOfCommands { get; private set; } internal int CountOfDotSourcedCommands { get; private set; } diff --git a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs index f8c7b1b16..ae4ee06e1 100644 --- a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs +++ b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs @@ -12,8 +12,8 @@ namespace System.Management.Automation.Internal /// internal static class TelemetryWrapper { - private static readonly PSObject eventSourceInstance; - private static readonly object eventSourceOptionsForWrite; + private static readonly PSObject s_eventSourceInstance; + private static readonly object s_eventSourceOptionsForWrite; /// /// Performing EventSource initialization in the Static Constructor since this is thread safe. @@ -52,7 +52,7 @@ namespace System.Management.Automation.Internal new[] { "ETW_GROUP", "{4f50731a-89cf-4782-b3e0-dce8c90476ba}" }}); // Wrap in PSObject so we can invoke a method dynamically using our binder (the C# dynamic binder fails for some reason.) - eventSourceInstance = new PSObject(eventSource); + s_eventSourceInstance = new PSObject(eventSource); // Initialize EventSourceOptions for Writing informational messages // WdiContext will ensure Universal Telemetry Client [UTC] will upload telemetry messages to Cosmos/xPert pipeline @@ -64,23 +64,23 @@ namespace System.Management.Automation.Internal // Create Instance of EventSourceOptions struct Type eventSourceOptionsType = diagnosticsTracingAssembly.GetType("System.Diagnostics.Tracing.EventSourceOptions"); - eventSourceOptionsForWrite = Activator.CreateInstance(eventSourceOptionsType, null); + s_eventSourceOptionsForWrite = Activator.CreateInstance(eventSourceOptionsType, null); // Set the Level and Keywords properties - eventSourceOptionsType.GetProperty("Level").SetValue(eventSourceOptionsForWrite, EventLevel.Informational, null); - eventSourceOptionsType.GetProperty("Keywords").SetValue(eventSourceOptionsForWrite, measuresKeyword, null); + eventSourceOptionsType.GetProperty("Level").SetValue(s_eventSourceOptionsForWrite, EventLevel.Informational, null); + eventSourceOptionsType.GetProperty("Keywords").SetValue(s_eventSourceOptionsForWrite, measuresKeyword, null); } catch { // If there are any exceptions, just disable tracing completely by making sure these are both null - eventSourceInstance = null; - eventSourceOptionsForWrite = null; + s_eventSourceInstance = null; + s_eventSourceOptionsForWrite = null; } } internal static bool IsEnabled { - get { return eventSourceInstance != null && ((EventSource) eventSourceInstance.BaseObject).IsEnabled(); } + get { return s_eventSourceInstance != null && ((EventSource)s_eventSourceInstance.BaseObject).IsEnabled(); } } /// @@ -125,7 +125,7 @@ namespace System.Management.Automation.Internal public static void TraceMessage(string message, T arguments) { - if (null != eventSourceOptionsForWrite) + if (null != s_eventSourceOptionsForWrite) { try { @@ -134,9 +134,9 @@ namespace System.Management.Automation.Internal // method on each call). // We use a PSObject wrapper to force calling the PowerShell binder because the C# binder fails // for an unknown reason. - + // The ETW provider GUID for events written here is: 5037b0a0-3a31-5cd2-ff19-103e9f160a74 - ((dynamic)eventSourceInstance).Write(message, eventSourceOptionsForWrite, arguments); + ((dynamic)s_eventSourceInstance).Write(message, s_eventSourceOptionsForWrite, arguments); } catch { diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index 02f92f2b9..41c2368a5 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -113,32 +113,32 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("errorId"); } - this.invocationInfo = invocationInfo; + _invocationInfo = invocationInfo; - if (this.invocationInfo != null) + if (_invocationInfo != null) { - this.commandName = invocationInfo.MyCommand.Name; + _commandName = invocationInfo.MyCommand.Name; } - this.parameterName = parameterName; - this.parameterType = parameterType; - this.typeSpecified = typeSpecified; + _parameterName = parameterName; + _parameterType = parameterType; + _typeSpecified = typeSpecified; - if ((errorPosition == null) && (this.invocationInfo != null)) + if ((errorPosition == null) && (_invocationInfo != null)) { errorPosition = invocationInfo.ScriptPosition; } if (errorPosition != null) { - this.line = errorPosition.StartLineNumber; - this.offset = errorPosition.StartColumnNumber; + _line = errorPosition.StartLineNumber; + _offset = errorPosition.StartColumnNumber; } - this.resourceString = resourceString; - this.errorId = errorId; + _resourceString = resourceString; + _errorId = errorId; if (args != null) { - this.args = args; + _args = args; } } @@ -237,11 +237,11 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("errorId"); } - this.invocationInfo = invocationInfo; - this.commandName = invocationInfo.MyCommand.Name; - this.parameterName = parameterName; - this.parameterType = parameterType; - this.typeSpecified = typeSpecified; + _invocationInfo = invocationInfo; + _commandName = invocationInfo.MyCommand.Name; + _parameterName = parameterName; + _parameterType = parameterType; + _typeSpecified = typeSpecified; if (errorPosition == null) { @@ -249,16 +249,16 @@ namespace System.Management.Automation } if (errorPosition != null) { - this.line = errorPosition.StartLineNumber; - this.offset = errorPosition.StartColumnNumber; + _line = errorPosition.StartLineNumber; + _offset = errorPosition.StartColumnNumber; } - this.resourceString = resourceString; - this.errorId = errorId; + _resourceString = resourceString; + _errorId = errorId; if (args != null) { - this.args = args; + _args = args; } } @@ -286,37 +286,37 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentException("resourceString"); } - this.invocationInfo = pbex.CommandInvocation; - if(this.invocationInfo != null) + _invocationInfo = pbex.CommandInvocation; + if (_invocationInfo != null) { - this.commandName = this.invocationInfo.MyCommand.Name; + _commandName = _invocationInfo.MyCommand.Name; } IScriptExtent errorPosition = null; - if (this.invocationInfo != null) + if (_invocationInfo != null) { - errorPosition = invocationInfo.ScriptPosition; + errorPosition = _invocationInfo.ScriptPosition; } - this.line = pbex.Line; - this.offset = pbex.Offset; + _line = pbex.Line; + _offset = pbex.Offset; - this.parameterName = pbex.ParameterName; - this.parameterType = pbex.ParameterType; - this.typeSpecified = pbex.TypeSpecified; - this.errorId = pbex.ErrorId; + _parameterName = pbex.ParameterName; + _parameterType = pbex.ParameterType; + _typeSpecified = pbex.TypeSpecified; + _errorId = pbex.ErrorId; - this.resourceString = resourceString; + _resourceString = resourceString; if (args != null) { - this.args = args; + _args = args; } base.SetErrorCategory(pbex.ErrorRecord._category); - base.SetErrorId(errorId); - if (this.invocationInfo != null) + base.SetErrorId(_errorId); + if (_invocationInfo != null) { - base.ErrorRecord.SetInvocationInfo(new InvocationInfo(invocationInfo.MyCommand, errorPosition)); + base.ErrorRecord.SetInvocationInfo(new InvocationInfo(_invocationInfo.MyCommand, errorPosition)); } } #endregion Preferred constructors @@ -334,14 +334,14 @@ namespace System.Management.Automation /// streaming context /// protected ParameterBindingException( - SerializationInfo info, - StreamingContext context) + SerializationInfo info, + StreamingContext context) : base(info, context) { - message = info.GetString("ParameterBindingException_Message"); - parameterName = info.GetString("ParameterName"); - line = info.GetInt64("Line"); - offset = info.GetInt64("Offset"); + _message = info.GetString("ParameterBindingException_Message"); + _parameterName = info.GetString("ParameterName"); + _line = info.GetInt64("Line"); + _offset = info.GetInt64("Offset"); } /// @@ -365,9 +365,9 @@ namespace System.Management.Automation base.GetObjectData(info, context); info.AddValue("ParameterBindingException_Message", this.Message); - info.AddValue("ParameterName", parameterName); - info.AddValue("Line", line); - info.AddValue("Offset", offset); + info.AddValue("ParameterName", _parameterName); + info.AddValue("Line", _line); + info.AddValue("Offset", _offset); } #endregion serialization @@ -380,7 +380,7 @@ namespace System.Management.Automation /// /// DO NOT USE!!! /// - public ParameterBindingException() : base() { ;} + public ParameterBindingException() : base() {; } /// /// Constructors a ParameterBindingException @@ -393,7 +393,7 @@ namespace System.Management.Automation /// /// DO NOT USE!!! /// - public ParameterBindingException(string message) : base(message) { this.message = message; } + public ParameterBindingException(string message) : base(message) { _message = message; } /// /// Constructs a ParameterBindingException @@ -411,9 +411,10 @@ namespace System.Management.Automation /// DO NOT USE!!! /// public ParameterBindingException( - string message, - Exception innerException) - : base (message, innerException) { this.message = message;} + string message, + Exception innerException) + : base(message, innerException) + { _message = message; } #endregion Do Not Use #endregion Constructors @@ -426,15 +427,15 @@ namespace System.Management.Automation { get { - if (message == null) + if (_message == null) { - message = BuildMessage(); + _message = BuildMessage(); } - return message; + return _message; } } - private string message; + private string _message; /// /// Gets the name of the parameter that the parameter binding @@ -444,10 +445,10 @@ namespace System.Management.Automation { get { - return parameterName; + return _parameterName; } } - private string parameterName = String.Empty; + private string _parameterName = String.Empty; /// /// Gets the type the parameter is expecting. @@ -456,10 +457,10 @@ namespace System.Management.Automation { get { - return parameterType; + return _parameterType; } } - private Type parameterType; + private Type _parameterType; /// /// Gets the Type that was specified as the parameter value @@ -468,10 +469,10 @@ namespace System.Management.Automation { get { - return typeSpecified; + return _typeSpecified; } } - private Type typeSpecified; + private Type _typeSpecified; /// /// Gets the errorId of this ParameterBindingException @@ -480,10 +481,10 @@ namespace System.Management.Automation { get { - return errorId; + return _errorId; } } - private string errorId; + private string _errorId; /// /// Gets the line in the script at which the error occurred. @@ -492,10 +493,10 @@ namespace System.Management.Automation { get { - return line; + return _line; } } - private Int64 line = Int64.MinValue; + private Int64 _line = Int64.MinValue; /// /// Gets the offset on the line in the script at which the error occurred. @@ -504,10 +505,10 @@ namespace System.Management.Automation { get { - return offset; + return _offset; } } - private Int64 offset = Int64.MinValue; + private Int64 _offset = Int64.MinValue; /// /// Gets the invocation information about the command. @@ -516,39 +517,39 @@ namespace System.Management.Automation { get { - return invocationInfo; + return _invocationInfo; } } - private InvocationInfo invocationInfo; + private InvocationInfo _invocationInfo; #endregion Properties #region private - private string resourceString; - private object[] args = new object[0]; - private string commandName; + private string _resourceString; + private object[] _args = new object[0]; + private string _commandName; - private string BuildMessage() + private string BuildMessage() { object[] messageArgs = new object[0]; - if (args != null) + if (_args != null) { - messageArgs = new object[args.Length + 6]; - messageArgs[0] = commandName; - messageArgs[1] = parameterName; - messageArgs[2] = parameterType; - messageArgs[3] = typeSpecified; - messageArgs[4] = line; - messageArgs[5] = offset; - args.CopyTo(messageArgs, 6); + messageArgs = new object[_args.Length + 6]; + messageArgs[0] = _commandName; + messageArgs[1] = _parameterName; + messageArgs[2] = _parameterType; + messageArgs[3] = _typeSpecified; + messageArgs[4] = _line; + messageArgs[5] = _offset; + _args.CopyTo(messageArgs, 6); } string result = String.Empty; - if (!String.IsNullOrEmpty(resourceString)) + if (!String.IsNullOrEmpty(_resourceString)) { - result = StringUtil.Format(resourceString, messageArgs); + result = StringUtil.Format(_resourceString, messageArgs); } return result; } @@ -630,11 +631,11 @@ namespace System.Management.Automation string errorId, params object[] args) : base( - errorCategory, - invocationInfo, + errorCategory, + invocationInfo, errorPosition, - parameterName, - parameterType, + parameterName, + parameterType, typeSpecified, resourceString, errorId, @@ -721,11 +722,11 @@ namespace System.Management.Automation params object[] args) : base( innerException, - errorCategory, + errorCategory, invocationInfo, - errorPosition, - parameterName, - parameterType, + errorPosition, + parameterName, + parameterType, typeSpecified, resourceString, errorId, @@ -734,7 +735,7 @@ namespace System.Management.Automation ValidationMetadataException validationException = innerException as ValidationMetadataException; if (validationException != null && validationException.SwallowException) { - this._swallowException = true; + _swallowException = true; } } #endregion Preferred constructors @@ -752,8 +753,8 @@ namespace System.Management.Automation /// streaming context /// protected ParameterBindingValidationException( - SerializationInfo info, - StreamingContext context) + SerializationInfo info, + StreamingContext context) : base(info, context) { } @@ -943,11 +944,11 @@ namespace System.Management.Automation params object[] args) : base( innerException, - errorCategory, - invocationInfo, - errorPosition, - parameterName, - parameterType, + errorCategory, + invocationInfo, + errorPosition, + parameterName, + parameterType, typeSpecified, resourceString, errorId, @@ -968,8 +969,8 @@ namespace System.Management.Automation /// streaming context /// protected ParameterBindingArgumentTransformationException( - SerializationInfo info, - StreamingContext context) + SerializationInfo info, + StreamingContext context) : base(info, context) { } @@ -1051,11 +1052,11 @@ namespace System.Management.Automation string errorId, params object[] args) : base( - errorCategory, - invocationInfo, - errorPosition, - parameterName, - parameterType, + errorCategory, + invocationInfo, + errorPosition, + parameterName, + parameterType, typeSpecified, resourceString, errorId, @@ -1142,11 +1143,11 @@ namespace System.Management.Automation params object[] args) : base( innerException, - errorCategory, - invocationInfo, - errorPosition, - parameterName, - parameterType, + errorCategory, + invocationInfo, + errorPosition, + parameterName, + parameterType, typeSpecified, resourceString, errorId, @@ -1169,13 +1170,12 @@ namespace System.Management.Automation /// protected ParameterBindingParameterDefaultValueException( SerializationInfo info, - StreamingContext context) + StreamingContext context) : base(info, context) { } #endregion serialization } - } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index fb7a82f2d..76ecfc728 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -125,7 +125,7 @@ namespace System.Management.Automation /// constructed object public ParseException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { base.SetErrorId(errorIdString); base.SetErrorCategory(ErrorCategory.ParserError); @@ -136,7 +136,7 @@ namespace System.Management.Automation /// /// The collection of error messages. [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", - Justification="ErrorRecord is not overridden in classes deriving from ParseException")] + Justification = "ErrorRecord is not overridden in classes deriving from ParseException")] public ParseException(Language.ParseError[] errors) { if ((errors == null) || (errors.Length == 0)) @@ -267,7 +267,7 @@ namespace System.Management.Automation /// constructed object public IncompleteParseException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { // Error category is set in base constructor base.SetErrorId(errorIdString); diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index b8008857d..c240b6b5a 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -318,42 +318,42 @@ namespace System.Management.Automation { string msg = StringUtil.Format(PathUtilsStrings.OutFile_ReadWriteFileNotFileSystemProvider, providerId); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(), "ReadWriteFileNotFileSystemProvider", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - cmdlet.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + cmdlet.ThrowTerminatingError(errorRecord); } internal static void ReportMultipleFilesNotSupported(Cmdlet cmdlet) { string msg = StringUtil.Format(PathUtilsStrings.OutFile_MultipleFilesNotSupported); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(), "ReadWriteMultipleFilesNotSupported", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); - cmdlet.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + cmdlet.ThrowTerminatingError(errorRecord); } internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath) { string msg = StringUtil.Format(PathUtilsStrings.OutFile_DidNotResolveFile, filePath); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( new FileNotFoundException(), "FileOpenFailure", ErrorCategory.OpenError, filePath); - errorRecord.ErrorDetails = new ErrorDetails (msg); - cmdlet.ThrowTerminatingError (errorRecord); + errorRecord.ErrorDetails = new ErrorDetails(msg); + cmdlet.ThrowTerminatingError(errorRecord); } internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) @@ -438,7 +438,6 @@ namespace System.Management.Automation Directory.CreateDirectory(moduleDirectory.FullName); return new DirectoryInfo(moduleDirectory.FullName); } - } internal static class EncodingConversion @@ -459,8 +458,8 @@ namespace System.Management.Automation /// it throws if the encoding does not match the known ones /// /// a System.Text.Encoding object (null if no encoding specified) - internal static Encoding Convert (Cmdlet cmdlet, string encoding) - { + internal static Encoding Convert(Cmdlet cmdlet, string encoding) + { if (string.IsNullOrEmpty(encoding)) { // no parameter passed, default to Unicode (OS preferred) @@ -475,22 +474,22 @@ namespace System.Management.Automation return System.Text.Encoding.Unicode; // these are the encodings the CLR supports - if (string.Equals (encoding, Unicode, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(encoding, Unicode, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.Unicode; - if (string.Equals (encoding, BigEndianUnicode, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(encoding, BigEndianUnicode, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.BigEndianUnicode; - if (string.Equals (encoding, Utf8, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(encoding, Utf8, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.UTF8; if (string.Equals(encoding, Ascii, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.ASCII; - if (string.Equals (encoding, Utf7, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.UTF7; - if (string.Equals (encoding, Utf32, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(encoding, Utf32, StringComparison.OrdinalIgnoreCase)) return System.Text.Encoding.UTF32; if (string.Equals(encoding, Default, StringComparison.OrdinalIgnoreCase)) @@ -508,13 +507,13 @@ namespace System.Management.Automation string msg = StringUtil.Format(PathUtilsStrings.OutFile_WriteToFileEncodingUnknown, encoding, validEncodingValues); - ErrorRecord errorRecord = new ErrorRecord ( + ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Encoding"), "WriteToFileEncodingUnknown", ErrorCategory.InvalidArgument, null); - errorRecord.ErrorDetails = new ErrorDetails (msg); + errorRecord.ErrorDetails = new ErrorDetails(msg); cmdlet.ThrowTerminatingError(errorRecord); return null; diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index f181fc283..44fd3dd69 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -36,13 +36,15 @@ namespace System.Management.Automation dwHighDateTime = 0; } - internal FILETIME(long fileTime) { - dwLowDateTime = (uint) fileTime; - dwHighDateTime = (uint) (fileTime >> 32); + internal FILETIME(long fileTime) + { + dwLowDateTime = (uint)fileTime; + dwHighDateTime = (uint)(fileTime >> 32); } - public long ToTicks() { - return ((long) dwHighDateTime << 32) + dwLowDateTime; + public long ToTicks() + { + return ((long)dwHighDateTime << 32) + dwLowDateTime; } }; @@ -156,7 +158,6 @@ namespace System.Management.Automation : base(ownsHandle) { base.SetHandle(existingHandle); - } [DllImport(PinvokeDllNames.LocalFreeDllName), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] @@ -164,7 +165,6 @@ namespace System.Management.Automation protected override bool ReleaseHandle() { return (LocalFree(base.handle) == IntPtr.Zero); - } } diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 3b58a2fc8..be60b2576 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -15,7 +15,7 @@ using System.Management.Automation.Internal; namespace System.Management.Automation.Tracing { //pragma warning disable 16001,16003 - #region Constants +#region Constants /// /// Defines enumerations for event ids @@ -29,7 +29,7 @@ namespace System.Management.Automation.Tracing /// None. (Should not be used) /// None = 0, - + /// /// HostNameResolve /// @@ -279,7 +279,7 @@ namespace System.Management.Automation.Tracing /// SerializerWorkflowLoadSuccess /// SerializerWorkflowLoadSuccess = 0x7001, - + /// /// SerializerWorkflowLoadFailure /// @@ -366,12 +366,12 @@ namespace System.Management.Automation.Tracing /// /// Writing a simple trace message from code /// - TraceMessage=0xB005, + TraceMessage = 0xB005, /// /// Trace the WSManConnectionInfo used for this connection /// - TraceWSManConnectionInfo=0xB006, + TraceWSManConnectionInfo = 0xB006, /// /// Writing a simple trace message from code with 2 @@ -384,7 +384,6 @@ namespace System.Management.Automation.Tracing /// strings /// TraceMessageGuid = 0xC002, - } /// @@ -464,7 +463,7 @@ namespace System.Management.Automation.Tracing /// None. (Should not be used) /// None = 0, - + /// /// Open /// @@ -620,9 +619,9 @@ namespace System.Management.Automation.Tracing /// /// Defines Keywords. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028")] [Flags] - public enum PowerShellTraceKeywords : ulong + public enum PowerShellTraceKeywords : ulong { /// /// None @@ -690,7 +689,7 @@ namespace System.Management.Automation.Tracing UseAlwaysAnalytic = 0x4000000000000000, } - #endregion +#endregion /// /// BaseChannelWriter is the abstract base class defines event specific methods that are used to write a trace. @@ -699,12 +698,14 @@ namespace System.Management.Automation.Tracing public abstract class BaseChannelWriter : IDisposable { private bool disposed; - + /// /// Dispose method /// - public virtual void Dispose() { - if (!disposed) { + public virtual void Dispose() + { + if (!disposed) + { GC.SuppressFinalize(this); disposed = true; } @@ -770,16 +771,16 @@ namespace System.Management.Automation.Tracing /// /// public virtual PowerShellTraceKeywords Keywords - { + { get { - return PowerShellTraceKeywords.None; + return PowerShellTraceKeywords.None; } set { PowerShellTraceKeywords powerShellTraceKeywords = value; } - } + } } /// @@ -802,7 +803,7 @@ namespace System.Management.Automation.Tracing return nullWriter; } } - + private NullWriter() { } @@ -821,7 +822,7 @@ namespace System.Management.Automation.Tracing * Making the provider static to reduce the number of buffers needed to 1. * */ private static readonly EventProvider _provider = new EventProvider(new Guid("A0C1853B-5C40-4b15-8766-3CF1C58F985A")); - + private bool disposed; private PowerShellTraceKeywords _keywords; @@ -851,7 +852,7 @@ namespace System.Management.Automation.Tracing /// public override void Dispose() { - if (!disposed) + if (!disposed) { GC.SuppressFinalize(this); disposed = true; @@ -861,8 +862,8 @@ namespace System.Management.Automation.Tracing private bool Trace(PowerShellTraceEvent traceEvent, PowerShellTraceLevel level, PowerShellTraceOperationCode operationCode, PowerShellTraceTask task, params object[] args) { - EventDescriptor ed = new EventDescriptor((int) traceEvent, 1, (byte) _traceChannel, (byte) level, - (byte) operationCode, (int) task, (long) _keywords); + EventDescriptor ed = new EventDescriptor((int)traceEvent, 1, (byte)_traceChannel, (byte)level, + (byte)operationCode, (int)task, (long)_keywords); /* * Not using locks because the _provider is thread safe itself. @@ -956,7 +957,7 @@ namespace System.Management.Automation.Tracing private readonly BaseChannelWriter operationsChannel; private bool disposed; - + /// /// Consturctor /// @@ -987,7 +988,7 @@ namespace System.Management.Automation.Tracing /// public void Dispose() { - if (!disposed) + if (!disposed) { disposed = true; GC.SuppressFinalize(this); @@ -1037,18 +1038,20 @@ namespace System.Management.Automation.Tracing /// public bool TraceErrorRecord(ErrorRecord errorRecord) { - if (errorRecord != null) + if (errorRecord != null) { Exception exception = errorRecord.Exception; string innerException = "None"; - if (exception.InnerException != null) { + if (exception.InnerException != null) + { innerException = exception.InnerException.Message; } ErrorCategoryInfo cinfo = errorRecord.CategoryInfo; string message = "None"; - if (errorRecord.ErrorDetails != null) { + if (errorRecord.ErrorDetails != null) + { message = errorRecord.ErrorDetails.Message; } return debugChannel.TraceError(PowerShellTraceEvent.ErrorRecord, @@ -1057,8 +1060,8 @@ namespace System.Management.Automation.Tracing cinfo.Category.ToString(), cinfo.Reason, cinfo.TargetName, errorRecord.FullyQualifiedErrorId, exception.Message, exception.StackTrace, innerException); - } - else + } + else { return debugChannel.TraceError(PowerShellTraceEvent.ErrorRecord, PowerShellTraceOperationCode.Exception, PowerShellTraceTask.None, @@ -1071,9 +1074,11 @@ namespace System.Management.Automation.Tracing /// public bool TraceException(Exception exception) { - if (exception != null) { + if (exception != null) + { string innerException = "None"; - if (exception.InnerException != null) { + if (exception.InnerException != null) + { innerException = exception.InnerException.Message; } @@ -1083,7 +1088,6 @@ namespace System.Management.Automation.Tracing } else { - return debugChannel.TraceError(PowerShellTraceEvent.Exception, PowerShellTraceOperationCode.Exception, PowerShellTraceTask.None, "NULL exception"); @@ -1112,7 +1116,7 @@ namespace System.Management.Automation.Tracing job.Location, job.JobStateInfo.State.ToString(), job.Command); } - else + else { return debugChannel.TraceDebug(PowerShellTraceEvent.Job, PowerShellTraceOperationCode.Method, PowerShellTraceTask.None, @@ -1129,7 +1133,7 @@ namespace System.Management.Automation.Tracing { return debugChannel.TraceInformational(PowerShellTraceEvent.TraceMessage, PowerShellTraceOperationCode.None, - PowerShellTraceTask.None, message); + PowerShellTraceTask.None, message); } /// @@ -1142,8 +1146,7 @@ namespace System.Management.Automation.Tracing { return debugChannel.TraceInformational(PowerShellTraceEvent.TraceMessage2, PowerShellTraceOperationCode.None, - PowerShellTraceTask.None, message1, message2); - + PowerShellTraceTask.None, message1, message2); } /// @@ -1156,8 +1159,7 @@ namespace System.Management.Automation.Tracing { return debugChannel.TraceInformational(PowerShellTraceEvent.TraceMessageGuid, PowerShellTraceOperationCode.None, - PowerShellTraceTask.None, message, instanceId); - + PowerShellTraceTask.None, message, instanceId); } @@ -1197,7 +1199,7 @@ namespace System.Management.Automation.Tracing { StringBuilder sb = new StringBuilder(); - if(job != null) + if (job != null) { try { @@ -1210,7 +1212,7 @@ namespace System.Management.Automation.Tracing } catch (Exception e) { - CommandProcessorBase.CheckForSevereException(e); + CommandProcessorBase.CheckForSevereException(e); // Exception in 3rd party code should never cause a crash due to tracing. The // Implementation of the property getters could throw. TraceException(e); diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index bbfbafff3..32a3a3849 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -64,13 +64,13 @@ namespace System.Management.Automation int caughtCount = 0; ProcessModule mainModule = null; - while(mainModule == null) + while (mainModule == null) { try { mainModule = targetProcess.MainModule; } - catch(System.ComponentModel.Win32Exception e) + catch (System.ComponentModel.Win32Exception e) { // If this is an Access Denied error (which can happen with thread impersonation) // then re-throw immediately. @@ -105,7 +105,7 @@ namespace System.Management.Automation /// parent of internal static Process GetParentProcess(Process current) { - string wmiQuery = String.Format(CultureInfo.CurrentCulture, + string wmiQuery = String.Format(CultureInfo.CurrentCulture, "Select * From Win32_Process Where Handle='{0}'", current.Id); @@ -186,7 +186,7 @@ namespace System.Management.Automation const string v4KeyName = @"v4\Client"; const string install = "Install"; const string oneToThreePointFivePrefix = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\"; - + // In .NET 4.5, there is no concept of Client and Full. There is only the full redistributable package available // http://msdn.microsoft.com/en-us/library/cc656912(VS.110).aspx const string v45KeyName = @"v4\Full"; @@ -334,7 +334,7 @@ namespace System.Management.Automation private static Version V3_0_00 = new Version(3, 0, 0, 0); private static Version V2_0_00 = new Version(2, 0, 0, 0); private static Version V1_1_00 = new Version(1, 1, 0, 0); - + // Dictionary holding compatible .NET framework versions // This is used in verifying the .NET framework version for loading module manifest internal static Dictionary> CompatibleNetFrameworkVersions = new Dictionary>() { @@ -347,7 +347,7 @@ namespace System.Management.Automation }; // .NET 4.5 is the highest known .NET version for PowerShell 3.0 - internal static Version KnownHighestNetFrameworkVersion = new Version(4,5); + internal static Version KnownHighestNetFrameworkVersion = new Version(4, 5); /// /// Returns true if IsFrameworkInstalled will be able to check for this framework version. @@ -504,7 +504,7 @@ namespace System.Management.Automation } // The detection logic for .NET 4.5 is to check for the existence of a DWORD key named Release under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full folder in the registry. // For .NET 4.5, the value of this key is the release number and not 1 (Install = 1 for .NET 3.5, .NET 4.0) . So, we need to bypasss the check below - if ((majorVersion != 4 && minorVersion != 5 ) && (installValue != 1)) + if ((majorVersion != 4 && minorVersion != 5) && (installValue != 1)) { Debug.Assert(PSVersionInfo.CLRVersion.Major == 4, "This check is valid only for CLR Version 4.0 and .NET Version 4.5"); return false; @@ -559,7 +559,7 @@ namespace System.Management.Automation result = ProcessorArchitecture.None; isRunningOnArm = true; break; - + default: result = ProcessorArchitecture.None; break; @@ -610,7 +610,7 @@ namespace System.Management.Automation internal static string WinGetHostName() { - System.Net.NetworkInformation.IPGlobalProperties ipProperties = + System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); string hostname = ipProperties.HostName; @@ -735,8 +735,8 @@ namespace System.Management.Automation parameterName, psDataFilePath, context, - Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets, - new[] {"PSScriptRoot"}, + Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets, + new[] { "PSScriptRoot" }, allowEnvironmentVariables: true, skipPathValidation: skipPathValidation); } @@ -876,9 +876,9 @@ namespace System.Management.Automation #endregion EvaluatePowerShellDataFile - internal static readonly string[] ManifestModuleVersionPropertyName = new[] {"ModuleVersion"}; + internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" }; internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" }; - internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] {"AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion"}; + internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] { "AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion" }; internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys) { @@ -924,7 +924,6 @@ namespace System.Management.Automation } return result; } - } throw PSTraceSource.NewInvalidOperationException( diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index d95e2bf64..ebdfa5306 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -19,13 +19,13 @@ namespace System.Management.Automation /// to the default resource assembly. The value is another dictionary that is keyed based on the base /// name for the resource that is being retrieved. The value for this dictionary is the ResourceManager. /// - static private Dictionary> resourceManagerCache = + static private Dictionary> s_resourceManagerCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); /// /// Used to synchronize access to the ResourceManagerCache /// - static object syncRoot = new Object(); + private static object s_syncRoot = new Object(); /// /// Gets the ResourceManager from the cache or gets an instance of the ResourceManager @@ -44,7 +44,7 @@ namespace System.Management.Automation /// A ResourceManager instance for the assembly and base name that were specified. /// /// - static internal ResourceManager GetResourceManager ( + static internal ResourceManager GetResourceManager( Assembly assembly, string baseName) { @@ -64,11 +64,11 @@ namespace System.Management.Automation Dictionary baseNameCache; string assemblyManifestFileLocation = assembly.Location; - lock (syncRoot) + lock (s_syncRoot) { // First do the lookup based on the assembly location - if (resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache != null) + if (s_resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache != null) { // Now do the lookup based on the resource base name baseNameCache.TryGetValue(baseName, out manager); @@ -78,13 +78,13 @@ namespace System.Management.Automation // If its not in the cache, create it an add it. if (manager == null) { - manager = InitRMWithAssembly (baseName, assembly); + manager = InitRMWithAssembly(baseName, assembly); // Add the new resource manager to the hash if (baseNameCache != null) { - lock (syncRoot) + lock (s_syncRoot) { // Since the assembly is already cached, we just have // to cache the base name entry @@ -98,19 +98,19 @@ namespace System.Management.Automation // cache entry and then add it into the cache keyed by the assembly // location - var baseNameCacheEntry = new Dictionary (); + var baseNameCacheEntry = new Dictionary(); baseNameCacheEntry[baseName] = manager; - lock (syncRoot) + lock (s_syncRoot) { - resourceManagerCache[assemblyManifestFileLocation] = baseNameCacheEntry; + s_resourceManagerCache[assemblyManifestFileLocation] = baseNameCacheEntry; } } } - Diagnostics.Assert ( - manager != null, + Diagnostics.Assert( + manager != null, "If the manager was not already created, it should have been dynamically created or an exception should have been thrown"); return manager; @@ -119,11 +119,11 @@ namespace System.Management.Automation /// /// Design For Testability -- assert on failed resource lookup /// - private static bool DFT_monitorFailingResourceLookup = true; + private static bool s_DFT_monitorFailingResourceLookup = true; static internal bool DFT_DoMonitorFailingResourceLookup { - get { return ResourceManagerCache.DFT_monitorFailingResourceLookup; } - set { ResourceManagerCache.DFT_monitorFailingResourceLookup = value; } + get { return ResourceManagerCache.s_DFT_monitorFailingResourceLookup; } + set { ResourceManagerCache.s_DFT_monitorFailingResourceLookup = value; } } /// @@ -158,29 +158,29 @@ namespace System.Management.Automation /// MissingManifestResourceException if no usable set of resources have been found, and /// there are no neutral culture resources. /// - static internal string GetResourceString ( + static internal string GetResourceString( Assembly assembly, string baseName, string resourceId) { if (assembly == null) { - throw PSTraceSource.NewArgumentNullException ("assembly"); + throw PSTraceSource.NewArgumentNullException("assembly"); } - if (String.IsNullOrEmpty (baseName)) + if (String.IsNullOrEmpty(baseName)) { - throw PSTraceSource.NewArgumentException ("baseName"); + throw PSTraceSource.NewArgumentException("baseName"); } - if (String.IsNullOrEmpty (resourceId)) + if (String.IsNullOrEmpty(resourceId)) { - throw PSTraceSource.NewArgumentException ("resourceId"); + throw PSTraceSource.NewArgumentException("resourceId"); } - ResourceManager resourceManager = GetResourceManager (assembly, baseName); - string text = resourceManager.GetString (resourceId); - if (String.IsNullOrEmpty(text) && DFT_monitorFailingResourceLookup) + ResourceManager resourceManager = GetResourceManager(assembly, baseName); + string text = resourceManager.GetString(resourceId); + if (String.IsNullOrEmpty(text) && s_DFT_monitorFailingResourceLookup) { Diagnostics.Assert(false, "Lookup failure: baseName " + baseName + " resourceId " + resourceId); @@ -209,7 +209,7 @@ namespace System.Management.Automation if (baseName != null && assemblyToUse != null) { - rm = new ResourceManager (baseName, assemblyToUse); + rm = new ResourceManager(baseName, assemblyToUse); } else { @@ -220,7 +220,6 @@ namespace System.Management.Automation return rm; } - } // class ResourceManagerCache } // namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index b45a725d5..ac035672d 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -95,7 +95,7 @@ namespace System.Management.Automation /// constructed object public RuntimeException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } @@ -110,9 +110,9 @@ namespace System.Management.Automation public RuntimeException(string message, Exception innerException, ErrorRecord errorRecord) - : base (message, innerException) + : base(message, innerException) { - this._errorRecord = errorRecord; + _errorRecord = errorRecord; } internal RuntimeException(ErrorCategory errorCategory, @@ -164,8 +164,8 @@ namespace System.Management.Automation { if (null == _errorRecord) { - _errorRecord = new ErrorRecord ( - new ParentContainsErrorRecordException (this), + _errorRecord = new ErrorRecord( + new ParentContainsErrorRecordException(this), _errorId, _errorCategory, _targetObject); @@ -273,10 +273,10 @@ namespace System.Management.Automation /// public bool WasThrownFromThrowStatement { - get { return thrownByThrowStatement; } - set - { - thrownByThrowStatement = value; + get { return _thrownByThrowStatement; } + set + { + _thrownByThrowStatement = value; if (_errorRecord != null) { RuntimeException exception = _errorRecord.Exception as RuntimeException; @@ -287,7 +287,7 @@ namespace System.Management.Automation } } } - private bool thrownByThrowStatement; + private bool _thrownByThrowStatement; /// /// fix for BUG: Windows Out Of Band Releases: 906263 and 906264 @@ -298,10 +298,10 @@ namespace System.Management.Automation /// internal bool SuppressPromptInInterpreter { - get { return suppressPromptInInterpreter; } - set { suppressPromptInInterpreter = value; } + get { return _suppressPromptInInterpreter; } + set { _suppressPromptInInterpreter = value; } } - private bool suppressPromptInInterpreter; + private bool _suppressPromptInInterpreter; #endregion Internal diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 6277765ea..e3c356b03 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -28,7 +28,7 @@ namespace System.Management.Automation /// /// Constructs a ProviderInvocationException /// - public ProviderInvocationException () : base() + public ProviderInvocationException() : base() { } @@ -46,7 +46,7 @@ namespace System.Management.Automation protected ProviderInvocationException( SerializationInfo info, StreamingContext context) - : base (info, context) + : base(info, context) { } @@ -58,7 +58,7 @@ namespace System.Management.Automation /// The message for the exception. /// public ProviderInvocationException(string message) - : base(message) + : base(message) { _message = message; } @@ -74,17 +74,16 @@ namespace System.Management.Automation /// /// The inner exception for this exception. /// - internal ProviderInvocationException(ProviderInfo provider, Exception innerException) - : base (RuntimeException.RetrieveMessage(innerException), innerException) + internal ProviderInvocationException(ProviderInfo provider, Exception innerException) + : base(RuntimeException.RetrieveMessage(innerException), innerException) { - _message = base.Message; _providerInfo = provider; IContainsErrorRecord icer = innerException as IContainsErrorRecord; if (null != icer && null != icer.ErrorRecord) { - _errorRecord = new ErrorRecord (icer.ErrorRecord, innerException); + _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } else { @@ -108,13 +107,13 @@ namespace System.Management.Automation /// /// Detailed error information /// - internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRecord) - : base (RuntimeException.RetrieveMessage(errorRecord), + internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRecord) + : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { if (null == errorRecord) { - throw new ArgumentNullException ("errorRecord"); + throw new ArgumentNullException("errorRecord"); } _message = base.Message; @@ -135,7 +134,7 @@ namespace System.Management.Automation /// The inner exception for this exception. /// public ProviderInvocationException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { _message = message; } @@ -209,14 +208,14 @@ namespace System.Management.Automation /// an ErrorRecord. If false, the error message retrieved using the errorId will be used. /// /// - internal ProviderInvocationException ( + internal ProviderInvocationException( string errorId, string resourceStr, ProviderInfo provider, string path, Exception innerException, bool useInnerExceptionMessage) - : base ( + : base( RetrieveMessage(errorId, resourceStr, provider, path, innerException), innerException) { @@ -241,7 +240,7 @@ namespace System.Management.Automation } else { - _errorRecord = new ErrorRecord ( + _errorRecord = new ErrorRecord( errorRecordException, errorId, ErrorCategory.InvalidOperation, @@ -281,12 +280,12 @@ namespace System.Management.Automation #endregion Properties #region Private/Internal - private static string RetrieveMessage ( + private static string RetrieveMessage( string errorId, string resourceStr, ProviderInfo provider, string path, - Exception innerException) + Exception innerException) { if (null == innerException) { @@ -294,25 +293,25 @@ namespace System.Management.Automation "ProviderInvocationException.RetrieveMessage needs innerException"); return ""; } - if (String.IsNullOrEmpty (errorId)) + if (String.IsNullOrEmpty(errorId)) { - Diagnostics.Assert (false, + Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs errorId"); return RuntimeException.RetrieveMessage(innerException); } if (null == provider) { - Diagnostics.Assert (false, + Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs provider"); - return RuntimeException.RetrieveMessage (innerException); + return RuntimeException.RetrieveMessage(innerException); } string format = resourceStr; - if (String.IsNullOrEmpty (format)) + if (String.IsNullOrEmpty(format)) { - Diagnostics.Assert (false, + Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage bad errorId " + errorId); - return RuntimeException.RetrieveMessage (innerException); + return RuntimeException.RetrieveMessage(innerException); } string result = null; @@ -440,7 +439,7 @@ namespace System.Management.Automation string resourceStr, ErrorCategory errorCategory, params object[] messageArgs) - : base (BuildMessage(itemName,resourceStr,messageArgs)) + : base(BuildMessage(itemName, resourceStr, messageArgs)) { _itemName = itemName; _sessionStateCategory = sessionStateCategory; @@ -481,7 +480,7 @@ namespace System.Management.Automation /// public SessionStateException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -661,7 +660,7 @@ namespace System.Management.Automation /// public SessionStateOverflowException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -757,7 +756,7 @@ namespace System.Management.Automation /// public SessionStateUnauthorizedAccessException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -818,9 +817,9 @@ namespace System.Management.Automation string resourceStr, params object[] messageArgs) : base( - itemName, + itemName, sessionStateCategory, - errorIdAndResourceId, + errorIdAndResourceId, resourceStr, ErrorCategory.ObjectNotFound, messageArgs) @@ -857,7 +856,7 @@ namespace System.Management.Automation /// public ProviderNotFoundException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -1059,7 +1058,7 @@ namespace System.Management.Automation /// public DriveNotFoundException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor @@ -1145,7 +1144,7 @@ namespace System.Management.Automation /// public ItemNotFoundException(string message, Exception innerException) - : base (message, innerException) + : base(message, innerException) { } #endregion ctor diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index f61e4da0b..87241c385 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -27,9 +27,9 @@ namespace System.Management.Automation.Internal return String.Format(System.Globalization.CultureInfo.CurrentCulture, formatSpec, o1, o2); } - - - internal static + + + internal static string Format(string formatSpec, params object[] o) { diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index f2c218aa3..b00810716 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -14,7 +14,6 @@ using System.Threading; namespace System.Management.Automation { - #region PSTraceSourceOptions /// /// These flags enable tracing based on the types of @@ -111,7 +110,7 @@ namespace System.Management.Automation /// - Error = 0x00000200, + Error = 0x00000200, /// /// Warnings will be traced @@ -152,13 +151,13 @@ namespace System.Management.Automation /// The methods associated with the flags; Constructor, Dispose, /// Finalizer, Method, Delegates, and Events will be enabled /// - ExecutionFlow = - Constructor | - Dispose | - Finalizer | - Method | - Delegates | - Events | + ExecutionFlow = + Constructor | + Dispose | + Finalizer | + Method | + Delegates | + Events | Scope, /// @@ -169,12 +168,12 @@ namespace System.Management.Automation /// The methods associated with the flags; Constructor, Dispose, /// Finalizer, Property, and WriteLine will be enabled /// - Data = - Constructor | - Dispose | - Finalizer | - Property | - Verbose | + Data = + Constructor | + Dispose | + Finalizer | + Property | + Verbose | WriteLine, /// @@ -184,8 +183,8 @@ namespace System.Management.Automation /// The methods associated with the flags; Error, /// and Exception will be enabled /// - Errors = - Error | + Errors = + Error | Exception, /// @@ -195,23 +194,22 @@ namespace System.Management.Automation /// /// All methods for tracing will be enabled. /// - All = - Constructor | - Dispose | - Finalizer | - Method | - Property | - Delegates | - Events | - Exception | - Error | - Warning | - Verbose | - Lock | - WriteLine | - Scope | + All = + Constructor | + Dispose | + Finalizer | + Method | + Property | + Delegates | + Events | + Exception | + Error | + Warning | + Verbose | + Lock | + WriteLine | + Scope | Assert - } #endregion PSTraceSourceOptions @@ -279,7 +277,7 @@ namespace System.Management.Automation /// internal PSTraceSource(string fullName, string name, string description, bool traceHeaders) { - if (String.IsNullOrEmpty (fullName)) + if (String.IsNullOrEmpty(fullName)) { // 2005/04/13-JonN In theory this should be ArgumentException, // but I don't want to deal with loading the string in this @@ -289,8 +287,8 @@ namespace System.Management.Automation try { - this.fullName = fullName; - this.name = name; + _fullName = fullName; + _name = name; #if !CORECLR // TraceSource.Attributes is not in CoreCLR string tracingEnvVar = Environment.GetEnvironmentVariable("MshEnableTrace"); @@ -303,19 +301,19 @@ namespace System.Management.Automation string options = this.TraceSource.Attributes["Options"]; if (options != null) { - flags = (PSTraceSourceOptions)Enum.Parse(typeof(PSTraceSourceOptions), options, true); + _flags = (PSTraceSourceOptions)Enum.Parse(typeof(PSTraceSourceOptions), options, true); } } #endif - this.showHeaders = traceHeaders; - this.description = description; + _showHeaders = traceHeaders; + _description = description; } catch (System.Xml.XmlException) { // This exception occurs when the config // file is malformed. Just default to Off. - flags = PSTraceSourceOptions.None; + _flags = PSTraceSourceOptions.None; } #if !CORECLR catch (System.Configuration.ConfigurationException) @@ -323,7 +321,7 @@ namespace System.Management.Automation // This exception occurs when the config // file is malformed. Just default to Off. - flags = PSTraceSourceOptions.None; + _flags = PSTraceSourceOptions.None; } #endif } @@ -358,7 +356,7 @@ namespace System.Management.Automation PSTraceSourceOptions.All, "\tCurrent time: {0}", DateTime.Now); - + // OS build OutputLine( @@ -397,7 +395,7 @@ namespace System.Management.Automation internal void TracerObjectHeader( Assembly callingAssembly) { - if (flags == PSTraceSourceOptions.None) + if (_flags == PSTraceSourceOptions.None) { return; } @@ -419,7 +417,7 @@ namespace System.Management.Automation PSTraceSourceOptions.All, "\tDescription: {0}", Description); - + if (callingAssembly != null) { // Assembly name @@ -430,7 +428,7 @@ namespace System.Management.Automation callingAssembly.FullName); // Assembly location - + OutputLine( PSTraceSourceOptions.All, "\tAssembly Location: {0}", @@ -452,7 +450,7 @@ namespace System.Management.Automation // Label flagBuilder.Append("\tFlags: "); - flagBuilder.Append(flags.ToString()); + flagBuilder.Append(_flags.ToString()); // Write out the flags @@ -464,11 +462,11 @@ namespace System.Management.Automation internal IDisposable TraceScope(string msg) { - if ((flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) { try { - return new ScopeTracer (this, PSTraceSourceOptions.Scope, null, null, String.Empty, msg); + return new ScopeTracer(this, PSTraceSourceOptions.Scope, null, null, String.Empty, msg); } catch { } } @@ -477,11 +475,11 @@ namespace System.Management.Automation internal IDisposable TraceScope(string format, object arg1) { - if ((flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) { try { - return new ScopeTracer (this, PSTraceSourceOptions.Scope, null, null, String.Empty, format, arg1); + return new ScopeTracer(this, PSTraceSourceOptions.Scope, null, null, String.Empty, format, arg1); } catch { } } @@ -490,11 +488,11 @@ namespace System.Management.Automation internal IDisposable TraceScope(string format, object arg1, object arg2) { - if ((flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Scope) != PSTraceSourceOptions.None) { try { - return new ScopeTracer (this, PSTraceSourceOptions.Scope, null, null, String.Empty, format, arg1, arg2); + return new ScopeTracer(this, PSTraceSourceOptions.Scope, null, null, String.Empty, format, arg1, arg2); } catch { } } @@ -544,7 +542,7 @@ namespace System.Management.Automation string format, params object[] args) { - if ((flags & PSTraceSourceOptions.Method) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Method) != PSTraceSourceOptions.None) { try { @@ -555,8 +553,8 @@ namespace System.Management.Automation string methodName = GetCallingMethodNameAndParameters(1); // Create the method tracer object - return - (IDisposable) + return + (IDisposable) new ScopeTracer( this, PSTraceSourceOptions.Method, @@ -579,7 +577,7 @@ namespace System.Management.Automation } #endregion PSTraceSourceOptions.Method methods/helpers - + #region PSTraceSourceOptions.Events methods/helpers /// @@ -592,7 +590,7 @@ namespace System.Management.Automation /// internal IDisposable TraceEventHandlers() { - if ((flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) { try { @@ -603,8 +601,8 @@ namespace System.Management.Automation string methodName = GetCallingMethodNameAndParameters(1); // Create the scope tracer object - return - (IDisposable) + return + (IDisposable) new ScopeTracer( this, PSTraceSourceOptions.Events, @@ -643,7 +641,7 @@ namespace System.Management.Automation string format, params object[] args) { - if ((flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Events) != PSTraceSourceOptions.None) { try { @@ -654,8 +652,8 @@ namespace System.Management.Automation string methodName = GetCallingMethodNameAndParameters(1); // Create the scope tracer object - return - (IDisposable) + return + (IDisposable) new ScopeTracer( this, PSTraceSourceOptions.Events, @@ -713,7 +711,7 @@ namespace System.Management.Automation /// internal IDisposable TraceLock(string lockName) { - if ((flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) { try { @@ -746,7 +744,7 @@ namespace System.Management.Automation /// internal void TraceLockAcquiring(string lockName) { - if ((flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) { TraceLockHelper( lockAcquiringFormatter, @@ -768,7 +766,7 @@ namespace System.Management.Automation /// internal void TraceLockAcquired(string lockName) { - if ((flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) { TraceLockHelper( lockEnterFormatter, @@ -786,7 +784,7 @@ namespace System.Management.Automation /// internal void TraceLockReleased(string lockName) { - if ((flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Lock) != PSTraceSourceOptions.None) { TraceLockHelper( lockLeavingFormatter, @@ -840,12 +838,12 @@ namespace System.Management.Automation string errorMessageFormat, params object[] args) { - if ((flags & PSTraceSourceOptions.Error) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Error) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.Error, - errorFormatter, - errorMessageFormat, + errorFormatter, + errorMessageFormat, args); } } @@ -867,12 +865,12 @@ namespace System.Management.Automation string warningMessageFormat, params object[] args) { - if ((flags & PSTraceSourceOptions.Warning) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Warning) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.Warning, - warningFormatter, - warningMessageFormat, + warningFormatter, + warningMessageFormat, args); } } @@ -890,13 +888,13 @@ namespace System.Management.Automation /// The arguments for the format string /// /// - internal void TraceVerbose ( + internal void TraceVerbose( string verboseMessageFormat, params object[] args) { - if ((flags & PSTraceSourceOptions.Verbose) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.Verbose) != PSTraceSourceOptions.None) { - FormatOutputLine ( + FormatOutputLine( PSTraceSourceOptions.Verbose, verboseFormatter, verboseMessageFormat, @@ -914,12 +912,12 @@ namespace System.Management.Automation /// internal void WriteLine(string format) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( - PSTraceSourceOptions.WriteLine, - writeLineFormatter, - format, + PSTraceSourceOptions.WriteLine, + writeLineFormatter, + format, Utils.EmptyArray()); } } @@ -933,13 +931,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( - PSTraceSourceOptions.WriteLine, - writeLineFormatter, - format, - new object[] {arg1}); + PSTraceSourceOptions.WriteLine, + writeLineFormatter, + format, + new object[] { arg1 }); } } @@ -953,13 +951,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1, object arg2) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( - PSTraceSourceOptions.WriteLine, - writeLineFormatter, - format, - new object[] {arg1, arg2}); + PSTraceSourceOptions.WriteLine, + writeLineFormatter, + format, + new object[] { arg1, arg2 }); } } @@ -974,13 +972,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1, object arg2, object arg3) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.WriteLine, writeLineFormatter, format, - new object[] {arg1, arg2, arg3}); + new object[] { arg1, arg2, arg3 }); } } @@ -996,13 +994,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.WriteLine, writeLineFormatter, format, - new object[] {arg1, arg2, arg3, arg4}); + new object[] { arg1, arg2, arg3, arg4 }); } } @@ -1019,13 +1017,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4, object arg5) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.WriteLine, writeLineFormatter, format, - new object[] {arg1, arg2, arg3, arg4, arg5}); + new object[] { arg1, arg2, arg3, arg4, arg5 }); } } @@ -1043,13 +1041,13 @@ namespace System.Management.Automation /// internal void WriteLine(string format, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { FormatOutputLine( PSTraceSourceOptions.WriteLine, writeLineFormatter, format, - new object[] {arg1, arg2, arg3, arg4, arg5, arg6}); + new object[] { arg1, arg2, arg3, arg4, arg5, arg6 }); } } @@ -1063,7 +1061,7 @@ namespace System.Management.Automation /// internal void WriteLine(object arg) { - if ((flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) + if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { WriteLine("{0}", arg == null ? "null" : arg.ToString()); } @@ -1112,7 +1110,7 @@ namespace System.Management.Automation { output.AppendFormat( CultureInfo.CurrentCulture, - format, + format, args); } @@ -1176,12 +1174,11 @@ namespace System.Management.Automation methodAndParameters.AppendFormat( CultureInfo.CurrentCulture, - "{0}.{1}(", + "{0}.{1}(", declaringType.Name, callingMethod.Name); methodAndParameters.Append(")"); - } catch { @@ -1277,7 +1274,7 @@ namespace System.Management.Automation private const string lockAcquiringFormatter = "Acquiring Lock: {0}"; - + private static StringBuilder GetLinePrefix(PSTraceSourceOptions flag) { StringBuilder prefixBuilder = new StringBuilder(); @@ -1302,8 +1299,8 @@ namespace System.Management.Automation int threadIndentLevel = ThreadIndentLevel; for ( - int index = 0; - index < indentSize * threadIndentLevel; + int index = 0; + index < indentSize * threadIndentLevel; index++) { lineBuilder.Append(" "); @@ -1311,7 +1308,7 @@ namespace System.Management.Automation } // used to find and blocks cyclic-loops in tracing. - private bool alreadyTracing = false; + private bool _alreadyTracing = false; /// /// Composes a line of trace output and then writes it /// @@ -1341,12 +1338,12 @@ namespace System.Management.Automation { // if already tracing something for this current TraceSource, // dont trace again. This will block cyclic-loops from happening. - if (alreadyTracing) + if (_alreadyTracing) { return; } - alreadyTracing = true; + _alreadyTracing = true; try { Diagnostics.Assert( @@ -1355,7 +1352,7 @@ namespace System.Management.Automation StringBuilder lineBuilder = new StringBuilder(); - if (showHeaders) + if (_showHeaders) { // Get the line prefix string which includes things // like App name, clock tick, thread ID, etc. @@ -1393,7 +1390,7 @@ namespace System.Management.Automation { // reset tracing for the current trace source.. // so future traces can go through. - alreadyTracing = false; + _alreadyTracing = false; } } @@ -1406,7 +1403,7 @@ namespace System.Management.Automation { // The first time access the ThreadLocal instance, the default int value will be used // to initialize the instance. The default int value is 0. - return LocalIndentLevel.Value; + return s_localIndentLevel.Value; } set @@ -1414,7 +1411,7 @@ namespace System.Management.Automation if (value >= 0) { // Set the new indent level in thread local storage - LocalIndentLevel.Value = value; + s_localIndentLevel.Value = value; } else { @@ -1426,22 +1423,22 @@ namespace System.Management.Automation /// /// Allocates some thread local storage to hold the indent level /// - private static readonly ThreadLocal LocalIndentLevel = new ThreadLocal(); + private static readonly ThreadLocal s_localIndentLevel = new ThreadLocal(); /// /// Local storage for the trace switch flags /// - private PSTraceSourceOptions flags = PSTraceSourceOptions.None; + private PSTraceSourceOptions _flags = PSTraceSourceOptions.None; /// /// Gets or sets the description for this trace sources /// public string Description { - get { return description; } - set { description = value; } + get { return _description; } + set { _description = value; } } - private string description = String.Empty; + private string _description = String.Empty; /// /// Determines if the line and switch headers should be shown @@ -1449,10 +1446,10 @@ namespace System.Management.Automation /// internal bool ShowHeaders { - get { return showHeaders; } - set { showHeaders = value; } + get { return _showHeaders; } + set { _showHeaders = value; } } - private bool showHeaders = true; + private bool _showHeaders = true; /// /// Gets the full name of the trace source category @@ -1460,10 +1457,10 @@ namespace System.Management.Automation /// internal string FullName { - get { return fullName; } + get { return _fullName; } } - private string fullName = String.Empty; - private string name; + private string _fullName = String.Empty; + private string _name; /// /// Creates an instance of the TraceSource on demand @@ -1473,14 +1470,14 @@ namespace System.Management.Automation { get { - if (traceSource == null) + if (_traceSource == null) { - traceSource = new MonadTraceSource(name); + _traceSource = new MonadTraceSource(_name); } - return traceSource; + return _traceSource; } } - private TraceSource traceSource; + private TraceSource _traceSource; #endregion Class helper methods and properties @@ -1491,18 +1488,18 @@ namespace System.Management.Automation /// public PSTraceSourceOptions Options { - get { return flags; } + get { return _flags; } set { - flags = value; - this.TraceSource.Switch.Level = (SourceLevels)flags; + _flags = value; + this.TraceSource.Switch.Level = (SourceLevels)_flags; } } internal bool IsEnabled { - get { return flags != PSTraceSourceOptions.None; } + get { return _flags != PSTraceSourceOptions.None; } } #if !CORECLR // TraceSource.Attributes is not in CoreCLR @@ -1541,7 +1538,7 @@ namespace System.Management.Automation { get { - return name; + return _name; } } @@ -1569,9 +1566,9 @@ namespace System.Management.Automation /// internal static Dictionary TraceCatalog { - get { return traceCatalog; } + get { return s_traceCatalog; } } - private static Dictionary traceCatalog = + private static Dictionary s_traceCatalog = new Dictionary(StringComparer.OrdinalIgnoreCase); /// @@ -1584,13 +1581,12 @@ namespace System.Management.Automation /// internal static Dictionary PreConfiguredTraceSource { - get { return preConfiguredTraceSource; } + get { return s_preConfiguredTraceSource; } } - private static Dictionary preConfiguredTraceSource = + private static Dictionary s_preConfiguredTraceSource = new Dictionary(StringComparer.OrdinalIgnoreCase); #endregion TraceCatalog - } // class PSTraceSource : Switch #region ScopeTracer object/helpers @@ -1644,11 +1640,11 @@ namespace System.Management.Automation internal ScopeTracer( PSTraceSource tracer, PSTraceSourceOptions flag, - string scopeOutputFormatter, + string scopeOutputFormatter, string leavingScopeFormatter, string scopeName) { - this._tracer = tracer; + _tracer = tracer; // Call the helper @@ -1710,7 +1706,7 @@ namespace System.Management.Automation string format, params object[] args) { - this._tracer = tracer; + _tracer = tracer; // Call the helper @@ -1780,25 +1776,25 @@ namespace System.Management.Automation // Store the flags, scopeName, and the leavingScopeFormatter // so that it can be used in the Dispose method - this._flag = flag; - this._scopeName = scopeName; - this._leavingScopeFormatter = leavingScopeFormatter; - + _flag = flag; + _scopeName = scopeName; + _leavingScopeFormatter = leavingScopeFormatter; + // Format the string for output StringBuilder output = new StringBuilder(); - if (!String.IsNullOrEmpty (scopeOutputFormatter)) + if (!String.IsNullOrEmpty(scopeOutputFormatter)) { - output.AppendFormat ( + output.AppendFormat( CultureInfo.CurrentCulture, scopeOutputFormatter, _scopeName); } - if (!String.IsNullOrEmpty (format)) + if (!String.IsNullOrEmpty(format)) { - output.AppendFormat ( + output.AppendFormat( CultureInfo.CurrentCulture, format, args); @@ -1822,12 +1818,12 @@ namespace System.Management.Automation // Decrement the indent level in thread local storage PSTraceSource.ThreadIndentLevel--; - + // Trace out the scope name - if (!String.IsNullOrEmpty (_leavingScopeFormatter)) + if (!String.IsNullOrEmpty(_leavingScopeFormatter)) { - _tracer.OutputLine (_flag, _leavingScopeFormatter, _scopeName); + _tracer.OutputLine(_flag, _leavingScopeFormatter, _scopeName); } GC.SuppressFinalize(this); } @@ -1877,7 +1873,7 @@ namespace System.Management.Automation /// [AttributeUsage( AttributeTargets.Field, - AllowMultiple=false)] + AllowMultiple = false)] internal class TraceSourceAttribute : Attribute { /// @@ -1890,41 +1886,40 @@ namespace System.Management.Automation /// /// A description for the category. /// - internal TraceSourceAttribute ( + internal TraceSourceAttribute( string category, string description) { - this.category = category; - this.description = description; + _category = category; + _description = description; } /// /// The category to be used for the TraceSource /// - private string category; + private string _category; /// /// The category to be used for the TraceSource /// internal string Category { - get { return category; } + get { return _category; } } /// /// The description for the category to be used for the TraceSource /// - private string description; + private string _description; /// /// The description for the category to be used for the TraceSource /// internal string Description { - get { return description; } - set { description = value; } + get { return _description; } + set { _description = value; } } - } #endregion TraceSourceAttribute @@ -1960,6 +1955,5 @@ namespace System.Management.Automation #endif } #endregion MonadTraceSource - } diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index f893bf3f0..b21822266 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -244,7 +244,7 @@ namespace System.Management.Automation /// Performs an in-place modification of a resource. /// public const string Edit = "Edit"; - + /// /// Uncompress or increase in size /// @@ -303,7 +303,7 @@ namespace System.Management.Automation /// /// Remove from public access and visibility /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId="Unpublish")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unpublish")] public const string Unpublish = "Unpublish"; /// @@ -325,7 +325,6 @@ namespace System.Management.Automation /// Out - direct to a port. Output something to a port. /// public const string Out = "Out"; - }//VerbsData /// @@ -367,12 +366,12 @@ namespace System.Management.Automation /// Stop and/or configure something to be unavailable (e.g unable to not start again) /// public const string Disable = "Disable"; - + /// /// Configure to be available (e.g. able to start) /// public const string Enable = "Enable"; - + /// /// Settle in an indicated place or condition (optionally initializing for use) /// @@ -398,7 +397,7 @@ namespace System.Management.Automation /// Terminate existing activity and begin it again (with the same configuration) /// public const string Restart = "Restart"; - + /// /// Begin an activity again after it was suspended /// @@ -408,7 +407,7 @@ namespace System.Management.Automation /// Begin an activity /// public const string Start = "Start"; - + /// ///Discontinue or cease an activity /// @@ -456,12 +455,12 @@ namespace System.Management.Automation /// Interatively interact with a resource or activity for the purpose finding a flaw or better understanding of what is occurring. /// public const string Debug = "Debug"; - + /// /// calculate/identify resources consumed by a specified operation or retrieve statistics about a resource /// public const string Measure = "Measure"; - + /// /// Determine whether a resource is alive and responding to requests /// @@ -471,17 +470,17 @@ namespace System.Management.Automation /// Detect and correct problems /// public const string Repair = "Repair"; - + /// /// Map a shorthand name will be bound to a longname /// public const string Resolve = "Resolve"; - + /// /// Verify the operational validity or consistency of a resource /// public const string Test = "Test"; - + /// /// Trace activities performed by a specified operation /// @@ -503,17 +502,17 @@ namespace System.Management.Automation /// Convey by an intermediary to a destination /// public const string Send = "Send"; - + /// /// Take or acquire from a source /// public const string Receive = "Receive"; - + /// /// Associate subsequent activies with a resource /// public const string Connect = "Connect"; - + /// /// Disassociate from a resource /// @@ -528,7 +527,6 @@ namespace System.Management.Automation /// To read - to obtain (data) from a storage medium or port /// public const string Read = "Read"; - }//VerbsCommunications /// @@ -565,7 +563,7 @@ namespace System.Management.Automation /// Prevent access to or usage of a resource. /// public const string Block = "Block"; - + /// /// Allow access to or usage of a resource. /// @@ -596,142 +594,142 @@ namespace System.Management.Automation { if (field.IsLiteral) { - validVerbs.Add((string)field.GetValue(null), true); + s_validVerbs.Add((string)field.GetValue(null), true); } } } - recommendedAlternateVerbs.Add("accept", new string[] {"Receive"}); - recommendedAlternateVerbs.Add("acquire", new string[] {"Get", "Read"}); - recommendedAlternateVerbs.Add("allocate", new string[] {"New"}); - recommendedAlternateVerbs.Add("allow", new string[] {"Enable", "Grant", "Unblock"}); - recommendedAlternateVerbs.Add("amend", new string[] {"Edit"}); - recommendedAlternateVerbs.Add("analyze", new string[] {"Measure", "Test"}); - recommendedAlternateVerbs.Add("append", new string[] {"Add"}); - recommendedAlternateVerbs.Add("assign", new string[] {"Set"}); - recommendedAlternateVerbs.Add("associate", new string[] {"Join", "Merge"}); - recommendedAlternateVerbs.Add("attach", new string[] {"Add", "Debug"}); - recommendedAlternateVerbs.Add("bc", new string[] {"Compare"}); - recommendedAlternateVerbs.Add("boot", new string[] {"Start"}); - recommendedAlternateVerbs.Add("break", new string[] {"Disconnect"}); - recommendedAlternateVerbs.Add("broadcast", new string[] {"Send"}); - recommendedAlternateVerbs.Add("build", new string[] {"New"}); - recommendedAlternateVerbs.Add("burn", new string[] {"Backup"}); - recommendedAlternateVerbs.Add("calculate", new string[] {"Measure"}); - recommendedAlternateVerbs.Add("cancel", new string[] {"Stop"}); - recommendedAlternateVerbs.Add("cat", new string[] {"Get"}); - recommendedAlternateVerbs.Add("change", new string[] {"Convert", "Edit", "Rename"}); - recommendedAlternateVerbs.Add("clean", new string[] {"Uninstall"}); - recommendedAlternateVerbs.Add("clone", new string[] {"Copy"}); - recommendedAlternateVerbs.Add("combine", new string[] {"Join", "Merge"}); - recommendedAlternateVerbs.Add("compact", new string[] {"Compress"}); - recommendedAlternateVerbs.Add("concatenate", new string[] {"Add"}); - recommendedAlternateVerbs.Add("configure", new string[] {"Set"}); - recommendedAlternateVerbs.Add("create", new string[] {"New"}); - recommendedAlternateVerbs.Add("cut", new string[] {"Remove"}); + s_recommendedAlternateVerbs.Add("accept", new string[] { "Receive" }); + s_recommendedAlternateVerbs.Add("acquire", new string[] { "Get", "Read" }); + s_recommendedAlternateVerbs.Add("allocate", new string[] { "New" }); + s_recommendedAlternateVerbs.Add("allow", new string[] { "Enable", "Grant", "Unblock" }); + s_recommendedAlternateVerbs.Add("amend", new string[] { "Edit" }); + s_recommendedAlternateVerbs.Add("analyze", new string[] { "Measure", "Test" }); + s_recommendedAlternateVerbs.Add("append", new string[] { "Add" }); + s_recommendedAlternateVerbs.Add("assign", new string[] { "Set" }); + s_recommendedAlternateVerbs.Add("associate", new string[] { "Join", "Merge" }); + s_recommendedAlternateVerbs.Add("attach", new string[] { "Add", "Debug" }); + s_recommendedAlternateVerbs.Add("bc", new string[] { "Compare" }); + s_recommendedAlternateVerbs.Add("boot", new string[] { "Start" }); + s_recommendedAlternateVerbs.Add("break", new string[] { "Disconnect" }); + s_recommendedAlternateVerbs.Add("broadcast", new string[] { "Send" }); + s_recommendedAlternateVerbs.Add("build", new string[] { "New" }); + s_recommendedAlternateVerbs.Add("burn", new string[] { "Backup" }); + s_recommendedAlternateVerbs.Add("calculate", new string[] { "Measure" }); + s_recommendedAlternateVerbs.Add("cancel", new string[] { "Stop" }); + s_recommendedAlternateVerbs.Add("cat", new string[] { "Get" }); + s_recommendedAlternateVerbs.Add("change", new string[] { "Convert", "Edit", "Rename" }); + s_recommendedAlternateVerbs.Add("clean", new string[] { "Uninstall" }); + s_recommendedAlternateVerbs.Add("clone", new string[] { "Copy" }); + s_recommendedAlternateVerbs.Add("combine", new string[] { "Join", "Merge" }); + s_recommendedAlternateVerbs.Add("compact", new string[] { "Compress" }); + s_recommendedAlternateVerbs.Add("concatenate", new string[] { "Add" }); + s_recommendedAlternateVerbs.Add("configure", new string[] { "Set" }); + s_recommendedAlternateVerbs.Add("create", new string[] { "New" }); + s_recommendedAlternateVerbs.Add("cut", new string[] { "Remove" }); //recommendedAlternateVerbs.Add("debug", new string[] {"Ping"}); - recommendedAlternateVerbs.Add("delete", new string[] {"Remove"}); - recommendedAlternateVerbs.Add("deploy", new string[] {"Install", "Publish"}); - recommendedAlternateVerbs.Add("detach", new string[] { "Dismount", "Remove" }); - recommendedAlternateVerbs.Add("determine", new string[] {"Measure", "Resolve"}); - recommendedAlternateVerbs.Add("diagnose", new string[] {"Debug", "Test"}); - recommendedAlternateVerbs.Add("diff", new string[] {"Checkpoint", "Compare"}); - recommendedAlternateVerbs.Add("difference", new string[] {"Checkpoint", "Compare"}); - recommendedAlternateVerbs.Add("dig", new string[] {"Trace"}); - recommendedAlternateVerbs.Add("dir", new string[] {"Get"}); - recommendedAlternateVerbs.Add("discard", new string[] {"Remove"}); - recommendedAlternateVerbs.Add("display", new string[] {"Show", "Write"}); - recommendedAlternateVerbs.Add("dispose", new string[] {"Remove"}); - recommendedAlternateVerbs.Add("divide", new string[] {"Split"}); - recommendedAlternateVerbs.Add("dump", new string[] {"Get"}); - recommendedAlternateVerbs.Add("duplicate", new string[] {"Copy"}); - recommendedAlternateVerbs.Add("empty", new string[] {"Clear"}); - recommendedAlternateVerbs.Add("end", new string[] {"Stop"}); - recommendedAlternateVerbs.Add("erase", new string[] {"Clear", "Remove"}); - recommendedAlternateVerbs.Add("examine", new string[] {"Get"}); - recommendedAlternateVerbs.Add("execute", new string[] {"Invoke"}); - recommendedAlternateVerbs.Add("explode", new string[] {"Expand"}); - recommendedAlternateVerbs.Add("extract", new string[] {"Export"}); - recommendedAlternateVerbs.Add("fix", new string[] {"Repair", "Restore"}); - recommendedAlternateVerbs.Add("flush", new string[] {"Clear"}); - recommendedAlternateVerbs.Add("follow", new string[] {"Trace"}); - recommendedAlternateVerbs.Add("generate", new string[] {"New"}); + s_recommendedAlternateVerbs.Add("delete", new string[] { "Remove" }); + s_recommendedAlternateVerbs.Add("deploy", new string[] { "Install", "Publish" }); + s_recommendedAlternateVerbs.Add("detach", new string[] { "Dismount", "Remove" }); + s_recommendedAlternateVerbs.Add("determine", new string[] { "Measure", "Resolve" }); + s_recommendedAlternateVerbs.Add("diagnose", new string[] { "Debug", "Test" }); + s_recommendedAlternateVerbs.Add("diff", new string[] { "Checkpoint", "Compare" }); + s_recommendedAlternateVerbs.Add("difference", new string[] { "Checkpoint", "Compare" }); + s_recommendedAlternateVerbs.Add("dig", new string[] { "Trace" }); + s_recommendedAlternateVerbs.Add("dir", new string[] { "Get" }); + s_recommendedAlternateVerbs.Add("discard", new string[] { "Remove" }); + s_recommendedAlternateVerbs.Add("display", new string[] { "Show", "Write" }); + s_recommendedAlternateVerbs.Add("dispose", new string[] { "Remove" }); + s_recommendedAlternateVerbs.Add("divide", new string[] { "Split" }); + s_recommendedAlternateVerbs.Add("dump", new string[] { "Get" }); + s_recommendedAlternateVerbs.Add("duplicate", new string[] { "Copy" }); + s_recommendedAlternateVerbs.Add("empty", new string[] { "Clear" }); + s_recommendedAlternateVerbs.Add("end", new string[] { "Stop" }); + s_recommendedAlternateVerbs.Add("erase", new string[] { "Clear", "Remove" }); + s_recommendedAlternateVerbs.Add("examine", new string[] { "Get" }); + s_recommendedAlternateVerbs.Add("execute", new string[] { "Invoke" }); + s_recommendedAlternateVerbs.Add("explode", new string[] { "Expand" }); + s_recommendedAlternateVerbs.Add("extract", new string[] { "Export" }); + s_recommendedAlternateVerbs.Add("fix", new string[] { "Repair", "Restore" }); + s_recommendedAlternateVerbs.Add("flush", new string[] { "Clear" }); + s_recommendedAlternateVerbs.Add("follow", new string[] { "Trace" }); + s_recommendedAlternateVerbs.Add("generate", new string[] { "New" }); //recommendedAlternateVerbs.Add("get", new string[] {"Read"}); - recommendedAlternateVerbs.Add("halt", new string[] {"Disable"}); - recommendedAlternateVerbs.Add("in", new string[] {"ConvertTo"}); - recommendedAlternateVerbs.Add("index", new string[] {"Update"}); - recommendedAlternateVerbs.Add("initiate", new string[] {"Start"}); - recommendedAlternateVerbs.Add("input", new string[] {"ConvertTo", "Unregister"}); - recommendedAlternateVerbs.Add("insert", new string[] {"Add", "Unregister"}); - recommendedAlternateVerbs.Add("inspect", new string[] {"Trace"}); - recommendedAlternateVerbs.Add("kill", new string[] {"Stop"}); - recommendedAlternateVerbs.Add("launch", new string[] {"Start"}); - recommendedAlternateVerbs.Add("load", new string[] {"Import"}); - recommendedAlternateVerbs.Add("locate", new string[] {"Search", "Select"}); - recommendedAlternateVerbs.Add("logoff", new string[] {"Disconnect"}); - recommendedAlternateVerbs.Add("mail", new string[] {"Send"}); - recommendedAlternateVerbs.Add("make", new string[] {"New"}); - recommendedAlternateVerbs.Add("match", new string[] {"Select"}); - recommendedAlternateVerbs.Add("migrate", new string[] {"Move"}); - recommendedAlternateVerbs.Add("modify", new string[] {"Edit"}); - recommendedAlternateVerbs.Add("name", new string[] {"Move"}); - recommendedAlternateVerbs.Add("nullify", new string[] {"Clear"}); - recommendedAlternateVerbs.Add("obtain", new string[] {"Get"}); + s_recommendedAlternateVerbs.Add("halt", new string[] { "Disable" }); + s_recommendedAlternateVerbs.Add("in", new string[] { "ConvertTo" }); + s_recommendedAlternateVerbs.Add("index", new string[] { "Update" }); + s_recommendedAlternateVerbs.Add("initiate", new string[] { "Start" }); + s_recommendedAlternateVerbs.Add("input", new string[] { "ConvertTo", "Unregister" }); + s_recommendedAlternateVerbs.Add("insert", new string[] { "Add", "Unregister" }); + s_recommendedAlternateVerbs.Add("inspect", new string[] { "Trace" }); + s_recommendedAlternateVerbs.Add("kill", new string[] { "Stop" }); + s_recommendedAlternateVerbs.Add("launch", new string[] { "Start" }); + s_recommendedAlternateVerbs.Add("load", new string[] { "Import" }); + s_recommendedAlternateVerbs.Add("locate", new string[] { "Search", "Select" }); + s_recommendedAlternateVerbs.Add("logoff", new string[] { "Disconnect" }); + s_recommendedAlternateVerbs.Add("mail", new string[] { "Send" }); + s_recommendedAlternateVerbs.Add("make", new string[] { "New" }); + s_recommendedAlternateVerbs.Add("match", new string[] { "Select" }); + s_recommendedAlternateVerbs.Add("migrate", new string[] { "Move" }); + s_recommendedAlternateVerbs.Add("modify", new string[] { "Edit" }); + s_recommendedAlternateVerbs.Add("name", new string[] { "Move" }); + s_recommendedAlternateVerbs.Add("nullify", new string[] { "Clear" }); + s_recommendedAlternateVerbs.Add("obtain", new string[] { "Get" }); //recommendedAlternateVerbs.Add("out", new string[] {"ConvertFrom"}); - recommendedAlternateVerbs.Add("output", new string[] {"ConvertFrom"}); - recommendedAlternateVerbs.Add("pause", new string[] {"Suspend", "Wait"}); - recommendedAlternateVerbs.Add("peek", new string[] {"Receive"}); - recommendedAlternateVerbs.Add("permit", new string[] {"Enable"}); - recommendedAlternateVerbs.Add("purge", new string[] {"Clear", "Remove"}); - recommendedAlternateVerbs.Add("pick", new string[] {"Select"}); + s_recommendedAlternateVerbs.Add("output", new string[] { "ConvertFrom" }); + s_recommendedAlternateVerbs.Add("pause", new string[] { "Suspend", "Wait" }); + s_recommendedAlternateVerbs.Add("peek", new string[] { "Receive" }); + s_recommendedAlternateVerbs.Add("permit", new string[] { "Enable" }); + s_recommendedAlternateVerbs.Add("purge", new string[] { "Clear", "Remove" }); + s_recommendedAlternateVerbs.Add("pick", new string[] { "Select" }); //recommendedAlternateVerbs.Add("pop", new string[] {"Enter", "Exit"}); - recommendedAlternateVerbs.Add("prevent", new string[] {"Block"}); - recommendedAlternateVerbs.Add("print", new string[] {"Write"}); - recommendedAlternateVerbs.Add("prompt", new string[] {"Read"}); + s_recommendedAlternateVerbs.Add("prevent", new string[] { "Block" }); + s_recommendedAlternateVerbs.Add("print", new string[] { "Write" }); + s_recommendedAlternateVerbs.Add("prompt", new string[] { "Read" }); //recommendedAlternateVerbs.Add("push", new string[] {"Enter", "Exit"}); - recommendedAlternateVerbs.Add("put", new string[] {"Send", "Write"}); - recommendedAlternateVerbs.Add("puts", new string[] {"Write"}); - recommendedAlternateVerbs.Add("quota", new string[] {"Limit"}); - recommendedAlternateVerbs.Add("quote", new string[] {"Limit"}); - recommendedAlternateVerbs.Add("rebuild", new string[] {"Initialize"}); - recommendedAlternateVerbs.Add("recycle", new string[] {"Restart"}); - recommendedAlternateVerbs.Add("refresh", new string[] {"Update"}); - recommendedAlternateVerbs.Add("reinitialize", new string[] {"Initialize"}); - recommendedAlternateVerbs.Add("release", new string[] {"Clear", "Install", "Publish", "Unlock"}); - recommendedAlternateVerbs.Add("reload", new string[] {"Update"}); - recommendedAlternateVerbs.Add("renew", new string[] {"Initialize", "Update"}); - recommendedAlternateVerbs.Add("replicate", new string[] {"Copy"}); - recommendedAlternateVerbs.Add("resample", new string[] {"Convert"}); + s_recommendedAlternateVerbs.Add("put", new string[] { "Send", "Write" }); + s_recommendedAlternateVerbs.Add("puts", new string[] { "Write" }); + s_recommendedAlternateVerbs.Add("quota", new string[] { "Limit" }); + s_recommendedAlternateVerbs.Add("quote", new string[] { "Limit" }); + s_recommendedAlternateVerbs.Add("rebuild", new string[] { "Initialize" }); + s_recommendedAlternateVerbs.Add("recycle", new string[] { "Restart" }); + s_recommendedAlternateVerbs.Add("refresh", new string[] { "Update" }); + s_recommendedAlternateVerbs.Add("reinitialize", new string[] { "Initialize" }); + s_recommendedAlternateVerbs.Add("release", new string[] { "Clear", "Install", "Publish", "Unlock" }); + s_recommendedAlternateVerbs.Add("reload", new string[] { "Update" }); + s_recommendedAlternateVerbs.Add("renew", new string[] { "Initialize", "Update" }); + s_recommendedAlternateVerbs.Add("replicate", new string[] { "Copy" }); + s_recommendedAlternateVerbs.Add("resample", new string[] { "Convert" }); //recommendedAlternateVerbs.Add("reset", new string[] {"Set"}); //recommendedAlternateVerbs.Add("resize", new string[] {"Convert"}); - recommendedAlternateVerbs.Add("restrict", new string[] {"Lock"}); - recommendedAlternateVerbs.Add("return", new string[] {"Repair", "Restore"}); - recommendedAlternateVerbs.Add("revert", new string[] {"Unpublish"}); - recommendedAlternateVerbs.Add("revise", new string[] {"Edit"}); - recommendedAlternateVerbs.Add("run", new string[] {"Invoke", "Start"}); - recommendedAlternateVerbs.Add("salvage", new string[] {"Test"}); + s_recommendedAlternateVerbs.Add("restrict", new string[] { "Lock" }); + s_recommendedAlternateVerbs.Add("return", new string[] { "Repair", "Restore" }); + s_recommendedAlternateVerbs.Add("revert", new string[] { "Unpublish" }); + s_recommendedAlternateVerbs.Add("revise", new string[] { "Edit" }); + s_recommendedAlternateVerbs.Add("run", new string[] { "Invoke", "Start" }); + s_recommendedAlternateVerbs.Add("salvage", new string[] { "Test" }); //recommendedAlternateVerbs.Add("save", new string[] {"Backup"}); - recommendedAlternateVerbs.Add("secure", new string[] {"Lock"}); - recommendedAlternateVerbs.Add("separate", new string[] {"Split"}); - recommendedAlternateVerbs.Add("setup", new string[] {"Initialize", "Install"}); - recommendedAlternateVerbs.Add("sleep", new string[] {"Suspend", "Wait"}); - recommendedAlternateVerbs.Add("starttransaction", new string[] {"Checkpoint"}); - recommendedAlternateVerbs.Add("telnet", new string[] {"Connect"}); - recommendedAlternateVerbs.Add("terminate", new string[] {"Stop"}); - recommendedAlternateVerbs.Add("track", new string[] {"Trace"}); - recommendedAlternateVerbs.Add("transfer", new string[] {"Move"}); - recommendedAlternateVerbs.Add("type", new string[] {"Get"}); + s_recommendedAlternateVerbs.Add("secure", new string[] { "Lock" }); + s_recommendedAlternateVerbs.Add("separate", new string[] { "Split" }); + s_recommendedAlternateVerbs.Add("setup", new string[] { "Initialize", "Install" }); + s_recommendedAlternateVerbs.Add("sleep", new string[] { "Suspend", "Wait" }); + s_recommendedAlternateVerbs.Add("starttransaction", new string[] { "Checkpoint" }); + s_recommendedAlternateVerbs.Add("telnet", new string[] { "Connect" }); + s_recommendedAlternateVerbs.Add("terminate", new string[] { "Stop" }); + s_recommendedAlternateVerbs.Add("track", new string[] { "Trace" }); + s_recommendedAlternateVerbs.Add("transfer", new string[] { "Move" }); + s_recommendedAlternateVerbs.Add("type", new string[] { "Get" }); //recommendedAlternateVerbs.Add("undo", new string[] {"Repair", "Restore"}); - recommendedAlternateVerbs.Add("unite", new string[] {"Join", "Merge"}); - recommendedAlternateVerbs.Add("unlink", new string[] {"Dismount"}); - recommendedAlternateVerbs.Add("unmark", new string[] {"Clear"}); - recommendedAlternateVerbs.Add("unrestrict", new string[] {"Unlock"}); - recommendedAlternateVerbs.Add("unsecure", new string[] {"Unlock"}); - recommendedAlternateVerbs.Add("unset", new string[] {"Clear"}); - recommendedAlternateVerbs.Add("verify", new string[] {"Test"}); + s_recommendedAlternateVerbs.Add("unite", new string[] { "Join", "Merge" }); + s_recommendedAlternateVerbs.Add("unlink", new string[] { "Dismount" }); + s_recommendedAlternateVerbs.Add("unmark", new string[] { "Clear" }); + s_recommendedAlternateVerbs.Add("unrestrict", new string[] { "Unlock" }); + s_recommendedAlternateVerbs.Add("unsecure", new string[] { "Unlock" }); + s_recommendedAlternateVerbs.Add("unset", new string[] { "Clear" }); + s_recommendedAlternateVerbs.Add("verify", new string[] { "Test" }); #if DEBUG - foreach (KeyValuePair entry in recommendedAlternateVerbs) + foreach (KeyValuePair entry in s_recommendedAlternateVerbs) { Dbg.Assert(!IsStandard(entry.Key), "prohibited verb is standard"); foreach (string suggested in entry.Value) @@ -742,18 +740,18 @@ namespace System.Management.Automation #endif } - static Dictionary validVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); - static Dictionary recommendedAlternateVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static Dictionary s_validVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static Dictionary s_recommendedAlternateVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); internal static bool IsStandard(string verb) { - return validVerbs.ContainsKey(verb); + return s_validVerbs.ContainsKey(verb); } internal static string[] SuggestedAlternates(string verb) { string[] result = null; - recommendedAlternateVerbs.TryGetValue(verb, out result); + s_recommendedAlternateVerbs.TryGetValue(verb, out result); return result; } } diff --git a/src/System.Management.Automation/utils/WindowsErrorReporting.cs b/src/System.Management.Automation/utils/WindowsErrorReporting.cs index 5d6b8896e..dc14a4f16 100644 --- a/src/System.Management.Automation/utils/WindowsErrorReporting.cs +++ b/src/System.Management.Automation/utils/WindowsErrorReporting.cs @@ -1,7 +1,8 @@ // // Copyright (C) Microsoft. All rights reserved. // -using System.Diagnostics; + +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -82,21 +83,21 @@ namespace System.Management.Automation [Flags] internal enum MiniDumpType : uint { - MiniDumpNormal = 0x00000000, - MiniDumpWithDataSegs = 0x00000001, - MiniDumpWithFullMemory = 0x00000002, - MiniDumpWithHandleData = 0x00000004, - MiniDumpFilterMemory = 0x00000008, - MiniDumpScanMemory = 0x00000010, - MiniDumpWithUnloadedModules = 0x00000020, - MiniDumpWithIndirectlyReferencedMemory = 0x00000040, - MiniDumpFilterModulePaths = 0x00000080, - MiniDumpWithProcessThreadData = 0x00000100, - MiniDumpWithPrivateReadWriteMemory = 0x00000200, - MiniDumpWithoutOptionalData = 0x00000400, - MiniDumpWithFullMemoryInfo = 0x00000800, - MiniDumpWithThreadInfo = 0x00001000, - MiniDumpWithCodeSegs = 0x00002000 + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, + MiniDumpWithFullMemory = 0x00000002, + MiniDumpWithHandleData = 0x00000004, + MiniDumpFilterMemory = 0x00000008, + MiniDumpScanMemory = 0x00000010, + MiniDumpWithUnloadedModules = 0x00000020, + MiniDumpWithIndirectlyReferencedMemory = 0x00000040, + MiniDumpFilterModulePaths = 0x00000080, + MiniDumpWithProcessThreadData = 0x00000100, + MiniDumpWithPrivateReadWriteMemory = 0x00000200, + MiniDumpWithoutOptionalData = 0x00000400, + MiniDumpWithFullMemoryInfo = 0x00000800, + MiniDumpWithThreadInfo = 0x00001000, + MiniDumpWithCodeSegs = 0x00002000 } /// @@ -348,11 +349,11 @@ namespace System.Management.Automation /// /// A handle to the report. If the function fails, this handle is NULL. /// hresult - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId="ReportInformation.wzDescription")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId="ReportInformation.wzApplicationPath")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId="ReportInformation.wzFriendlyEventName")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId="ReportInformation.wzConsentKey")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId="ReportInformation.wzApplicationName")] + [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "ReportInformation.wzDescription")] + [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "ReportInformation.wzApplicationPath")] + [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "ReportInformation.wzFriendlyEventName")] + [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "ReportInformation.wzConsentKey")] + [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "ReportInformation.wzApplicationName")] [DllImport(WerDll, CharSet = CharSet.Unicode)] static internal extern int WerReportCreate( [MarshalAs(UnmanagedType.LPWStr)] string pwzEventType, @@ -446,11 +447,11 @@ namespace System.Management.Automation static internal extern bool MiniDumpWriteDump( IntPtr hProcess, Int32 processId, - Microsoft.Win32.SafeHandles.SafeFileHandle hFile, - MiniDumpType dumpType, - IntPtr exceptionParam, - IntPtr userStreamParam, - IntPtr callackParam); + Microsoft.Win32.SafeHandles.SafeFileHandle hFile, + MiniDumpType dumpType, + IntPtr exceptionParam, + IntPtr userStreamParam, + IntPtr callackParam); } #endregion Native methods @@ -518,7 +519,7 @@ namespace System.Management.Automation { int suffixLength = maxLength - prefixLength - ellipsis.Length; Debug.Assert((prefixLength + ellipsis.Length + suffixLength) <= maxLength); - message = message.Substring(0, prefixLength) + + message = message.Substring(0, prefixLength) + ellipsis + message.Substring(message.Length - suffixLength, suffixLength); } @@ -572,7 +573,7 @@ namespace System.Management.Automation return StackFrame2BucketParameter(frame, maxLength); } - private static readonly string[] powerShellModulesWithoutGlobalMembers = new string[] { + private static readonly string[] s_powerShellModulesWithoutGlobalMembers = new string[] { "Microsoft.PowerShell.Commands.Diagnostics.dll", "Microsoft.PowerShell.Commands.Management.dll", "Microsoft.PowerShell.Commands.Utility.dll", @@ -584,7 +585,7 @@ namespace System.Management.Automation "Microsoft.PowerShell.GraphicalHost.dll" }; - private static readonly string[] powerShellModulesWithGlobalMembers = new string[] { + private static readonly string[] s_powerShellModulesWithGlobalMembers = new string[] { "powershell.exe", "powershell_ise.exe", "pwrshplugin.dll", @@ -595,7 +596,7 @@ namespace System.Management.Automation private static bool IsPowerShellModule(string moduleName, bool globalMember) { - foreach (string powerShellModule in powerShellModulesWithGlobalMembers) + foreach (string powerShellModule in s_powerShellModulesWithGlobalMembers) { if (moduleName.Equals(powerShellModule, StringComparison.OrdinalIgnoreCase)) { @@ -605,19 +606,18 @@ namespace System.Management.Automation if (!globalMember) { - foreach (string powerShellModule in powerShellModulesWithoutGlobalMembers) + foreach (string powerShellModule in s_powerShellModulesWithoutGlobalMembers) { if (moduleName.Equals(powerShellModule, StringComparison.OrdinalIgnoreCase)) { return true; } } - } return false; } - + /// /// Returns the deepest frame belonging to powershell. /// @@ -648,7 +648,7 @@ namespace System.Management.Automation return string.Empty; } - + /// /// Some failure HRESULTs map to well-defined exceptions, while others do not map /// to a defined exception. If the HRESULT maps to a defined exception, ThrowExceptionForHR @@ -688,12 +688,12 @@ namespace System.Management.Automation SetBucketParameter( reportHandle, BucketParameterId.NameOfExe, - TruncateExeName(nameOfExe, 20)); + TruncateExeName(s_nameOfExe, 20)); SetBucketParameter( reportHandle, BucketParameterId.FileVersionOfSystemManagementAutomation, - TruncateBucketParameter(versionOfPowerShellLibraries, 16)); + TruncateBucketParameter(s_versionOfPowerShellLibraries, 16)); SetBucketParameter( reportHandle, @@ -721,17 +721,17 @@ namespace System.Management.Automation TruncateBucketParameter(GetThreadName(), 20)); } - static private string versionOfPowerShellLibraries = string.Empty; + static private string s_versionOfPowerShellLibraries = string.Empty; // This variable will be set during registration phase. We will // try to populate this using Process.MainModule but for some reason // if this fails, we want to provide a default value. - static private string nameOfExe = "GetMainModuleError"; - static private string applicationName = "GetMainModuleError"; - static private string applicationPath = "GetMainModuleError"; - static private IntPtr hCurrentProcess = IntPtr.Zero; - static private IntPtr hwndMainWindow = IntPtr.Zero; - static private Process currentProcess = null; - + static private string s_nameOfExe = "GetMainModuleError"; + static private string s_applicationName = "GetMainModuleError"; + static private string s_applicationPath = "GetMainModuleError"; + static private IntPtr s_hCurrentProcess = IntPtr.Zero; + static private IntPtr s_hwndMainWindow = IntPtr.Zero; + static private Process s_currentProcess = null; + /// /// You are trying to access the MainModule property for a process that is running /// on a remote computer. This property is available only for processes that are @@ -747,19 +747,19 @@ namespace System.Management.Automation { string sma = typeof(PSObject).Assembly.Location; FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(sma); - versionOfPowerShellLibraries = fvi.FileVersion; + s_versionOfPowerShellLibraries = fvi.FileVersion; - currentProcess = Process.GetCurrentProcess(); - ProcessModule mainModule = PsUtils.GetMainModule(currentProcess); + s_currentProcess = Process.GetCurrentProcess(); + ProcessModule mainModule = PsUtils.GetMainModule(s_currentProcess); if (mainModule != null) { - applicationPath = mainModule.FileName; + s_applicationPath = mainModule.FileName; } - nameOfExe = Path.GetFileName(applicationPath); - hCurrentProcess = currentProcess.Handle; - hwndMainWindow = currentProcess.MainWindowHandle; - applicationName = currentProcess.ProcessName; + s_nameOfExe = Path.GetFileName(s_applicationPath); + s_hCurrentProcess = s_currentProcess.Handle; + s_hwndMainWindow = s_currentProcess.MainWindowHandle; + s_applicationName = s_currentProcess.ProcessName; } #endregion @@ -786,16 +786,16 @@ namespace System.Management.Automation Marshal.ThrowExceptionForHR(hresult); } - static private bool? isWindowsErrorReportingAvailable; + static private bool? s_isWindowsErrorReportingAvailable; static private bool IsWindowsErrorReportingAvailable() { - if (!(isWindowsErrorReportingAvailable.HasValue)) + if (!(s_isWindowsErrorReportingAvailable.HasValue)) { Version version = Environment.OSVersion.Version; // WER has been introduced in Vista - isWindowsErrorReportingAvailable = (version.Major >= 6); + s_isWindowsErrorReportingAvailable = (version.Major >= 6); } - return isWindowsErrorReportingAvailable.Value; + return s_isWindowsErrorReportingAvailable.Value; } #endregion @@ -805,9 +805,9 @@ namespace System.Management.Automation /// /// Registered??? TODO/FIXME /// - const string powerShellEventType = "PowerShell"; + private const string powerShellEventType = "PowerShell"; - static private readonly object reportCreationLock = new object(); + static private readonly object s_reportCreationLock = new object(); /// /// Submits a Dr. Watson (aka Windows Error Reporting / WER) crash report and then terminates the process. @@ -824,7 +824,7 @@ namespace System.Management.Automation /// static private void SubmitReport(Exception uncaughtException) { - lock (reportCreationLock) + lock (s_reportCreationLock) { if (uncaughtException == null) { @@ -833,10 +833,10 @@ namespace System.Management.Automation ReportInformation reportInformation = new ReportInformation(); reportInformation.dwSize = Marshal.SizeOf(reportInformation); - reportInformation.hProcess = hCurrentProcess; - reportInformation.hwndParent = hwndMainWindow; - reportInformation.wzApplicationName = applicationName; - reportInformation.wzApplicationPath = applicationPath; + reportInformation.hProcess = s_hCurrentProcess; + reportInformation.hwndParent = s_hwndMainWindow; + reportInformation.wzApplicationName = s_applicationName; + reportInformation.wzApplicationPath = s_applicationPath; reportInformation.wzConsentKey = null; // null = the name specified by the pwzEventType parameter of WerReportCreate. reportInformation.wzDescription = null; // we can't provide a description of the problem - this an uncaught = *unexpected* exception reportInformation.wzFriendlyEventName = null; // null = the name specified by pwzEventType parameter of WerReportCreate. @@ -860,21 +860,21 @@ namespace System.Management.Automation HandleHResult(NativeMethods.WerReportAddDump( reportHandle, - hCurrentProcess, + s_hCurrentProcess, IntPtr.Zero, // thread id is only required for *micro* dumps DumpType.MiniDump, IntPtr.Zero, // exception details. IntPtr.Zero, // dumpCustomOptions - if this parameter is NULL, the standard minidump information is collected. - /*DumpFlags.NoHeap_OnQueue*/0)); // can't use NoHeap_OnQueue, because then we probably won't - // be able to request full heap dumps via http://watson web UI + /*DumpFlags.NoHeap_OnQueue*/0)); // can't use NoHeap_OnQueue, because then we probably won't + // be able to request full heap dumps via http://watson web UI SubmitResult submitResult = SubmitResult.ReportFailed; - SubmitFlags submitFlags = - SubmitFlags.HonorRecovery | - SubmitFlags.HonorRestart | - SubmitFlags.OutOfProcess | + SubmitFlags submitFlags = + SubmitFlags.HonorRecovery | + SubmitFlags.HonorRestart | + SubmitFlags.OutOfProcess | SubmitFlags.AddRegisteredData; - if (WindowsErrorReporting.unattendedServerMode) + if (WindowsErrorReporting.s_unattendedServerMode) { submitFlags |= SubmitFlags.Queue; } @@ -895,7 +895,7 @@ namespace System.Management.Automation static internal void WaitForPendingReports() { - lock (reportCreationLock) + lock (s_reportCreationLock) { // only return if the lock is not taken return; @@ -922,7 +922,7 @@ namespace System.Management.Automation try { - if (registered && (null != exception)) + if (s_registered && (null != exception)) { Debug.Assert(IsWindowsErrorReportingAvailable(), "Registration should succeed only if WER.dll is available"); WindowsErrorReporting.SubmitReport(exception); @@ -943,9 +943,9 @@ namespace System.Management.Automation } } - static private readonly object registrationLock = new object(); - static private bool registered = false; - static private bool unattendedServerMode = false; + static private readonly object s_registrationLock = new object(); + static private bool s_registered = false; + static private bool s_unattendedServerMode = false; /// /// Sets everything up to report unhandled exceptions. @@ -956,9 +956,9 @@ namespace System.Management.Automation /// If true, then reports are not going to require any user interaction static internal void RegisterWindowsErrorReporting(bool unattendedServer) { - lock (registrationLock) + lock (s_registrationLock) { - if (!registered && IsWindowsErrorReportingAvailable()) + if (!s_registered && IsWindowsErrorReportingAvailable()) { try { @@ -969,14 +969,14 @@ namespace System.Management.Automation // get Process related data..and it is ok to not report // that data (this data helps making debugging/analysing easy) catch (Exception e) - { + { CommandProcessorBase.CheckForSevereException(e); // suppress the exception } try { - WindowsErrorReporting.unattendedServerMode = unattendedServer; + WindowsErrorReporting.s_unattendedServerMode = unattendedServer; if (unattendedServer) { HandleHResult(NativeMethods.WerSetFlags(ReportingFlags.Queue)); @@ -987,7 +987,7 @@ namespace System.Management.Automation } AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); - registered = true; + s_registered = true; } // there is some problem setting flags...handle those cases catch (Exception e) diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs index a6a5830ca..945e4b3d3 100644 --- a/src/System.Management.Automation/utils/assert.cs +++ b/src/System.Management.Automation/utils/assert.cs @@ -25,18 +25,18 @@ namespace System.Management.Automation /// /// Exception with a full stack trace excluding the last two frames /// - internal class AssertException: SystemException + internal class AssertException : SystemException { /// /// calls the base class with message and sets the stack frame /// /// repassed to the base class - internal AssertException(string message):base(message) + internal AssertException(string message) : base(message) { // 3 will skip the assertion caller, this method and AssertException.StackTrace - stackTrace = Diagnostics.StackTrace(3); + _stackTrace = Diagnostics.StackTrace(3); } - private string stackTrace; + private string _stackTrace; /// /// returns the stack trace set in the constructor /// @@ -45,7 +45,7 @@ namespace System.Management.Automation { get { - return stackTrace; + return _stackTrace; } } } @@ -87,9 +87,9 @@ namespace System.Management.Automation #endif } - private static object throwInsteadOfAssertLock = 1; + private static object s_throwInsteadOfAssertLock = 1; - private static bool throwInsteadOfAssert = false; + private static bool s_throwInsteadOfAssert = false; /// /// If set to true will prevent the assertion dialog from showing up /// by throwing an exception instead of calling Debug.Assert @@ -97,18 +97,18 @@ namespace System.Management.Automation /// false for dialog, true for exception internal static bool ThrowInsteadOfAssert { - get + get { - lock (throwInsteadOfAssertLock) + lock (s_throwInsteadOfAssertLock) { - return throwInsteadOfAssert; + return s_throwInsteadOfAssert; } } - set + set { - lock (throwInsteadOfAssertLock) + lock (s_throwInsteadOfAssertLock) { - throwInsteadOfAssert = value; + s_throwInsteadOfAssert = value; } } } @@ -116,7 +116,7 @@ namespace System.Management.Automation /// /// This class only has statics, so we shouldn't need to instantiate any object. /// - private Diagnostics() {} + private Diagnostics() { } /// /// Basic assertion with logical condition and message @@ -169,7 +169,7 @@ namespace System.Management.Automation #if RESHARPER_ATTRIBUTES [JetBrains.Annotations.AssertionMethod] #endif - internal static void + internal static void Assert( #if RESHARPER_ATTRIBUTES [JetBrains.Annotations.AssertionCondition(JetBrains.Annotations.AssertionConditionType.IS_TRUE)] diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs index a38e96a7f..83f82ed4e 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs @@ -42,7 +42,7 @@ namespace System.Management.Automation.PerformanceData /// Dictionary mapping counter name to id. /// [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - protected ConcurrentDictionary _counterNameToIdMapping; + protected ConcurrentDictionary _counterNameToIdMapping; /// /// Dictionary mapping counter id to counter type. /// @@ -61,7 +61,7 @@ namespace System.Management.Automation.PerformanceData CounterInfo[] counterInfoArray = this._counterSetRegistrarBase.CounterInfoArray; - for(int i=0; i < counterInfoArray.Length; i++) + for (int i = 0; i < counterInfoArray.Length; i++) { this._counterIdToTypeMapping.TryAdd(counterInfoArray[i].Id, counterInfoArray[i].Type); if (!string.IsNullOrWhiteSpace(counterInfoArray[i].Name)) @@ -103,7 +103,7 @@ namespace System.Management.Automation.PerformanceData } if (isDenominatorValid == false) { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, @@ -130,7 +130,7 @@ namespace System.Management.Automation.PerformanceData int counterId, long stepAmount, bool isNumerator); - + /// /// If isNumerator is true, then updates the numerator component @@ -307,7 +307,7 @@ namespace System.Management.Automation.PerformanceData protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. - if (!this._Disposed) + if (!_Disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. @@ -318,7 +318,7 @@ namespace System.Management.Automation.PerformanceData _CounterSet.Dispose(); } // Note disposing has been done. - this._Disposed = true; + _Disposed = true; } } @@ -337,7 +337,6 @@ namespace System.Management.Automation.PerformanceData // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); - } #endregion @@ -353,7 +352,7 @@ namespace System.Management.Automation.PerformanceData /// public override bool UpdateCounterByValue(int counterId, long stepAmount, bool isNumerator) { - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -362,9 +361,9 @@ namespace System.Management.Automation.PerformanceData } int targetCounterId; - if(base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) + if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) { - CounterData targetCounterData = this._CounterSetInstance.Counters[targetCounterId]; + CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; if (targetCounterData != null) { this.UpdateCounterByValue(targetCounterData, stepAmount); @@ -394,7 +393,7 @@ namespace System.Management.Automation.PerformanceData /// public override bool UpdateCounterByValue(string counterName, long stepAmount, bool isNumerator) { - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -425,7 +424,6 @@ namespace System.Management.Automation.PerformanceData _tracer.TraceException(invalidOperationException); return false; } - } /// @@ -435,7 +433,7 @@ namespace System.Management.Automation.PerformanceData /// public override bool SetCounterValue(int counterId, long counterValue, bool isNumerator) { - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -444,9 +442,9 @@ namespace System.Management.Automation.PerformanceData } int targetCounterId; - if(base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) + if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) { - CounterData targetCounterData = this._CounterSetInstance.Counters[targetCounterId]; + CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; if (targetCounterData != null) { @@ -455,11 +453,11 @@ namespace System.Management.Automation.PerformanceData } else { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter id {0} failed", + "Lookup for counter corresponding to counter id {0} failed", counterId)); _tracer.TraceException(invalidOperationException); return false; @@ -478,7 +476,7 @@ namespace System.Management.Automation.PerformanceData /// public override bool SetCounterValue(string counterName, long counterValue, bool isNumerator) { - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -504,12 +502,11 @@ namespace System.Management.Automation.PerformanceData new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, - "Lookup for counter corresponding to counter name {0} failed", + "Lookup for counter corresponding to counter name {0} failed", counterName)); _tracer.TraceException(invalidOperationException); return false; } - } /// @@ -519,7 +516,7 @@ namespace System.Management.Automation.PerformanceData public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue) { counterValue = -1; - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -529,7 +526,7 @@ namespace System.Management.Automation.PerformanceData int targetCounterId; if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) { - CounterData targetCounterData = this._CounterSetInstance.Counters[targetCounterId]; + CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; if (targetCounterData != null) { @@ -538,7 +535,7 @@ namespace System.Management.Automation.PerformanceData } else { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, @@ -552,7 +549,6 @@ namespace System.Management.Automation.PerformanceData { return false; } - } @@ -563,7 +559,7 @@ namespace System.Management.Automation.PerformanceData public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue) { counterValue = -1; - if (this._Disposed) + if (_Disposed) { ObjectDisposedException objectDisposedException = new ObjectDisposedException("PSCounterSetInstance"); @@ -593,13 +589,10 @@ namespace System.Management.Automation.PerformanceData 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 index 215e0a5a1..7b6bf41be 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -40,9 +40,9 @@ namespace System.Management.Automation.PerformanceData /// public CounterInfo(int id, CounterType type, string name) { - this._Id = id; - this._Type = type; - this._Name = name; + _Id = id; + _Type = type; + _Name = name; } /// @@ -50,9 +50,9 @@ namespace System.Management.Automation.PerformanceData /// public CounterInfo(int id, CounterType type) { - this._Id = id; - this._Type = type; - this._Name = null; + _Id = id; + _Type = type; + _Name = null; } #endregion @@ -64,7 +64,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._Name; + return _Name; } } @@ -75,7 +75,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._Id; + return _Id; } } @@ -87,7 +87,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._Type; + return _Type; } } @@ -113,7 +113,7 @@ namespace System.Management.Automation.PerformanceData private readonly CounterInfo[] _counterInfoArray; #endregion - + #region Protected Members /// /// A reference to the encapsulated counter set instance. @@ -130,7 +130,7 @@ namespace System.Management.Automation.PerformanceData #endregion - + #region Constructors /// /// Constructor that creates an instance of CounterSetRegistrarBase derived type @@ -143,23 +143,23 @@ namespace System.Management.Automation.PerformanceData Guid counterSetId, CounterSetInstanceType counterSetInstType, CounterInfo[] counterInfoArray, - string counterSetName=null) + string counterSetName = null) { - this._providerId = providerId; - this._counterSetId = counterSetId; - this._counterSetInstanceType = counterSetInstType; - this._counterSetName = counterSetName; - if((counterInfoArray == null) + _providerId = providerId; + _counterSetId = counterSetId; + _counterSetInstanceType = counterSetInstType; + _counterSetName = counterSetName; + if ((counterInfoArray == null) || (counterInfoArray.Length == 0)) { throw new ArgumentNullException("counterInfoArray"); } - this._counterInfoArray = new CounterInfo[counterInfoArray.Length]; + _counterInfoArray = new CounterInfo[counterInfoArray.Length]; for (int i = 0; i < counterInfoArray.Length; i++) { - this._counterInfoArray[i] = + _counterInfoArray[i] = new CounterInfo( counterInfoArray[i].Id, counterInfoArray[i].Type, @@ -179,23 +179,22 @@ namespace System.Management.Automation.PerformanceData { throw new ArgumentNullException("srcCounterSetRegistrarBase"); } - this._providerId = srcCounterSetRegistrarBase._providerId; - this._counterSetId = srcCounterSetRegistrarBase._counterSetId; - this._counterSetInstanceType = srcCounterSetRegistrarBase._counterSetInstanceType; - this._counterSetName = srcCounterSetRegistrarBase._counterSetName; + _providerId = srcCounterSetRegistrarBase._providerId; + _counterSetId = srcCounterSetRegistrarBase._counterSetId; + _counterSetInstanceType = srcCounterSetRegistrarBase._counterSetInstanceType; + _counterSetName = srcCounterSetRegistrarBase._counterSetName; CounterInfo[] counterInfoArrayRef = srcCounterSetRegistrarBase._counterInfoArray; - this._counterInfoArray = new CounterInfo[counterInfoArrayRef.Length]; + _counterInfoArray = new CounterInfo[counterInfoArrayRef.Length]; for (int i = 0; i < counterInfoArrayRef.Length; i++) { - this._counterInfoArray[i] = + _counterInfoArray[i] = new CounterInfo( counterInfoArrayRef[i].Id, counterInfoArrayRef[i].Type, counterInfoArrayRef[i].Name); } - } #endregion @@ -204,11 +203,11 @@ namespace System.Management.Automation.PerformanceData /// /// Getter method for ProviderId property /// - public Guid ProviderId - { + public Guid ProviderId + { get { - return this._providerId; + return _providerId; } } @@ -219,7 +218,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._counterSetId; + return _counterSetId; } } @@ -230,7 +229,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._counterSetName; + return _counterSetName; } } @@ -241,7 +240,7 @@ namespace System.Management.Automation.PerformanceData { get { - return this._counterSetInstanceType; + return _counterSetInstanceType; } } @@ -253,11 +252,11 @@ namespace System.Management.Automation.PerformanceData { get { - return this._counterInfoArray; + return _counterInfoArray; } } - + /// /// Getter method that returns an instance of the CounterSetInstanceBase's /// derived type @@ -273,13 +272,13 @@ namespace System.Management.Automation.PerformanceData return this._counterSetInstanceBase; } } - + #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 @@ -287,9 +286,8 @@ namespace System.Management.Automation.PerformanceData /// cleanup procedure. /// public abstract void DisposeCounterSetInstance(); - + #endregion - } /// @@ -333,7 +331,7 @@ namespace System.Management.Automation.PerformanceData #endregion #region CounterSetRegistrarBase Overrides - + #region Protected Methods /// @@ -354,12 +352,10 @@ namespace System.Management.Automation.PerformanceData { base._counterSetInstanceBase.Dispose(); } - - #endregion - - + #endregion + + #endregion } - } diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs index a533978e2..d84ee4534 100644 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs @@ -24,7 +24,7 @@ namespace System.Management.Automation.PerformanceData public class PSPerfCountersMgr { #region Private Members - private static PSPerfCountersMgr _PSPerfCountersMgrInstance; + private static PSPerfCountersMgr s_PSPerfCountersMgrInstance; private ConcurrentDictionary _CounterSetIdToInstanceMapping; private ConcurrentDictionary _CounterSetNameToIdMapping; private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); @@ -33,8 +33,8 @@ namespace System.Management.Automation.PerformanceData private PSPerfCountersMgr() { - this._CounterSetIdToInstanceMapping = new ConcurrentDictionary(); - this._CounterSetNameToIdMapping = new ConcurrentDictionary(); + _CounterSetIdToInstanceMapping = new ConcurrentDictionary(); + _CounterSetNameToIdMapping = new ConcurrentDictionary(); } #endregion @@ -63,11 +63,11 @@ namespace System.Management.Automation.PerformanceData { get { - if (_PSPerfCountersMgrInstance == null) + if (s_PSPerfCountersMgrInstance == null) { - _PSPerfCountersMgrInstance = new PSPerfCountersMgr(); + s_PSPerfCountersMgrInstance = new PSPerfCountersMgr(); } - return _PSPerfCountersMgrInstance; + return s_PSPerfCountersMgrInstance; } } @@ -94,7 +94,7 @@ namespace System.Management.Automation.PerformanceData _tracer.TraceException(argNullException); return false; } - return this._CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId); + return _CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId); } /// @@ -103,7 +103,7 @@ namespace System.Management.Automation.PerformanceData /// public bool IsCounterSetRegistered(Guid counterSetId, out CounterSetInstanceBase counterSetInst) { - return this._CounterSetIdToInstanceMapping.TryGetValue(counterSetId, out counterSetInst); + return _CounterSetIdToInstanceMapping.TryGetValue(counterSetId, out counterSetInst); } /// @@ -111,14 +111,13 @@ namespace System.Management.Automation.PerformanceData /// 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; @@ -151,12 +150,11 @@ namespace System.Management.Automation.PerformanceData _tracer.TraceException(invalidOperationException); return false; } - this._CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId); + _CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId); } - this._CounterSetIdToInstanceMapping.TryAdd( + _CounterSetIdToInstanceMapping.TryAdd( counterSetId, counterSetRegistrarInstance.CounterSetInstance); - } catch (OverflowException overflowException) { @@ -164,7 +162,7 @@ namespace System.Management.Automation.PerformanceData return false; } return true; - } + } /// /// If IsNumerator is true, then updates the numerator component @@ -186,7 +184,7 @@ namespace System.Management.Automation.PerformanceData } else { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, @@ -251,7 +249,7 @@ namespace System.Management.Automation.PerformanceData Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { - CounterSetInstanceBase counterSetInst = this._CounterSetIdToInstanceMapping[counterSetId]; + CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator); } else @@ -292,7 +290,7 @@ namespace System.Management.Automation.PerformanceData if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { - CounterSetInstanceBase counterSetInst = this._CounterSetIdToInstanceMapping[counterSetId]; + CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator); } else @@ -328,7 +326,7 @@ namespace System.Management.Automation.PerformanceData } else { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, @@ -394,7 +392,7 @@ namespace System.Management.Automation.PerformanceData Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { - CounterSetInstanceBase counterSetInst = this._CounterSetIdToInstanceMapping[counterSetId]; + CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator); } else @@ -434,12 +432,12 @@ namespace System.Management.Automation.PerformanceData Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { - CounterSetInstanceBase counterSetInst = this._CounterSetIdToInstanceMapping[counterSetId]; + CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator); } else { - InvalidOperationException invalidOperationException = + InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, @@ -460,17 +458,16 @@ namespace System.Management.Automation.PerformanceData /// internal void RemoveAllCounterSets() { - ICollection counterSetIdKeys = this._CounterSetIdToInstanceMapping.Keys; + ICollection counterSetIdKeys = _CounterSetIdToInstanceMapping.Keys; foreach (Guid counterSetId in counterSetIdKeys) { - CounterSetInstanceBase currentCounterSetInstance = this._CounterSetIdToInstanceMapping[counterSetId]; + CounterSetInstanceBase currentCounterSetInstance = _CounterSetIdToInstanceMapping[counterSetId]; currentCounterSetInstance.Dispose(); } - this._CounterSetIdToInstanceMapping.Clear(); - this._CounterSetNameToIdMapping.Clear(); + _CounterSetIdToInstanceMapping.Clear(); + _CounterSetNameToIdMapping.Clear(); } #endregion - } } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 5352749db..fa6f37af4 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -10,35 +10,36 @@ using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Tracing { - /// - /// Attribute to represent an EtwEvent - /// - [AttributeUsage(AttributeTargets.Method)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] - public sealed class EtwEvent : Attribute - { - private long eventId; + /// + /// Attribute to represent an EtwEvent + /// + [AttributeUsage(AttributeTargets.Method)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] + public sealed class EtwEvent : Attribute + { + private long eventId; - /// - /// Constructor - /// - /// - public EtwEvent(long eventId) - { - this.eventId = eventId; - } + /// + /// Constructor + /// + /// + public EtwEvent(long eventId) + { + this.eventId = eventId; + } - /// - /// EventId - /// - public long EventId { - get - { - return eventId; - } - } - } + /// + /// EventId + /// + public long EventId + { + get + { + return eventId; + } + } + } /// /// Delegates that defines a call back with no parameter @@ -103,7 +104,7 @@ namespace System.Management.Automation.Tracing /// /// This the abstract base class of all activity classes that represent an end-to-end scenario. /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public abstract class EtwActivity { /// @@ -265,7 +266,7 @@ namespace System.Management.Automation.Tracing private static Dictionary providers = new Dictionary(); private static object syncLock = new object(); - private static EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long) 0x4000000000000000); + private static EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); private EventProvider currentProvider; @@ -274,7 +275,8 @@ namespace System.Management.Automation.Tracing /// public static event EventHandler EventWritten; - static EtwActivity() { + static EtwActivity() + { } /// @@ -308,7 +310,7 @@ namespace System.Management.Automation.Tracing /// Returns the ActivityId set in current thread /// /// - [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] + [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] public static Guid GetActivityId() { Guid activityId = Guid.Empty; @@ -319,7 +321,8 @@ namespace System.Management.Automation.Tracing /// /// Constructor /// - protected EtwActivity() { + protected EtwActivity() + { } /// @@ -374,7 +377,7 @@ namespace System.Management.Automation.Tracing Guid parentAcitvity = GetActivityId(); CorrelateWithActivity(parentAcitvity); } - + /// /// Wraps a callback with no params /// @@ -464,9 +467,10 @@ namespace System.Management.Automation.Tracing /// /// EventDescriptor /// payload - protected void WriteEvent(EventDescriptor ed, params object[] payload) { + protected void WriteEvent(EventDescriptor ed, params object[] payload) + { EventProvider provider = GetProvider(); - + if (!provider.IsEnabled()) return; diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs index ad79f6160..32f0b7526 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs @@ -1,6 +1,5 @@ #if !UNIX //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index 3a3c48463..2ff6e47de 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -1,6 +1,5 @@ #if !UNIX //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- @@ -12,14 +11,14 @@ namespace System.Management.Automation.Tracing internal class EtwActivityReverterMethodInvoker : IMethodInvoker { - #region Instance Data +#region Instance Data private readonly IEtwEventCorrelator _eventCorrelator; private readonly Func _invoker; - #endregion +#endregion - #region Creation/Cleanup +#region Creation/Cleanup public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { @@ -32,9 +31,9 @@ namespace System.Management.Automation.Tracing _invoker = DoInvoke; } - #endregion +#endregion - #region Instsance Access +#region Instsance Access public Delegate Invoker { @@ -54,9 +53,9 @@ namespace System.Management.Automation.Tracing return retInvokerArgs; } - #endregion +#endregion - #region Instance Utilities +#region Instance Utilities private object DoInvoke(Guid relatedActivityId, Delegate method, object[] methodArgs) { @@ -66,7 +65,7 @@ namespace System.Management.Automation.Tracing } } - #endregion +#endregion } } diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index b08cc7586..182b0afea 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -1,6 +1,5 @@ #if !UNIX //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- diff --git a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs index 3f1ebf579..134e6bc90 100644 --- a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs @@ -1,6 +1,5 @@ #if !UNIX //----------------------------------------------------------------------- -// // Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------- diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 7e3030b0d..9f3d9d28c 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -270,14 +270,14 @@ namespace System.Management.Automation.Tracing provider.SetActivityIdForCurrentThread(newActivityId); } - static internal void ReplaceActivityIdForCurrentThread(Guid newActivityId, + static internal void ReplaceActivityIdForCurrentThread(Guid newActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - // set the new activity id + // set the new activity id provider.SetActivityIdForCurrentThread(newActivityId); // Once the activity id is set, write the transfer event - WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); + WriteTransferEvent(newActivityId, eventForOperationalChannel, eventForAnalyticChannel, keyword, task); } /// @@ -294,7 +294,7 @@ namespace System.Management.Automation.Tracing static internal void WriteTransferEvent(Guid relatedActivityId, PSEventId eventForOperationalChannel, PSEventId eventForAnalyticChannel, PSKeyword keyword, PSTask task) { - provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method,PSLevel.Informational, task, + provider.WriteEvent(eventForOperationalChannel, PSChannel.Operational, PSOpcode.Method, PSLevel.Informational, task, PSKeyword.UseAlwaysOperational); provider.WriteEvent(eventForAnalyticChannel, PSChannel.Analytic, PSOpcode.Method, PSLevel.Informational, task, diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 8fd0d9612..f159f7b25 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -18,27 +18,27 @@ namespace System.Management.Automation.Tracing private static readonly string PowerShellEventProviderGuid = "A0C1853B-5C40-4b15-8766-3CF1C58F985A"; private static EventDescriptor _xferEventDescriptor = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); - static class Strings + private static class Strings { // The strings are stored in a different class to defer loading the resources until as late // as possible, e.g. if logging is never on, these strings won't be loaded. - internal static readonly string LogContextSeverity = EtwLoggingStrings.LogContextSeverity; - internal static readonly string LogContextHostName = EtwLoggingStrings.LogContextHostName; - internal static readonly string LogContextHostVersion = EtwLoggingStrings.LogContextHostVersion; - internal static readonly string LogContextHostId = EtwLoggingStrings.LogContextHostId; + internal static readonly string LogContextSeverity = EtwLoggingStrings.LogContextSeverity; + internal static readonly string LogContextHostName = EtwLoggingStrings.LogContextHostName; + internal static readonly string LogContextHostVersion = EtwLoggingStrings.LogContextHostVersion; + internal static readonly string LogContextHostId = EtwLoggingStrings.LogContextHostId; internal static readonly string LogContextHostApplication = EtwLoggingStrings.LogContextHostApplication; - internal static readonly string LogContextEngineVersion = EtwLoggingStrings.LogContextEngineVersion; - internal static readonly string LogContextRunspaceId = EtwLoggingStrings.LogContextRunspaceId; - internal static readonly string LogContextPipelineId = EtwLoggingStrings.LogContextPipelineId; - internal static readonly string LogContextCommandName = EtwLoggingStrings.LogContextCommandName; - internal static readonly string LogContextCommandType = EtwLoggingStrings.LogContextCommandType; - internal static readonly string LogContextScriptName = EtwLoggingStrings.LogContextScriptName; - internal static readonly string LogContextCommandPath = EtwLoggingStrings.LogContextCommandPath; - internal static readonly string LogContextSequenceNumber = EtwLoggingStrings.LogContextSequenceNumber; - internal static readonly string LogContextUser = EtwLoggingStrings.LogContextUser; - internal static readonly string LogContextConnectedUser = EtwLoggingStrings.LogContextConnectedUser; - internal static readonly string LogContextTime = EtwLoggingStrings.LogContextTime; - internal static readonly string LogContextShellId = EtwLoggingStrings.LogContextShellId; + internal static readonly string LogContextEngineVersion = EtwLoggingStrings.LogContextEngineVersion; + internal static readonly string LogContextRunspaceId = EtwLoggingStrings.LogContextRunspaceId; + internal static readonly string LogContextPipelineId = EtwLoggingStrings.LogContextPipelineId; + internal static readonly string LogContextCommandName = EtwLoggingStrings.LogContextCommandName; + internal static readonly string LogContextCommandType = EtwLoggingStrings.LogContextCommandType; + internal static readonly string LogContextScriptName = EtwLoggingStrings.LogContextScriptName; + internal static readonly string LogContextCommandPath = EtwLoggingStrings.LogContextCommandPath; + internal static readonly string LogContextSequenceNumber = EtwLoggingStrings.LogContextSequenceNumber; + internal static readonly string LogContextUser = EtwLoggingStrings.LogContextUser; + internal static readonly string LogContextConnectedUser = EtwLoggingStrings.LogContextConnectedUser; + internal static readonly string LogContextTime = EtwLoggingStrings.LogContextTime; + internal static readonly string LogContextShellId = EtwLoggingStrings.LogContextShellId; } /// @@ -63,7 +63,7 @@ namespace System.Management.Automation.Tracing /// internal bool IsEnabled(PSLevel level, PSKeyword keywords) { - return etwProvider.IsEnabled((byte) level, (long) keywords); + return etwProvider.IsEnabled((byte)level, (long)keywords); } /// @@ -444,7 +444,7 @@ namespace System.Management.Automation.Tracing etwProvider.WriteEvent(ref desc, args); } - + /// /// Writes an activity transfer event /// diff --git a/src/System.Management.Automation/utils/tracing/Tracing.cs b/src/System.Management.Automation/utils/tracing/Tracing.cs index b7360ca09..06744989e 100644 --- a/src/System.Management.Automation/utils/tracing/Tracing.cs +++ b/src/System.Management.Automation/utils/tracing/Tracing.cs @@ -4,55 +4,56 @@ // using System.Text; -namespace System.Management.Automation.Tracing { +namespace System.Management.Automation.Tracing +{ + /// + /// Tracer + /// + public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity + { + /// + /// DebugMessage + /// + [EtwEvent(0xc000)] + public void DebugMessage(Exception exception) + { + if (exception == null) + return; - /// - /// Tracer - /// - public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity { - /// - /// DebugMessage - /// - [EtwEvent(0xc000)] - public void DebugMessage(Exception exception) - { - if (exception == null) - return; + DebugMessage(GetExceptionString(exception)); + } - DebugMessage(GetExceptionString(exception)); - } + /// + /// Converts exception object into a string. + /// + /// + /// + public static string GetExceptionString(Exception exception) + { + if (exception == null) + return string.Empty; - /// - /// Converts exception object into a string. - /// - /// - /// - public static string GetExceptionString(Exception exception) - { - if (exception == null) - return string.Empty; + StringBuilder sb = new StringBuilder(); + while (WriteExceptionText(sb, exception)) + { + exception = exception.InnerException; + } + return sb.ToString(); + } - StringBuilder sb = new StringBuilder(); - while(WriteExceptionText(sb, exception)) - { - exception = exception.InnerException; - } - return sb.ToString(); - } + private static bool WriteExceptionText(StringBuilder sb, Exception e) + { + if (e == null) + return false; - private static bool WriteExceptionText(StringBuilder sb, Exception e) - { - if (e == null) - return false; + sb.Append(e.GetType().Name); + sb.Append(Environment.NewLine); + sb.Append(e.Message); + sb.Append(Environment.NewLine); - sb.Append(e.GetType().Name); - sb.Append(Environment.NewLine); - sb.Append(e.Message); - sb.Append(Environment.NewLine); - - return true; - } - } + return true; + } + } } #endif diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index 3cff0e265..d45618bb4 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -6,985 +6,984 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Tracing; -namespace System.Management.Automation.Tracing { - - /// - /// Tracer - /// - public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity { - /// - /// Critical level - /// - public const byte LevelCritical = 1; - /// - /// Error level - /// - public const byte LevelError = 2; - /// - /// Warning level - /// - public const byte LevelWarning = 3; - /// - /// Informational level - /// - public const byte LevelInformational = 4; - /// - /// Verbose level - /// - public const byte LevelVerbose = 5; - /// - /// Keyword all - /// - public const long KeywordAll = 0xFFFFFFFF; - private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); - private static EventDescriptor WriteTransferEventEvent; - private static EventDescriptor DebugMessageEvent; - private static EventDescriptor M3PAbortingWorkflowExecutionEvent; - private static EventDescriptor M3PActivityExecutionFinishedEvent; - private static EventDescriptor M3PActivityExecutionQueuedEvent; - private static EventDescriptor M3PActivityExecutionStartedEvent; - private static EventDescriptor M3PBeginContainerParentJobExecutionEvent; - private static EventDescriptor M3PBeginCreateNewJobEvent; - private static EventDescriptor M3PBeginJobLogicEvent; - private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobExecutionEvent; - private static EventDescriptor M3PBeginRunGarbageCollectionEvent; - private static EventDescriptor M3PBeginStartWorkflowApplicationEvent; - private static EventDescriptor M3PBeginWorkflowExecutionEvent; - private static EventDescriptor M3PCancellingWorkflowExecutionEvent; - private static EventDescriptor M3PChildWorkflowJobAdditionEvent; - private static EventDescriptor M3PEndContainerParentJobExecutionEvent; - private static EventDescriptor M3PEndCreateNewJobEvent; - private static EventDescriptor M3PEndJobLogicEvent; - private static EventDescriptor M3PEndpointDisabledEvent; - private static EventDescriptor M3PEndpointEnabledEvent; - private static EventDescriptor M3PEndpointModifiedEvent; - private static EventDescriptor M3PEndpointRegisteredEvent; - private static EventDescriptor M3PEndpointUnregisteredEvent; - private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobExecutionEvent; - private static EventDescriptor M3PEndRunGarbageCollectionEvent; - private static EventDescriptor M3PEndStartWorkflowApplicationEvent; - private static EventDescriptor M3PEndWorkflowExecutionEvent; - private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent; - private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; - private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent; - private static EventDescriptor M3PImportedWorkflowFromXamlEvent; - private static EventDescriptor M3PImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PJobCreationCompleteEvent; - private static EventDescriptor M3PJobErrorEvent; - private static EventDescriptor M3PJobRemovedEvent; - private static EventDescriptor M3PJobRemoveErrorEvent; - private static EventDescriptor M3PJobStateChangedEvent; - private static EventDescriptor M3PLoadingWorkflowForExecutionEvent; - private static EventDescriptor M3POutOfProcessRunspaceStartedEvent; - private static EventDescriptor M3PParameterSplattingWasPerformedEvent; - private static EventDescriptor M3PParentJobCreatedEvent; - private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; - private static EventDescriptor M3PPersistingWorkflowEvent; - private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent; - private static EventDescriptor M3PRemoveJobStartedEvent; - private static EventDescriptor M3PRunspaceAvailabilityChangedEvent; - private static EventDescriptor M3PRunspaceStateChangedEvent; - private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; - private static EventDescriptor M3PUnloadingWorkflowEvent; - private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent; - private static EventDescriptor M3PWorkflowActivityValidatedEvent; - private static EventDescriptor M3PWorkflowActivityValidationFailedEvent; - private static EventDescriptor M3PWorkflowCleanupPerformedEvent; - private static EventDescriptor M3PWorkflowDeletedFromDiskEvent; - private static EventDescriptor M3PWorkflowEngineStartedEvent; - private static EventDescriptor M3PWorkflowExecutionAbortedEvent; - private static EventDescriptor M3PWorkflowExecutionCancelledEvent; - private static EventDescriptor M3PWorkflowExecutionErrorEvent; - private static EventDescriptor M3PWorkflowExecutionFinishedEvent; - private static EventDescriptor M3PWorkflowExecutionStartedEvent; - private static EventDescriptor M3PWorkflowJobCreatedEvent; - private static EventDescriptor M3PWorkflowLoadedForExecutionEvent; - private static EventDescriptor M3PWorkflowLoadedFromDiskEvent; - private static EventDescriptor M3PWorkflowManagerCheckpointEvent; - private static EventDescriptor M3PWorkflowPersistedEvent; - private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; - private static EventDescriptor M3PWorkflowPluginRestartedEvent; - private static EventDescriptor M3PWorkflowPluginStartedEvent; - private static EventDescriptor M3PWorkflowQuotaViolatedEvent; - private static EventDescriptor M3PWorkflowResumedEvent; - private static EventDescriptor M3PWorkflowResumingEvent; - private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; - private static EventDescriptor M3PWorkflowStateChangedEvent; - private static EventDescriptor M3PWorkflowUnloadedEvent; - private static EventDescriptor M3PWorkflowValidationErrorEvent; - private static EventDescriptor M3PWorkflowValidationFinishedEvent; - private static EventDescriptor M3PWorkflowValidationStartedEvent; - - /// - /// Static constructor - /// - static Tracer() { - unchecked { - WriteTransferEventEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); - DebugMessageEvent = new EventDescriptor(0xc000, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PAbortingWorkflowExecutionEvent = new EventDescriptor(0xb038, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PActivityExecutionFinishedEvent = new EventDescriptor(0xb03f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PActivityExecutionQueuedEvent = new EventDescriptor(0xb017, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PActivityExecutionStartedEvent = new EventDescriptor(0xb018, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PBeginContainerParentJobExecutionEvent = new EventDescriptor(0xb50c, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginCreateNewJobEvent = new EventDescriptor(0xb503, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginJobLogicEvent = new EventDescriptor(0xb506, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginProxyChildJobEventHandlerEvent = new EventDescriptor(0xb512, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginProxyJobEventHandlerEvent = new EventDescriptor(0xb510, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginProxyJobExecutionEvent = new EventDescriptor(0xb50e, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginRunGarbageCollectionEvent = new EventDescriptor(0xb514, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginStartWorkflowApplicationEvent = new EventDescriptor(0xb501, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PBeginWorkflowExecutionEvent = new EventDescriptor(0xb508, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PCancellingWorkflowExecutionEvent = new EventDescriptor(0xb037, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PChildWorkflowJobAdditionEvent = new EventDescriptor(0xb50a, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndContainerParentJobExecutionEvent = new EventDescriptor(0xb50d, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndCreateNewJobEvent = new EventDescriptor(0xb504, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndJobLogicEvent = new EventDescriptor(0xb507, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndpointDisabledEvent = new EventDescriptor(0xb044, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); - M3PEndpointEnabledEvent = new EventDescriptor(0xb045, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); - M3PEndpointModifiedEvent = new EventDescriptor(0xb042, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); - M3PEndpointRegisteredEvent = new EventDescriptor(0xb041, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); - M3PEndpointUnregisteredEvent = new EventDescriptor(0xb043, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); - M3PEndProxyChildJobEventHandlerEvent = new EventDescriptor(0xb513, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndProxyJobEventHandlerEvent = new EventDescriptor(0xb511, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndProxyJobExecutionEvent = new EventDescriptor(0xb50f, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndRunGarbageCollectionEvent = new EventDescriptor(0xb515, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndStartWorkflowApplicationEvent = new EventDescriptor(0xb502, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PEndWorkflowExecutionEvent = new EventDescriptor(0xb509, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PErrorImportingWorkflowFromXamlEvent = new EventDescriptor(0xb01b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PForcedWorkflowShutdownErrorEvent = new EventDescriptor(0xb03c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PForcedWorkflowShutdownFinishedEvent = new EventDescriptor(0xb03b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PForcedWorkflowShutdownStartedEvent = new EventDescriptor(0xb03a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PImportedWorkflowFromXamlEvent = new EventDescriptor(0xb01a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PImportingWorkflowFromXamlEvent = new EventDescriptor(0xb019, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PJobCreationCompleteEvent = new EventDescriptor(0xb032, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PJobErrorEvent = new EventDescriptor(0xb02e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PJobRemovedEvent = new EventDescriptor(0xb033, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PJobRemoveErrorEvent = new EventDescriptor(0xb034, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PJobStateChangedEvent = new EventDescriptor(0xb02d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PLoadingWorkflowForExecutionEvent = new EventDescriptor(0xb035, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3POutOfProcessRunspaceStartedEvent = new EventDescriptor(0xb046, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PParameterSplattingWasPerformedEvent = new EventDescriptor(0xb047, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PParentJobCreatedEvent = new EventDescriptor(0xb031, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PPersistenceStoreMaxSizeReachedEvent = new EventDescriptor(0xb516, 0x1, 0x10, 0x3, 0x0, 0x0, (long)0x8000000000000000); - M3PPersistingWorkflowEvent = new EventDescriptor(0xb03d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PProxyJobRemoteJobAssociationEvent = new EventDescriptor(0xb50b, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PRemoveJobStartedEvent = new EventDescriptor(0xb02c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PRunspaceAvailabilityChangedEvent = new EventDescriptor(0xb022, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PRunspaceStateChangedEvent = new EventDescriptor(0xb023, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PTrackingGuidContainerParentJobCorrelationEvent = new EventDescriptor(0xb505, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); - M3PUnloadingWorkflowEvent = new EventDescriptor(0xb039, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowActivityExecutionFailedEvent = new EventDescriptor(0xb021, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowActivityValidatedEvent = new EventDescriptor(0xb01f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowActivityValidationFailedEvent = new EventDescriptor(0xb020, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); - M3PWorkflowCleanupPerformedEvent = new EventDescriptor(0xb028, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowDeletedFromDiskEvent = new EventDescriptor(0xb02a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowEngineStartedEvent = new EventDescriptor(0xb048, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); - M3PWorkflowExecutionAbortedEvent = new EventDescriptor(0xb027, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowExecutionCancelledEvent = new EventDescriptor(0xb026, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowExecutionErrorEvent = new EventDescriptor(0xb040, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowExecutionFinishedEvent = new EventDescriptor(0xb036, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowExecutionStartedEvent = new EventDescriptor(0xb008, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowJobCreatedEvent = new EventDescriptor(0xb030, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowLoadedForExecutionEvent = new EventDescriptor(0xb024, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowLoadedFromDiskEvent = new EventDescriptor(0xb029, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowManagerCheckpointEvent = new EventDescriptor(0xb049, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000200); - M3PWorkflowPersistedEvent = new EventDescriptor(0xb03e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowPluginRequestedToShutdownEvent = new EventDescriptor(0xb010, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); - M3PWorkflowPluginRestartedEvent = new EventDescriptor(0xb011, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); - M3PWorkflowPluginStartedEvent = new EventDescriptor(0xb007, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); - M3PWorkflowQuotaViolatedEvent = new EventDescriptor(0xb013, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowResumedEvent = new EventDescriptor(0xb014, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowResumingEvent = new EventDescriptor(0xb012, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowRunspacePoolCreatedEvent = new EventDescriptor(0xb016, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowStateChangedEvent = new EventDescriptor(0xb009, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowUnloadedEvent = new EventDescriptor(0xb025, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); - M3PWorkflowValidationErrorEvent = new EventDescriptor(0xb01e, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); - M3PWorkflowValidationFinishedEvent = new EventDescriptor(0xb01d, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); - M3PWorkflowValidationStartedEvent = new EventDescriptor(0xb01c, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); - - } - } - - /// - /// Constructor - /// - public Tracer() : base() {} - - /// - /// Provider Guid - /// - protected override Guid ProviderId - { - get - { - return providerId; - } - } - - /// - /// Transfer Event - /// - protected override EventDescriptor TransferEvent - { - get - { - return WriteTransferEventEvent; - } - } - - /// - /// WriteTransferEvent (EventId: 0x1f05/7941) - /// - [EtwEvent(0x1f05)] - public void WriteTransferEvent(Guid currentActivityId, Guid parentActivityId) - { - WriteEvent(WriteTransferEventEvent, currentActivityId, parentActivityId); - } - - - /// - /// DebugMessage (EventId: 0xc000/49152) - /// - [EtwEvent(0xc000)] - public void DebugMessage(string message) - { - WriteEvent(DebugMessageEvent, message); - } - - - /// - /// AbortingWorkflowExecution (EventId: 0xb038/45112) - /// - [EtwEvent(0xb038)] - public void AbortingWorkflowExecution(Guid workflowId, string reason) - { - WriteEvent(M3PAbortingWorkflowExecutionEvent, workflowId, reason); - } - - /// - /// ActivityExecutionFinished (EventId: 0xb03f/45119) - /// - [EtwEvent(0xb03f)] - public void ActivityExecutionFinished(string activityName) - { - WriteEvent(M3PActivityExecutionFinishedEvent, activityName); - } - - /// - /// ActivityExecutionQueued (EventId: 0xb017/45079) - /// - [EtwEvent(0xb017)] - public void ActivityExecutionQueued(Guid workflowId, string activityName) - { - WriteEvent(M3PActivityExecutionQueuedEvent, workflowId, activityName); - } - - /// - /// ActivityExecutionStarted (EventId: 0xb018/45080) - /// - [EtwEvent(0xb018)] - public void ActivityExecutionStarted(string activityName, string activityTypeName) - { - WriteEvent(M3PActivityExecutionStartedEvent, activityName, activityTypeName); - } - - /// - /// BeginContainerParentJobExecution (EventId: 0xb50c/46348) - /// - [EtwEvent(0xb50c)] - public void BeginContainerParentJobExecution(Guid containerParentJobInstanceId) - { - WriteEvent(M3PBeginContainerParentJobExecutionEvent, containerParentJobInstanceId); - } - - /// - /// BeginCreateNewJob (EventId: 0xb503/46339) - /// - [EtwEvent(0xb503)] - public void BeginCreateNewJob(Guid trackingId) - { - WriteEvent(M3PBeginCreateNewJobEvent, trackingId); - } - - /// - /// BeginJobLogic (EventId: 0xb506/46342) - /// - [EtwEvent(0xb506)] - public void BeginJobLogic(Guid workflowJobJobInstanceId) - { - WriteEvent(M3PBeginJobLogicEvent, workflowJobJobInstanceId); - } - - /// - /// BeginProxyChildJobEventHandler (EventId: 0xb512/46354) - /// - [EtwEvent(0xb512)] - public void BeginProxyChildJobEventHandler(Guid proxyChildJobInstanceId) - { - WriteEvent(M3PBeginProxyChildJobEventHandlerEvent, proxyChildJobInstanceId); - } - - /// - /// BeginProxyJobEventHandler (EventId: 0xb510/46352) - /// - [EtwEvent(0xb510)] - public void BeginProxyJobEventHandler(Guid proxyJobInstanceId) - { - WriteEvent(M3PBeginProxyJobEventHandlerEvent, proxyJobInstanceId); - } - - /// - /// BeginProxyJobExecution (EventId: 0xb50e/46350) - /// - [EtwEvent(0xb50e)] - public void BeginProxyJobExecution(Guid proxyJobInstanceId) - { - WriteEvent(M3PBeginProxyJobExecutionEvent, proxyJobInstanceId); - } - - /// - /// BeginRunGarbageCollection (EventId: 0xb514/46356) - /// - [EtwEvent(0xb514)] - public void BeginRunGarbageCollection() - { - WriteEvent(M3PBeginRunGarbageCollectionEvent); - } - - /// - /// BeginStartWorkflowApplication (EventId: 0xb501/46337) - /// - [EtwEvent(0xb501)] - public void BeginStartWorkflowApplication(Guid trackingId) - { - WriteEvent(M3PBeginStartWorkflowApplicationEvent, trackingId); - } - - /// - /// BeginWorkflowExecution (EventId: 0xb508/46344) - /// - [EtwEvent(0xb508)] - public void BeginWorkflowExecution(Guid workflowJobJobInstanceId) - { - WriteEvent(M3PBeginWorkflowExecutionEvent, workflowJobJobInstanceId); - } - - /// - /// CancellingWorkflowExecution (EventId: 0xb037/45111) - /// - [EtwEvent(0xb037)] - public void CancellingWorkflowExecution(Guid workflowId) - { - WriteEvent(M3PCancellingWorkflowExecutionEvent, workflowId); - } - - /// - /// ChildWorkflowJobAddition (EventId: 0xb50a/46346) - /// - [EtwEvent(0xb50a)] - public void ChildWorkflowJobAddition(Guid workflowJobInstanceId, Guid containerParentJobInstanceId) - { - WriteEvent(M3PChildWorkflowJobAdditionEvent, workflowJobInstanceId, containerParentJobInstanceId); - } - - /// - /// EndContainerParentJobExecution (EventId: 0xb50d/46349) - /// - [EtwEvent(0xb50d)] - public void EndContainerParentJobExecution(Guid containerParentJobInstanceId) - { - WriteEvent(M3PEndContainerParentJobExecutionEvent, containerParentJobInstanceId); - } - - /// - /// EndCreateNewJob (EventId: 0xb504/46340) - /// - [EtwEvent(0xb504)] - public void EndCreateNewJob(Guid trackingId) - { - WriteEvent(M3PEndCreateNewJobEvent, trackingId); - } - - /// - /// EndJobLogic (EventId: 0xb507/46343) - /// - [EtwEvent(0xb507)] - public void EndJobLogic(Guid workflowJobJobInstanceId) - { - WriteEvent(M3PEndJobLogicEvent, workflowJobJobInstanceId); - } - - /// - /// EndpointDisabled (EventId: 0xb044/45124) - /// - [EtwEvent(0xb044)] - public void EndpointDisabled(string endpointName, string disabledBy) - { - WriteEvent(M3PEndpointDisabledEvent, endpointName, disabledBy); - } - - /// - /// EndpointEnabled (EventId: 0xb045/45125) - /// - [EtwEvent(0xb045)] - public void EndpointEnabled(string endpointName, string enabledBy) - { - WriteEvent(M3PEndpointEnabledEvent, endpointName, enabledBy); - } - - /// - /// EndpointModified (EventId: 0xb042/45122) - /// - [EtwEvent(0xb042)] - public void EndpointModified(string endpointName, string modifiedBy) - { - WriteEvent(M3PEndpointModifiedEvent, endpointName, modifiedBy); - } - - /// - /// EndpointRegistered (EventId: 0xb041/45121) - /// - [EtwEvent(0xb041)] - public void EndpointRegistered(string endpointName, string endpointType, string registeredBy) - { - WriteEvent(M3PEndpointRegisteredEvent, endpointName, endpointType, registeredBy); - } - - /// - /// EndpointUnregistered (EventId: 0xb043/45123) - /// - [EtwEvent(0xb043)] - public void EndpointUnregistered(string endpointName, string unregisteredBy) - { - WriteEvent(M3PEndpointUnregisteredEvent, endpointName, unregisteredBy); - } - - /// - /// EndProxyChildJobEventHandler (EventId: 0xb513/46355) - /// - [EtwEvent(0xb513)] - public void EndProxyChildJobEventHandler(Guid proxyChildJobInstanceId) - { - WriteEvent(M3PEndProxyChildJobEventHandlerEvent, proxyChildJobInstanceId); - } - - /// - /// EndProxyJobEventHandler (EventId: 0xb511/46353) - /// - [EtwEvent(0xb511)] - public void EndProxyJobEventHandler(Guid proxyJobInstanceId) - { - WriteEvent(M3PEndProxyJobEventHandlerEvent, proxyJobInstanceId); - } - - /// - /// EndProxyJobExecution (EventId: 0xb50f/46351) - /// - [EtwEvent(0xb50f)] - public void EndProxyJobExecution(Guid proxyJobInstanceId) - { - WriteEvent(M3PEndProxyJobExecutionEvent, proxyJobInstanceId); - } - - /// - /// EndRunGarbageCollection (EventId: 0xb515/46357) - /// - [EtwEvent(0xb515)] - public void EndRunGarbageCollection() - { - WriteEvent(M3PEndRunGarbageCollectionEvent); - } - - /// - /// EndStartWorkflowApplication (EventId: 0xb502/46338) - /// - [EtwEvent(0xb502)] - public void EndStartWorkflowApplication(Guid trackingId) - { - WriteEvent(M3PEndStartWorkflowApplicationEvent, trackingId); - } - - /// - /// EndWorkflowExecution (EventId: 0xb509/46345) - /// - [EtwEvent(0xb509)] - public void EndWorkflowExecution(Guid workflowJobJobInstanceId) - { - WriteEvent(M3PEndWorkflowExecutionEvent, workflowJobJobInstanceId); - } - - /// - /// ErrorImportingWorkflowFromXaml (EventId: 0xb01b/45083) - /// - [EtwEvent(0xb01b)] - public void ErrorImportingWorkflowFromXaml(Guid workflowId, string errorDescription) - { - WriteEvent(M3PErrorImportingWorkflowFromXamlEvent, workflowId, errorDescription); - } - - /// - /// ForcedWorkflowShutdownError (EventId: 0xb03c/45116) - /// - [EtwEvent(0xb03c)] - public void ForcedWorkflowShutdownError(Guid workflowId, string errorDescription) - { - WriteEvent(M3PForcedWorkflowShutdownErrorEvent, workflowId, errorDescription); - } - - /// - /// ForcedWorkflowShutdownFinished (EventId: 0xb03b/45115) - /// - [EtwEvent(0xb03b)] - public void ForcedWorkflowShutdownFinished(Guid workflowId) - { - WriteEvent(M3PForcedWorkflowShutdownFinishedEvent, workflowId); - } - - /// - /// ForcedWorkflowShutdownStarted (EventId: 0xb03a/45114) - /// - [EtwEvent(0xb03a)] - public void ForcedWorkflowShutdownStarted(Guid workflowId) - { - WriteEvent(M3PForcedWorkflowShutdownStartedEvent, workflowId); - } - - /// - /// ImportedWorkflowFromXaml (EventId: 0xb01a/45082) - /// - [EtwEvent(0xb01a)] - public void ImportedWorkflowFromXaml(Guid workflowId, string xamlFile) - { - WriteEvent(M3PImportedWorkflowFromXamlEvent, workflowId, xamlFile); - } - - /// - /// ImportingWorkflowFromXaml (EventId: 0xb019/45081) - /// - [EtwEvent(0xb019)] - public void ImportingWorkflowFromXaml(Guid workflowId, string xamlFile) - { - WriteEvent(M3PImportingWorkflowFromXamlEvent, workflowId, xamlFile); - } - - /// - /// JobCreationComplete (EventId: 0xb032/45106) - /// - [EtwEvent(0xb032)] - public void JobCreationComplete(Guid jobId, Guid workflowId) - { - WriteEvent(M3PJobCreationCompleteEvent, jobId, workflowId); - } - - /// - /// JobError (EventId: 0xb02e/45102) - /// - [EtwEvent(0xb02e)] - public void JobError(int jobId, Guid workflowId, string errorDescription) - { - WriteEvent(M3PJobErrorEvent, jobId, workflowId, errorDescription); - } - - /// - /// JobRemoved (EventId: 0xb033/45107) - /// - [EtwEvent(0xb033)] - public void JobRemoved(Guid parentJobId, Guid childJobId, Guid workflowId) - { - WriteEvent(M3PJobRemovedEvent, parentJobId, childJobId, workflowId); - } - - /// - /// JobRemoveError (EventId: 0xb034/45108) - /// - [EtwEvent(0xb034)] - public void JobRemoveError(Guid parentJobId, Guid childJobId, Guid workflowId, string error) - { - WriteEvent(M3PJobRemoveErrorEvent, parentJobId, childJobId, workflowId, error); - } - - /// - /// JobStateChanged (EventId: 0xb02d/45101) - /// - [EtwEvent(0xb02d)] - public void JobStateChanged(int jobId, Guid workflowId, string newState, string oldState) - { - WriteEvent(M3PJobStateChangedEvent, jobId, workflowId, newState, oldState); - } - - /// - /// LoadingWorkflowForExecution (EventId: 0xb035/45109) - /// - [EtwEvent(0xb035)] - public void LoadingWorkflowForExecution(Guid workflowId) - { - WriteEvent(M3PLoadingWorkflowForExecutionEvent, workflowId); - } - - /// - /// OutOfProcessRunspaceStarted (EventId: 0xb046/45126) - /// - [EtwEvent(0xb046)] - public void OutOfProcessRunspaceStarted(string command) - { - WriteEvent(M3POutOfProcessRunspaceStartedEvent, command); - } - - /// - /// ParameterSplattingWasPerformed (EventId: 0xb047/45127) - /// - [EtwEvent(0xb047)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public void ParameterSplattingWasPerformed(string parameters, string computers) - { - WriteEvent(M3PParameterSplattingWasPerformedEvent, parameters, computers); - } - - /// - /// ParentJobCreated (EventId: 0xb031/45105) - /// - [EtwEvent(0xb031)] - public void ParentJobCreated(Guid jobId) - { - WriteEvent(M3PParentJobCreatedEvent, jobId); - } - - /// - /// PersistenceStoreMaxSizeReached (EventId: 0xb516/46358) - /// - [EtwEvent(0xb516)] - public void PersistenceStoreMaxSizeReached() - { - WriteEvent(M3PPersistenceStoreMaxSizeReachedEvent); - } - - /// - /// PersistingWorkflow (EventId: 0xb03d/45117) - /// - [EtwEvent(0xb03d)] - public void PersistingWorkflow(Guid workflowId, string persistPath) - { - WriteEvent(M3PPersistingWorkflowEvent, workflowId, persistPath); - } - - /// - /// ProxyJobRemoteJobAssociation (EventId: 0xb50b/46347) - /// - [EtwEvent(0xb50b)] - public void ProxyJobRemoteJobAssociation(Guid proxyJobInstanceId, Guid containerParentJobInstanceId) - { - WriteEvent(M3PProxyJobRemoteJobAssociationEvent, proxyJobInstanceId, containerParentJobInstanceId); - } - - /// - /// RemoveJobStarted (EventId: 0xb02c/45100) - /// - [EtwEvent(0xb02c)] - public void RemoveJobStarted(Guid jobId) - { - WriteEvent(M3PRemoveJobStartedEvent, jobId); - } - - /// - /// RunspaceAvailabilityChanged (EventId: 0xb022/45090) - /// - [EtwEvent(0xb022)] - public void RunspaceAvailabilityChanged(string runspaceId, string availability) - { - WriteEvent(M3PRunspaceAvailabilityChangedEvent, runspaceId, availability); - } - - /// - /// RunspaceStateChanged (EventId: 0xb023/45091) - /// - [EtwEvent(0xb023)] - public void RunspaceStateChanged(string runspaceId, string newState, string oldState) - { - WriteEvent(M3PRunspaceStateChangedEvent, runspaceId, newState, oldState); - } - - /// - /// TrackingGuidContainerParentJobCorrelation (EventId: 0xb505/46341) - /// - [EtwEvent(0xb505)] - public void TrackingGuidContainerParentJobCorrelation(Guid trackingId, Guid containerParentJobInstanceId) - { - WriteEvent(M3PTrackingGuidContainerParentJobCorrelationEvent, trackingId, containerParentJobInstanceId); - } - - /// - /// UnloadingWorkflow (EventId: 0xb039/45113) - /// - [EtwEvent(0xb039)] - public void UnloadingWorkflow(Guid workflowId) - { - WriteEvent(M3PUnloadingWorkflowEvent, workflowId); - } - - /// - /// WorkflowActivityExecutionFailed (EventId: 0xb021/45089) - /// - [EtwEvent(0xb021)] - public void WorkflowActivityExecutionFailed(Guid workflowId, string activityName, string failureDescription) - { - WriteEvent(M3PWorkflowActivityExecutionFailedEvent, workflowId, activityName, failureDescription); - } - - /// - /// WorkflowActivityValidated (EventId: 0xb01f/45087) - /// - [EtwEvent(0xb01f)] - public void WorkflowActivityValidated(Guid workflowId, string activityDisplayName, string activityType) - { - WriteEvent(M3PWorkflowActivityValidatedEvent, workflowId, activityDisplayName, activityType); - } - - /// - /// WorkflowActivityValidationFailed (EventId: 0xb020/45088) - /// - [EtwEvent(0xb020)] - public void WorkflowActivityValidationFailed(Guid workflowId, string activityDisplayName, string activityType) - { - WriteEvent(M3PWorkflowActivityValidationFailedEvent, workflowId, activityDisplayName, activityType); - } - - /// - /// WorkflowCleanupPerformed (EventId: 0xb028/45096) - /// - [EtwEvent(0xb028)] - public void WorkflowCleanupPerformed(Guid workflowId) - { - WriteEvent(M3PWorkflowCleanupPerformedEvent, workflowId); - } - - /// - /// WorkflowDeletedFromDisk (EventId: 0xb02a/45098) - /// - [EtwEvent(0xb02a)] - public void WorkflowDeletedFromDisk(Guid workflowId, string path) - { - WriteEvent(M3PWorkflowDeletedFromDiskEvent, workflowId, path); - } - - /// - /// WorkflowEngineStarted (EventId: 0xb048/45128) - /// - [EtwEvent(0xb048)] - public void WorkflowEngineStarted(string endpointName) - { - WriteEvent(M3PWorkflowEngineStartedEvent, endpointName); - } - - /// - /// WorkflowExecutionAborted (EventId: 0xb027/45095) - /// - [EtwEvent(0xb027)] - public void WorkflowExecutionAborted(Guid workflowId) - { - WriteEvent(M3PWorkflowExecutionAbortedEvent, workflowId); - } - - /// - /// WorkflowExecutionCancelled (EventId: 0xb026/45094) - /// - [EtwEvent(0xb026)] - public void WorkflowExecutionCancelled(Guid workflowId) - { - WriteEvent(M3PWorkflowExecutionCancelledEvent, workflowId); - } - - /// - /// WorkflowExecutionError (EventId: 0xb040/45120) - /// - [EtwEvent(0xb040)] - public void WorkflowExecutionError(Guid workflowId, string errorDescription) - { - WriteEvent(M3PWorkflowExecutionErrorEvent, workflowId, errorDescription); - } - - /// - /// WorkflowExecutionFinished (EventId: 0xb036/45110) - /// - [EtwEvent(0xb036)] - public void WorkflowExecutionFinished(Guid workflowId) - { - WriteEvent(M3PWorkflowExecutionFinishedEvent, workflowId); - } - - /// - /// WorkflowExecutionStarted (EventId: 0xb008/45064) - /// - [EtwEvent(0xb008)] - public void WorkflowExecutionStarted(Guid workflowId, string managedNodes) - { - WriteEvent(M3PWorkflowExecutionStartedEvent, workflowId, managedNodes); - } - - /// - /// WorkflowJobCreated (EventId: 0xb030/45104) - /// - [EtwEvent(0xb030)] - public void WorkflowJobCreated(Guid parentJobId, Guid childJobId, Guid childWorkflowId) - { - WriteEvent(M3PWorkflowJobCreatedEvent, parentJobId, childJobId, childWorkflowId); - } - - /// - /// WorkflowLoadedForExecution (EventId: 0xb024/45092) - /// - [EtwEvent(0xb024)] - public void WorkflowLoadedForExecution(Guid workflowId) - { - WriteEvent(M3PWorkflowLoadedForExecutionEvent, workflowId); - } - - /// - /// WorkflowLoadedFromDisk (EventId: 0xb029/45097) - /// - [EtwEvent(0xb029)] - public void WorkflowLoadedFromDisk(Guid workflowId, string path) - { - WriteEvent(M3PWorkflowLoadedFromDiskEvent, workflowId, path); - } - - /// - /// WorkflowManagerCheckpoint (EventId: 0xb049/45129) - /// - [EtwEvent(0xb049)] - public void WorkflowManagerCheckpoint(string checkpointPath, string configProviderId, string userName, string path) - { - WriteEvent(M3PWorkflowManagerCheckpointEvent, checkpointPath, configProviderId, userName, path); - } - - /// - /// WorkflowPersisted (EventId: 0xb03e/45118) - /// - [EtwEvent(0xb03e)] - public void WorkflowPersisted(Guid workflowId) - { - WriteEvent(M3PWorkflowPersistedEvent, workflowId); - } - - /// - /// WorkflowPluginRequestedToShutdown (EventId: 0xb010/45072) - /// - [EtwEvent(0xb010)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public void WorkflowPluginRequestedToShutdown(string endpointName) - { - WriteEvent(M3PWorkflowPluginRequestedToShutdownEvent, endpointName); - } - - /// - /// WorkflowPluginRestarted (EventId: 0xb011/45073) - /// - [EtwEvent(0xb011)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public void WorkflowPluginRestarted(string endpointName) - { - WriteEvent(M3PWorkflowPluginRestartedEvent, endpointName); - } - - /// - /// WorkflowPluginStarted (EventId: 0xb007/45063) - /// - [EtwEvent(0xb007)] - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] - public void WorkflowPluginStarted(string endpointName, string user, string hostingMode, string protocol, string configuration) - { - WriteEvent(M3PWorkflowPluginStartedEvent, endpointName, user, hostingMode, protocol, configuration); - } - - /// - /// WorkflowQuotaViolated (EventId: 0xb013/45075) - /// - [EtwEvent(0xb013)] - public void WorkflowQuotaViolated(string endpointName, string configName, string allowedValue, string valueInQuestion) - { - WriteEvent(M3PWorkflowQuotaViolatedEvent, endpointName, configName, allowedValue, valueInQuestion); - } - - /// - /// WorkflowResumed (EventId: 0xb014/45076) - /// - [EtwEvent(0xb014)] - public void WorkflowResumed(Guid workflowId) - { - WriteEvent(M3PWorkflowResumedEvent, workflowId); - } - - /// - /// WorkflowResuming (EventId: 0xb012/45074) - /// - [EtwEvent(0xb012)] - public void WorkflowResuming(Guid workflowId) - { - WriteEvent(M3PWorkflowResumingEvent, workflowId); - } - - /// - /// WorkflowRunspacePoolCreated (EventId: 0xb016/45078) - /// - [EtwEvent(0xb016)] - public void WorkflowRunspacePoolCreated(Guid workflowId, string managedNode) - { - WriteEvent(M3PWorkflowRunspacePoolCreatedEvent, workflowId, managedNode); - } - - /// - /// WorkflowStateChanged (EventId: 0xb009/45065) - /// - [EtwEvent(0xb009)] - public void WorkflowStateChanged(Guid workflowId, string newState, string oldState) - { - WriteEvent(M3PWorkflowStateChangedEvent, workflowId, newState, oldState); - } - - /// - /// WorkflowUnloaded (EventId: 0xb025/45093) - /// - [EtwEvent(0xb025)] - public void WorkflowUnloaded(Guid workflowId) - { - WriteEvent(M3PWorkflowUnloadedEvent, workflowId); - } - - /// - /// WorkflowValidationError (EventId: 0xb01e/45086) - /// - [EtwEvent(0xb01e)] - public void WorkflowValidationError(Guid workflowId) - { - WriteEvent(M3PWorkflowValidationErrorEvent, workflowId); - } - - /// - /// WorkflowValidationFinished (EventId: 0xb01d/45085) - /// - [EtwEvent(0xb01d)] - public void WorkflowValidationFinished(Guid workflowId) - { - WriteEvent(M3PWorkflowValidationFinishedEvent, workflowId); - } - - /// - /// WorkflowValidationStarted (EventId: 0xb01c/45084) - /// - [EtwEvent(0xb01c)] - public void WorkflowValidationStarted(Guid workflowId) - { - WriteEvent(M3PWorkflowValidationStartedEvent, workflowId); - } - - - } - +namespace System.Management.Automation.Tracing +{ + /// + /// Tracer + /// + public sealed partial class Tracer : System.Management.Automation.Tracing.EtwActivity + { + /// + /// Critical level + /// + public const byte LevelCritical = 1; + /// + /// Error level + /// + public const byte LevelError = 2; + /// + /// Warning level + /// + public const byte LevelWarning = 3; + /// + /// Informational level + /// + public const byte LevelInformational = 4; + /// + /// Verbose level + /// + public const byte LevelVerbose = 5; + /// + /// Keyword all + /// + public const long KeywordAll = 0xFFFFFFFF; + private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); + private static EventDescriptor WriteTransferEventEvent; + private static EventDescriptor DebugMessageEvent; + private static EventDescriptor M3PAbortingWorkflowExecutionEvent; + private static EventDescriptor M3PActivityExecutionFinishedEvent; + private static EventDescriptor M3PActivityExecutionQueuedEvent; + private static EventDescriptor M3PActivityExecutionStartedEvent; + private static EventDescriptor M3PBeginContainerParentJobExecutionEvent; + private static EventDescriptor M3PBeginCreateNewJobEvent; + private static EventDescriptor M3PBeginJobLogicEvent; + private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; + private static EventDescriptor M3PBeginProxyJobEventHandlerEvent; + private static EventDescriptor M3PBeginProxyJobExecutionEvent; + private static EventDescriptor M3PBeginRunGarbageCollectionEvent; + private static EventDescriptor M3PBeginStartWorkflowApplicationEvent; + private static EventDescriptor M3PBeginWorkflowExecutionEvent; + private static EventDescriptor M3PCancellingWorkflowExecutionEvent; + private static EventDescriptor M3PChildWorkflowJobAdditionEvent; + private static EventDescriptor M3PEndContainerParentJobExecutionEvent; + private static EventDescriptor M3PEndCreateNewJobEvent; + private static EventDescriptor M3PEndJobLogicEvent; + private static EventDescriptor M3PEndpointDisabledEvent; + private static EventDescriptor M3PEndpointEnabledEvent; + private static EventDescriptor M3PEndpointModifiedEvent; + private static EventDescriptor M3PEndpointRegisteredEvent; + private static EventDescriptor M3PEndpointUnregisteredEvent; + private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent; + private static EventDescriptor M3PEndProxyJobEventHandlerEvent; + private static EventDescriptor M3PEndProxyJobExecutionEvent; + private static EventDescriptor M3PEndRunGarbageCollectionEvent; + private static EventDescriptor M3PEndStartWorkflowApplicationEvent; + private static EventDescriptor M3PEndWorkflowExecutionEvent; + private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; + private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent; + private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; + private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent; + private static EventDescriptor M3PImportedWorkflowFromXamlEvent; + private static EventDescriptor M3PImportingWorkflowFromXamlEvent; + private static EventDescriptor M3PJobCreationCompleteEvent; + private static EventDescriptor M3PJobErrorEvent; + private static EventDescriptor M3PJobRemovedEvent; + private static EventDescriptor M3PJobRemoveErrorEvent; + private static EventDescriptor M3PJobStateChangedEvent; + private static EventDescriptor M3PLoadingWorkflowForExecutionEvent; + private static EventDescriptor M3POutOfProcessRunspaceStartedEvent; + private static EventDescriptor M3PParameterSplattingWasPerformedEvent; + private static EventDescriptor M3PParentJobCreatedEvent; + private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; + private static EventDescriptor M3PPersistingWorkflowEvent; + private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent; + private static EventDescriptor M3PRemoveJobStartedEvent; + private static EventDescriptor M3PRunspaceAvailabilityChangedEvent; + private static EventDescriptor M3PRunspaceStateChangedEvent; + private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; + private static EventDescriptor M3PUnloadingWorkflowEvent; + private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent; + private static EventDescriptor M3PWorkflowActivityValidatedEvent; + private static EventDescriptor M3PWorkflowActivityValidationFailedEvent; + private static EventDescriptor M3PWorkflowCleanupPerformedEvent; + private static EventDescriptor M3PWorkflowDeletedFromDiskEvent; + private static EventDescriptor M3PWorkflowEngineStartedEvent; + private static EventDescriptor M3PWorkflowExecutionAbortedEvent; + private static EventDescriptor M3PWorkflowExecutionCancelledEvent; + private static EventDescriptor M3PWorkflowExecutionErrorEvent; + private static EventDescriptor M3PWorkflowExecutionFinishedEvent; + private static EventDescriptor M3PWorkflowExecutionStartedEvent; + private static EventDescriptor M3PWorkflowJobCreatedEvent; + private static EventDescriptor M3PWorkflowLoadedForExecutionEvent; + private static EventDescriptor M3PWorkflowLoadedFromDiskEvent; + private static EventDescriptor M3PWorkflowManagerCheckpointEvent; + private static EventDescriptor M3PWorkflowPersistedEvent; + private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; + private static EventDescriptor M3PWorkflowPluginRestartedEvent; + private static EventDescriptor M3PWorkflowPluginStartedEvent; + private static EventDescriptor M3PWorkflowQuotaViolatedEvent; + private static EventDescriptor M3PWorkflowResumedEvent; + private static EventDescriptor M3PWorkflowResumingEvent; + private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; + private static EventDescriptor M3PWorkflowStateChangedEvent; + private static EventDescriptor M3PWorkflowUnloadedEvent; + private static EventDescriptor M3PWorkflowValidationErrorEvent; + private static EventDescriptor M3PWorkflowValidationFinishedEvent; + private static EventDescriptor M3PWorkflowValidationStartedEvent; + + /// + /// Static constructor + /// + static Tracer() + { + unchecked + { + WriteTransferEventEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); + DebugMessageEvent = new EventDescriptor(0xc000, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PAbortingWorkflowExecutionEvent = new EventDescriptor(0xb038, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PActivityExecutionFinishedEvent = new EventDescriptor(0xb03f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PActivityExecutionQueuedEvent = new EventDescriptor(0xb017, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PActivityExecutionStartedEvent = new EventDescriptor(0xb018, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PBeginContainerParentJobExecutionEvent = new EventDescriptor(0xb50c, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginCreateNewJobEvent = new EventDescriptor(0xb503, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginJobLogicEvent = new EventDescriptor(0xb506, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginProxyChildJobEventHandlerEvent = new EventDescriptor(0xb512, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginProxyJobEventHandlerEvent = new EventDescriptor(0xb510, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginProxyJobExecutionEvent = new EventDescriptor(0xb50e, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginRunGarbageCollectionEvent = new EventDescriptor(0xb514, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginStartWorkflowApplicationEvent = new EventDescriptor(0xb501, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PBeginWorkflowExecutionEvent = new EventDescriptor(0xb508, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PCancellingWorkflowExecutionEvent = new EventDescriptor(0xb037, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PChildWorkflowJobAdditionEvent = new EventDescriptor(0xb50a, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndContainerParentJobExecutionEvent = new EventDescriptor(0xb50d, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndCreateNewJobEvent = new EventDescriptor(0xb504, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndJobLogicEvent = new EventDescriptor(0xb507, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndpointDisabledEvent = new EventDescriptor(0xb044, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); + M3PEndpointEnabledEvent = new EventDescriptor(0xb045, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); + M3PEndpointModifiedEvent = new EventDescriptor(0xb042, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); + M3PEndpointRegisteredEvent = new EventDescriptor(0xb041, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); + M3PEndpointUnregisteredEvent = new EventDescriptor(0xb043, 0x1, 0x11, 0x5, 0x14, 0x9, (long)0x4000000000000200); + M3PEndProxyChildJobEventHandlerEvent = new EventDescriptor(0xb513, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndProxyJobEventHandlerEvent = new EventDescriptor(0xb511, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndProxyJobExecutionEvent = new EventDescriptor(0xb50f, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndRunGarbageCollectionEvent = new EventDescriptor(0xb515, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndStartWorkflowApplicationEvent = new EventDescriptor(0xb502, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PEndWorkflowExecutionEvent = new EventDescriptor(0xb509, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PErrorImportingWorkflowFromXamlEvent = new EventDescriptor(0xb01b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PForcedWorkflowShutdownErrorEvent = new EventDescriptor(0xb03c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PForcedWorkflowShutdownFinishedEvent = new EventDescriptor(0xb03b, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PForcedWorkflowShutdownStartedEvent = new EventDescriptor(0xb03a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PImportedWorkflowFromXamlEvent = new EventDescriptor(0xb01a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PImportingWorkflowFromXamlEvent = new EventDescriptor(0xb019, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PJobCreationCompleteEvent = new EventDescriptor(0xb032, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PJobErrorEvent = new EventDescriptor(0xb02e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PJobRemovedEvent = new EventDescriptor(0xb033, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PJobRemoveErrorEvent = new EventDescriptor(0xb034, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PJobStateChangedEvent = new EventDescriptor(0xb02d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PLoadingWorkflowForExecutionEvent = new EventDescriptor(0xb035, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3POutOfProcessRunspaceStartedEvent = new EventDescriptor(0xb046, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PParameterSplattingWasPerformedEvent = new EventDescriptor(0xb047, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PParentJobCreatedEvent = new EventDescriptor(0xb031, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PPersistenceStoreMaxSizeReachedEvent = new EventDescriptor(0xb516, 0x1, 0x10, 0x3, 0x0, 0x0, (long)0x8000000000000000); + M3PPersistingWorkflowEvent = new EventDescriptor(0xb03d, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PProxyJobRemoteJobAssociationEvent = new EventDescriptor(0xb50b, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PRemoveJobStartedEvent = new EventDescriptor(0xb02c, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PRunspaceAvailabilityChangedEvent = new EventDescriptor(0xb022, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PRunspaceStateChangedEvent = new EventDescriptor(0xb023, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PTrackingGuidContainerParentJobCorrelationEvent = new EventDescriptor(0xb505, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000000); + M3PUnloadingWorkflowEvent = new EventDescriptor(0xb039, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowActivityExecutionFailedEvent = new EventDescriptor(0xb021, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowActivityValidatedEvent = new EventDescriptor(0xb01f, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowActivityValidationFailedEvent = new EventDescriptor(0xb020, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); + M3PWorkflowCleanupPerformedEvent = new EventDescriptor(0xb028, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowDeletedFromDiskEvent = new EventDescriptor(0xb02a, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowEngineStartedEvent = new EventDescriptor(0xb048, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); + M3PWorkflowExecutionAbortedEvent = new EventDescriptor(0xb027, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowExecutionCancelledEvent = new EventDescriptor(0xb026, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowExecutionErrorEvent = new EventDescriptor(0xb040, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowExecutionFinishedEvent = new EventDescriptor(0xb036, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowExecutionStartedEvent = new EventDescriptor(0xb008, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowJobCreatedEvent = new EventDescriptor(0xb030, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowLoadedForExecutionEvent = new EventDescriptor(0xb024, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowLoadedFromDiskEvent = new EventDescriptor(0xb029, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowManagerCheckpointEvent = new EventDescriptor(0xb049, 0x1, 0x12, 0x4, 0x0, 0x0, (long)0x2000000000000200); + M3PWorkflowPersistedEvent = new EventDescriptor(0xb03e, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowPluginRequestedToShutdownEvent = new EventDescriptor(0xb010, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); + M3PWorkflowPluginRestartedEvent = new EventDescriptor(0xb011, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); + M3PWorkflowPluginStartedEvent = new EventDescriptor(0xb007, 0x1, 0x11, 0x5, 0x14, 0x5, (long)0x4000000000000200); + M3PWorkflowQuotaViolatedEvent = new EventDescriptor(0xb013, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowResumedEvent = new EventDescriptor(0xb014, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowResumingEvent = new EventDescriptor(0xb012, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowRunspacePoolCreatedEvent = new EventDescriptor(0xb016, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowStateChangedEvent = new EventDescriptor(0xb009, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowUnloadedEvent = new EventDescriptor(0xb025, 0x1, 0x11, 0x5, 0x14, 0x6, (long)0x4000000000000200); + M3PWorkflowValidationErrorEvent = new EventDescriptor(0xb01e, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); + M3PWorkflowValidationFinishedEvent = new EventDescriptor(0xb01d, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); + M3PWorkflowValidationStartedEvent = new EventDescriptor(0xb01c, 0x1, 0x11, 0x5, 0x14, 0x8, (long)0x4000000000000200); + } + } + + /// + /// Constructor + /// + public Tracer() : base() { } + + /// + /// Provider Guid + /// + protected override Guid ProviderId + { + get + { + return providerId; + } + } + + /// + /// Transfer Event + /// + protected override EventDescriptor TransferEvent + { + get + { + return WriteTransferEventEvent; + } + } + + /// + /// WriteTransferEvent (EventId: 0x1f05/7941) + /// + [EtwEvent(0x1f05)] + public void WriteTransferEvent(Guid currentActivityId, Guid parentActivityId) + { + WriteEvent(WriteTransferEventEvent, currentActivityId, parentActivityId); + } + + + /// + /// DebugMessage (EventId: 0xc000/49152) + /// + [EtwEvent(0xc000)] + public void DebugMessage(string message) + { + WriteEvent(DebugMessageEvent, message); + } + + + /// + /// AbortingWorkflowExecution (EventId: 0xb038/45112) + /// + [EtwEvent(0xb038)] + public void AbortingWorkflowExecution(Guid workflowId, string reason) + { + WriteEvent(M3PAbortingWorkflowExecutionEvent, workflowId, reason); + } + + /// + /// ActivityExecutionFinished (EventId: 0xb03f/45119) + /// + [EtwEvent(0xb03f)] + public void ActivityExecutionFinished(string activityName) + { + WriteEvent(M3PActivityExecutionFinishedEvent, activityName); + } + + /// + /// ActivityExecutionQueued (EventId: 0xb017/45079) + /// + [EtwEvent(0xb017)] + public void ActivityExecutionQueued(Guid workflowId, string activityName) + { + WriteEvent(M3PActivityExecutionQueuedEvent, workflowId, activityName); + } + + /// + /// ActivityExecutionStarted (EventId: 0xb018/45080) + /// + [EtwEvent(0xb018)] + public void ActivityExecutionStarted(string activityName, string activityTypeName) + { + WriteEvent(M3PActivityExecutionStartedEvent, activityName, activityTypeName); + } + + /// + /// BeginContainerParentJobExecution (EventId: 0xb50c/46348) + /// + [EtwEvent(0xb50c)] + public void BeginContainerParentJobExecution(Guid containerParentJobInstanceId) + { + WriteEvent(M3PBeginContainerParentJobExecutionEvent, containerParentJobInstanceId); + } + + /// + /// BeginCreateNewJob (EventId: 0xb503/46339) + /// + [EtwEvent(0xb503)] + public void BeginCreateNewJob(Guid trackingId) + { + WriteEvent(M3PBeginCreateNewJobEvent, trackingId); + } + + /// + /// BeginJobLogic (EventId: 0xb506/46342) + /// + [EtwEvent(0xb506)] + public void BeginJobLogic(Guid workflowJobJobInstanceId) + { + WriteEvent(M3PBeginJobLogicEvent, workflowJobJobInstanceId); + } + + /// + /// BeginProxyChildJobEventHandler (EventId: 0xb512/46354) + /// + [EtwEvent(0xb512)] + public void BeginProxyChildJobEventHandler(Guid proxyChildJobInstanceId) + { + WriteEvent(M3PBeginProxyChildJobEventHandlerEvent, proxyChildJobInstanceId); + } + + /// + /// BeginProxyJobEventHandler (EventId: 0xb510/46352) + /// + [EtwEvent(0xb510)] + public void BeginProxyJobEventHandler(Guid proxyJobInstanceId) + { + WriteEvent(M3PBeginProxyJobEventHandlerEvent, proxyJobInstanceId); + } + + /// + /// BeginProxyJobExecution (EventId: 0xb50e/46350) + /// + [EtwEvent(0xb50e)] + public void BeginProxyJobExecution(Guid proxyJobInstanceId) + { + WriteEvent(M3PBeginProxyJobExecutionEvent, proxyJobInstanceId); + } + + /// + /// BeginRunGarbageCollection (EventId: 0xb514/46356) + /// + [EtwEvent(0xb514)] + public void BeginRunGarbageCollection() + { + WriteEvent(M3PBeginRunGarbageCollectionEvent); + } + + /// + /// BeginStartWorkflowApplication (EventId: 0xb501/46337) + /// + [EtwEvent(0xb501)] + public void BeginStartWorkflowApplication(Guid trackingId) + { + WriteEvent(M3PBeginStartWorkflowApplicationEvent, trackingId); + } + + /// + /// BeginWorkflowExecution (EventId: 0xb508/46344) + /// + [EtwEvent(0xb508)] + public void BeginWorkflowExecution(Guid workflowJobJobInstanceId) + { + WriteEvent(M3PBeginWorkflowExecutionEvent, workflowJobJobInstanceId); + } + + /// + /// CancellingWorkflowExecution (EventId: 0xb037/45111) + /// + [EtwEvent(0xb037)] + public void CancellingWorkflowExecution(Guid workflowId) + { + WriteEvent(M3PCancellingWorkflowExecutionEvent, workflowId); + } + + /// + /// ChildWorkflowJobAddition (EventId: 0xb50a/46346) + /// + [EtwEvent(0xb50a)] + public void ChildWorkflowJobAddition(Guid workflowJobInstanceId, Guid containerParentJobInstanceId) + { + WriteEvent(M3PChildWorkflowJobAdditionEvent, workflowJobInstanceId, containerParentJobInstanceId); + } + + /// + /// EndContainerParentJobExecution (EventId: 0xb50d/46349) + /// + [EtwEvent(0xb50d)] + public void EndContainerParentJobExecution(Guid containerParentJobInstanceId) + { + WriteEvent(M3PEndContainerParentJobExecutionEvent, containerParentJobInstanceId); + } + + /// + /// EndCreateNewJob (EventId: 0xb504/46340) + /// + [EtwEvent(0xb504)] + public void EndCreateNewJob(Guid trackingId) + { + WriteEvent(M3PEndCreateNewJobEvent, trackingId); + } + + /// + /// EndJobLogic (EventId: 0xb507/46343) + /// + [EtwEvent(0xb507)] + public void EndJobLogic(Guid workflowJobJobInstanceId) + { + WriteEvent(M3PEndJobLogicEvent, workflowJobJobInstanceId); + } + + /// + /// EndpointDisabled (EventId: 0xb044/45124) + /// + [EtwEvent(0xb044)] + public void EndpointDisabled(string endpointName, string disabledBy) + { + WriteEvent(M3PEndpointDisabledEvent, endpointName, disabledBy); + } + + /// + /// EndpointEnabled (EventId: 0xb045/45125) + /// + [EtwEvent(0xb045)] + public void EndpointEnabled(string endpointName, string enabledBy) + { + WriteEvent(M3PEndpointEnabledEvent, endpointName, enabledBy); + } + + /// + /// EndpointModified (EventId: 0xb042/45122) + /// + [EtwEvent(0xb042)] + public void EndpointModified(string endpointName, string modifiedBy) + { + WriteEvent(M3PEndpointModifiedEvent, endpointName, modifiedBy); + } + + /// + /// EndpointRegistered (EventId: 0xb041/45121) + /// + [EtwEvent(0xb041)] + public void EndpointRegistered(string endpointName, string endpointType, string registeredBy) + { + WriteEvent(M3PEndpointRegisteredEvent, endpointName, endpointType, registeredBy); + } + + /// + /// EndpointUnregistered (EventId: 0xb043/45123) + /// + [EtwEvent(0xb043)] + public void EndpointUnregistered(string endpointName, string unregisteredBy) + { + WriteEvent(M3PEndpointUnregisteredEvent, endpointName, unregisteredBy); + } + + /// + /// EndProxyChildJobEventHandler (EventId: 0xb513/46355) + /// + [EtwEvent(0xb513)] + public void EndProxyChildJobEventHandler(Guid proxyChildJobInstanceId) + { + WriteEvent(M3PEndProxyChildJobEventHandlerEvent, proxyChildJobInstanceId); + } + + /// + /// EndProxyJobEventHandler (EventId: 0xb511/46353) + /// + [EtwEvent(0xb511)] + public void EndProxyJobEventHandler(Guid proxyJobInstanceId) + { + WriteEvent(M3PEndProxyJobEventHandlerEvent, proxyJobInstanceId); + } + + /// + /// EndProxyJobExecution (EventId: 0xb50f/46351) + /// + [EtwEvent(0xb50f)] + public void EndProxyJobExecution(Guid proxyJobInstanceId) + { + WriteEvent(M3PEndProxyJobExecutionEvent, proxyJobInstanceId); + } + + /// + /// EndRunGarbageCollection (EventId: 0xb515/46357) + /// + [EtwEvent(0xb515)] + public void EndRunGarbageCollection() + { + WriteEvent(M3PEndRunGarbageCollectionEvent); + } + + /// + /// EndStartWorkflowApplication (EventId: 0xb502/46338) + /// + [EtwEvent(0xb502)] + public void EndStartWorkflowApplication(Guid trackingId) + { + WriteEvent(M3PEndStartWorkflowApplicationEvent, trackingId); + } + + /// + /// EndWorkflowExecution (EventId: 0xb509/46345) + /// + [EtwEvent(0xb509)] + public void EndWorkflowExecution(Guid workflowJobJobInstanceId) + { + WriteEvent(M3PEndWorkflowExecutionEvent, workflowJobJobInstanceId); + } + + /// + /// ErrorImportingWorkflowFromXaml (EventId: 0xb01b/45083) + /// + [EtwEvent(0xb01b)] + public void ErrorImportingWorkflowFromXaml(Guid workflowId, string errorDescription) + { + WriteEvent(M3PErrorImportingWorkflowFromXamlEvent, workflowId, errorDescription); + } + + /// + /// ForcedWorkflowShutdownError (EventId: 0xb03c/45116) + /// + [EtwEvent(0xb03c)] + public void ForcedWorkflowShutdownError(Guid workflowId, string errorDescription) + { + WriteEvent(M3PForcedWorkflowShutdownErrorEvent, workflowId, errorDescription); + } + + /// + /// ForcedWorkflowShutdownFinished (EventId: 0xb03b/45115) + /// + [EtwEvent(0xb03b)] + public void ForcedWorkflowShutdownFinished(Guid workflowId) + { + WriteEvent(M3PForcedWorkflowShutdownFinishedEvent, workflowId); + } + + /// + /// ForcedWorkflowShutdownStarted (EventId: 0xb03a/45114) + /// + [EtwEvent(0xb03a)] + public void ForcedWorkflowShutdownStarted(Guid workflowId) + { + WriteEvent(M3PForcedWorkflowShutdownStartedEvent, workflowId); + } + + /// + /// ImportedWorkflowFromXaml (EventId: 0xb01a/45082) + /// + [EtwEvent(0xb01a)] + public void ImportedWorkflowFromXaml(Guid workflowId, string xamlFile) + { + WriteEvent(M3PImportedWorkflowFromXamlEvent, workflowId, xamlFile); + } + + /// + /// ImportingWorkflowFromXaml (EventId: 0xb019/45081) + /// + [EtwEvent(0xb019)] + public void ImportingWorkflowFromXaml(Guid workflowId, string xamlFile) + { + WriteEvent(M3PImportingWorkflowFromXamlEvent, workflowId, xamlFile); + } + + /// + /// JobCreationComplete (EventId: 0xb032/45106) + /// + [EtwEvent(0xb032)] + public void JobCreationComplete(Guid jobId, Guid workflowId) + { + WriteEvent(M3PJobCreationCompleteEvent, jobId, workflowId); + } + + /// + /// JobError (EventId: 0xb02e/45102) + /// + [EtwEvent(0xb02e)] + public void JobError(int jobId, Guid workflowId, string errorDescription) + { + WriteEvent(M3PJobErrorEvent, jobId, workflowId, errorDescription); + } + + /// + /// JobRemoved (EventId: 0xb033/45107) + /// + [EtwEvent(0xb033)] + public void JobRemoved(Guid parentJobId, Guid childJobId, Guid workflowId) + { + WriteEvent(M3PJobRemovedEvent, parentJobId, childJobId, workflowId); + } + + /// + /// JobRemoveError (EventId: 0xb034/45108) + /// + [EtwEvent(0xb034)] + public void JobRemoveError(Guid parentJobId, Guid childJobId, Guid workflowId, string error) + { + WriteEvent(M3PJobRemoveErrorEvent, parentJobId, childJobId, workflowId, error); + } + + /// + /// JobStateChanged (EventId: 0xb02d/45101) + /// + [EtwEvent(0xb02d)] + public void JobStateChanged(int jobId, Guid workflowId, string newState, string oldState) + { + WriteEvent(M3PJobStateChangedEvent, jobId, workflowId, newState, oldState); + } + + /// + /// LoadingWorkflowForExecution (EventId: 0xb035/45109) + /// + [EtwEvent(0xb035)] + public void LoadingWorkflowForExecution(Guid workflowId) + { + WriteEvent(M3PLoadingWorkflowForExecutionEvent, workflowId); + } + + /// + /// OutOfProcessRunspaceStarted (EventId: 0xb046/45126) + /// + [EtwEvent(0xb046)] + public void OutOfProcessRunspaceStarted(string command) + { + WriteEvent(M3POutOfProcessRunspaceStartedEvent, command); + } + + /// + /// ParameterSplattingWasPerformed (EventId: 0xb047/45127) + /// + [EtwEvent(0xb047)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public void ParameterSplattingWasPerformed(string parameters, string computers) + { + WriteEvent(M3PParameterSplattingWasPerformedEvent, parameters, computers); + } + + /// + /// ParentJobCreated (EventId: 0xb031/45105) + /// + [EtwEvent(0xb031)] + public void ParentJobCreated(Guid jobId) + { + WriteEvent(M3PParentJobCreatedEvent, jobId); + } + + /// + /// PersistenceStoreMaxSizeReached (EventId: 0xb516/46358) + /// + [EtwEvent(0xb516)] + public void PersistenceStoreMaxSizeReached() + { + WriteEvent(M3PPersistenceStoreMaxSizeReachedEvent); + } + + /// + /// PersistingWorkflow (EventId: 0xb03d/45117) + /// + [EtwEvent(0xb03d)] + public void PersistingWorkflow(Guid workflowId, string persistPath) + { + WriteEvent(M3PPersistingWorkflowEvent, workflowId, persistPath); + } + + /// + /// ProxyJobRemoteJobAssociation (EventId: 0xb50b/46347) + /// + [EtwEvent(0xb50b)] + public void ProxyJobRemoteJobAssociation(Guid proxyJobInstanceId, Guid containerParentJobInstanceId) + { + WriteEvent(M3PProxyJobRemoteJobAssociationEvent, proxyJobInstanceId, containerParentJobInstanceId); + } + + /// + /// RemoveJobStarted (EventId: 0xb02c/45100) + /// + [EtwEvent(0xb02c)] + public void RemoveJobStarted(Guid jobId) + { + WriteEvent(M3PRemoveJobStartedEvent, jobId); + } + + /// + /// RunspaceAvailabilityChanged (EventId: 0xb022/45090) + /// + [EtwEvent(0xb022)] + public void RunspaceAvailabilityChanged(string runspaceId, string availability) + { + WriteEvent(M3PRunspaceAvailabilityChangedEvent, runspaceId, availability); + } + + /// + /// RunspaceStateChanged (EventId: 0xb023/45091) + /// + [EtwEvent(0xb023)] + public void RunspaceStateChanged(string runspaceId, string newState, string oldState) + { + WriteEvent(M3PRunspaceStateChangedEvent, runspaceId, newState, oldState); + } + + /// + /// TrackingGuidContainerParentJobCorrelation (EventId: 0xb505/46341) + /// + [EtwEvent(0xb505)] + public void TrackingGuidContainerParentJobCorrelation(Guid trackingId, Guid containerParentJobInstanceId) + { + WriteEvent(M3PTrackingGuidContainerParentJobCorrelationEvent, trackingId, containerParentJobInstanceId); + } + + /// + /// UnloadingWorkflow (EventId: 0xb039/45113) + /// + [EtwEvent(0xb039)] + public void UnloadingWorkflow(Guid workflowId) + { + WriteEvent(M3PUnloadingWorkflowEvent, workflowId); + } + + /// + /// WorkflowActivityExecutionFailed (EventId: 0xb021/45089) + /// + [EtwEvent(0xb021)] + public void WorkflowActivityExecutionFailed(Guid workflowId, string activityName, string failureDescription) + { + WriteEvent(M3PWorkflowActivityExecutionFailedEvent, workflowId, activityName, failureDescription); + } + + /// + /// WorkflowActivityValidated (EventId: 0xb01f/45087) + /// + [EtwEvent(0xb01f)] + public void WorkflowActivityValidated(Guid workflowId, string activityDisplayName, string activityType) + { + WriteEvent(M3PWorkflowActivityValidatedEvent, workflowId, activityDisplayName, activityType); + } + + /// + /// WorkflowActivityValidationFailed (EventId: 0xb020/45088) + /// + [EtwEvent(0xb020)] + public void WorkflowActivityValidationFailed(Guid workflowId, string activityDisplayName, string activityType) + { + WriteEvent(M3PWorkflowActivityValidationFailedEvent, workflowId, activityDisplayName, activityType); + } + + /// + /// WorkflowCleanupPerformed (EventId: 0xb028/45096) + /// + [EtwEvent(0xb028)] + public void WorkflowCleanupPerformed(Guid workflowId) + { + WriteEvent(M3PWorkflowCleanupPerformedEvent, workflowId); + } + + /// + /// WorkflowDeletedFromDisk (EventId: 0xb02a/45098) + /// + [EtwEvent(0xb02a)] + public void WorkflowDeletedFromDisk(Guid workflowId, string path) + { + WriteEvent(M3PWorkflowDeletedFromDiskEvent, workflowId, path); + } + + /// + /// WorkflowEngineStarted (EventId: 0xb048/45128) + /// + [EtwEvent(0xb048)] + public void WorkflowEngineStarted(string endpointName) + { + WriteEvent(M3PWorkflowEngineStartedEvent, endpointName); + } + + /// + /// WorkflowExecutionAborted (EventId: 0xb027/45095) + /// + [EtwEvent(0xb027)] + public void WorkflowExecutionAborted(Guid workflowId) + { + WriteEvent(M3PWorkflowExecutionAbortedEvent, workflowId); + } + + /// + /// WorkflowExecutionCancelled (EventId: 0xb026/45094) + /// + [EtwEvent(0xb026)] + public void WorkflowExecutionCancelled(Guid workflowId) + { + WriteEvent(M3PWorkflowExecutionCancelledEvent, workflowId); + } + + /// + /// WorkflowExecutionError (EventId: 0xb040/45120) + /// + [EtwEvent(0xb040)] + public void WorkflowExecutionError(Guid workflowId, string errorDescription) + { + WriteEvent(M3PWorkflowExecutionErrorEvent, workflowId, errorDescription); + } + + /// + /// WorkflowExecutionFinished (EventId: 0xb036/45110) + /// + [EtwEvent(0xb036)] + public void WorkflowExecutionFinished(Guid workflowId) + { + WriteEvent(M3PWorkflowExecutionFinishedEvent, workflowId); + } + + /// + /// WorkflowExecutionStarted (EventId: 0xb008/45064) + /// + [EtwEvent(0xb008)] + public void WorkflowExecutionStarted(Guid workflowId, string managedNodes) + { + WriteEvent(M3PWorkflowExecutionStartedEvent, workflowId, managedNodes); + } + + /// + /// WorkflowJobCreated (EventId: 0xb030/45104) + /// + [EtwEvent(0xb030)] + public void WorkflowJobCreated(Guid parentJobId, Guid childJobId, Guid childWorkflowId) + { + WriteEvent(M3PWorkflowJobCreatedEvent, parentJobId, childJobId, childWorkflowId); + } + + /// + /// WorkflowLoadedForExecution (EventId: 0xb024/45092) + /// + [EtwEvent(0xb024)] + public void WorkflowLoadedForExecution(Guid workflowId) + { + WriteEvent(M3PWorkflowLoadedForExecutionEvent, workflowId); + } + + /// + /// WorkflowLoadedFromDisk (EventId: 0xb029/45097) + /// + [EtwEvent(0xb029)] + public void WorkflowLoadedFromDisk(Guid workflowId, string path) + { + WriteEvent(M3PWorkflowLoadedFromDiskEvent, workflowId, path); + } + + /// + /// WorkflowManagerCheckpoint (EventId: 0xb049/45129) + /// + [EtwEvent(0xb049)] + public void WorkflowManagerCheckpoint(string checkpointPath, string configProviderId, string userName, string path) + { + WriteEvent(M3PWorkflowManagerCheckpointEvent, checkpointPath, configProviderId, userName, path); + } + + /// + /// WorkflowPersisted (EventId: 0xb03e/45118) + /// + [EtwEvent(0xb03e)] + public void WorkflowPersisted(Guid workflowId) + { + WriteEvent(M3PWorkflowPersistedEvent, workflowId); + } + + /// + /// WorkflowPluginRequestedToShutdown (EventId: 0xb010/45072) + /// + [EtwEvent(0xb010)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public void WorkflowPluginRequestedToShutdown(string endpointName) + { + WriteEvent(M3PWorkflowPluginRequestedToShutdownEvent, endpointName); + } + + /// + /// WorkflowPluginRestarted (EventId: 0xb011/45073) + /// + [EtwEvent(0xb011)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public void WorkflowPluginRestarted(string endpointName) + { + WriteEvent(M3PWorkflowPluginRestartedEvent, endpointName); + } + + /// + /// WorkflowPluginStarted (EventId: 0xb007/45063) + /// + [EtwEvent(0xb007)] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + public void WorkflowPluginStarted(string endpointName, string user, string hostingMode, string protocol, string configuration) + { + WriteEvent(M3PWorkflowPluginStartedEvent, endpointName, user, hostingMode, protocol, configuration); + } + + /// + /// WorkflowQuotaViolated (EventId: 0xb013/45075) + /// + [EtwEvent(0xb013)] + public void WorkflowQuotaViolated(string endpointName, string configName, string allowedValue, string valueInQuestion) + { + WriteEvent(M3PWorkflowQuotaViolatedEvent, endpointName, configName, allowedValue, valueInQuestion); + } + + /// + /// WorkflowResumed (EventId: 0xb014/45076) + /// + [EtwEvent(0xb014)] + public void WorkflowResumed(Guid workflowId) + { + WriteEvent(M3PWorkflowResumedEvent, workflowId); + } + + /// + /// WorkflowResuming (EventId: 0xb012/45074) + /// + [EtwEvent(0xb012)] + public void WorkflowResuming(Guid workflowId) + { + WriteEvent(M3PWorkflowResumingEvent, workflowId); + } + + /// + /// WorkflowRunspacePoolCreated (EventId: 0xb016/45078) + /// + [EtwEvent(0xb016)] + public void WorkflowRunspacePoolCreated(Guid workflowId, string managedNode) + { + WriteEvent(M3PWorkflowRunspacePoolCreatedEvent, workflowId, managedNode); + } + + /// + /// WorkflowStateChanged (EventId: 0xb009/45065) + /// + [EtwEvent(0xb009)] + public void WorkflowStateChanged(Guid workflowId, string newState, string oldState) + { + WriteEvent(M3PWorkflowStateChangedEvent, workflowId, newState, oldState); + } + + /// + /// WorkflowUnloaded (EventId: 0xb025/45093) + /// + [EtwEvent(0xb025)] + public void WorkflowUnloaded(Guid workflowId) + { + WriteEvent(M3PWorkflowUnloadedEvent, workflowId); + } + + /// + /// WorkflowValidationError (EventId: 0xb01e/45086) + /// + [EtwEvent(0xb01e)] + public void WorkflowValidationError(Guid workflowId) + { + WriteEvent(M3PWorkflowValidationErrorEvent, workflowId); + } + + /// + /// WorkflowValidationFinished (EventId: 0xb01d/45085) + /// + [EtwEvent(0xb01d)] + public void WorkflowValidationFinished(Guid workflowId) + { + WriteEvent(M3PWorkflowValidationFinishedEvent, workflowId); + } + + /// + /// WorkflowValidationStarted (EventId: 0xb01c/45084) + /// + [EtwEvent(0xb01c)] + public void WorkflowValidationStarted(Guid workflowId) + { + WriteEvent(M3PWorkflowValidationStartedEvent, workflowId); + } + } } // This code was generated on 02/01/2012 19:52:32
"); @@ -463,7 +464,7 @@ namespace Microsoft.PowerShell.Commands /// /// To write the Property name /// - private void WritePropertyName(StringBuilder Listtag,MshParameter p) + private void WritePropertyName(StringBuilder Listtag, MshParameter p) { //for writing the property name string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; @@ -481,12 +482,12 @@ namespace Microsoft.PowerShell.Commands /// /// To write the Property value /// - private void WritePropertyValue(StringBuilder Listtag,MshParameter p) + private void WritePropertyValue(StringBuilder Listtag, MshParameter p) { MshExpression exValue = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; // get the value of the property - List resultList = exValue.GetValues(inputObject); + List resultList = exValue.GetValues(_inputObject); foreach (MshExpressionResult result in resultList) { // create comma sep list for multiple results @@ -532,8 +533,8 @@ namespace Microsoft.PowerShell.Commands } //count of the objects - int numberObjects = 0; - + private int _numberObjects = 0; + /// /// /// @@ -543,39 +544,39 @@ namespace Microsoft.PowerShell.Commands // writes the table headers // it is not in BeginProcessing because the first inputObject is needed for // the number of columns and column name - if (inputObject == null || inputObject == AutomationNull.Value) + if (_inputObject == null || _inputObject == AutomationNull.Value) { return; } - numberObjects++; - if (!isTHWritten) + _numberObjects++; + if (!_isTHWritten) { InitializeResolvedNameMshParameters(); - if (resolvedNameMshParameters == null || resolvedNameMshParameters.Count == 0) + if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0) { return; } - + //if the As parameter is given as List if (_as.Equals("List", StringComparison.OrdinalIgnoreCase)) { //if more than one object,write the horizontal rule to put visual separator - if (numberObjects > 1) + if (_numberObjects > 1) WriteObject("